fix: Refactor main loop for graceful shutdown and improved error handling

This commit is contained in:
Aaron 2025-11-15 14:11:20 -05:00
parent d76b11430c
commit c8102e62ee

36
main.py
View File

@ -369,18 +369,21 @@ retry_ntp_attempts = 0
max_ntp_attempts = 5 # Try up to 5 times after initial failure
last_ntp_sync = time.time() # Track when we last synced
# ===== START: Main Loop =====
# Main monitoring loop (runs forever until Ctrl+C)
last_monitor_run = {
try:
while True:
# ===== START: Main Loop =====
# Main monitoring loop (runs forever until Ctrl+C)
last_monitor_run = {
"wifi": 0,
"schedule": 0,
"ac": 0,
"heater": 0,
"inside_temp": 0,
"outside_temp": 0,
}
}
while True:
while True:
now = time.time()
# WiFi monitor every 5 seconds (can be stateless)
@ -460,4 +463,25 @@ while True:
gc.collect()
time.sleep(0.1)
# ===== END: Main Loop =====
# ===== END: Main Loop =====
except KeyboardInterrupt:
print("\n" + "="*50)
print("Shutting down gracefully...")
print("="*50)
try:
print("Turning off AC...")
ac_controller.turn_off()
except Exception as e:
print("AC shutdown error:", e)
try:
print("Turning off heater...")
heater_controller.turn_off()
except Exception as e:
print("Heater shutdown error:", e)
try:
print("Turning off LED...")
led.low()
except Exception as e:
print("LED shutdown error:", e)
print("Shutdown complete!")
print("="*50)