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()
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.
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.
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.
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With