Skip to content

Commit

Permalink
Make sure socket is closed on exception
Browse files Browse the repository at this point in the history
  • Loading branch information
justmobilize committed May 20, 2024
1 parent 906e676 commit 16b6c6d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
12 changes: 9 additions & 3 deletions adafruit_minimqtt/adafruit_minimqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,7 @@ def connect(
self.logger.warning(f"Socket error when connecting: {e}")
backoff = False
except MMQTTException as e:
self._close_socket()
self.logger.info(f"MMQT error: {e}")
if e.code in [
CONNACK_ERROR_INCORECT_USERNAME_PASSWORD,
Expand All @@ -452,9 +453,9 @@ def connect(
exc_msg = "Repeated connect failures"
else:
exc_msg = "Connect failure"

if last_exception:
raise MMQTTException(exc_msg) from last_exception

raise MMQTTException(exc_msg)

# pylint: disable=too-many-branches, too-many-statements, too-many-locals
Expand Down Expand Up @@ -565,6 +566,12 @@ def _connect(
f"No data received from broker for {self._recv_timeout} seconds."
)

def _close_socket(self):
if self._sock:
self.logger.debug("Closing socket")
self._connection_manager.close_socket(self._sock)
self._sock = None

# pylint: disable=no-self-use
def _encode_remaining_length(
self, fixed_header: bytearray, remaining_length: int
Expand Down Expand Up @@ -593,8 +600,7 @@ def disconnect(self) -> None:
self._sock.send(MQTT_DISCONNECT)
except RuntimeError as e:
self.logger.warning(f"Unable to send DISCONNECT packet: {e}")
self.logger.debug("Closing socket")
self._connection_manager.close_socket(self._sock)
self._close_socket()
self._is_connected = False
self._subscribed_topics = []
self._last_msg_sent_timestamp = 0
Expand Down
2 changes: 2 additions & 0 deletions tests/test_backoff.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def test_failing_connect(self) -> None:
print("connecting")
with pytest.raises(MQTT.MMQTTException) as context:
mqtt_client.connect()
assert mqtt_client._sock is None
assert "Repeated connect failures" in str(context)

mock_method.assert_called()
Expand Down Expand Up @@ -86,6 +87,7 @@ def test_unauthorized(self) -> None:
print("connecting")
with pytest.raises(MQTT.MMQTTException) as context:
mqtt_client.connect()
assert mqtt_client._sock is None
assert "Connection Refused - Unauthorized" in str(context)

mock_method.assert_called()
Expand Down

0 comments on commit 16b6c6d

Please sign in to comment.