我有一个示例代码,用于从 Mqtt经纪人
获取消息import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("123")
def on_message(client, userdata, msg):
x = int(msg.payload)*10
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.connect("broker.hivemq.com", 1883)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
如何在msg.payload
中获取on_message
的变量?
我在x
的函数中添加on_connect
变量:
def on_message(client, userdata, msg):
x = int(msg.payload)*10
print(msg.topic+" "+str(msg.payload))
return x
问题:如何获取变量x
?
答案 0 :(得分:0)
我解决这个问题的方法如下:
import paho.mqtt.client as mqtt
msg_arrived_flag = False
global_X = 0
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("123")
def on_message(client, userdata, msg):
global_X = int(msg.payload)*10
print(msg.topic+" "+str(msg.payload))
msg_arrived_flag = True
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.hivemq.com", 1883)
while True:
client.loop_start()
time.sleep(5)
client.loop_stop()
if msg_arrived_flag:
msg_arrived_flag = False
#Use global_X here
可以将开始和停止之间的睡眠时间设置为方便。另外我建议在连接之前设置回调。希望这有帮助!