2015-06-27 19:38:04 +00:00
|
|
|
import asyncio
|
2024-12-19 19:34:09 +00:00
|
|
|
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
|
|
|
|
2025-06-17 21:03:40 +00:00
|
|
|
"""
|
|
|
|
This sample shows how to publish messages to broker using different QOS
|
|
|
|
"""
|
2015-07-06 20:19:31 +00:00
|
|
|
|
2015-06-28 20:48:07 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2015-07-21 19:41:46 +00:00
|
|
|
config = {
|
2021-03-14 21:16:51 +00:00
|
|
|
"will": {
|
|
|
|
"topic": "/will/client",
|
|
|
|
"message": b"Dead or alive",
|
|
|
|
"qos": 0x01,
|
|
|
|
"retain": True,
|
2024-12-19 19:34:09 +00:00
|
|
|
},
|
2015-07-21 19:41:46 +00:00
|
|
|
}
|
2015-08-11 20:20:03 +00:00
|
|
|
|
|
|
|
|
2025-06-17 21:03:40 +00:00
|
|
|
async def test_coro1() -> None:
|
|
|
|
client = MQTTClient()
|
|
|
|
await client.connect("mqtt://test.mosquitto.org/")
|
2015-06-28 20:48:07 +00:00
|
|
|
tasks = [
|
2025-06-17 21:03:40 +00:00
|
|
|
asyncio.ensure_future(client.publish("a/b", b"TEST MESSAGE WITH QOS_0")),
|
|
|
|
asyncio.ensure_future(client.publish("a/b", b"TEST MESSAGE WITH QOS_1", qos=QOS_1)),
|
|
|
|
asyncio.ensure_future(client.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)
|
2025-06-17 21:03:40 +00:00
|
|
|
logger.info("test_coro1 messages published")
|
|
|
|
await client.disconnect()
|
2015-06-27 19:38:04 +00:00
|
|
|
|
|
|
|
|
2024-12-19 19:34:09 +00:00
|
|
|
async def test_coro2() -> None:
|
2015-08-12 16:46:56 +00:00
|
|
|
try:
|
2025-06-17 21:03:40 +00:00
|
|
|
client = MQTTClient()
|
|
|
|
await client.connect("mqtt://test.mosquitto.org:1883/")
|
|
|
|
await client.publish("a/b", b"TEST MESSAGE WITH QOS_0", qos=0x00)
|
|
|
|
await client.publish("a/b", b"TEST MESSAGE WITH QOS_1", qos=0x01)
|
|
|
|
await client.publish("a/b", b"TEST MESSAGE WITH QOS_2", qos=0x02)
|
|
|
|
logger.info("test_coro2 messages published")
|
|
|
|
await client.disconnect()
|
2025-05-26 15:27:42 +00:00
|
|
|
except ConnectError:
|
|
|
|
logger.exception(f"Connection failed", exc_info=True)
|
2015-08-11 20:20:03 +00:00
|
|
|
|
|
|
|
|
2025-06-17 21:03:40 +00:00
|
|
|
def __main__():
|
|
|
|
|
|
|
|
formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
|
|
|
|
logging.basicConfig(level=logging.INFO, format=formatter)
|
|
|
|
|
|
|
|
asyncio.run(test_coro1())
|
|
|
|
asyncio.run(test_coro2())
|
|
|
|
|
2021-03-14 21:16:51 +00:00
|
|
|
if __name__ == "__main__":
|
2025-06-17 21:03:40 +00:00
|
|
|
__main__()
|