asyncio-mqtt

0.16.2 · deprecated · verified Wed Apr 15

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

Warnings

Install

Imports

Quickstart

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())

view raw JSON →