名称错误:未定义名称“消息”

2024-10-16 20:45:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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

我收到了

^{pr2}$

我知道消息将在从mqtt接收时显示。。。我试图创建空值,但没有正常工作,上面的代码被简化,我已经删除了所有的“如果”,只留下了引起问题的部分


Tags: thetoimportclientloop信息messagehome
1条回答
网友
1楼 · 发布于 2024-10-16 20:45:10

你的问题是缩进,message超出了你的功能。您将message作为wiadomosc()函数的一个参数传递,但是在该函数减速之后,使用之前未定义的message.payload初始化{}。在

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)

相关问题 更多 >