How to keep subscriber active and listen for new messages #494
-
I have the following piece of code: try:
connect_future = mqtt_connection.connect()
# Future.result() waits until a result is available
connect_future.result()
logging.info(f"Connected to IoT Core endpoint: {aws_iot_endpoint}")
# Subscribe
logging.info(f"Subscribing to topic {message_topic}...")
subscribe_future, packet_id = mqtt_connection.subscribe(
topic=message_topic,
qos=mqtt.QoS.AT_LEAST_ONCE,
callback=on_message_received)
subscribe_result = subscribe_future.result()
logging.info(f"Subscribed to topic {message_topic}. Waiting for new messages.")
while True:
await asyncio.sleep(10)
except Exception as e:
logging.error(f"There was an error: {e}")
mqtt_connection.unsubscribe(message_topic)
finally:
disconnect_future = mqtt_connection.disconnect()
disconnect_future.result()
logging.info(f"Disconnected from IoT Core endpoint: {aws_iot_endpoint}") What would be the appropriate way to keep the listener active and listen for new MQTT messages? I've done this using while True part, but is this ok, and what would be the preferred way? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
@github-actions proposed-answer received_all_event.wait() You don't need to use a |
Beta Was this translation helpful? Give feedback.
-
Hello! Reopening this discussion to make it searchable. |
Beta Was this translation helpful? Give feedback.
@github-actions proposed-answer
You could just use a threading event wait like we do in the pubsub sample:
You don't need to use a
while True
because theon_message_received
is handled in another thread. What your doing also looks fine, but the choice is up to you to decided how you handle this. Please let us know if you have any other questions about this sdk.