Registry / http-networking / asyncio-mqtt

asyncio-mqtt

JSON →
library0.16.2pypypi✓ verified 85d ago

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-mqtt
INSTALL
IMPORT
SIG · ASYNCIO-MQTT
A
asyncio-mqtt
http-networkingpythonv0.16.2
Install
1.7s avg
Import
295ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.16.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.318s · 18.4MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 1.7s · import 0.272s · 19MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Client
from asyncio_mqtt import Client
MqttError
from asyncio_mqtt import MqttError

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+.

import asyncio from asyncio_mqtt import Client, MqttError async def publish_message(): async with Client("test.mosquitto.org") as client: await client.publish("my/topic", payload=b"Hello, asyncio-mqtt!") print("Published 'Hello, asyncio-mqtt!' to my/topic") async def subscribe_and_receive(): async with Client("test.mosquitto.org") as client: async with client.filtered_messages("my/topic") as messages: await client.subscribe("my/topic") print("Subscribed to my/topic. Waiting for messages...") async for message in messages: print(f"Received: {message.payload.decode()} on topic {message.topic}") # For quickstart, exit after one message break async def main(): await asyncio.gather(publish_message(), subscribe_and_receive()) if __name__ == "__main__": # Note for Windows users: Since Python 3.8, the default asyncio event loop is the # ProactorEventLoop. It doesn't support the add_reader method required by asyncio-mqtt. # Switch to SelectorEventLoop if encountering issues. # import sys # if sys.platform.lower() == "win32" or os.name.lower() == "nt": # from asyncio import set_event_loop_policy, WindowsSelectorEventLoopPolicy # set_event_loop_policy(WindowsSelectorEventLoopPolicy()) asyncio.run(main())
Debug
Known issues
breakingThe `asyncio-mqtt` project was renamed to `aiomqtt`. Version `0.17.0` of `asyncio-mqtt` was yanked due to the rename causing breaking changes for users of an older `aiomqtt` library. Users are strongly encouraged to migrate to `aiomqtt` (version `1.0.0` or higher) for continued maintenance and new features.
fix
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 ...`.
affects: <1.0.0 (under `asyncio-mqtt` name)
breakingAs of `aiomqtt` (the successor to `asyncio-mqtt`) v1.0.0, `asyncio.TimeoutError` is no longer raised for timeout-related issues in `Client.subscribe`, `unsubscribe`, or `publish`. Instead, `MqttError` is raised.
fix
Update exception handling to catch `MqttError` instead of `asyncio.TimeoutError` for MQTT-specific operations. `try...except MqttError:`
affects: >=1.0.0 (of `aiomqtt` equivalent)
gotchaOn Windows, for Python 3.8 and later, the default `ProactorEventLoop` does not support the `add_reader` method required by `asyncio-mqtt`. This can lead to runtime errors or the client not functioning correctly.
fix
Switch to the `SelectorEventLoop` at the start of your application. Example: `import asyncio; asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())`.
affects: All versions on Python 3.8+ on Windows
gotchaThe library strongly advocates for the use of `async with Client(...)` context managers for connecting and disconnecting. Manual `client.connect()` and `client.disconnect()` methods are discouraged and may lead to connection management issues and footguns related to graceful disconnection.
fix
Always use `async with Client(...)` to ensure proper connection and disconnection handling.
affects: All versions
breakingA change was introduced where `client.filtered_messages()` and `client.unfiltered_messages()` yield the full `MQTTMessage` object (from `paho-mqtt`) instead of just the payload. This provides access to `topic`, `qos`, `retain` flags, etc.
fix
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())`.
affects: >=0.16.2
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'asyncio_mqtt'
The 'asyncio-mqtt' package is not installed in the Python environment.
fix
pip install asyncio-mqtt
socket.gaierror: [Errno -2] Name or service not known
The MQTT broker hostname is incorrect or cannot be resolved.
fix
Verify the broker hostname and ensure it is correct and accessible.
asyncio_mqtt.error.MqttError: [Errno -2] Name or service not known
The MQTT client cannot connect to the broker due to an incorrect or unreachable hostname.
fix
Check the broker's hostname and network connectivity to ensure the broker is reachable.
asyncio_mqtt.MqttError: Operation timed out
The MQTT client failed to establish a connection with the broker within the specified timeout period, often due to network issues or the broker being unresponsive.
fix
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)`.
ConnectionRefusedError: [Errno 111] Connection refused
The MQTT client was actively refused a connection by the broker, typically because the broker is not running, is not listening on the specified port, or a firewall is blocking the connection.
fix
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.
Upgrade
Version history
0.16.2latest on PyPI · released Jun 26, 2023
Audit
Dependencies
paho-mqttrequiredCore MQTT client functionality, asyncio-mqtt acts as an asynchronous wrapper.
Agent activity
37 hits · last 30 days
node
32
OpenAI (training)
1
Resources
asyncio-mqtt — pip install asyncio-mqtt · libregistry