Aws-iot-device-sdk-python-v2: 持久会话的 AWS IOT MQTT = True 但订阅失败

创建于 2020-05-31  ·  4评论  ·  资料来源: aws/aws-iot-device-sdk-python-v2

亲爱的大家,

在使用持久会话试验 AWS IOT MQTT 时,我发现 Broker 返回 'session_present = True' 以回复具有 'clean_session = False' 的连接请求。
这是预期的,因为我在 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---------")

您的连接已连接,但您仍需要在 _Connection_ 对象上注册回调以通过on_message接收消息。

所有4条评论

你好,
感谢您伸出援手。 我已经测试过了,持久会话对我有用。
在 pubsub.py 示例中,如果连接丢失并恢复,则 mqtt_conneciton 继续接收消息。 但是您需要在 _Connection_ 对象上注册您的回调以接收消息。
例如,如果您创建另一个 _Connection_ 对象,以 'session_present = True' 作为连接结果,您将需要调用on_message来设置回调。 然后您可以通过您设置的回调接收传入的消息。
谢谢!

嗨@TingDaoK
谢谢你的帮助。 但不幸的是,我仍然无法解决这个问题。
您能否查看以下代码以找出问题所在?

我的步骤:
运行订阅脚本
运行发布脚本
// 在订阅脚本上收到的消息
现在终止两个脚本
等待一分钟或更长时间
运行订阅脚本
// 连接未来结果返回 .... 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---------")

您的连接已连接,但您仍需要在 _Connection_ 对象上注册回调以通过on_message接收消息。

谢谢

嗨@GauravPatni

请试试:

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

您的连接已连接,但您仍需要在 _Connection_ 对象上注册回调以通过on_message接收消息。

谢谢@TingDaoK

添加后
mqtt_connection.on_message(on_message_received) #注册你的回调
问题解决了 !!

再次感谢您的快速回复!!

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

mkozjak picture mkozjak  ·  17评论

supertick picture supertick  ·  7评论

mkozjak picture mkozjak  ·  8评论

satay99 picture satay99  ·  6评论

shravan097 picture shravan097  ·  6评论