我有一个在MQTT中调整为主题的python脚本,它工作正常吗。
import paho.mqtt.client as mqtt #import the client1
import time
import json
import requests
def on_log(client, userdata, level, buf) :
#print("log: "+buf)
k=0
def on_connect(client, userdata, flags, rc) :
if rc==0:
print("connected ok")
else:
print("not connected", rc)
def on_disconnect(client, userdata, flags, rc=0) :
print("disconnect result code "+str(rc))
def on_message(client,userdata,msg) :
global m_decode
topic=msg.topic
m_decode=str(msg.payload.decode("utf-8","ignore"))
time.sleep(1)
lora_s = str(m_decode)
lora = {"lora_tram":lora_s}
resp = requests.post('http://51.75.120.146/lora_tram_reception.php', data = lora)
broker_address="127.0.0.1:1883"
client = mqtt.Client("paca") #create new instance
client.on_connect=on_connect
client.on_disconnect=on_disconnect
client.on_log=on_log
client.on_message=on_message
print ("cnct to broker", broker_address)
client.connect("127.0.0.1", 1883, 60)
client.subscribe("gateway/a555b555c555d555/rx")
client.loop_forever()
我想同时订阅另一个主题!有可能这样做吗?
我尝试在以下位置添加client.subscribe(“ gateway / new topic / rx”):
client.subscribe("gateway/a555b555c555d555/rx")
它看起来像在工作,但是我不确定是否可以编码多个主题。
答案 0 :(得分:1)
您还可以在一封MQTT订阅消息中订阅多个主题。
client.subscribe([("gateway/a555b555c555d555/rx", 0), ("gateway/new topic/rx", 0)])
https://github.com/eclipse/paho.mqtt.python#subscribe-unsubscribe
答案 1 :(得分:0)
使用不同的主题多次调用订阅非常好,您只需要在on_mescsage
回调中确定消息来自哪个主题即可。
您可以使用if语句来检查msg.topic
的值,然后相应地处理该消息。
您可能还应该将对subscribe
的调用移至on_connect
回调