Search code examples
pythonmqttpaho

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 doesn't work as it gives me just the variable and not the value of it i.e. doesn't give me the values of "on_message". Can someone please help me?

Thanks

My code is as follows:

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()

I have tried other attempts but have failed. I am fairly new to python and still learning.


Solution

  • 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
    
    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
    

    Now if you publish message on "some/topic" your code shall append data to the file