每隔10秒发布一条消息mqtt

时间:2014-05-28 10:37:18

标签: python mqtt

我是mqtt的新手,仍然发现这个有趣的协议。 我想在python中创建一个客户端,每隔10秒发布一条消息。到目前为止,我成功只发布了一条消息并保持客户端与代理连接。

如何使发布部分成为循环?

以下是我的客户:

import mosquitto
mqttc=mosquitto.Mosquitto("ioana")
mqttc.connect("127.0.0.1",1884,60,True)
mqttc.publish("test","Hello")
mqttc.subscribe("test/", 2)

while mqttc.loop() == 0:
pass

感谢。

2 个答案:

答案 0 :(得分:3)

我建议:

import paho.mqtt.client as mqtt # mosquitto.py is deprecated
import time

mqttc = mqtt.Client("ioana")
mqttc.connect("127.0.0.1", 1883, 60)
#mqttc.subscribe("test/", 2) # <- pointless unless you include a subscribe callback
mqttc.loop_start()
while True:
    mqttc.publish("test","Hello")
    time.sleep(10)# sleep for 10 seconds before next call

答案 1 :(得分:1)

你可以在两次通话之间睡觉:

import mosquitto
import time # import time module
mqttc=mosquitto.Mosquitto("ioana")
mqttc.connect("127.0.0.1",8000,60,True)
mqttc.subscribe("test/", 2)
while mqttc.loop() == 0:
    mqttc.publish("test","Hello")
    time.sleep(10)# sleep for 10 seconds before next call