amqtt/samples/client_publish.py

57 wiersze
1.7 KiB
Python
Czysty Zwykły widok Historia

import asyncio
import logging
2015-06-18 17:41:12 +00:00
2025-01-12 19:52:50 +00:00
from amqtt.client import ConnectError, 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:19:31 +00:00
#
# This sample shows how to publish messages to broker using different QOS
# Debug outputs shows the message flows
#
2015-06-28 20:48:07 +00:00
logger = logging.getLogger(__name__)
2015-07-21 19:41:46 +00:00
config = {
"will": {
"topic": "/will/client",
"message": b"Dead or alive",
"qos": 0x01,
"retain": True,
},
2015-07-21 19:41:46 +00:00
}
async def test_coro() -> None:
2015-11-11 21:03:32 +00:00
C = MQTTClient()
await C.connect("mqtt://test.mosquitto.org/")
2015-06-28 20:48:07 +00:00
tasks = [
asyncio.ensure_future(C.publish("a/b", b"TEST MESSAGE WITH QOS_0")),
asyncio.ensure_future(C.publish("a/b", b"TEST MESSAGE WITH QOS_1", qos=QOS_1)),
asyncio.ensure_future(C.publish("a/b", b"TEST MESSAGE WITH QOS_2", qos=QOS_2)),
2015-06-28 20:48:07 +00:00
]
2020-12-31 00:16:45 +00:00
await asyncio.wait(tasks)
2015-06-28 20:48:07 +00:00
logger.info("messages published")
2020-12-31 00:16:45 +00:00
await C.disconnect()
async def test_coro2() -> None:
try:
2015-11-11 21:03:32 +00:00
C = MQTTClient()
await C.connect("mqtt://test.mosquitto.org:1883/")
await C.publish("a/b", b"TEST MESSAGE WITH QOS_0", qos=0x00)
await C.publish("a/b", b"TEST MESSAGE WITH QOS_1", qos=0x01)
await C.publish("a/b", b"TEST MESSAGE WITH QOS_2", qos=0x02)
logger.info("messages published")
2020-12-31 00:16:45 +00:00
await C.disconnect()
except ConnectError:
logger.exception(f"Connection failed", exc_info=True)
asyncio.get_event_loop().stop()
if __name__ == "__main__":
formatter = "[%(asctime)s] %(name)s {%(filename)s:%(lineno)d} %(levelname)s - %(message)s"
2015-11-11 21:03:32 +00:00
formatter = "%(message)s"
logging.basicConfig(level=logging.DEBUG, format=formatter)
2015-11-11 21:03:32 +00:00
asyncio.get_event_loop().run_until_complete(test_coro())
asyncio.get_event_loop().run_until_complete(test_coro2())