aiomqtt
aiomqtt is an idiomatic asyncio MQTT client for Python, providing a modern asynchronous API built on top of the paho-mqtt library. The current stable version is 2.5.1. It maintains a regular release cadence, with minor and patch releases occurring every few weeks to months, and a major version (3.0.0) currently in alpha with significant breaking changes.
Warnings
- breaking aiomqtt v3.0.0 introduces extensive breaking changes. It replaces the `paho-mqtt` dependency with `mqtt5`, drops support for MQTTv3.1/3.1.1, makes all `Client` parameters keyword-only, changes message types from `aiomqtt.Message` to `mqtt5.PublishPacket`, alters the `publish` payload argument from `payload=` keyword to a positional `bytes` argument, and makes `client.messages` a method (`client.messages()`).
- gotcha The `client.messages` asynchronous iterator was not reusable prior to version 2.2.0. If you tried to iterate over it multiple times or in different contexts, it would only yield messages during the first iteration.
- deprecated Internal usage of `asyncio.get_event_loop()` was replaced with `asyncio.get_running_loop()` to align with modern asyncio best practices. While this primarily affects internal library behavior, users relying on specific event loop interactions with older Python versions or less common asyncio setups might observe subtle differences.
- gotcha Combining `tls_params` with `tls_insecure=True` could lead to connection failures in versions prior to 2.5.1.
Install
-
pip install aiomqtt
Imports
- Client
from aiomqtt import Client
- Message
from aiomqtt import Message
- Topic
from aiomqtt import Topic
Quickstart
import asyncio
import os
from aiomqtt import Client, Topic
async def main():
mqtt_host = os.environ.get("MQTT_HOST", "localhost")
mqtt_port = int(os.environ.get("MQTT_PORT", 1883))
mqtt_topic = os.environ.get("MQTT_TOPIC", "test/topic")
print(f"Connecting to mqtt://{mqtt_host}:{mqtt_port}...")
async with Client(hostname=mqtt_host, port=mqtt_port) as client:
await client.subscribe(Topic(mqtt_topic, qos=1))
print(f"Subscribed to '{mqtt_topic}'. Waiting for messages...")
async for message in client.messages:
# For aiomqtt v2.x, message is an aiomqtt.Message object.
# For aiomqtt v3.x+, message will be an mqtt5.PublishPacket object.
print(f"Received message on topic '{message.topic}': {message.payload.decode()}")
if message.payload.decode() == "exit":
print("Received 'exit' message, shutting down.")
break
if __name__ == "__main__":
asyncio.run(main())