簡體   English   中英

paho-MQTT python:如何讓loop_forever支持訂閱消息?

[英]paho-MQTT python: How to let the loop_forever support subscribe message?

我已經在paho-mqtt上測試了示例程序,並且我知道loop_forever()函數可以處理重新連接。 但是我的問題是,盡管loop_forever()可以重新連接,但無法重新訂閱。 當服務器突然崩潰時,應該是一個問題,在這種情況下,客戶端仍在偵聽,但是當服務器重新啟動時,客戶端可以重新連接,但不能再訂閱消息。 我想也許我應該重新編寫loop_forever()函數,但是我不確定自己是否正確以及如何做到這一點。

import sys
try:
    import paho.mqtt.client as mqtt
except ImportError:
    # This part is only required to run the example from within the examples
    # directory when the module itself is not installed.
    #
    # If you have the module installed, just use "import paho.mqtt.client"
    import os
    import inspect
    cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../src")))
    if cmd_subfolder not in sys.path:
        sys.path.insert(0, cmd_subfolder)
    import paho.mqtt.client as mqtt

def on_connect(mqttc, obj, flags, rc):
    print("rc: "+str(rc))

def on_message(mqttc, obj, msg):
    print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

def on_publish(mqttc, obj, mid):
    print("mid: "+str(mid))

def on_subscribe(mqttc, obj, mid, granted_qos):
    print("Subscribed: "+str(mid)+" "+str(granted_qos))

def on_log(mqttc, obj, level, string):
    print(string)

# If you want to use a specific client id, use
# mqttc = mqtt.Client("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
#mqttc.on_log = on_log
mqttc.connect("m2m.eclipse.org", 1883, 60)
mqttc.subscribe("$SYS/#", 0)


mqttc.loop_forever()

解決此問題的簡單方法是在on_connect回調中進行訂閱,然后在重新連接時,所有訂閱也會恢復。

在實例化mqtt客戶端時,可以將“ clean session”標志設置為false。

mqttc = mqtt.Client(clean_session=False)

mosquitto手冊中的引文:

干凈的會話/持久的連接

在連接時,客戶端設置“干凈會話”標志,有時也稱為“干凈啟動”標志。 如果將干凈會話設置為false,則將連接視為持久連接。 這意味着,當客戶端斷開連接時,它將保留其具有的所有訂閱,並且將存儲任何后續的QoS 1或2消息,直到將來再次連接為止。 如果clean session為true,則當客戶端斷開連接時,將刪除該客戶端的所有訂閱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM