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
|
|
|
|
2025-06-17 21:03:40 +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
|
|
|
|
2024-12-19 19:34:09 +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")
|
2025-06-17 21:03:40 +00:00
|
|
|
|
|
|
|
await client.subscribe(
|
2021-03-14 21:16:51 +00:00
|
|
|
[
|
|
|
|
("$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:
|
2025-06-17 21:03:40 +00:00
|
|
|
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/#"])
|
2015-10-07 20:42:04 +00:00
|
|
|
logger.info("UnSubscribed")
|
2025-06-17 21:03:40 +00:00
|
|
|
await client.disconnect()
|
2025-05-26 15:27:42 +00:00
|
|
|
except ClientError:
|
|
|
|
logger.exception("Client exception")
|
2015-06-30 20:48:15 +00:00
|
|
|
|
|
|
|
|
2025-06-17 21:03:40 +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)
|
2025-06-17 21:03:40 +00:00
|
|
|
asyncio.run(uptime_coro())
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
__main__()
|