NameError: name 'message' is not defined

NameError: name 'message' is not defined

我对python没有任何经验...但我需要将它用于 (raspberry+mqtt+wiringpi)+home_assistance 集成,我想创建简单的操作,mqtt 客户端正在监听,并且在适当的主题上接收到适当的信息时,他将更改 wiringpi 设置...部分起作用...当我尝试创建对信息的依赖时出现问题。

import paho.mqtt.client as mqtt #import the client1
import wiringpi
import time

wiringpi.wiringPiSetup()

############
def wiadomosc(client, userdata, message):
    global external_value1, added_value2
    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)
external_value1 = str(message.payload.decode("utf-8"))
wiringpi.pinMode(29, 0)
########################################
broker_address="192.168.0.211"
print("creating new instance")
client = mqtt.Client("P1") #create new instance
client.on_message=wiadomosc #attach function to callback
print("connecting to broker")
client.connect(broker_address) #connect to broker
client.loop_start() #start the loop
print("Subscribing to topic","home/kitchen/output/lights/set")
client.subscribe("home/kitchen/output/lights/set")
time.sleep(40000) # wait
client.loop_stop() #stop the loop

我正在收到

NameError: name 'message' is not defined

我知道从 mqtt 收到消息时会显示...我尝试创建空值,但它没有正常工作,上面的代码已简化,我已删除所有 "if", 只留下引起问题的部分

你的问题是缩进,message不在你的功能范围内。您将 message 作为 wiadomosc() 函数的参数传递,但在该函数减速之后,使用之前未定义的 message.payload 初始化 external_value1

def wiadomosc(client, userdata, message):
    global external_value1, added_value2
    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)
    external_value1 = str(message.payload.decode("utf-8"))
wiringpi.pinMode(29, 0)