Skip to content

how to publish a message when client disconnects #91

Answered by frederikaalund
mangroovie asked this question in Q&A
Discussion options

You must be logged in to vote

For unexpected disconnects I can use will to set the /service/state to offline and broker should handle these ok.

That's a good use of the will feature in MQTT. 👍

But how about normal disconnect? when service is stopped or Keyboard interrupted?
How to ensure the state is published before client disconnects?

Good question. :) Sounds like a case for the finally block. I suggest something like the following (adapted from the basic example in README.md):

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:
          …

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
2 replies
@mangroovie
Comment options

@mangroovie
Comment options

Answer selected by mangroovie
Comment options

You must be logged in to vote
1 reply
@mangroovie
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants