Paho MQTT客户端连接可靠性(断开时重新连接)

Ell*_*val 6 python mqtt paho

使用Python Paho MQTT客户端最可靠的方法是什么?我希望能够处理因WiFi丢失导致的连接中断,并继续尝试重新连接,直到成功为止.

我所拥有的是以下内容,但有没有我不遵守的最佳实践?

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()
Run Code Online (Sandbox Code Playgroud)

har*_*llb 8

  1. 设置一个client_id,使其在重新连接时保持不变
  2. 设置clean_session = false连接选项
  3. 在QOS订阅大于0

这些选项有助于确保在恢复连接后,将在断开连接时发布任何消息.

您可以在构造函数中设置client_id和clean_session标志

client = mqtt.Client(client_id="foo123", clean_session=False)
Run Code Online (Sandbox Code Playgroud)

并在主题后设置订阅的QOS

client.subscribe(topic, qos=1)
Run Code Online (Sandbox Code Playgroud)