empicano / aiomqtt

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

how to open and close the mqtt client except "with" statement #331

Closed Jzhenli closed 2 months ago

Jzhenli commented 2 months ago

hi, if I don't use the "with" statement, how to open and close the mqtt client? I try to use aenter and aexit, but rasie some error. Below is my test script.

mqtt_connector.zip

empicano commented 2 months ago

Hi there, thanks for opening this issue! šŸ™‚

We recommend to always use the with statement to manage connection and disconnection, except if you have very good reasons to do otherwise. Can you tell me more about why you cannot use the context manager?

Jzhenli commented 2 months ago

@empicano Iā€˜m working on IOT, and there are some iot connectors such as modbus, bluetooh, mqtt, etc. I want to make them have the same behavior, which should have open, close, send, receive... 1725550550858

empicano commented 2 months ago

When I run your script, I get aiomqtt.exceptions.MqttError: [Errno 8] nodename nor servname provided, or not known, is that what you mean? When I change the AsyncMQTTClient's broker argument from "mqtt.eclipse.org" to the public "test.mosquitto.org" it works fine for me. Can you tell me more about what errors you're seeing and what you've tried to solve them?

Btw. you can paste code into GitHub comments by surrounding it with triple backticks (```), that makes it a lot faster for me to help you than when I'm juggling with zip files and screenshots šŸ˜‰

Jzhenli commented 2 months ago

@empicano thanks for your reply. When subscribing to a topic, messages will be queued internally, but I usually use diskcache lib for message persistence other than asyncio queues, if there's way to implement it?

empicano commented 2 months ago

At the moment, aiomqtt only supports asyncio queues. You could relay the messages with something like this:

async with Client("test.mosquitto.org") as client:
    await client.subscribe("temperature/#")
    async for message in client.messages:
        ...  # Put the message into diskcache here, then consume it from somewhere else

I'll convert this into a discussion, maybe someone else has done something similar šŸ™‚