aiomqtt

2.5.1 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an MQTT broker, subscribe to a topic, and asynchronously receive messages. It uses environment variables for host, port, and topic, falling back to defaults. Replace `MQTT_HOST` with your broker's address (e.g., `mqtt.eclipseprojects.io`).

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

view raw JSON →