From 1778c7cfd6773c6523ef6390bd973929e21bfc0a Mon Sep 17 00:00:00 2001 From: Vladimir Kotal Date: Sun, 9 Feb 2025 23:34:03 +0100 Subject: [PATCH 1/5] fix typo --- tests/conftest.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/conftest.py b/tests/conftest.py index 93eefcbd..2b8b03ec 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -10,7 +10,7 @@ @pytest.fixture(autouse=True) def reset_connection_manager(monkeypatch): - """Reset the ConnectionManager, since it's a singlton and will hold data""" + """Reset the ConnectionManager, since it's a singleton and will hold data""" monkeypatch.setattr( "adafruit_minimqtt.adafruit_minimqtt.get_connection_manager", adafruit_connection_manager.ConnectionManager, From dc361342e4604b9725ed3af6a84c6d4bafeb8302 Mon Sep 17 00:00:00 2001 From: Vladimir Kotal Date: Sun, 9 Feb 2025 23:34:37 +0100 Subject: [PATCH 2/5] disconnect on reconnect() if connected fixes #243 --- adafruit_minimqtt/adafruit_minimqtt.py | 11 +- tests/test_reconnect.py | 205 +++++++++++++++++++++++++ 2 files changed, 214 insertions(+), 2 deletions(-) create mode 100644 tests/test_reconnect.py diff --git a/adafruit_minimqtt/adafruit_minimqtt.py b/adafruit_minimqtt/adafruit_minimqtt.py index 75148ed4..1c63d5ca 100644 --- a/adafruit_minimqtt/adafruit_minimqtt.py +++ b/adafruit_minimqtt/adafruit_minimqtt.py @@ -939,11 +939,18 @@ def reconnect(self, resub_topics: bool = True) -> int: """ self.logger.debug("Attempting to reconnect with MQTT broker") + subscribed_topics = [] + if self.is_connected(): + # disconnect() will reset subscribed topics so stash them now. + if resub_topics: + subscribed_topics = self._subscribed_topics.copy() + self.disconnect() + ret = self.connect() self.logger.debug("Reconnected with broker") - if resub_topics: + + if resub_topics and subscribed_topics: self.logger.debug("Attempting to resubscribe to previously subscribed topics.") - subscribed_topics = self._subscribed_topics.copy() self._subscribed_topics = [] while subscribed_topics: feed = subscribed_topics.pop() diff --git a/tests/test_reconnect.py b/tests/test_reconnect.py new file mode 100644 index 00000000..6b049246 --- /dev/null +++ b/tests/test_reconnect.py @@ -0,0 +1,205 @@ +# SPDX-FileCopyrightText: 2025 VladimĂ­r Kotal +# +# SPDX-License-Identifier: Unlicense + +"""reconnect tests""" + +import logging +import ssl +import sys + +import pytest +from mocket import Mocket + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +if not sys.implementation.name == "circuitpython": + from typing import Optional + + from circuitpython_typing.socket import ( + SocketType, + SSLContextType, + ) + + +class FakeConnectionManager: + """ + Fake ConnectionManager class + """ + + def __init__(self, socket): + self._socket = socket + + def get_socket( # noqa: PLR0913, Too many arguments + self, + host: str, + port: int, + proto: str, + session_id: Optional[str] = None, + *, + timeout: float = 1.0, + is_ssl: bool = False, + ssl_context: Optional[SSLContextType] = None, + ) -> SocketType: + """ + Return the specified socket. + """ + return self._socket + + def close_socket(self, socket) -> None: + pass + + +def handle_subscribe(client, user_data, topic, qos): + """ + Record topics into user data. + """ + assert topic + assert user_data["topics"] is not None + assert qos == 0 + + user_data["topics"].append(topic) + + +def handle_disconnect(client, user_data, zero): + """ + Record disconnect. + """ + + user_data["disconnect"] = True + + +# The MQTT packet contents below were captured using Mosquitto client+server. +testdata = [ + ( + [], + bytearray( + [ + 0x20, # CONNACK + 0x02, + 0x00, + 0x00, + 0x90, # SUBACK + 0x03, + 0x00, + 0x01, + 0x00, + 0x20, # CONNACK + 0x02, + 0x00, + 0x00, + 0x90, # SUBACK + 0x03, + 0x00, + 0x02, + 0x00, + ] + ), + ), + ( + [("foo/bar", 0)], + bytearray( + [ + 0x20, # CONNACK + 0x02, + 0x00, + 0x00, + 0x90, # SUBACK + 0x03, + 0x00, + 0x01, + 0x00, + 0x20, # CONNACK + 0x02, + 0x00, + 0x00, + 0x90, # SUBACK + 0x03, + 0x00, + 0x02, + 0x00, + ] + ), + ), + ( + [("foo/bar", 0), ("bah", 0)], + bytearray( + [ + 0x20, # CONNACK + 0x02, + 0x00, + 0x00, + 0x90, # SUBACK + 0x03, + 0x00, + 0x01, + 0x00, + 0x00, + 0x20, # CONNACK + 0x02, + 0x00, + 0x00, + 0x90, # SUBACK + 0x03, + 0x00, + 0x02, + 0x00, + 0x90, # SUBACK + 0x03, + 0x00, + 0x03, + 0x00, + ] + ), + ), +] + + +@pytest.mark.parametrize( + "topics,to_send", + testdata, + ids=[ + "no_topic", + "single_topic", + "multi_topic", + ], +) +def test_reconnect(topics, to_send) -> None: + """ + Test reconnect() handling, mainly that it performs disconnect on already connected socket. + + Nothing will travel over the wire, it is all fake. + """ + logging.basicConfig() + logger = logging.getLogger(__name__) + logger.setLevel(logging.DEBUG) + + host = "localhost" + port = 1883 + + user_data = {"topics": [], "disconnect": False} + mqtt_client = MQTT.MQTT( + broker=host, + port=port, + ssl_context=ssl.create_default_context(), + connect_retries=1, + user_data=user_data, + ) + + mocket = Mocket(to_send) + mqtt_client._connection_manager = FakeConnectionManager(mocket) + mqtt_client.connect() + + mqtt_client.logger = logger + + if topics: + logger.info(f"subscribing to {topics}") + mqtt_client.subscribe(topics) + + logger.info("reconnecting") + mqtt_client.on_subscribe = handle_subscribe + mqtt_client.on_disconnect = handle_disconnect + mqtt_client.reconnect() + + assert user_data.get("disconnect") == True + assert set(user_data.get("topics")) == set([t[0] for t in topics]) From 6ebbb2601bf934ab0d376c7deaca9f3ce524bf04 Mon Sep 17 00:00:00 2001 From: Vladimir Kotal Date: Mon, 10 Feb 2025 08:02:21 +0100 Subject: [PATCH 3/5] check close count --- tests/test_reconnect.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_reconnect.py b/tests/test_reconnect.py index 6b049246..5e0a5331 100644 --- a/tests/test_reconnect.py +++ b/tests/test_reconnect.py @@ -29,6 +29,7 @@ class FakeConnectionManager: def __init__(self, socket): self._socket = socket + self.close_cnt = 0 def get_socket( # noqa: PLR0913, Too many arguments self, @@ -47,7 +48,7 @@ def get_socket( # noqa: PLR0913, Too many arguments return self._socket def close_socket(self, socket) -> None: - pass + self.close_cnt += 1 def handle_subscribe(client, user_data, topic, qos): @@ -202,4 +203,5 @@ def test_reconnect(topics, to_send) -> None: mqtt_client.reconnect() assert user_data.get("disconnect") == True + assert mqtt_client._connection_manager.close_cnt == 1 assert set(user_data.get("topics")) == set([t[0] for t in topics]) From 8f4c421c69aa412f64176c3d2034e56db0b88fd2 Mon Sep 17 00:00:00 2001 From: Vladimir Kotal Date: Mon, 10 Feb 2025 08:10:57 +0100 Subject: [PATCH 4/5] add test for the not connected case --- tests/test_reconnect.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/tests/test_reconnect.py b/tests/test_reconnect.py index 5e0a5331..bd9d3926 100644 --- a/tests/test_reconnect.py +++ b/tests/test_reconnect.py @@ -205,3 +205,43 @@ def test_reconnect(topics, to_send) -> None: assert user_data.get("disconnect") == True assert mqtt_client._connection_manager.close_cnt == 1 assert set(user_data.get("topics")) == set([t[0] for t in topics]) + + +def test_reconnect_not_connected() -> None: + """ + Test reconnect() handling not connected. + """ + logging.basicConfig() + logger = logging.getLogger(__name__) + logger.setLevel(logging.DEBUG) + + host = "localhost" + port = 1883 + + user_data = {"topics": [], "disconnect": False} + mqtt_client = MQTT.MQTT( + broker=host, + port=port, + ssl_context=ssl.create_default_context(), + connect_retries=1, + user_data=user_data, + ) + + mocket = Mocket( + bytearray( + [ + 0x20, # CONNACK + 0x02, + 0x00, + 0x00, + ] + ) + ) + mqtt_client._connection_manager = FakeConnectionManager(mocket) + + mqtt_client.logger = logger + mqtt_client.on_disconnect = handle_disconnect + mqtt_client.reconnect() + + assert user_data.get("disconnect") == False + assert mqtt_client._connection_manager.close_cnt == 0 From 933b1cb66daa7b2d0e1995d329eeebea12052bd5 Mon Sep 17 00:00:00 2001 From: Vladimir Kotal Date: Mon, 10 Feb 2025 18:02:41 +0100 Subject: [PATCH 5/5] preserve sesion ID on reconnect --- adafruit_minimqtt/adafruit_minimqtt.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/adafruit_minimqtt/adafruit_minimqtt.py b/adafruit_minimqtt/adafruit_minimqtt.py index 1c63d5ca..a8d53428 100644 --- a/adafruit_minimqtt/adafruit_minimqtt.py +++ b/adafruit_minimqtt/adafruit_minimqtt.py @@ -204,6 +204,8 @@ def __init__( # noqa: PLR0915, PLR0913, Too many statements, Too many arguments if port: self.port = port + self.session_id = None + # define client identifier if client_id: # user-defined client_id MAY allow client_id's > 23 bytes or @@ -528,6 +530,7 @@ def _connect( # noqa: PLR0912, PLR0913, PLR0915, Too many branches, Too many ar is_ssl=self._is_ssl, ssl_context=self._ssl_context, ) + self.session_id = session_id self._backwards_compatible_sock = not hasattr(self._sock, "recv_into") fixed_header = bytearray([0x10]) @@ -946,7 +949,7 @@ def reconnect(self, resub_topics: bool = True) -> int: subscribed_topics = self._subscribed_topics.copy() self.disconnect() - ret = self.connect() + ret = self.connect(session_id=self.session_id) self.logger.debug("Reconnected with broker") if resub_topics and subscribed_topics: