订阅并使用python阅读mqtt mosquitto上的几个主题paho
问题描述:
我设法发布了几个主题并阅读其中的一个。我需要做的是听取并阅读所有已发布的主题并获取消息。这是我的代码使用方法:订阅并使用python阅读mqtt mosquitto上的几个主题paho
-
发布消息3个主题:
#!/usr/bin/env python3 import paho.mqtt.client as mqtt client = mqtt.Client() client.connect("localhost",1883,60) client.publish("topic/1", "400 | 350 | 320 | 410"); client.publish("topic/2", "200 | 350 | 420 | 110"); client.publish("topic/3", "200 | 350 | 420 | 110"); client.disconnect();
-
1个主题订阅和阅读邮件
#!/usr/bin/env python3 import paho.mqtt.client as mqttClient import time def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to broker") global Connected #Use global variable Connected = True #Signal connection else: print("Connection failed") def on_message(client, userdata, message): print "Message received : " + message.payload Connected = False broker_address= "localhost" port = 1883 client = mqttClient.Client("Python") client.on_connect= on_connect client.on_message= on_message client.connect(broker_address, port=port) client.loop_start() while Connected != True: time.sleep(0.1) client.subscribe("topic/2") try: while True: time.sleep(1) except KeyboardInterrupt: print "exiting" client.disconnect() client.loop_stop()
答
您可以拨打client.subscribe()
功能多次订阅多个主题。
此外,您应该将呼叫移动到订阅on_connect
回调以删除第一个循环的需要。
#!/usr/bin/env python3
import paho.mqtt.client as mqttClient
import time
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to broker")
client.subscribe("topic/1")
client.subscribe("topic/2")
client.subscribe("topic/3")
client.subscribe("topic/4")
else:
print("Connection failed")
def on_message(client, userdata, message):
print("Message received : " + str(message.payload) + " on " + message.topic)
broker_address= "localhost"
port = 1883
client = mqttClient.Client("Python")
client.on_connect= on_connect
client.on_message= on_message
client.connect(broker_address, port=port)
client.loop_start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("exiting")
client.disconnect()
client.loop_stop()
编辑:
您也可以订阅多个主题一次性使用的语法如下
client.subscribe([("topic/1", 0), ("topic/2", 0), ("topic/3", 0),("topic/4", 0)])
还拥有您的发布代码的一个问题,你需要调用客户端。循环函数在每次发布之间确保它们全部被刷新到网络堆栈,或使用单/多发布函数(https://pypi.python.org/pypi/paho-mqtt/1.1#id17) – hardillb