Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MQTT Paho Python reliable reconnect

Tags:

python

mqtt

I'm trying to get my MQTT Paho Python script to stay connected (and reconnect when it gets disconnected). Sadly, I'm not sure how to go about this.

That said, the machine is connected through WiFi so in the case the signal falls out or the USB dongle is janked out I don't want the code to bork out on me, so I'm trying to cover all exceptions/errors.

Here's the a chunk of the code I'm trying to work with:

mqttc = mqtt.Client(machine_id, clean_session=False)
mqttc.username_pw_set(machine_id, mqtt_pwd)
mqttc.connect(mqtt_host, mqtt_port)
mqttc.subscribe(machine_id, qos=1)

def on_disconnect(client, userdata, rc):
        if rc != 0:
                print "Unexpected MQTT disconnection. Attempting to reconnect."
                try:
                        mqttc.reconnect()
                except socket.error:
                            ??????
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.on_disconnect = on_disconnect
mqttc.loop_forever()

I wasn't able to get much further because I don't know how I can get it to connect again? Unless it's able to reconnect the first time, i can't seem to get a proper reconnecting loop going.

Any advise would be really helpful!

Thanks!

like image 342
user5740843 Avatar asked Apr 05 '16 14:04

user5740843


People also ask

What is connection timeout MQTT?

public void setConnectionTimeout(int connectionTimeout) Sets the connection timeout value. This value, measured in seconds, defines the maximum time interval the client will wait for the network connection to the MQTT server to be established. The default timeout is 30 seconds.


1 Answers

Reading the source(1), the loop_forver() method, calls loop() method in an infinite blocking loop. It is the loop() method which ensures that pub/sub messages and mqtt keepalive traffic is maintained with broker. loop_forver() also does automatic re-connections, if connection is broken.

Also note that loop_forever() blocks until client explicitly calls disconnect(). So it will be useful if you only want to run MQTT client in your program. I prefer loop_start()/loop_stop() methods.

mqttc = mqtt.Client(machine_id, clean_session=False)
mqttc.username_pw_set(mqtt_user, mqtt_pwd)
mqttc.connect(mqtt_host, mqtt_port)
mqttc.subscribe(mqtt_topic, qos=1)

def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected MQTT disconnection. Will auto-reconnect")

mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.on_disconnect = on_disconnect
mqttc.loop_forever()

Not sure why you used machine_id in username_pw_set() and subscribe() calls. Changed them.

like image 187
kiranpradeep Avatar answered Sep 29 '22 09:09

kiranpradeep