Skip to content

Commit

Permalink
Close the socket when there is an error using the socket.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
rbedia committed Oct 8, 2024
1 parent bdcea6b commit 8595e36
Showing 1 changed file with 2 additions and 1 deletion.
3 changes: 2 additions & 1 deletion adafruit_minimqtt/adafruit_minimqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,7 @@ def connect(
except (MemoryError, OSError, RuntimeError) as e:
if isinstance(e, RuntimeError) and e.args == ("pystack exhausted",):
raise
self._close_socket()
self.logger.warning(f"Socket error when connecting: {e}")
last_exception = e
backoff = False
Expand Down Expand Up @@ -591,7 +592,7 @@ def disconnect(self) -> None:
self.logger.debug("Sending DISCONNECT packet to broker")
try:
self._sock.send(MQTT_DISCONNECT)
except RuntimeError as e:
except (MemoryError, OSError, RuntimeError) as e:
self.logger.warning(f"Unable to send DISCONNECT packet: {e}")
self._close_socket()
self._is_connected = False
Expand Down

0 comments on commit 8595e36

Please sign in to comment.