Improve Connection Logic

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

33
main.py
View File

@ -340,49 +340,30 @@ 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:
# Test connection
await client.connect()
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 self.mqtt_client = client
self.logger.info("MQTT connection successful")
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() 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 # Main publishing loop
while True: while True:
await asyncio.sleep(self.publish_interval) await asyncio.sleep(self.publish_interval)
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...")
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}")