amqtt/samples/client_subscribe_acl.py

49 wiersze
1.6 KiB
Python

2018-03-19 09:58:56 +00:00
import asyncio
import logging
2018-03-19 09:58:56 +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
2018-03-19 09:58:56 +00:00
"""
Run `samples/broker_acl.py` or `samples/broker_taboo.py`
This sample shows how to subscribe to different topics, some of which are allowed.
"""
2018-03-19 09:58:56 +00:00
logger = logging.getLogger(__name__)
async def uptime_coro() -> None:
client = MQTTClient()
await client.connect("mqtt://test:test@0.0.0.0:1883")
result = await client.subscribe(
[
("$SYS/#", QOS_1), # Topic forbidden when running `broker_acl.py`
("data/memes", QOS_1), # Topic allowed
("data/classified", QOS_1), # Topic forbidden
2021-03-27 12:59:48 +00:00
("repositories/amqtt/master", QOS_1), # Topic allowed
("repositories/amqtt/devel", QOS_1), # Topic forbidden when running `broker_acl.py`
2021-03-27 12:59:48 +00:00
("calendar/amqtt/releases", QOS_1), # Topic allowed
],
)
logger.info(f"Subscribed results: {result}")
2018-03-19 09:58:56 +00:00
try:
for _i in range(1, 100):
if msg := await client.deliver_message():
logger.info(f"{msg.topic} >> {msg.data.decode()}")
await client.unsubscribe(["$SYS/#", "data/memes"])
2018-03-19 09:58:56 +00:00
logger.info("UnSubscribed")
await client.disconnect()
2025-01-12 19:52:50 +00:00
except ClientError as ce:
logger.exception("Client exception")
2018-03-19 09:58:56 +00:00
def __main__():
2018-03-19 09:58:56 +00:00
formatter = "[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s"
logging.basicConfig(level=logging.INFO, format=formatter)
asyncio.get_event_loop().run_until_complete(uptime_coro())
if __name__ == "__main__":
__main__()