Package: asyncio-paho
Asynchronous I/O (asyncio) Paho MQTT clientAPaho MQTTclient supportingasyncioloop without additional setup. Forget about configuring thePaho network-loop. The client can almost be used as a drop-in replacement for Paho Client. The asyncio loop is automatically configured when you connect.FeaturesDrop-in replacement of Paho Client (inherits from Paho Client)Automatic configuration of asyncio loop.Reconnect on connection loss.Type hinted.Async callbacks.Non blocking connect (await client.asyncio_connect()).Python Asynchronous Context Manager handles cleanup.No threading, only asyncio.Installationpip install asyncio-pahoUsageYou should use Pahoconnect_async()or extensionasyncio_connect()when connecting to avoid blocking. It is often usefull to configure subscriptions in on_connect callback to make sure all subscriptions is also setup on reconnect after connection loss.Drop-in replacementRemove all you calls to Paho looping like loop_forever() etc.client=AsyncioPahoClient()client.connect_async("mqtt.eclipseprojects.io")# remove your current looping (loop_forever() etc)# do mqtt stuffclient.Disconnect()Asynchronous Context ManagerThe client is an Asynchronous Context Manager and can be used with the Python with statement to atomatically disconnect and clean up.asyncwithAsyncioPahoClient()asclient:client.connect_async("mqtt.eclipseprojects.io")# do mqtt stuff - client.Disconnect() is called when exiting context.ExtensionsThe client has some additional async features (functions prefixed withasyncio_).asyncio_connectThe classic Pahoconnect()is blocking. Pahoconnect_async()is not blocking, but returns before the connect is complete. Useasyncio_connect()to wait for connect to complete without blocking. This function also throws exception on connect failure. Please note thatasyncio_connect()cannot be used together withon_connect/on_connect_fail(useasyncio_add_on_connect_listenerandasyncio_add_on_connect_fail_listenerinstead ofon_connectandon_connect_fail).asyncwithAsyncioPahoClient()asclient:awaitclient.asyncio_connect("mqtt.eclipseprojects.io")asyncio_subscribeThe classic Pahoconnect()returns before the subscriptions is acknowledged by the broker, andon_subscribe/asyncio_listeners.add_on_subscribe()has to be uses to capture the acknowledge if needed. The async extensionasyncio_subscribe()can be used to subscribe and wait for the acknowledge without blocking. It is often usefull to configure subscriptions when connecting to make sure subscriptions are reconfigured on reconnect (connection lost).asyncdefon_connect_async(client,userdata,flags_dict,result):awaitclient.asyncio_subscribe("mytopic")asyncdefon_message_async(client,userdata,msg):print(f"Received from{msg.topic}:{str(msg.payload)}")asyncwithAsyncioPahoClient()asclient:client.asyncio_listeners.add_on_connect(on_connect_async)client.asyncio_listeners.add_on_message(on_message_async)awaitclient.asyncio_connect("mqtt.eclipseprojects.io")CallbacksPaho has a lot of callbacks. Async alternatives have been added for some of them, but they are mutally exclusive (you have to pick sync or async for eatch callback type). Multiple async listeners can be added to the same event, and a function handle to unsubscribe is returned when adding.Classic PahoExtension alternativeCalled whenon_connectasyncio_listeners.add_on_connect()the broker responds to our connectionon_connect_failasyncio_listeners.add_on_connect_fail()the client failed to connect to the brokeron_messageasyncio_listeners.add_on_message()a message has been received on a topic that the client subscribes tomessage_callback_addasyncio_listeners.message_callback_add()a message has been received on a topic for specific subscription filterson_subscribeasyncio_listeners.add_on_subscribe()the broker responds to a subscribe requeston_publishasyncio_listeners.add_on_publish()a message that was to be sent using the publish() call has completed transmission to the brokerasyncdefon_connect_async(client,userdata,message)->None:client.subscribe("mytopic")asyncwithAsyncioPahoClient()asclient:client.asyncio_add_on_connect_listener(on_connect_async)awaitclient.asyncio_connect("mqtt.eclipseprojects.io")asyncio_listeners.add_on_connect()Add async on_connect event listener.MQTT v3 callback signature:asyncdefcallback(client:AsyncioPahoClient,userdata:Any,flags:dict[str,Any],rc:int)MQTT v5 callback signature:asyncdefcallback(client:AsyncioPahoClient,userdata:Any,flags:dict[str,reasonCode:ReasonCodes,properties:Properties])asyncio_listeners.add_on_message()Add async on_connect event listener. Callback signature:asyncdefcallback(client:AsyncioPahoClient,userdata:Any,msg:MQTTMessage)DependenciesPython 3.8 or later.Paho MQTTThe client uses asyncio event loopadd_reader()andadd_writer()methods. These methods are not supported onWindowsbyProactorEventLoop(default onWindowsfrom Python 3.8). You should be able to use another event loop likeSelectorEventLoop.