【发布时间】:2019-01-21 14:35:10
【问题描述】:
我正在设置接收来自订阅主题的 MQTT 数据,并且我想将数据保存在文本文件中。
我添加了将变量保存到文本文件的代码。但是这不起作用,因为它只给了我变量而不是它的值,即没有给我“on_message”的值。有人可以帮帮我吗?
谢谢
我的代码如下:
import paho.mqtt.client as mqttClient
import time
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to broker")
global Connected #Use global variable
Connected = True #Signal connection
else:
print("Connection failed")
def on_message(client, userdata, message):
print "Message received: " + message.payload
Connected = False #global variable for the state of the connection
broker_address= "192.168.0.6" #Broker address
port = 1883 #Broker port
user = "me" #Connection username
password = "abcdef" #Connection password
client = mqttClient.Client("Python") #create new instance
client.username_pw_set(user, password=password) #set username and password
client.on_connect= on_connect #attach function to callback
client.on_message= on_message #attach function to callback
f = open('/home/pi/test.txt','w')
f.write('on_message')
f.close()
client.connect(broker_address, port=port) #connect to broker
client.loop_start() #start the loop
while Connected != True: #Wait for connection
time.sleep(0.1)
client.subscribe("home/OpenMQTTGateway/433toMQTT")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print "exiting"
client.disconnect()
client.loop_stop()
我尝试了其他尝试,但都失败了。我对 python 还很陌生,还在学习。
【问题讨论】:
-
这看起来像是基本的订阅者代码,但我看不到您尝试将输出保存到文件的位置。请尝试编辑
on_message函数以包含您尝试过的内容,如果您无法使其正常工作,请使用该代码更新问题并说明它如何不起作用,我们将帮助您修复它。 -
对不起,我没有添加任何代码来将输出保存到文件中,因为我是一个完整的菜鸟。这确实是一个订阅者代码。
-
好的,现在我们进入基本的python来处理变量范围和函数。我已经编辑了标签,以便 python 社区的人可以提供帮助
-
我几乎要发布完整的答案,但后来我明白了为什么你的代码不起作用。 @Ahmed,你为什么不尝试改变:f.write('on_message') 到 f.write('this is just string')。之后尝试 f.write(password) 和 f.write('password')。之后你就知道该怎么做了
-
@Martin 我得到
NameError: name 'password' is not defined就像我提到的值不会写入文本文件,而只是引用中的单词,即'xxxx'将在文本文件中产生xxxx,而不是xxxx