asyncio-mqtt is an idiomatic Python asyncio wrapper built around the robust paho-mqtt library. It provides a modern `async`/`await` interface, eliminating the need for callbacks and simplifying MQTT communication in asynchronous applications. The library aims for graceful disconnection and clear error handling via `MqttError`. As of version 0.16.2, it is stable but has since been superseded by `aiomqtt` (version 1.0.0+), which is the actively maintained successor. The project adheres to Semantic Versioning, with significant API changes expected before a 1.0.0 release (which occurred under the `aiomqtt` name).
pip install asyncio-mqttVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates both publishing and subscribing to an MQTT topic using `asyncio-mqtt`'s context manager pattern. It connects to a public test broker, publishes a single message, and then subscribes to the same topic to receive it. On Windows, a specific `asyncio` event loop policy might be required for Python 3.8+.
Migrate your project to use `aiomqtt`. Uninstall `asyncio-mqtt` and install `aiomqtt` (`pip install aiomqtt`). Update import statements from `from asyncio_mqtt import ...` to `from aiomqtt import ...`.
Update exception handling to catch `MqttError` instead of `asyncio.TimeoutError` for MQTT-specific operations. `try...except MqttError:`
Switch to the `SelectorEventLoop` at the start of your application. Example: `import asyncio; asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())`.
Always use `async with Client(...)` to ensure proper connection and disconnection handling.
If your code previously expected only the payload, update it to access `message.payload` and other attributes as needed. E.g., `async for message in messages: print(message.payload.decode())`.
pip install asyncio-mqtt
Verify the broker hostname and ensure it is correct and accessible.
Check the broker's hostname and network connectivity to ensure the broker is reachable.
Verify the broker's address and port are correct and the broker is running. Implement a `try...except asyncio_mqtt.MqttError` block with a reconnection strategy, including `await asyncio.sleep(reconnect_interval)`.
Check that the MQTT broker (e.g., Mosquitto) is running and configured to listen on the correct IP address and port. Verify no firewall rules are blocking the connection on both the client and broker machines.