import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("/leds/pi")
def on_message(client, userdata, msg):
if msg.topic == '/leds/pi':
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost", 1883, 60)
client.loop_start()
我使用此基本代码订阅主题并接收消息。每当收到消息时都会调用on_message函数。我需要能够访问函数外部的msg.payload并将其存储到变量中。每当收到消息时,都应更新变量中的值。我试图将msg.payload存储到函数内部的Global变量并访问它,但是,这给出了一个错误,说明该变量未定义。请帮忙。
答案 0 :(得分:3)
我需要能够访问函数外的msg.payload和 将其存储到变量中。
您需要一个全局变量,如:
myGlobalMessagePayload = '' #HERE!
def on_message(client, userdata, msg):
global myGlobalMessagePayload
if msg.topic == '/leds/pi':
myGlobalMessagePayload = msg.payload #HERE!
print(msg.topic+" "+str(msg.payload))