0

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.

hardillb
  • 54,545
  • 11
  • 67
  • 105
Ahmed.B
  • 89
  • 1
  • 2
  • 10
  • 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 Jan 21 '19 at 14:46
  • 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 Jan 21 '19 at 14:51
  • 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 help – hardillb Jan 21 '19 at 19:28
  • 1
    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 do – Martin Jan 21 '19 at 21:12
  • @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 xxxx – Ahmed.B Jan 22 '19 at 10:26
  • @Ahmed.B it means, the variable password doesnt have any value at all. You need to assign some password to it. like: password = '1234' . then if you do write(password), the file will contain 1234. I recommend to comment (delete) the line:client.username_pw_set(user, password=password) as you dont need it for now. MQTT can run without it – Martin Jan 22 '19 at 11:29

1 Answers1

3

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

Yugandhar Chaudhari
  • 3,831
  • 3
  • 24
  • 40
  • I used your code and did the append however I get "on_message" saved in my text file and not the value of the text file. – Ahmed.B Jan 22 '19 at 22:47
  • 2
    I assume that you mean 'the value of the text file' to be the message payload in the file? If so then try changing the `f.write('on_message')` to `f.write(message.payload)` – Ben T Jan 23 '19 at 01:48
  • that is a simple change I edited if that helped you can accept as answer – Yugandhar Chaudhari Jan 23 '19 at 03:50
  • @YugandharChaudhari thank you it worked. Is it possible If I could update the text file according to new values from the MQTT topic? e.g. if I received a value "a" and after 5mins I received a value "b" is it possible to remove "a" from the text file and just show "b" ? – Ahmed.B Jan 24 '19 at 16:11