# MQTT : Clients : aiomqtt > [!WARNING] This page is abandoned. > I ran into so many annoyances and documentation omissions in such a short time that I've decided to throw out aiomqtt and just learn and use paho-mqtt directly. > > The worst was having to access the hidden Paho client using `client._client` to call `tls_set()` so I could connect to port 8883. `aiomqtt` literally takes existing functionality away from you. The only dependency is [[paho-mqtt]]. #### Basics ```python import asyncio import aiomqtt async def main(): ... asyncio.run( main() ) ## Connect and Publish async with aiomqtt.Client( "test.mosquitto.org" ) as client: await client.publish( "temperature/outside", payload=28.4 ) ## Connect and Subscribe async with aiomqtt.Client( "test.mosquitto.org" ) as client: await client.subscribe( "temperature/#" ) async for message in client.messages: ... # filtering if message.topic.matches( "temperature/foo/#" ): print( message.payload ) ``` > [!WARNING] > Don't create `Client` outside of async code #### Payloads Accepted types: - int, float (converted to str, then bytes) - str (converted to bytes) - bytes, bytesarray When no payload is specified or when it’s set to `None`, a zero-length payload is sent. > [!TIP] > If you want to send a true `int` or `float`, you can use `struct.pack()` to encode it as a `bytes` object. #### Concurrent Message Processing ```python async def work( client ): async for message in client.messages: await asyncio.sleep( 5 ) # simulate some I/O-bound work print( message.payload ) async with asyncio.TaskGroup() as tg: for _ in range( 2 ): tg.create_task( work( client ) ) ``` Coroutines only make sense if your message handling is I/O-bound. If it’s CPU-bound, you should spawn multiple processes instead. #### Listening Without Blocking You can use asyncio.TaskGroup to safely run other tasks alongside the MQTT listener. ```python async with asyncio.TaskGroup() as tg: tg.create_task( listen() ) # message-reading loop tg.create_task( other1() ) tg.create_task( other2() ) ``` #### Stop Listening ```python loop = asyncio.get_event_loop() task = loop.create_task( listen() ) ... task.cancel() ``` #### Reconnection ```python while True: try: async with client: await client.subscribe( "humidity/#" ) async for message in client.messages: print( message.payload ) except aiomqtt.MqttError: print( f"Connection lost; Reconnecting in 5 seconds ..." ) await asyncio.sleep( interval ) ``` #### API ```python client.publish( ..., qos=0 ) client.subscribe( ..., qos=0 ) message.topic -> aiomqq.client.Topic message.payload -> str | bytes | bytearray | int | float | None message.qos -> int message.retain -> bool message.mid -> int message.properties -> paho.mqtt.properties.Properties | None topic.value -> str topic.matches(...) -> bool ``` ##### Paho API ```python SubscribeOptions( qos=0, noLocal=False, retainasPublished=False, retainHandling= ``` ##### aiomqtt API ```python c = Client( hostname, port = 1883, username = None, password = None, logger = None, identifier = None, # MQTT Client ID - autogenerated if None will = None, # Will clean_session = None, clean_start = 3, # True | False | 3 (MQTT v5.0 only) # always, never, or only on first successful connection ) with c: # usable as context manager (connect/disconnect) c.messages # MessagesIterator c.subscribe( # async topic, # str -or- qos = 0, options = None: # SubscribeOptions( qos=0, noLocal=False, retainasPublished=False, retainHandling=) ) str | tuple[ str, paho.mqtt.subscribeoptions.SubscribeOptions ] | list[ tuple[ str, paho.mqtt.subscribeoptions.SubscribeOptions ] ] | list[ tuple[ str, int ] ], qos: int = 0_, options: paho.mqtt.subscribeoptions.SubscribeOptions | None = None_, properties: paho.mqtt.properties.Properties = None, - **options** – (MQTT v5.0 only) Optional paho-mqtt subscription options. - **properties** – (MQTT v5.0 only) Optional paho-mqtt properties. - ***args** – Additional positional arguments to pass to paho-mqtt’s subscribe method. - ****kwargs** – Additional keyword arguments to pass to paho-mqtt’s subscribe method. Message Topic Will ```