Improve Connection Logic

This commit is contained in:
Oliver 2025-09-17 19:58:32 +00:00
parent 81773074f9
commit 0a9b13eacf

65
main.py
View File

@ -340,54 +340,35 @@ class GadgetbridgeMQTTPublisher:
self.logger.info(f"Published sensor data: {data}")
async def mqtt_connect_with_retry(self):
"""Connect to MQTT broker with retry logic"""
for attempt in range(self.max_retries):
try:
self.logger.info(f"Attempting MQTT connection (attempt {attempt + 1}/{self.max_retries})")
client = aiomqtt.Client(
hostname=self.mqtt_config["broker"],
port=self.mqtt_config["port"],
username=self.mqtt_config["username"] or None,
password=self.mqtt_config["password"] or None,
)
# Test connection
await client.connect()
async def run_main_loop(self):
"""Main execution loop with error recovery - simplified version"""
while True:
try:
async with aiomqtt.Client(
hostname=self.mqtt_config["broker"],
port=self.mqtt_config["port"],
username=self.mqtt_config["username"] or None,
password=self.mqtt_config["password"] or None,
) as client:
self.mqtt_client = client
self.logger.info("MQTT connection successful")
return client
except Exception as e:
self.logger.error(f"MQTT connection attempt {attempt + 1} failed: {e}")
if attempt < self.max_retries - 1:
self.logger.info(f"Retrying in {self.retry_delay} seconds...")
await asyncio.sleep(self.retry_delay)
else:
self.logger.error("All MQTT connection attempts failed")
raise
async def run_main_loop(self):
"""Main execution loop with error recovery"""
while True:
try:
async with await self.mqtt_connect_with_retry() as client:
self.mqtt_client = client
await self.setup_home_assistant_entities()
await self.setup_home_assistant_entities()
# Publish immediately on startup
# Publish immediately on startup
sensor_data = self.get_sensor_data()
await self.publish_sensor_data(sensor_data)
# Main publishing loop
while True:
await asyncio.sleep(self.publish_interval)
sensor_data = self.get_sensor_data()
await self.publish_sensor_data(sensor_data)
self.logger.info(f"Sleeping for {self.publish_interval} seconds before next publish...")
# Main publishing loop
while True:
await asyncio.sleep(self.publish_interval)
sensor_data = self.get_sensor_data()
await self.publish_sensor_data(sensor_data)
self.logger.info(f"Sleeping for {self.publish_interval} seconds before next publish...")
except Exception as e:
self.logger.error(f"Error in main loop: {e}")
self.logger.info(f"Restarting main loop in {self.retry_delay} seconds...")
await asyncio.sleep(self.retry_delay)
except Exception as e:
self.logger.error(f"Error in main loop: {e}")
self.logger.info(f"Restarting main loop in {self.retry_delay} seconds...")
await asyncio.sleep(self.retry_delay)
async def run(self):
"""Main execution method (async) - now with proper error recovery"""