Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The client does not publish a Will message if raised asyncio.CancelledError #340

Open
rudenko-ks opened this issue Oct 24, 2024 · 1 comment

Comments

@rudenko-ks
Copy link

rudenko-ks commented Oct 24, 2024

The version of aiomqtt: 2.3.0

He!
Tell me, please, why when pressing CTRL+C or raised CancelledError, "inactive" is not published in the will_msg topic? The script has already stopped working and is not running. How to properly terminate the script so that the Will message is published?
Noticed if I press CTRL+Z then Will message will be published.
I'm not an expert in Python async, so any opinions you can share would be appreciated.

import asyncio
import logging

from aiomqtt import MqttError, Client as MqttClient, Will

logging.basicConfig(level=logging.INFO)

MQTT_BROKER = "localhost"
MQTT_PORT = 1883
MQTT_WILL_MSG = "will_msg"

async def main():

    will_msg = Will(
        topic=MQTT_WILL_MSG,
        payload="inactive",
        retain=True
    )

    while True:
        try:
            async with MqttClient(hostname=MQTT_BROKER, port=MQTT_PORT, will=will_msg, keepalive=2) as mqtt_client:

                await mqtt_client.subscribe("temperature/#")

                await mqtt_client.publish(MQTT_WILL_MSG, "active")

                async for message in mqtt_client.messages:
                    logging.info(message.payload)

        except asyncio.CancelledError:
            logging.info("Task cancelled. Disconnecting MQTT client.")
            break

if __name__ == '__main__':
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logging.info("Program interrupted by user. Shutting down...")
@empicano
Copy link
Owner

Hi there! That's an good point you bring up 🙂 I think issue #28 might be related. The whole discussion is interesting, but the last message from Frederik proposes a potential way forward. I'd be very interested to hear what you think about that!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants