amqtt/samples/client_subscribe.py

43 wiersze
1.4 KiB
Python
Czysty Zwykły widok Historia

2015-06-30 20:48:15 +00:00
import logging
import asyncio
from hbmqtt.client import MQTTClient, ClientException
2015-09-01 20:42:23 +00:00
from hbmqtt.mqtt.constants import QOS_1, QOS_2
2015-07-07 19:55:17 +00:00
2015-07-06 20:20:05 +00:00
#
# This sample shows how to subscbribe a topic and receive data from incoming messages
# It subscribes to '$SYS/broker/uptime' topic and displays the first ten values returned
# by the broker.
#
2015-06-30 20:48:15 +00:00
logger = logging.getLogger(__name__)
2017-08-06 22:06:57 +00:00
2015-11-01 14:58:20 +00:00
@asyncio.coroutine
def uptime_coro():
2015-11-11 21:03:32 +00:00
C = MQTTClient()
yield from C.connect('mqtt://test.mosquitto.org/')
2015-07-06 20:20:05 +00:00
# Subscribe to '$SYS/broker/uptime' with QOS=1
2015-11-01 14:58:20 +00:00
yield from C.subscribe([
('$SYS/broker/uptime', QOS_1),
('$SYS/broker/load/#', QOS_2),
])
2015-06-30 20:48:15 +00:00
logger.info("Subscribed")
try:
for i in range(1, 100):
2015-11-01 14:58:20 +00:00
message = yield from C.deliver_message()
2015-11-01 13:23:00 +00:00
packet = message.publish_packet
2015-11-11 21:03:32 +00:00
print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
logger.info("UnSubscribed")
2015-11-01 14:58:20 +00:00
yield from C.disconnect()
except ClientException as ce:
logger.error("Client exception: %s" % ce)
2015-06-30 20:48:15 +00:00
if __name__ == '__main__':
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)
2017-08-06 22:06:57 +00:00
asyncio.get_event_loop().run_until_complete(uptime_coro())