python - 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 接收到消息时会显示该消息...我尝试创建空值,但无法正常工作,上面的代码已简化,我已删除所有“如果”,只留下了部分这导致了问题
解决方案
您的问题是缩进,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)
推荐阅读
- reactjs - React 无法识别引导模式错误“未定义导航栏”
- python - Azure Databricks Jupyter Notebook Python 和 R 在一个单元格中
- javascript - reduxjs - 在规范化状态形状中跟踪冗余数据
- php - 价格 + PHP 价格的 20%
- javascript - Passport authenticate 卡住了,不返回任何值
- tsql - 合并连接无法在 varchar 列上正确连接
- scala - 在 Apache Flink 中将自定义类写入 HDFS
- r - 尽管我在说明中使用了导入,但命名空间依赖项不需要错误
- javascript - 使用 Tizen 正确编辑 Web GUI
- code-signing - 警告:无法为签名者“开发者 ID 应用程序:xxxxxx:errSecInternalComponent”构建自签名根的链