amqtt/samples/client_subscribe.py

44 wiersze
1.2 KiB
Python
Czysty Zwykły widok Historia

2015-06-30 20:48:15 +00:00
import asyncio
import logging
2015-06-30 20:48:15 +00:00
2025-01-12 19:52:50 +00:00
from amqtt.client import ClientError, MQTTClient
2021-03-27 12:59:48 +00:00
from amqtt.mqtt.constants import QOS_1, QOS_2
2015-07-07 19:55:17 +00:00
"""
This sample shows how to subscribe to different $SYS topics and how to receive incoming messages
"""
2015-07-06 20:20:05 +00:00
2015-06-30 20:48:15 +00:00
logger = logging.getLogger(__name__)
2017-08-06 22:06:57 +00:00
async def uptime_coro() -> None:
2025-07-02 17:49:16 +00:00
client = MQTTClient(config={'auto_reconnect': False})
await client.connect("mqtt://localhost:1883")
await client.subscribe(
[
("$SYS/broker/uptime", QOS_1),
("$SYS/broker/load/#", QOS_2),
],
)
2015-06-30 20:48:15 +00:00
logger.info("Subscribed")
try:
for _i in range(1, 10):
if msg := await client.deliver_message():
logger.info(f"{msg.topic} >> {msg.data.decode()}")
await client.unsubscribe(["$SYS/broker/uptime", "$SYS/broker/load/#"])
logger.info("UnSubscribed")
await client.disconnect()
except ClientError:
logger.exception("Client exception")
2015-06-30 20:48:15 +00:00
def __main__():
2015-06-30 20:48:15 +00:00
formatter = "[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s"
2015-11-11 21:03:32 +00:00
logging.basicConfig(level=logging.INFO, format=formatter)
asyncio.run(uptime_coro())
if __name__ == "__main__":
__main__()