Closed skewty closed 6 months ago
Hi skewty, thank you for opening this issue. 👍 Let me have a look.
Use-case I need to listen to MQTT messages until I get a signal from an external non MQTT system to stop.
Sounds like a reasonable use case.
Have you considered using task cancellation? It seems ideal for what you want to achieve. Something like this:
async def process_messages(client: Client) -> None:
async for message in client.messages:
...
async with Client(...) as client, asyncio.TaskGroup() as tg:
task = tg.create_task(process_messages(client)) # This schedules the task to run in the background
await your_signal_arrives
task.cancel() # This stops the infinite loop inside process_messages
You can do something similar even without asyncio.TaskGroup
(if you don't have python 3.11 or later).
Let me know if that helps you or not. :)
The log / logging messages are less useful but it works. Thank you.
Use-case I need to listen to MQTT messages until I get a signal from an external non MQTT system to stop.
If I use the
async for client.messages
I am locked in thefor loop
until MQTT is disconnected or a message arrives. Neither are likely to trigger for hours or days in my scenario.I can't
client.disconnect()
because that isn't implemented. Even if it did though (which I think it should) callingclient.disconnect()
seems wrong / excessive (it generates an MqttError after all). There is no error. I want a graceful shutdown.So I guess what I am proposing / have in mind something like:
I also looked into using the raw iterator outside the
Client
class but it seems wrong and is ugly