how to publish a message when client disconnects #91
-
I have service which should report its state in a topic /service/state as online/offline But how about normal disconnect? when service is stopped or Keyboard interrupted? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
That's a good use of the
Good question. :) Sounds like a case for the async with Client("test.mosquitto.org") as client:
try:
async with client.filtered_messages("floors/+/humidity") as messages:
await client.subscribe("floors/#")
async for message in messages:
print(message.payload.decode())
# The `finally` block always runs (both on exception and otherwise)
finally:
await client.publish("service/state", payload="offline".encode()) Does it make sense? |
Beta Was this translation helpful? Give feedback.
-
On an unrelated note: Avoid a leading forward slash in MQTT topics. That is, prefer Reference: https://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices/ |
Beta Was this translation helpful? Give feedback.
That's a good use of the
will
feature in MQTT. 👍Good question. :) Sounds like a case for the
finally
block. I suggest something like the following (adapted from the basic example inREADME.md
):