format MQTT code with ruff

This commit is contained in:
Dan 2025-09-01 15:54:48 -04:00
parent a45915517f
commit 3952035579

View File

@ -45,7 +45,7 @@ class MqttClient(Communicator):
self._stop_reconnect = True self._stop_reconnect = True
if self._reconnect_thread and self._reconnect_thread.is_alive(): if self._reconnect_thread and self._reconnect_thread.is_alive():
self._reconnect_thread.join(timeout=5) self._reconnect_thread.join(timeout=5)
if hasattr(self, 'client'): if hasattr(self, "client"):
self.client.disconnect() self.client.disconnect()
def _set_initial_topics(self) -> None: def _set_initial_topics(self) -> None:
@ -203,27 +203,31 @@ class MqttClient(Communicator):
"""Mqtt disconnection callback.""" """Mqtt disconnection callback."""
self.connected = False self.connected = False
# Debug reason code thoroughly # Debug reason code thoroughly
reason_name = reason_code.getName() if hasattr(reason_code, 'getName') else str(reason_code) reason_name = (
reason_value = getattr(reason_code, 'value', reason_code) reason_code.getName()
logger.error(f"MQTT disconnected - reason: '{reason_name}', code: {reason_value}, type: {type(reason_code)}") if hasattr(reason_code, "getName")
else str(reason_code)
)
reason_value = getattr(reason_code, "value", reason_code)
logger.error(
f"MQTT disconnected - reason: '{reason_name}', code: {reason_value}, type: {type(reason_code)}"
)
# Don't attempt reconnection if we're stopping or if it was a clean disconnect # Don't attempt reconnection if we're stopping or if it was a clean disconnect
if self._stop_reconnect: if self._stop_reconnect:
logger.error("MQTT not reconnecting - stop flag set") logger.error("MQTT not reconnecting - stop flag set")
return return
if reason_code == 0: if reason_code == 0:
logger.error("MQTT not reconnecting - clean disconnect (code 0)") logger.error("MQTT not reconnecting - clean disconnect (code 0)")
return return
logger.error("MQTT will attempt reconnection...") logger.error("MQTT will attempt reconnection...")
# Start reconnection in a separate thread to avoid blocking # Start reconnection in a separate thread to avoid blocking
if not self._reconnect_thread or not self._reconnect_thread.is_alive(): if not self._reconnect_thread or not self._reconnect_thread.is_alive():
self._reconnect_thread = threading.Thread( self._reconnect_thread = threading.Thread(
target=self._reconnect_loop, target=self._reconnect_loop, name="mqtt-reconnect", daemon=True
name="mqtt-reconnect",
daemon=True
) )
self._reconnect_thread.start() self._reconnect_thread.start()
@ -321,45 +325,53 @@ class MqttClient(Communicator):
attempt = 0 attempt = 0
while not self._stop_reconnect and not self.connected: while not self._stop_reconnect and not self.connected:
attempt += 1 attempt += 1
logger.error(f"Will attempt MQTT reconnection in {self._reconnect_delay} seconds (attempt {attempt})") logger.error(
f"Will attempt MQTT reconnection in {self._reconnect_delay} seconds (attempt {attempt})"
)
# Wait with ability to exit early if stopping # Wait with ability to exit early if stopping
for _ in range(self._reconnect_delay): for _ in range(self._reconnect_delay):
if self._stop_reconnect: if self._stop_reconnect:
logger.error("MQTT reconnection stopped during delay") logger.error("MQTT reconnection stopped during delay")
return return
time.sleep(1) time.sleep(1)
if self._stop_reconnect: if self._stop_reconnect:
logger.error("MQTT reconnection stopped after delay") logger.error("MQTT reconnection stopped after delay")
break break
try: try:
logger.error(f"Creating fresh MQTT client for reconnection attempt {attempt}...") logger.error(
f"Creating fresh MQTT client for reconnection attempt {attempt}..."
)
# Clean up old client if it exists # Clean up old client if it exists
if hasattr(self, 'client'): if hasattr(self, "client"):
try: try:
self.client.disconnect() self.client.disconnect()
self.client.loop_stop() self.client.loop_stop()
except Exception: except Exception:
pass # Ignore cleanup errors pass # Ignore cleanup errors
# Create completely fresh client and attempt connection # Create completely fresh client and attempt connection
self._start() self._start()
# Give the connection attempt some time to complete # Give the connection attempt some time to complete
for _ in range(5): # Wait up to 5 seconds for connection for _ in range(5): # Wait up to 5 seconds for connection
if self.connected: if self.connected:
logger.error(f"MQTT fresh connection successful on attempt {attempt}!") logger.error(
f"MQTT fresh connection successful on attempt {attempt}!"
)
return return
time.sleep(1) time.sleep(1)
logger.error(f"MQTT fresh connection attempt {attempt} timed out, will retry") logger.error(
f"MQTT fresh connection attempt {attempt} timed out, will retry"
)
# Continue the loop to retry # Continue the loop to retry
except Exception as e: except Exception as e:
logger.error(f"MQTT fresh connection attempt {attempt} failed: {e}") logger.error(f"MQTT fresh connection attempt {attempt} failed: {e}")
# Continue the loop to retry # Continue the loop to retry
logger.error("MQTT reconnection loop finished") logger.error("MQTT reconnection loop finished")