amqtt/samples/client_subscribe.py

41 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
2015-07-06 20:20:05 +00:00
#
# This sample shows how to subscbribe a topic and receive data from incoming messages
# It subscribes to '$SYS/broker/uptime' topic and displays the first ten values returned
# by the broker.
#
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:
2015-11-11 21:03:32 +00:00
C = MQTTClient()
await C.connect("mqtt://test.mosquitto.org/")
2015-07-06 20:20:05 +00:00
# Subscribe to '$SYS/broker/uptime' with QOS=1
await C.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, 100):
await C.deliver_message()
await C.unsubscribe(["$SYS/broker/uptime", "$SYS/broker/load/#"])
logger.info("UnSubscribed")
2020-12-31 00:16:45 +00:00
await C.disconnect()
except ClientError:
logger.exception("Client exception")
2015-06-30 20:48:15 +00:00
if __name__ == "__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)
2017-08-06 22:06:57 +00:00
asyncio.get_event_loop().run_until_complete(uptime_coro())