Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paho MQTT client connection reliability (reconnect on disconnection)

Tags:

python

mqtt

paho

What is the most reliable way to use the Python Paho MQTT client? I want to be able to handle connection interruptions due to WiFi drops and keep trying to reconnect until it's successful.

What I have is the following, but are there any best practices I'm not adhering to?

import argparse
from time import sleep

import paho.mqtt.client as mqtt


SUB_TOPICS = ("topic/something", "topic/something_else")
RECONNECT_DELAY_SECS = 2


def on_connect(client, userdata, flags, rc):
    print "Connected with result code %s" % rc
    for topic in SUB_TOPICS:
        client.subscribe(topic)

# EDIT: I've removed this function because the library handles
#       reconnection on its own anyway.
# def on_disconnect(client, userdata, rc):
#     print "Disconnected from MQTT server with code: %s" % rc
#     while rc != 0:
#         sleep(RECONNECT_DELAY_SECS)
#         print "Reconnecting..."
#         rc = client.reconnect()


def on_msg(client, userdata, msg):
    print "%s %s" % (msg.topic, msg.payload)


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("user")
    p.add_argument("password")
    p.add_argument("host")
    p.add_argument("--port", type=int, default=1883)
    args = p.parse_args()

    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_msg
    client.username_pw_set(args.user, args.password)
    client.connect(args.host, args.port, 60)
    client.loop_start()

    try:
        while True:
            sleep(1)
    except KeyboardInterrupt:
        pass
    finally:
        client.loop_stop()
like image 426
Ellis Percival Avatar asked Feb 23 '16 15:02

Ellis Percival


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.

What is callback in MQTT?

The MQTT client calls a callback method on a separate thread to the main application thread. The client application does not create a thread for the callback, it is created by the MQTT client. The MQTT client synchronizes callback methods. Only one instance of the callback method runs at a time.

What is client connection status in MQTT?

The MQTT connection is always between one client and the broker. Clients never connect to each other directly. To initiate a connection, the client sends a CONNECT message to the broker. The broker responds with a CONNACK message and a status code.

Is MQTT one way?

Introduction: Using the MQTT (Message Queuing Telemetry Transport) broker, the user should be able to create an MQTT connection using one-way authentication (only MQTT server authenticates via the certificate).


1 Answers

  1. Set a client_id so it's the same across reconnects
  2. Set the clean_session=false connection option
  3. Subscribe at QOS greater than 0

These options will help ensure that any messages published while disconnected will be delivered once the connection is restored.

You can set the client_id and clean_session flag in the constructor

client = mqtt.Client(client_id="foo123", clean_session=False)

And set the QOS of the subscription after the topic

client.subscribe(topic, qos=1)
like image 147
hardillb Avatar answered Sep 19 '22 17:09

hardillb