0
votes

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.

2
That looks like basic subscriber code, but I can't see where you've tried to save output to the file. Please try editing the on_message function to include what you've tried and if you can't get it to work update the question with that code and a description of how it doesn't work and we'll help you fix it.hardillb
sorry I haven't added any code to save output to the file as I am a complete noob. This is indeed a subscriber code.Ahmed.B
OK, now we are into basic python to do with variable scope and functions. I've edited the tags so somebody from the python community can helphardillb
I was almost about to publish complete answer, but then I saw why your code doesnt work. @Ahmed, why dont you try change: f.write('on_message') to f.write('this is just string'). After that try f.write(password) and f.write('password'). After that, you will know what to doMartin
@Martin I get NameError: name 'password' is not defined like I mentioned the values are not written to the text file rather just the words in the quotation i.e. 'xxxx' will yield xxxx in the text file and not the values of xxxxAhmed.B

2 Answers

1
votes

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

-1
votes

why do i get "b , \nb and \n\ randomly in my text file?