empicano / aiomqtt

The idiomatic asyncio MQTT client
https://aiomqtt.bo3hm.com
BSD 3-Clause "New" or "Revised" License
430 stars 77 forks source link

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

Open rudenko-ks opened 4 weeks ago

rudenko-ks commented 4 weeks ago

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 commented 4 weeks ago

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!