此代码建议用于处理每10秒发布一条消息。但如果需要,如何处理重新连接?
import paho.mqtt as mqtt
import time
mqttc=mqtt.Client("ioana")
mqttc.connect("127.0.0.1" 1883, 60, True)
#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
答案 0 :(得分:1)
脚本是重复发送MQTT消息所需要的绝对骨架,但如果断开连接,它将自动重新连接。
您可以让它在断开连接时打印一条消息并重新连接以通过修改它来跟踪它:
import paho.mqtt.client as mqtt
import time
def onDisconnect(client, userdata, rc):
print("disonnected")
def onConnect(client, userdata, rc):
print("connected")
mqttc=mqtt.Client("ioana")
mqttc.on_connect = onConnect
mqttc.on_disconnect = onDisconnect
mqttc.connect("127.0.0.1", port=1883, keepalive=60)
mqttc.loop_start()
while True:
mqttc.publish("test","Hello")
time.sleep(10)# sleep for 10 seconds before next call
编辑: 去测试。如果您使用mosquitto作为您的经纪人,那么您可能会安装mosquitto_pub命令,您可以使用它来强制python通过使用相同的客户端ID断开连接。
mosquitto_pub -t test -i 'ioana' -m foo