Dave
Dave

Reputation: 99

Publish MQTT Message every 10 Seconds...and reconnect if needed

This code that was suggested to handle publishing a message every 10 seconds. But how to handle reconnects if needed?

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

Upvotes: 1

Views: 2876

Answers (1)

hardillb
hardillb

Reputation: 59608

The script is the absolute bare bones of what is needed send a MQTT message repeatedly but it will automatically reconnect if disconnected as it stands.

You can have it print a message when it is disconnected and reconnected to track this by modifying it as follows:

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

EDIT: To test. If you are using mosquitto as your broker then you will probably have the mosquitto_pub command installed, you can use this to force the python to disconnect by using the same client id.

mosquitto_pub -t test -i 'ioana' -m foo

Upvotes: 1

Related Questions