diff --git a/main.py b/main.py index 312e052..735b1d8 100644 --- a/main.py +++ b/main.py @@ -350,12 +350,24 @@ class GadgetbridgeMQTTPublisher: return row[0] if row else None def query_is_awake(self, cursor) -> Any: - cursor.execute( - "SELECT IS_AWAKE FROM XIAOMI_SLEEP_TIME_SAMPLE ORDER BY TIMESTAMP DESC LIMIT 1" - ) + cursor.execute("""SELECT TIMESTAMP, IS_AWAKE, WAKEUP_TIME FROM XIAOMI_SLEEP_TIME_SAMPLE ORDER BY TIMESTAMP DESC LIMIT 1""") row = cursor.fetchone() - # Return as boolean or string for Home Assistant - return not bool(row[0]) if row else None # inverted + # 1. No data at all -> Assume Awake + if not row: + return True + last_ts_epoch = row[0] + is_awake_val = row[1] # This can be 1, 0, or None (NULL) + # 2. Timeout Safety: If last sleep data is older than 4 hours, force Awake + # This handles "Band Removed" or "Sync Failed" scenarios where the + # user has been up for hours but no new "awake" row was inserted. + import time + if (int(time.time()) - last_ts_epoch) > (4 * 3600): + return True + # 3. Explicit Status Check + if is_awake_val == 1: + return True + # If is_awake_val is 0 or None, the user is likely asleep (TODO: verify None) + return False def query_total_sleep_duration(self, cursor) -> Any: cursor.execute(