2015-06-30 20:48:15 +00:00
|
|
|
import asyncio
|
2024-12-19 19:34:09 +00:00
|
|
|
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
|
|
|
|
2024-12-19 19:34:09 +00:00
|
|
|
async def uptime_coro() -> None:
|
2015-11-11 21:03:32 +00:00
|
|
|
C = MQTTClient()
|
2021-03-14 21:16:51 +00:00
|
|
|
await C.connect("mqtt://test.mosquitto.org/")
|
2015-07-06 20:20:05 +00:00
|
|
|
# Subscribe to '$SYS/broker/uptime' with QOS=1
|
2021-03-14 21:16:51 +00:00
|
|
|
await C.subscribe(
|
|
|
|
[
|
|
|
|
("$SYS/broker/uptime", QOS_1),
|
|
|
|
("$SYS/broker/load/#", QOS_2),
|
2024-12-19 19:34:09 +00:00
|
|
|
],
|
2021-03-14 21:16:51 +00:00
|
|
|
)
|
2015-06-30 20:48:15 +00:00
|
|
|
logger.info("Subscribed")
|
2015-10-07 20:42:04 +00:00
|
|
|
try:
|
2024-12-19 19:34:09 +00:00
|
|
|
for _i in range(1, 100):
|
|
|
|
await C.deliver_message()
|
2021-03-14 21:16:51 +00:00
|
|
|
await C.unsubscribe(["$SYS/broker/uptime", "$SYS/broker/load/#"])
|
2015-10-07 20:42:04 +00:00
|
|
|
logger.info("UnSubscribed")
|
2020-12-31 00:16:45 +00:00
|
|
|
await C.disconnect()
|
2025-05-26 15:27:42 +00:00
|
|
|
except ClientError:
|
|
|
|
logger.exception("Client exception")
|
2015-06-30 20:48:15 +00:00
|
|
|
|
|
|
|
|
2021-03-14 21:16:51 +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())
|