Aws-iot-device-sdk-python-v2: 永続セッション= TrueのAWSIOT MQTTですが、サブスクリプションが失敗しました

作成日 2020年05月31日  ·  4コメント  ·  ソース: aws/aws-iot-device-sdk-python-v2

親愛なるみんな、

永続セッションを使用してAWSIOT MQTTを実験しているときに、ブローカーが「clean_session = False」の接続リクエストに応答して「session_present = True」を返すことがわかりました。
AWSドキュメントで指定されているように60分以内に再接続したのでこれは予想されます(実際には5分未満でした)

問題 :
理論によれば、「session_present = True」の場合、ブローカーは前のセッションの情報を保存するため、トピックを再度サブスクライブする必要はありません。
しかし、トピックをサブスクライブするステップをスキップすると、メッセージは受信されません。
それは明らかな振る舞いですか? 'session_present = True'であっても、購読を解除する必要がありますか?

私はaws-iot-device-sdk-python-v2を使用しています

def conenct_mqtt(mqtt_connection):
    connect_future = mqtt_connection.connect()

    excep_count = 0
    while True:
        print(f"[{datetime.now()}]Connecting......")
        try:
            # Future.result() waits until a result is available
            result = connect_future.result(timeout=30)
            print(f"Connected! session persistent = {result['session_present']}")
            return result['session_present']

        except Exception as exc:
            print(f"[{datetime.now()}]Error while connecting {exc}")
            time.sleep(10)
            excep_count=excep_count+1
            if excep_count > 5 :
                print(f"[{datetime.now()}]Exiting Script.....")
                quit()
bug guidance needs-triage

最も参考になるコメント

こんにちは@GauravPatni

してみてください:

   if not is_session_persistent:
        XXX
   else:
        mqtt_connection.on_message(on_message_received) #register your callback
        print("-----------Session is Persistent---------")

接続は接続されていますが、メッセージを受信するには、 on_messageを介して_Connection_オブジェクトにコールバックを登録する必要があります。

全てのコメント4件

やあ、
お問い合わせいただきありがとうございます。 私はそれをテストしました、そして、永続的なセッションは私のために働きます。
pubsub.pyサンプルでは、​​接続が失われて戻ってきた場合、mqtt_connecitonは引き続きメッセージを受信します。 ただし、メッセージを受信するには、_Connection_オブジェクトにコールバックを登録する必要があります。
たとえば、あなたが別の_Connection_オブジェクトを作成する場合は、接続結果として「session_present =真」で、あなたが呼び出す必要がありますON_MESSAGEをコールバックを設定します。 次に、設定したコールバックを介して着信メッセージを受信できます。
ありがとうございました!

こんにちは@TingDaoK
ご協力いただきありがとうございます。 しかし、残念ながら、それでも、私は問題を解決することができません。
次のコードを調べて、何が問題なのかを理解してください。

私のステップ:
サブスクライブスクリプトを実行する
公開スクリプトを実行する
//サブスクライブスクリプトで受信したメッセージ
両方のスクリプトを終了します
1分以上待つ
サブスクライブスクリプトを実行する
//接続の将来の結果は.... result ['session_present'] = Trueを返します。 したがって、サブスクライブループはスキップされます
公開スクリプトを実行する
//問題:サブスクライブスクリプトでメッセージを受信しません

def conenct_mqtt(mqtt_connection):
    connect_future = mqtt_connection.connect()

    excep_count = 0
    while True:
        print(f"[{datetime.now()}]Connecting......")
        try:
            # Future.result() waits until a result is available
            result = connect_future.result(timeout=30)
            print(f"[{datetime.now()}]Connected! session persistent = {result['session_present']}")
            return result['session_present']

        except Exception as exc:
            print(f"[{datetime.now()}]Error while connecting {exc}")
            time.sleep(10)
            excep_count=excep_count+1
            if excep_count > 5 :
                print(f"[{datetime.now()}]Exiting Script.....")
                quit()

if __name__ == '__main__':
    # Spin up resources
    event_loop_group = io.EventLoopGroup(1)
    host_resolver = io.DefaultHostResolver(event_loop_group)
    client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)


    mqtt_connection = mqtt_connection_builder.mtls_from_path(
        endpoint=host,
        cert_filepath=certificatePath,
        pri_key_filepath=privateKeyPath,
        client_bootstrap=client_bootstrap,
        ca_filepath=rootCAPath,
        on_connection_interrupted=on_connection_interrupted,
        on_connection_resumed=on_connection_resumed,
        client_id=clientId,
        clean_session=False, # set as persistent sessions
        keep_alive_secs=60, # 1 min as any data communication or PINGREQ . x1.5 to detect disconenct
        reconnect_min_timeout_secs=2,
        reconnect_max_timeout_secs =300,
        ping_timeout_ms = 10000, # wait for 6 secs for ping response
        )

    print(f"[{datetime.now()}]Connecting with client ID '{clientId}'...")
    is_session_persistent = conenct_mqtt(mqtt_connection)

    # subscribe to topics only if previous session was lost 
    if not is_session_persistent:
        topic_index = 0
        excep_count = 0
        while topic_index < 2:
            # Subscribe
            topic = topic_list[topic_index]
            print(f"[{datetime.now()}]Subscribing to topic '{topic}'...")
            subscribe_future, packet_id = mqtt_connection.subscribe(
                topic=topic,
                qos=mqtt.QoS.AT_LEAST_ONCE,
                callback=on_message_received)


            try:
                subscribe_result = subscribe_future.result()
                print(f"[{datetime.now()}]Subscribed with {str(subscribe_result['qos'])}")
                topic_index+=1
                excep_count = 0
            except Exception as exc:
                print(f"Error:Subscribe: {exc}")
                excep_count+=1
                if excep_count > 3 :
                    print(f"[{datetime.now()}]Exiting Script.....")
                    quit()
                time.sleep(10)
    else:
        print("-----------Session is Persistent---------")




    # Wait for all messages to be received.
    # This waits forever if count was set to 0.
    if max_count != 0 and not received_all_event.is_set():
        print("Waiting for all messages to be received...")

    received_all_event.wait()
    print("{} message(s) received.".format(received_count))

こんにちは@GauravPatni

してみてください:

   if not is_session_persistent:
        XXX
   else:
        mqtt_connection.on_message(on_message_received) #register your callback
        print("-----------Session is Persistent---------")

接続は接続されていますが、メッセージを受信するには、 on_messageを介して_Connection_オブジェクトにコールバックを登録する必要があります。

ありがとう

こんにちは@GauravPatni

してみてください:

   if not is_session_persistent:
        XXX
   else:
        mqtt_connection.on_message(on_message_received) #register your callback
        print("-----------Session is Persistent---------")

接続は接続されていますが、メッセージを受信するには、 on_messageを介して_Connection_オブジェクトにコールバックを登録する必要があります。

ありがとう@TingDaoK

追加後
mqtt_connection.on_message(on_message_received)#コールバックを登録する
問題は解決された !!

もう一度迅速な返信をありがとう!

このページは役に立ちましたか?
0 / 5 - 0 評価

関連する問題

qcabrol picture qcabrol  ·  8コメント

banuprathap picture banuprathap  ·  10コメント

mkozjak picture mkozjak  ·  8コメント

mkozjak picture mkozjak  ·  17コメント

victorct-pronto picture victorct-pronto  ·  3コメント