【发布时间】:2021-08-27 08:54:58
【问题描述】:
def on_message(client, userdata, message):
global msg
#print("message received " ,str(message.payload.decode("utf-8")))
#print("message topic=",message.topic)
#print("message qos=",message.qos)
#print("message retain flag=",message.retain)
msg = str(message.payload)
broker_address="10.87.7.27"
print("creating new instance")
client = mqtt.Client("P1") #create new instance
client.on_message= on_message #attach function to callback
print("connecting to broker")
client.connect(broker_address,1883) #connect to broker
client.loop_start() #start the loop
print("Subscribing to topic","home/kitchen/output/lights/set")
client.subscribe("Sekurit_KTBlower_Optimizer_write")
time.sleep(10)
print(msg)
dict_str = msg.decode("UTF-8")
#jsonload = json.loads(dict_str)
mydata = ast.literal_eval(dict_str)
Lowerpredict = mydata["Lowerpredict"]
Upperpredict = mydata["Upperpredict"]
print(Lowerpredict,UpperPredict)
client.loop_stop() #stop the loop
我收到一个错误,因为“NameError: name 'msg' is not defined” 直到 time.sleep 代码运行之后,我在 dict_str 中收到此错误。如果我在函数之外声明 msg 并且 msg = None 我没有得到 mydata['lowerpredict'] 和 mydata['Upperpredict']...代码精确错误在 dict_str 中。 有人有解决办法吗?
【问题讨论】:
-
正如它所说的 -
msg未在全局范围内定义。它只在函数范围内定义。 -
A minimal reproducible example 会有所帮助...您的代码错过了导入语句(可能还有更多?)
-
请在函数之前全局声明 mes
标签: python raspberry-pi mqtt publish-subscribe