MWE: Simplified transparent reconnect #316
Replies: 2 comments
-
Hi there, I only just now got a chance to have a look. Thanks much for the example implementation, it's a great reference and definitely does some things better than the current draft for reconnection! I'll see how I can work this into the PR 👍 |
Beta Was this translation helpful? Give feedback.
-
No worries. I've just updated above MWE to the latest version with some minor improvements. I've also just published a repository that includes a bunch of unit tests. This has been sitting on the shelf for 2 months and has since passed its baptism of fire by reliably transferring multiple gigabytes of telemetry data over half a dozen spotty mobile LTE connections. So I have reason to believe that this actually works. Hope it helps! |
Beta Was this translation helpful? Give feedback.
-
In need of an asyncio MQTT client, I stumbled over aiomqtt. However, the Reconnection example did not satisfy my requirements for transparent reconnect. Eventually, I implemented a small asyncio wrapper around Paho MQTT inspired by Paho's
loop_asyncio.py
example. It reconnects transparently, i.e. without any user intervention, also supporting uninterrupted async iteration.I've intentionally kept the reconnect logic away from the
on_connect()
andon_disconnect()
callbacks, but instead integrated it into the same coroutine that periodically callsloop_misc()
to minimize implementation complexity by delegating connection state tracking to the wrapped Paho client. This approach could possibly simplify #287 a bit, as it obviates both Futures used to synchronize_reconnection(self)
with the callbacks.Unfortunately, I don't have the time to turn this into a PR. Instead, I've extracted an MWE from my Paho client wrapper, hoping that it could be useful for aiomqtt. What's currently missing, is an option to raise an exception if the very first connection attempt fails.
UPDATE: Refactored and improved below MWE. Asynchronous connect is now optional, successive reconnect attempts use incremental delay, messages preceding CONNACK are discarded, logging moved to a child class, and publish() will drop messages if the send buffer is full to avoid building an infinite backlog of QoS=0 messages.
UPDATE 2: Improved cancellation of async iteration and fixed disconnect() logic while not currently connected, e.g., while sleeping during reconnect attempts.
UPDATE 3: Added arbitrarily configurable connect delay and improved the backlog handling by relying on whether send() on socket would block.
Beta Was this translation helpful? Give feedback.
All reactions