NameError:名称“消息”未定义

时间:2018-11-29 08:17:34

标签: python undefined mqtt

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

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”,并且仅离开了引起问题的部分

2 个答案:

答案 0 :(得分:0)

您的问题是缩进,message无法使用。您正在传递message作为wiadomosc()函数的参数,但是在此函数减速之后,立即使用external_value1初始化message.payload,而之前未定义。{p >

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)

答案 1 :(得分:0)

您绝对正确-谢谢!您发布的答案是正确的,它使我了解了Python的基础知识