Skip to content

Commit f5fd485

Browse files
committed
examples: mqtt: add pub sub
1 parent d111eaa commit f5fd485

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

examples/mqtt/pub_sub.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import asyncio
2+
import time
3+
4+
import enapter
5+
6+
7+
async def subscriber(client: enapter.mqtt.Client) -> None:
8+
async with client.subscribe("/+") as messages:
9+
async for msg in messages:
10+
print(msg.topic, msg.payload.decode())
11+
12+
13+
async def publisher(client: enapter.mqtt.Client) -> None:
14+
while True:
15+
await client.publish(topic="/time", payload=str(time.time()))
16+
await asyncio.sleep(1)
17+
18+
19+
async def main() -> None:
20+
config = enapter.mqtt.Config(host="127.0.0.1", port=1883)
21+
async with enapter.mqtt.Client(config=config) as client:
22+
async with asyncio.TaskGroup() as tg:
23+
tg.create_task(subscriber(client))
24+
tg.create_task(publisher(client))
25+
26+
27+
if __name__ == "__main__":
28+
asyncio.run(main())

0 commit comments

Comments
 (0)