Mqtt:发布定期更新文件的最后一行

3 投票
4 回答
2665 浏览
提问于 2025-04-18 08:28

我有一个Arduino开发板,它会定期把温度数据发送到一个txt文件里。这个文件每分钟更新一次(新的数据会覆盖旧的数据,而不是在后面添加)。

我想做一个MQTT客户端,它可以定期读取这个文件,并发布最新的数据。可是我的客户端没有发布任何内容。

有没有办法可以做到这一点呢?

这是我目前的代码:

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) 

4 个回答

1

我可能来得有点晚,但我在找其他东西的时候偶然看到了这个问题。

对于你或者那些想解决类似问题的人,我想推荐一个很棒的工具:“MQTT-Watchdir”:

https://github.com/jpmens/mqtt-watchdir

“这个简单的Python程序可以递归地监视一个文件夹,并把新创建和修改的文件内容作为信息发布到MQTT服务器。”

我已经在各种情况下使用它一段时间了。它的一个优点是你可以轻松添加过滤方法,这样它只会发布你真正感兴趣的那些修改过的文件的内容。

2

顺便提一下,你应该使用Eclipse Paho的Python客户端,而不是mosquitto.py。其实这两个是一样的代码,只是被捐赠给Paho后,放在了一个稍微不同的命名空间里。

我会这样做:

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

如果你在使用Linux(或者类似的系统),那么可以试试下面这个命令:

tail --follow=name file.txt | mosquitto_pub -l -t ioana/test

这个命令的效果会根据你使用的文件而有所不同。

1

我对mqtt了解不多,但我觉得你应该把代码放在

f=open("/home/ioana/date_sensor","rb")

time.sleep(60) 

里面的while循环里,并且在while循环快结束的时候加一个文件关闭的操作...

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)

我假设你是想一直在这个while循环里,这样每分钟就能发布一次新的温度值。

撰写回答