2016-05-14 20 views
0

私はpaho-mqttでサンプルプログラムをテストしましたが、loop_forever()関数が再接続を処理できることはわかっています。しかし、私の質問は、loop_forever()は再接続できますが、再購読できないということです。サーバーが突然クラッシュしたときに問題になるはずです。この場合、クライアントは引き続きリスニングしていますが、サーバーを再起動すると、クライアントは再接続できますが、メッセージをそれ以上購読できません。私はおそらくloop_forever()関数を書き直すべきだと思いますが、私が正しいかどうか、そしてそれをどうやって行うのかは分かりません。paho-MQTT python: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() 

答えて

2

これに対処するための簡単な方法は、あなたが再接続したときに、すべてのサブスクリプションも同様に復元され、on_connectコールバックであなたのサブスクライブを行うことです。

+0

本当にありがとうございます! –

0

mqttクライアントのインスタンスを作成する際に、「クリーンセッション」フラグをfalseに設定できます。 mosquittoマニュアルから

mqttc = mqtt.Client(clean_session=False)

引用:

クリーンセッション/接続で耐久性のある接続

、クライアントは時々としても知られている「クリーンセッション」フラグを設定します"クリーンスタート"フラグ。 clean sessionがfalseに設定されている場合、接続は永続的として扱われます。つまり、クライアントが切断されると、そのサブスクリプションが残っていて、それ以降のQoS 1または2のメッセージは、今後再び接続されるまで保存されます。 clean sessionがtrueの場合、切断されるとすべてのサブスクリプションがクライアントに対して削除されます。

関連する問題