From 1ad83cec9755ef8aa082812b3707e9757f5ae671 Mon Sep 17 00:00:00 2001 From: Eric Callahan Date: Mon, 6 Dec 2021 08:38:27 -0500 Subject: [PATCH] mqtt: fix connect/reconnect issues Handle all potential exceptions. Run the connect/disconnect in another thread, as its possible for some calls to block the event loop. Signed-off-by: Eric Callahan --- moonraker/components/mqtt.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/moonraker/components/mqtt.py b/moonraker/components/mqtt.py index 512a008..98643fe 100644 --- a/moonraker/components/mqtt.py +++ b/moonraker/components/mqtt.py @@ -232,8 +232,9 @@ class MQTTClient(APITransport, Subscribable): retries = 5 for _ in range(retries): try: - self.client.connect(self.address, self.port) - except (ConnectionRefusedError, socket.gaierror) as e: + await self.event_loop.run_in_thread( + self.client.connect, self.address, self.port) + except Exception as e: logging.info(f"MQTT connection error, {e}, " f"retries remaining: {retries}") await asyncio.sleep(2.) @@ -351,14 +352,15 @@ class MQTTClient(APITransport, Subscribable): async def _do_reconnect(self) -> None: logging.info("Attempting MQTT Reconnect") + self.event_loop while True: try: await asyncio.sleep(2.) except asyncio.CancelledError: break try: - self.client.reconnect() - except (ConnectionRefusedError, socket.gaierror): + await self.event_loop.run_in_thread(self.client.reconnect) + except Exception: continue self.client.socket().setsockopt( socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)