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

时间:2016-02-23 15:01:58

标签: 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()

1 个答案:

答案 0 :(得分:6)

  1. 设置一个client_id,使其在重新连接时保持相同
  2. 设置clean_session = false连接选项
  3. 订阅QOS大于0
  4. 这些选项有助于确保在连接恢复后,将在断开连接时发布任何消息。

    您可以在构造函数

    中设置client_id和clean_session标志
    client = mqtt.Client(client_id="foo123", clean_session=False)
    

    在主题

    之后设置订阅的QOS
    client.subscribe(topic, qos=1)