Saving Mqtt Data From Subscribe Topic On A Text File
I am setting up to receive MQTT data from a subscribed topic and I want to save the data in a text file. I have added the code to save the variable to a text file. However this doe
Solution 1:
You should append data to file in on_message call back and obviously should connect then subscribe to topic
import paho.mqtt.client as mqttClient
import time
defon_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to broker")
global Connected #Use global variable
Connected = True#Signal connectionelse:
print("Connection failed")
defon_message(client, userdata, message):
print"Message received: " + message.payload
withopen('/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
Now if you publish message on "some/topic" your code shall append data to the file
Post a Comment for "Saving Mqtt Data From Subscribe Topic On A Text File"