amqtt/samples/client_subscribe.py

42 wiersze
1.3 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__)
C = MQTTClient()
2015-11-01 14:58:20 +00:00
@asyncio.coroutine
def uptime_coro():
yield from C.connect('mqtt://localhost/')
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([
2015-09-01 20:42:23 +00:00
('$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
print("%d %s : %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
2015-11-01 14:58:20 +00:00
yield from C.unsubscribe(['$SYS/broker/uptime'])
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"
logging.basicConfig(level=logging.DEBUG, format=formatter)
2015-07-21 19:41:46 +00:00
asyncio.get_event_loop().run_until_complete(uptime_coro())