diff --git a/server.py b/server.py index b36aa1c..9745ea9 100644 --- a/server.py +++ b/server.py @@ -33,6 +33,9 @@ PREDICTION_HISTORY = [] PREDICTION_HISTORY_MAX_LENGTH = 3 PREVIOUS_STATE = "unknown" LAST_OPEN_SAVE_TIME = None +DOOR_OPEN_START_TIME = None +OPEN_ALERT_THRESHOLDS_MINUTES = [5, 15, 30, 60, 120] +OPEN_ALERTS_SENT_FOR_CURRENT_OPENING = [] def get_derived_state(): @@ -165,16 +168,32 @@ async def monitor_garage_door(app): async def monitor_state_transitions(app): """Periodically checks for state transitions and logs them.""" - global PREVIOUS_STATE + global PREVIOUS_STATE, DOOR_OPEN_START_TIME, OPEN_ALERTS_SENT_FOR_CURRENT_OPENING logging.info("Starting state transition monitoring task.") while True: try: await asyncio.sleep(5) current_state = get_derived_state() - if current_state != "unknown": - if current_state != PREVIOUS_STATE: - logging.info(f"State transitioned from '{PREVIOUS_STATE}' to '{current_state}'.") + if current_state != "unknown" and current_state != PREVIOUS_STATE: + logging.info(f"State transitioned from '{PREVIOUS_STATE}' to '{current_state}'.") PREVIOUS_STATE = current_state + + if current_state == 'open': + if DOOR_OPEN_START_TIME is None: + DOOR_OPEN_START_TIME = datetime.now() + OPEN_ALERTS_SENT_FOR_CURRENT_OPENING = [] + + open_duration = datetime.now() - DOOR_OPEN_START_TIME + open_duration_minutes = open_duration.total_seconds() / 60 + + for threshold in OPEN_ALERT_THRESHOLDS_MINUTES: + if open_duration_minutes >= threshold and threshold not in OPEN_ALERTS_SENT_FOR_CURRENT_OPENING: + logging.info(f"ALERT: Garage door has been open for {threshold} minutes.") + OPEN_ALERTS_SENT_FOR_CURRENT_OPENING.append(threshold) + else: + DOOR_OPEN_START_TIME = None + OPEN_ALERTS_SENT_FOR_CURRENT_OPENING = [] + except asyncio.CancelledError: logging.info("State transition monitoring task cancelled.") break