handled multiple race conditions

This commit is contained in:
2026-04-18 22:12:07 +05:30
parent d236804b69
commit bf72a0c213

93
main.py
View File

@@ -46,41 +46,66 @@ def main():
with serial.Serial(device_name, 115200, timeout=1) as ser: with serial.Serial(device_name, 115200, timeout=1) as ser:
shutdown_triggered = False shutdown_triggered = False
inverter_online = True inverter_online = True
while running: last_online = time.monotonic()
line = ser.readline().decode(errors="ignore").strip() receiving_data = True
if line == "": last_logged = -1
logger.warning("No serial data") try:
continue while running:
elif line == "0": line = ser.readline().decode(errors="ignore").strip()
logger.debug("Inverter Online")
inverter_online = True
elif not inverter_online:
if time.time() - last_online > shutdown_timer:
shutdown_triggered = True
break
else:
if inverter_online:
inverter_online = False
last_online = time.time()
logger.info(f"Running on UPS reserve, offline for {time.time()-last_online}s")
if shutdown_triggered: if line != "" and not receiving_data:
logger.info(f"Inverter offline for {shutdown_timer} seconds") receiving_data = True
try: logger.info("Serial data restored")
requests.post(
"https://ntfy.fieryeagle.org/Internet-Alerts", if line == "0":
data="Inverter offline, shutting down".encode("utf-8"), if not inverter_online:
headers={ logger.info("Inverter restored")
"Title": "Hydrogen running on reserve power", inverter_online = True
"Authorization": f"Bearer {ntfy_token}" last_online = time.monotonic()
},
timeout=5 elif line == "1":
) if inverter_online:
except Exception as e: inverter_online = False
logger.error(f"Failed to send notification: {e}") logger.info("Running on UPS reserve")
os.system("shutdown now")
else: elif line == "":
logger.info("Exited cleanly (service stop)") if receiving_data:
receiving_data = False
logger.warning("No serial data")
else:
logger.warning(f"Unexpected serial data: {line}")
if not inverter_online:
sec = int(time.monotonic() - last_online)
if sec % 10 == 0 and sec != last_logged:
logger.info(f"Offline for {sec}s")
last_logged = sec
if sec >= shutdown_timer:
shutdown_triggered = True
break
if shutdown_triggered:
logger.info(f"Inverter offline for {shutdown_timer} seconds")
try:
requests.post(
"https://ntfy.fieryeagle.org/Internet-Alerts",
data="Inverter offline, shutting down".encode("utf-8"),
headers={
"Title": "Hydrogen running on reserve power",
"Authorization": f"Bearer {ntfy_token}"
},
timeout=5
)
except Exception as e:
logger.error(f"Failed to send notification: {e}")
os.system("shutdown now")
else:
logger.info("Exited cleanly (service stop)")
except serial.SerialException as e:
logger.error(f"Serial device error: {e}")
raise
if __name__ == "__main__": if __name__ == "__main__":
main() main()