Reconnection#

Network connections are inherently unstable and can fail at any time. Especially for long-running applications, this can be a challenge. To make our application resilient against connection failures, we can wrap the code in a try/except-block, listen for MqttErrors, and reconnect like so:

import asyncio
import aiomqtt


async def main():
    interval = 5  # Seconds
    while True:
        try:
            async with aiomqtt.Client("test.mosquitto.org") as client:
                await client.subscribe("humidity/#")
                async for message in client.messages:
                    print(message.payload)
        except aiomqtt.MqttError:
            print(f"Connection lost; Reconnecting in {interval} seconds ...")
            await asyncio.sleep(interval)


asyncio.run(main())