Skip to content

Commit 8595e36

Browse files
committed
Close the socket when there is an error using the socket.
This fixes two related problems which made reconnecting not work after the connection to the server gets dropped unexpectedly. The MQTT client continues sending messages and on ESP32 eventually an OSError is raised. The client must then reconnect. But reconnect was failing because the Adafruit Connection Manager was returning the same broken socket for the server since it hadn't yet been closed by MiniMQTT. Explicitly calling disconnect() would also not close the socket because it tries to send the disconnect packet on the broken socket which raised an OSError preventing the socket from being closed.
1 parent bdcea6b commit 8595e36

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

adafruit_minimqtt/adafruit_minimqtt.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ def connect(
436436
except (MemoryError, OSError, RuntimeError) as e:
437437
if isinstance(e, RuntimeError) and e.args == ("pystack exhausted",):
438438
raise
439+
self._close_socket()
439440
self.logger.warning(f"Socket error when connecting: {e}")
440441
last_exception = e
441442
backoff = False
@@ -591,7 +592,7 @@ def disconnect(self) -> None:
591592
self.logger.debug("Sending DISCONNECT packet to broker")
592593
try:
593594
self._sock.send(MQTT_DISCONNECT)
594-
except RuntimeError as e:
595+
except (MemoryError, OSError, RuntimeError) as e:
595596
self.logger.warning(f"Unable to send DISCONNECT packet: {e}")
596597
self._close_socket()
597598
self._is_connected = False

0 commit comments

Comments
 (0)