Improve Connection Logic

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

69
main.py
View File

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