2016-02-23 191 views
3

什麼是使用Python Paho MQTT客戶端的最可靠方法?我希望能夠處理由於WiFi丟失而導致的連接中斷,並且一直試圖重新連接,直到成功爲止。Paho MQTT客戶端連接可靠性(斷開時重新連接)

我擁有的是以下內容,但有沒有我不遵守的最佳做法?

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() 
+0

喜後設置訂閱的QOS,我想實現這個上一個Django服務器。我面臨的問題是服務器上的MQTT客戶端在引發任何異常後停止響應。你能幫我解決這個問題嗎! –

回答

3
  1. 設置一個CLIENT_ID所以它是相同的跨越墜崖
  2. 設置clean_session =假連接選項
  3. 訂閱的QOS大於0

這些選項將有助於確保任何斷開連接後發佈的消息將在連接恢復後發送。

您可以設置CLIENT_ID和clean_session標誌在構造函數中

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

而且話題

client.subscribe(topic, qos=1) 
相關問題