peterhinch / micropython-mqtt

A 'resilient' asynchronous MQTT driver. Recovers from WiFi and broker outages.
MIT License
549 stars 116 forks source link

Stuck on disconnections #144

Closed rdagger closed 4 days ago

rdagger commented 4 days ago

I created a simple test using the example code to publish and subscribe. It works. However, I simulated a WIFI disconnection by power cycling my access point and the MQTT client just got stuck and never recovered. I also tried restarting my MQTT broker and again the client just got stuck and never recovered. Here's my sample code using a QT PY ESP32-S2 running ESP32_GENERIC_S2-20240602-v1.23.0.

from mqtt_as import MQTTClient, config
import asyncio

# Local configuration
config['ssid'] = 'OA1'
config['wifi_pw'] = "mywifipassword"
config['server'] = '192.168.1.44'  # MQTT Server
config['port'] = 1883
config['user'] = "mymqttusername"
config['password'] = "mymqttpassword"

def callback(topic, msg, retained):
    print((topic, msg, retained))

async def conn_han(client):
    await client.subscribe('homeassistant/sensor/irrigation/command', 1)

async def main(client):
    await client.connect()
    n = 0
    while True:
        await asyncio.sleep(5)
        print('publish', n)
        # If WiFi is down the following will pause for the duration.
        await client.publish('result', '{}'.format(n), qos=1)
        n += 1

config['subs_cb'] = callback
config['connect_coro'] = conn_han

MQTTClient.DEBUG = True  # Optional: print diagnostic messages
client = MQTTClient(config)
try:
    asyncio.run(main(client))
finally:
    client.close()  # Prevent LmacRxBlk:1 errors
peterhinch commented 4 days ago

It's a while since I've run the S2 so I re-tested in case a firmware release had caused a regression. I did the following on a UM FeatherS2. Testing was done using mpremote.

The connection recovered correctly and publications resumed.

Your code looks fine. At the moment I'm stumped as to why it's not working for you.

rdagger commented 4 days ago

Thanks for your response! I'll do some more debugging.

rdagger commented 4 days ago

It was my fault. I was connecting to the Wi-Fi in my main.py before running mqtt_as which worked, but I had a typo in config['wifi_pw'].

My code is running now and recovering from both Wi-Fi and broker interruptions.

Thanks for the great project!