首页 > 解决方案 > NameError:未定义名称“消息”

问题描述

我对 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 接收到消息时会显示该消息...我尝试创建空值,但无法正常工作,上面的代码已简化,我已删除所有“如果”,只留下了部分这导致了问题

标签: pythonundefinedmqtt

解决方案


您的问题是缩进,message超出了您的功能。您message作为wiadomosc()函数的参数传递,但在此函数减速之后,external_value1使用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)

推荐阅读