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.
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. – hardillbNameError: 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