gpt4 book ai didi

python-3.x - 在 python 脚本中订阅两个主题 MQTT

转载 作者:行者123 更新时间:2023-12-04 02:52:04 24 4
gpt4 key购买 nike

我有一个针对 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")

它看起来很有效,但我不确定我们是否喜欢编写多个主题。

最佳答案

您也可以在一条 MQTT 订阅消息中订阅多个主题。

client.subscribe([("gateway/a555b555c555d555/rx", 0), ("gateway/new topic/rx", 0)])

https://github.com/eclipse/paho.mqtt.python#subscribe-unsubscribe

关于python-3.x - 在 python 脚本中订阅两个主题 MQTT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54635786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com