2018-03-19 09:58:56 +00:00
|
|
|
import asyncio
|
2024-12-19 19:34:09 +00:00
|
|
|
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
|
|
|
|
2025-06-17 21:03:40 +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__)
|
|
|
|
|
|
|
|
|
2024-12-19 19:34:09 +00:00
|
|
|
async def uptime_coro() -> None:
|
2025-06-17 21:03:40 +00:00
|
|
|
client = MQTTClient()
|
|
|
|
await client.connect("mqtt://test:test@0.0.0.0:1883")
|
|
|
|
|
|
|
|
result = await client.subscribe(
|
2021-03-14 21:16:51 +00:00
|
|
|
[
|
2025-06-17 21:03:40 +00:00
|
|
|
("$SYS/#", QOS_1), # Topic forbidden when running `broker_acl.py`
|
2021-03-14 21:16:51 +00:00
|
|
|
("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
|
2025-06-17 21:03:40 +00:00
|
|
|
("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
|
2024-12-19 19:34:09 +00:00
|
|
|
],
|
2021-03-14 21:16:51 +00:00
|
|
|
)
|
2025-06-17 21:03:40 +00:00
|
|
|
logger.info(f"Subscribed results: {result}")
|
2018-03-19 09:58:56 +00:00
|
|
|
try:
|
2024-12-19 19:34:09 +00:00
|
|
|
for _i in range(1, 100):
|
2025-06-17 21:03:40 +00:00
|
|
|
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")
|
2025-06-17 21:03:40 +00:00
|
|
|
await client.disconnect()
|
2025-01-12 19:52:50 +00:00
|
|
|
except ClientError as ce:
|
2025-05-26 15:27:42 +00:00
|
|
|
logger.exception("Client exception")
|
2018-03-19 09:58:56 +00:00
|
|
|
|
|
|
|
|
2025-06-17 21:03:40 +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())
|
2025-06-17 21:03:40 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
__main__()
|