Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reconnect restoration #244

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Conversation

vladak
Copy link
Contributor

@vladak vladak commented Feb 9, 2025

This change restores the behavior of disconnecting on reconnect() if already connected.

@vladak
Copy link
Contributor Author

vladak commented Feb 10, 2025

Tested on my trusty Adafruit CircuitPython 9.2.4 on 2025-01-29; Adafruit QT Py ESP32S2 with ESP32S2 with:

#!/usr/bin/env python3

import adafruit_minimqtt.adafruit_minimqtt as MQTT
import ssl
import adafruit_logging as logging
import socketpool
import wifi

try:
    from secrets import secrets
except ImportError:
    print(
        "WiFi and Adafruit IO credentials are kept in secrets.py, please add them there!"
    )
    raise


def connect_hook(client, user_data, result, code):
    print(f"Connect: {user_data} {result} {code}")


def message_hook(client, topic, message):
    # print(f"Message: topic='{topic}' message='{message}'")
    print(f"Message: topic='{topic}'")


def main():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    logger.info("Connecting to wifi")
    wifi.radio.connect(secrets["ssid"], secrets["password"], timeout=10)
    logger.info(f"Connected to {secrets['ssid']}")
    logger.debug(f"IP: {wifi.radio.ipv4_address}")

    pool = socketpool.SocketPool(wifi.radio)  # pylint: disable=no-member

    broker = "172.40.0.3"
    port = 1883

    mqtt_client = MQTT.MQTT(
        broker=broker,
        port=port,
        socket_pool=pool,
        ssl_context=ssl.create_default_context(),
    )

    mqtt_client.enable_logger(logging, log_level=logging.DEBUG)

    mqtt_client.on_connect = connect_hook
    mqtt_client.on_message = message_hook

    mqtt_client.connect()
    mqtt_client.subscribe('devices/foo/#')

    mqtt_client.reconnect()

    while True:
        mqtt_client.loop()

try:
    main()
except Exception as e:
    print(f"Got exception: {e}")

Produces the following output:

code.py output:
3125.951: INFO - Connecting to wifi
3125.954: INFO - Connected to foo
3125.959: DEBUG - Attempting to connect to MQTT broker (attempt #0)
3125.961: DEBUG - Attempting to establish MQTT connection...
3125.968: DEBUG - Sending CONNECT to broker...
3125.971: DEBUG - Fixed Header: bytearray(b'\x10\x13')
3125.973: DEBUG - Variable Header: bytearray(b'\x00\x04MQTT\x04\x02\x00<')
3125.983: DEBUG - Receiving CONNACK packet from broker
3125.987: DEBUG - Got message type: 0x20 pkt: 0x20
Connect: None 0 0
3125.991: DEBUG - Resetting reconnect backoff
3125.993: DEBUG - Sending SUBSCRIBE to broker...
3125.997: DEBUG - Fixed Header: bytearray(b'\x82\x17')
3126.000: DEBUG - Variable Header: b'\x00\x01'
3126.005: DEBUG - SUBSCRIBING to topic devices/foo/# with QoS 0
3126.007: DEBUG - payload: b'\x00\x12devices/foo/#\x00'
3126.055: DEBUG - Got message type: 0x90 pkt: 0x90
3126.059: DEBUG - Attempting to reconnect with MQTT broker
3126.061: DEBUG - Sending DISCONNECT packet to broker
3126.063: DEBUG - Closing socket
3126.070: DEBUG - Attempting to connect to MQTT broker (attempt #0)
3126.072: DEBUG - Attempting to establish MQTT connection...
3126.080: DEBUG - Sending CONNECT to broker...
3126.082: DEBUG - Fixed Header: bytearray(b'\x10\x13')
3126.084: DEBUG - Variable Header: bytearray(b'\x00\x04MQTT\x04\x02\x00<')
3126.090: DEBUG - Receiving CONNACK packet from broker
3126.097: DEBUG - Got message type: 0x20 pkt: 0x20
Connect: None 0 0
3126.101: DEBUG - Resetting reconnect backoff
3126.103: DEBUG - Reconnected with broker
3126.106: DEBUG - Attempting to resubscribe to previously subscribed topics.
3126.108: DEBUG - Sending SUBSCRIBE to broker...
3126.111: DEBUG - Fixed Header: bytearray(b'\x82\x17')
3126.115: DEBUG - Variable Header: b'\x00\x02'
3126.120: DEBUG - SUBSCRIBING to topic devices/foo/# with QoS 0
3126.122: DEBUG - payload: b'\x00\x12devices/foo/#\x00'
3126.165: DEBUG - Got message type: 0x90 pkt: 0x90
3126.168: DEBUG - waiting for messages for 1.0 seconds
3127.171: DEBUG - Loop timed out after 1.0 seconds
3127.173: DEBUG - waiting for messages for 1.0 seconds
3127.234: DEBUG - Got message type: 0x30 pkt: 0x30
3127.238: DEBUG - Receiving PUBLISH 
Topic: devices/foo/qtpy
Msg: bytearray(b'{"lux": 8.2944, "brightness": 0.74, "cpu_temp": 89.5844, "light": 18}')
Message: topic='devices/foo/qtpy'
3128.243: DEBUG - Loop timed out after 1.0 seconds
3128.246: DEBUG - waiting for messages for 1.0 seconds
3129.691: DEBUG - Got message type: 0x30 pkt: 0x30
3129.695: DEBUG - Receiving PUBLISH 
Topic: devices/foo/qtpy
Msg: bytearray(b'{"lux": 8.2944, "brightness": 0.74, "cpu_temp": 67.6544, "light": 18}')
Message: topic='devices/foo/qtpy'
3129.700: DEBUG - Loop timed out after 1.0 seconds
3129.704: DEBUG - waiting for messages for 1.0 seconds
...

Copy link
Contributor

@tyeth tyeth left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me, thanks for the extra tests too.

@brentru thinking about merging this one in, plus secrets (#245) and releasing.
I could pickup the MQTTStateException (#240) too in the same release, or do patch ones then major for the exceptions change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants