问题
I have an arduino board that sends periodically the temperature to a txt file. The file is updating every minute(the new data is overwritten not appended).
I want to make a mqtt client that reads the file periodically and publishes the last received data. My client publishes no text.
Is there a way I can do that ?
Here what I have until now:
import mosquitto
import time
client=mosquitto.Mosquitto("read-file")
client.connect("broker.mqttdashboard.com", 1883)
f=open("/home/ioana/date_sensor","rb")
while client.loop()==0:
file=f.read()
client.publish("ioana/test",file)
time.sleep(60)
回答1:
I have little idea of what mqtt needs, but I think you should put the code
f=open("/home/ioana/date_sensor","rb")
and the
time.sleep(60)
inside the while loop, and add a file close too (near end of while loop)...
import mosquitto
import time
client=mosquitto.Mosquitto("read-file")
client.connect("broker.mqttdashboard.com", 1883)
while client.loop() == 0:
f = open("/home/ioana/date_sensor", "rb")
data = f.read()
client.publish("ioana/test", data)
f.close()
time.sleep(60)
I am assuming that you would like to be in the while loop all the time, which publishes the new temperature values every minute or so.
回答2:
If your on Linux (or something similar) then something like this should work:
tail --follow=name file.txt | mosquitto_pub -l -t ioana/test
It does depend on the file
回答3:
As a by-the-by, you should move to using the Eclipse Paho Python client instead of mosquitto.py. It's the same code that has been donated to Paho in a slightly different namespace.
I would do this:
import paho.mqtt as mqtt
import time
client = mqtt.Client("read-file") # no real need to use a fixed client id here, unless you're using it for authentication or have clean_session set to False.
client.connect("broker.mqttdashboard.com", 1883)
client.loop_start() # This runs the network code in a background thread and also handles reconnecting for you.
while True:
f = open("/home/ioana/date_sensor", "rb")
client.publish("ioana/test", f.read())
f.close()
time.sleep(60)
回答4:
I might be a bit late to answering this question, but I stumbled upon this question looking for something else.
For you or those who are trying to solve this kind of situation, I would like to recommend this excellent "MQTT-Watchdir" tool:
https://github.com/jpmens/mqtt-watchdir
"This simple Python program portably watches a directory recursively and publishes the content of newly created and modified files as payload to an MQTT broker."
I've been using it for some time now in all kinds of situations. It's great that you can easily add a filter method as well, so that it only publishes the content of the changed files that you're actually interested in.
来源:https://stackoverflow.com/questions/24023277/mqtt-publish-the-last-line-from-a-file-that-is-periodically-updated