Paho MQTT客户端连接可靠性(断开连接时重新连接) [英] Paho MQTT client connection reliability (reconnect on disconnection)
问题描述
使用Python Paho MQTT客户端最可靠的方法是什么?我希望能够处理由于WiFi掉线而导致的连接中断,并继续尝试重新连接,直到连接成功为止.
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()
推荐答案
- 设置一个client_id,以便在重新连接时相同
- 设置clean_session = false连接选项
- 以大于0的QOS订阅
这些选项将有助于确保在恢复连接后将释放断开连接时发布的所有消息.
These options will help ensure that any messages published while disconnected will be delivered once the connection is restored.
您可以在构造函数中设置client_id和clean_session标志
You can set the client_id and clean_session flag in the constructor
client = mqtt.Client(client_id="foo123", clean_session=False)
并在主题之后设置订阅的QOS
And set the QOS of the subscription after the topic
client.subscribe(topic, qos=1)
这篇关于Paho MQTT客户端连接可靠性(断开连接时重新连接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!