【问题标题】:Saving MQTT data from subscribe topic on a text file将订阅主题中的 MQTT 数据保存在文本文件中
【发布时间】: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

标签: python mqtt paho


【解决方案1】:

您应该在 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
    with open('/home/pi/test.txt','a+') as f:
         f.write("Message received: "  + message.payload + "\n")

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
client.connect(broker_address,port,60) #connect
client.subscribe("some/topic") #subscribe
client.loop_forever() #then keep listening forever

现在,如果您在“某些/主题”上发布消息,您的代码应将数据附加到文件中

【讨论】:

  • 我使用了您的代码并进行了附加,但是我的文本文件中保存了“on_message”,而不是文本文件的值。
  • 我假设您的意思是“文本文件的值”是文件中的消息有效负载?如果是这样,请尝试将 f.write('on_message') 更改为 f.write(message.payload)
  • 这是我编辑的一个简单更改,如果这有助于您接受作为答案
  • @YugandharChaudhari 谢谢你成功了。如果我可以根据 MQTT 主题的新值更新文本文件,是否有可能?例如如果我收到一个值“a”并在 5 分钟后收到一个值“b”,是否可以从文本文件中删除“a”并只显示“b”?
猜你喜欢
  • 1970-01-01
  • 2016-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多