Here an asyncio example:
It's a real shame that asyncio isn't that easy to understand. It's a disaster for beginners in particular, as most of them don't know whether it's a function or a coroutine function.
One thing you should never do with asyncio is use blocking functions in asynchronous code. This blocks the entire event loop. So, time.sleep() is forbidden in couroutines.
Code:
import asyncioimport randomimport jsonfrom dataclasses import dataclass, asdictfrom aiomqtt import Client@dataclassclass SensorData: """ Structure of SensorData """ value: float unit: str name: str @property def json(self): return json.dumps(asdict(self))def read_sensor_1() -> SensorData: # this could be your sensor data value = random.uniform(0,10) return SensorData(value=value, unit="m/s", name="Sensor 1")async def reader(client: Client): async for msg in client.messages: print(msg.payload)async def writer(client: Client): while True: await asyncio.sleep(5) # sending sensor data as str (json) # read_sensor_1() returns SensorData # and SensorData has one property called json # which does the conversion from # dataclass > dict > json-str await client.publish("/sensor1", read_sensor_1().json)async def MQTT(): """ Opens a connection to MQTT-Broker @localhost Subscribes /receive Starts two tasks in a TaskGroup one reader, one writer If one of the tasks throws an Exception it bubbles up to the caller """ async with Client("localhost") as client: print("Connected") await client.subscribe("/receive") print("/receive subscribed") async with asyncio.TaskGroup() as tg: tg.create_task(reader(client)) tg.create_task(writer(client))async def main(): while True: try: print("Connecting") await MQTT() # <- this coroutine could throw an exception except *Exception as e: # TaskGroups do have more than one exception for exc in e.exceptions: print(f"Exception: {exc}") finally: await asyncio.sleep(10) print("Trying to reconnect")if __name__ == "__main__": # for windows asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop) # for linux # asyncio.run(main())One thing you should never do with asyncio is use blocking functions in asynchronous code. This blocks the entire event loop. So, time.sleep() is forbidden in couroutines.
Statistics: Posted by DeaD_EyE — Tue Jan 13, 2026 3:11 pm