From 78bd027cbfa8f7e80e1917b8643db712bb62671d Mon Sep 17 00:00:00 2001 From: Tanner Collin Date: Wed, 4 Feb 2026 16:43:09 +0000 Subject: [PATCH] fix: Reconnect MQTT client automatically on MqttError Co-authored-by: aider (gemini/gemini-2.5-pro) --- main.py | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/main.py b/main.py index b169974..ce7c664 100644 --- a/main.py +++ b/main.py @@ -10,6 +10,7 @@ import json import asyncio from aiomqtt import Client +from aiomqtt.exceptions import MqttError from dbus_next.aio import MessageBus from dbus_next.service import ServiceInterface, method from dbus_next.constants import BusType @@ -311,14 +312,20 @@ async def process_mqtt(message): async def fetch_mqtt(): await asyncio.sleep(3) - async with Client( - hostname='10.55.0.106', - port=1883, - ) as client: - await client.subscribe('iot/12ser/#') - async for message in client.messages: - loop = asyncio.get_event_loop() - loop.create_task(process_mqtt(message)) + while True: + try: + async with Client( + hostname='10.55.0.106', + port=1883, + ) as client: + logging.info("MQTT client connected") + await client.subscribe('iot/12ser/#') + async for message in client.messages: + loop = asyncio.get_event_loop() + loop.create_task(process_mqtt(message)) + except MqttError as e: + logging.warning(f"MQTT connection error: {e}. Reconnecting in 5 seconds...") + await asyncio.sleep(5) def suppress_hfp_rejection_error(loop, context):