-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathspa_database.py
More file actions
1055 lines (882 loc) · 33.7 KB
/
Copy pathspa_database.py
File metadata and controls
1055 lines (882 loc) · 33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Spa Database - SQLite persistence layer for spa status, connection events, and schedules.
Provides thread-safe database operations for:
- Status readings (temperature, heat mode, pump states, etc.)
- Connection event tracking (connected/disconnected/error)
- Schedule management (heat mode, temperature, smart temp schedules)
- Schedule execution history
"""
import json
import os
import sqlite3
import threading
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional
from spa_control import SpaStatus
class SpaDatabase:
"""
SQLite database layer for spa data persistence.
Thread-safe with connection-per-thread pattern.
Creates tables automatically on first use.
"""
def __init__(self, db_path: str = "data/spadata/spa.db"):
"""
Initialize database connection.
Args:
db_path: Path to SQLite database file (created if doesn't exist)
"""
self.db_path = db_path
self._local = threading.local()
# Ensure directory exists
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
# Initialize schema
self._init_schema()
def _get_connection(self) -> sqlite3.Connection:
"""Get thread-local database connection."""
if not hasattr(self._local, "connection") or self._local.connection is None:
self._local.connection = sqlite3.connect(
self.db_path,
check_same_thread=False,
timeout=30.0
)
self._local.connection.row_factory = sqlite3.Row
# Enable foreign keys
self._local.connection.execute("PRAGMA foreign_keys = ON")
return self._local.connection
def _init_schema(self):
"""Create database tables if they don't exist."""
conn = self._get_connection()
cursor = conn.cursor()
# Spa readings table - stores status snapshots
cursor.execute("""
CREATE TABLE IF NOT EXISTS spa_readings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
current_temp REAL,
target_temp REAL NOT NULL,
temp_unit TEXT NOT NULL,
heat_mode TEXT NOT NULL,
temp_range TEXT NOT NULL,
heating INTEGER NOT NULL,
heat_state TEXT NOT NULL,
pumps_json TEXT,
lights_json TEXT,
blower_state INTEGER,
circ_pump_running INTEGER,
model TEXT,
software_version TEXT
)
""")
# Index for efficient time-range queries
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_readings_timestamp
ON spa_readings(timestamp)
""")
# Connection events table
cursor.execute("""
CREATE TABLE IF NOT EXISTS connection_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
event_type TEXT NOT NULL,
error_message TEXT
)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_connection_timestamp
ON connection_events(timestamp)
""")
# Schedules table
cursor.execute("""
CREATE TABLE IF NOT EXISTS schedules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
schedule_type TEXT NOT NULL,
action_value TEXT NOT NULL,
target_time TEXT NOT NULL,
recurrence_type TEXT NOT NULL,
days_of_week TEXT,
next_run TEXT,
smart_start_offset_minutes INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
""")
# Schedule executions table
cursor.execute("""
CREATE TABLE IF NOT EXISTS schedule_executions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
schedule_id INTEGER NOT NULL,
scheduled_time TEXT NOT NULL,
executed_at TEXT,
status TEXT NOT NULL,
result_message TEXT,
starting_temp REAL,
FOREIGN KEY (schedule_id) REFERENCES schedules(id) ON DELETE CASCADE
)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_executions_schedule
ON schedule_executions(schedule_id)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_executions_scheduled
ON schedule_executions(scheduled_time)
""")
# Command queue table - stores commands when spa is offline
cursor.execute("""
CREATE TABLE IF NOT EXISTS command_queue (
id INTEGER PRIMARY KEY AUTOINCREMENT,
command_type TEXT NOT NULL,
endpoint TEXT NOT NULL,
data_json TEXT,
source TEXT NOT NULL,
created_at TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
executed_at TEXT,
error_message TEXT
)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_command_queue_status
ON command_queue(status)
""")
# Settings table - stores user preferences
cursor.execute("""
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL
)
""")
# Initialize default temperature preferences if not set
cursor.execute("""
INSERT OR IGNORE INTO settings (key, value, updated_at)
VALUES ('high_temp_preference', '104', datetime('now'))
""")
cursor.execute("""
INSERT OR IGNORE INTO settings (key, value, updated_at)
VALUES ('low_temp_preference', '70', datetime('now'))
""")
conn.commit()
# =========================================================================
# Reading Operations
# =========================================================================
def save_reading(self, status: SpaStatus) -> int:
"""
Save a spa status reading to the database.
Args:
status: SpaStatus object from spa_control
Returns:
Row ID of inserted reading
"""
conn = self._get_connection()
cursor = conn.cursor()
# Extract blower state
blower_state = None
if status.blower:
blower_state = status.blower.get("state")
# Extract circ pump state
circ_pump_running = None
if status.circ_pump:
circ_pump_running = 1 if status.circ_pump.get("running") else 0
cursor.execute("""
INSERT INTO spa_readings (
timestamp, current_temp, target_temp, temp_unit,
heat_mode, temp_range, heating, heat_state,
pumps_json, lights_json, blower_state, circ_pump_running,
model, software_version
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
datetime.now().isoformat(),
status.current_temp,
status.target_temp,
status.temp_unit,
status.heat_mode,
status.temp_range,
1 if status.heating else 0,
status.heat_state,
json.dumps(status.pumps),
json.dumps(status.lights),
blower_state,
circ_pump_running,
status.model,
status.software_version,
))
conn.commit()
return cursor.lastrowid
def get_latest_reading(self) -> Optional[dict]:
"""
Get the most recent spa status reading.
Returns:
Dictionary with 'status' (dict) and 'timestamp' (str), or None
"""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM spa_readings
ORDER BY timestamp DESC
LIMIT 1
""")
row = cursor.fetchone()
if row is None:
return None
return self._row_to_reading(row)
def get_readings(
self,
since: datetime,
until: Optional[datetime] = None,
limit: int = 100
) -> list[dict]:
"""
Get status readings within a time range.
Args:
since: Start of time range
until: End of time range (default: now)
limit: Maximum number of readings to return
Returns:
List of reading dictionaries, newest first
"""
conn = self._get_connection()
cursor = conn.cursor()
if until is None:
until = datetime.now()
cursor.execute("""
SELECT * FROM spa_readings
WHERE timestamp >= ? AND timestamp <= ?
ORDER BY timestamp DESC
LIMIT ?
""", (since.isoformat(), until.isoformat(), limit))
return [self._row_to_reading(row) for row in cursor.fetchall()]
def _row_to_reading(self, row: sqlite3.Row) -> dict:
"""Convert database row to reading dictionary."""
status = {
"current_temp": row["current_temp"],
"target_temp": row["target_temp"],
"temp_unit": row["temp_unit"],
"heat_mode": row["heat_mode"],
"temp_range": row["temp_range"],
"heating": bool(row["heating"]),
"heat_state": row["heat_state"],
"pumps": json.loads(row["pumps_json"]) if row["pumps_json"] else [],
"lights": json.loads(row["lights_json"]) if row["lights_json"] else [],
"blower": {"state": row["blower_state"]} if row["blower_state"] is not None else None,
"circ_pump": {"running": bool(row["circ_pump_running"])} if row["circ_pump_running"] is not None else None,
"model": row["model"],
"software_version": row["software_version"],
"connected": True, # If we have a reading, it was connected
}
return {
"status": status,
"timestamp": row["timestamp"],
"id": row["id"],
}
def cleanup_old_readings(self, days: int = 30) -> int:
"""
Delete readings older than specified days.
Args:
days: Number of days to retain
Returns:
Number of rows deleted
"""
conn = self._get_connection()
cursor = conn.cursor()
cutoff = datetime.now() - timedelta(days=days)
cursor.execute(
"DELETE FROM spa_readings WHERE timestamp < ?",
(cutoff.isoformat(),)
)
deleted = cursor.rowcount
conn.commit()
return deleted
# =========================================================================
# Connection Event Operations
# =========================================================================
def record_connection_event(self, event_type: str, error: Optional[str] = None):
"""
Record a connection state change.
Args:
event_type: 'connected', 'disconnected', or 'error'
error: Error message (for 'disconnected' or 'error' events)
"""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("""
INSERT INTO connection_events (timestamp, event_type, error_message)
VALUES (?, ?, ?)
""", (datetime.now().isoformat(), event_type, error))
conn.commit()
def get_connection_history(self, limit: int = 50) -> list[dict]:
"""
Get recent connection events.
Args:
limit: Maximum number of events to return
Returns:
List of event dictionaries, newest first
"""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM connection_events
ORDER BY timestamp DESC
LIMIT ?
""", (limit,))
return [
{
"id": row["id"],
"timestamp": row["timestamp"],
"event_type": row["event_type"],
"error_message": row["error_message"],
}
for row in cursor.fetchall()
]
def is_connected(self) -> tuple[bool, Optional[datetime]]:
"""
Check current connection state based on last event.
Returns:
Tuple of (is_connected, last_event_timestamp)
"""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM connection_events
ORDER BY timestamp DESC
LIMIT 1
""")
row = cursor.fetchone()
if row is None:
return False, None
is_connected = row["event_type"] == "connected"
timestamp = datetime.fromisoformat(row["timestamp"])
return is_connected, timestamp
# =========================================================================
# Schedule Operations
# =========================================================================
def create_schedule(self, schedule: dict) -> int:
"""
Create a new schedule.
Args:
schedule: Dictionary with schedule configuration:
- name: Display name
- schedule_type: 'heat_mode', 'temperature', or 'smart_temp'
- action_value: JSON string or dict with action details
- target_time: "HH:MM" format
- recurrence_type: 'once', 'daily', or 'weekly'
- days_of_week: List of day numbers (0=Mon) for weekly
- enabled: Boolean (default True)
Returns:
ID of created schedule
"""
conn = self._get_connection()
cursor = conn.cursor()
now = datetime.now().isoformat()
# Serialize action_value if it's a dict
action_value = schedule["action_value"]
if isinstance(action_value, dict):
action_value = json.dumps(action_value)
# Serialize days_of_week if provided
days_of_week = schedule.get("days_of_week")
if days_of_week and isinstance(days_of_week, list):
days_of_week = json.dumps(days_of_week)
# Calculate initial next_run
next_run = self._calculate_next_run(
schedule["target_time"],
schedule["recurrence_type"],
days_of_week,
)
cursor.execute("""
INSERT INTO schedules (
name, enabled, schedule_type, action_value,
target_time, recurrence_type, days_of_week,
next_run, smart_start_offset_minutes,
created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
schedule["name"],
1 if schedule.get("enabled", True) else 0,
schedule["schedule_type"],
action_value,
schedule["target_time"],
schedule["recurrence_type"],
days_of_week,
next_run.isoformat() if next_run else None,
schedule.get("smart_start_offset_minutes"),
now,
now,
))
conn.commit()
return cursor.lastrowid
def get_schedules(self, enabled_only: bool = False) -> list[dict]:
"""
Get all schedules.
Args:
enabled_only: If True, only return enabled schedules
Returns:
List of schedule dictionaries
"""
conn = self._get_connection()
cursor = conn.cursor()
if enabled_only:
cursor.execute(
"SELECT * FROM schedules WHERE enabled = 1 ORDER BY target_time"
)
else:
cursor.execute("SELECT * FROM schedules ORDER BY target_time")
return [self._row_to_schedule(row) for row in cursor.fetchall()]
def get_schedule(self, schedule_id: int) -> Optional[dict]:
"""Get a single schedule by ID."""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM schedules WHERE id = ?", (schedule_id,))
row = cursor.fetchone()
if row is None:
return None
return self._row_to_schedule(row)
def get_due_schedules(self) -> list[dict]:
"""
Get schedules that are due to execute (next_run <= now).
Returns:
List of schedule dictionaries ready to execute
"""
conn = self._get_connection()
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute("""
SELECT * FROM schedules
WHERE enabled = 1 AND next_run IS NOT NULL AND next_run <= ?
ORDER BY next_run
""", (now,))
return [self._row_to_schedule(row) for row in cursor.fetchall()]
def update_schedule(self, schedule_id: int, updates: dict):
"""
Update an existing schedule.
Args:
schedule_id: ID of schedule to update
updates: Dictionary of fields to update
"""
conn = self._get_connection()
cursor = conn.cursor()
# Build update query dynamically
allowed_fields = {
"name", "enabled", "schedule_type", "action_value",
"target_time", "recurrence_type", "days_of_week",
"next_run", "smart_start_offset_minutes"
}
set_clauses = []
values = []
for field, value in updates.items():
if field not in allowed_fields:
continue
# Serialize if needed
if field == "action_value" and isinstance(value, dict):
value = json.dumps(value)
elif field == "days_of_week" and isinstance(value, list):
value = json.dumps(value)
elif field == "enabled":
value = 1 if value else 0
set_clauses.append(f"{field} = ?")
values.append(value)
if not set_clauses:
return
# Add updated_at
set_clauses.append("updated_at = ?")
values.append(datetime.now().isoformat())
# Add schedule_id for WHERE clause
values.append(schedule_id)
cursor.execute(f"""
UPDATE schedules
SET {', '.join(set_clauses)}
WHERE id = ?
""", values)
# Recalculate next_run if timing changed
if any(f in updates for f in ["target_time", "recurrence_type", "days_of_week"]):
schedule = self.get_schedule(schedule_id)
if schedule:
next_run = self._calculate_next_run(
schedule["target_time"],
schedule["recurrence_type"],
schedule.get("days_of_week"),
)
cursor.execute(
"UPDATE schedules SET next_run = ? WHERE id = ?",
(next_run.isoformat() if next_run else None, schedule_id)
)
conn.commit()
def delete_schedule(self, schedule_id: int):
"""Delete a schedule and its execution history."""
conn = self._get_connection()
cursor = conn.cursor()
# Cascade delete will handle executions due to foreign key
cursor.execute("DELETE FROM schedules WHERE id = ?", (schedule_id,))
conn.commit()
def _row_to_schedule(self, row: sqlite3.Row) -> dict:
"""Convert database row to schedule dictionary."""
days_of_week = None
if row["days_of_week"]:
days_of_week = json.loads(row["days_of_week"])
action_value = row["action_value"]
try:
action_value = json.loads(action_value)
except (json.JSONDecodeError, TypeError):
pass
return {
"id": row["id"],
"name": row["name"],
"enabled": bool(row["enabled"]),
"schedule_type": row["schedule_type"],
"action_value": action_value,
"target_time": row["target_time"],
"recurrence_type": row["recurrence_type"],
"days_of_week": days_of_week,
"next_run": row["next_run"],
"smart_start_offset_minutes": row["smart_start_offset_minutes"],
"created_at": row["created_at"],
"updated_at": row["updated_at"],
}
def _calculate_next_run(
self,
target_time: str,
recurrence_type: str,
days_of_week: Optional[str] = None,
) -> Optional[datetime]:
"""
Calculate the next run time for a schedule.
Args:
target_time: "HH:MM" format
recurrence_type: 'once', 'daily', or 'weekly'
days_of_week: JSON string of day numbers for weekly
Returns:
datetime of next scheduled run
"""
if recurrence_type == "once":
# For one-time schedules, return None after execution
# Initial creation should set to today/tomorrow at target_time
pass
try:
hour, minute = map(int, target_time.split(":"))
except ValueError:
return None
now = datetime.now()
today_target = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
if recurrence_type == "once":
# If target time today hasn't passed, use today; otherwise tomorrow
if today_target > now:
return today_target
return today_target + timedelta(days=1)
elif recurrence_type == "daily":
if today_target > now:
return today_target
return today_target + timedelta(days=1)
elif recurrence_type == "weekly":
if not days_of_week:
return None
try:
if isinstance(days_of_week, str):
days = json.loads(days_of_week)
else:
days = days_of_week
except (json.JSONDecodeError, TypeError):
return None
if not days:
return None
# Python weekday: Monday=0, Sunday=6
current_weekday = now.weekday()
# Find next matching day
for i in range(7):
check_day = (current_weekday + i) % 7
if check_day in days:
candidate = today_target + timedelta(days=i)
if candidate > now:
return candidate
# Wrap to next week
for day in sorted(days):
days_until = (day - current_weekday) % 7
if days_until == 0:
days_until = 7
return today_target + timedelta(days=days_until)
return None
def advance_schedule(self, schedule_id: int):
"""
Calculate and set next_run after a schedule executes.
Args:
schedule_id: ID of executed schedule
"""
schedule = self.get_schedule(schedule_id)
if not schedule:
return
if schedule["recurrence_type"] == "once":
# One-time schedule - disable it
self.update_schedule(schedule_id, {"enabled": False, "next_run": None})
else:
# Recurring - calculate next run
next_run = self._calculate_next_run(
schedule["target_time"],
schedule["recurrence_type"],
schedule.get("days_of_week"),
)
self.update_schedule(
schedule_id,
{"next_run": next_run.isoformat() if next_run else None}
)
# =========================================================================
# Schedule Execution History
# =========================================================================
def record_execution(
self,
schedule_id: int,
status: str,
message: Optional[str] = None,
starting_temp: Optional[float] = None
) -> int:
"""
Record a schedule execution attempt.
Args:
schedule_id: ID of the executed schedule
status: 'pending', 'executed', 'failed', or 'skipped'
message: Result message or error details
starting_temp: Temperature when execution started (for smart_temp)
Returns:
ID of created execution record
"""
conn = self._get_connection()
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute("""
INSERT INTO schedule_executions (
schedule_id, scheduled_time, executed_at, status,
result_message, starting_temp
) VALUES (?, ?, ?, ?, ?, ?)
""", (
schedule_id,
now, # scheduled_time
now if status in ("executed", "failed") else None,
status,
message,
starting_temp,
))
conn.commit()
return cursor.lastrowid
def get_execution_history(
self,
schedule_id: Optional[int] = None,
limit: int = 50
) -> list[dict]:
"""
Get schedule execution history.
Args:
schedule_id: If provided, filter to specific schedule
limit: Maximum number of records to return
Returns:
List of execution records, newest first
"""
conn = self._get_connection()
cursor = conn.cursor()
if schedule_id:
cursor.execute("""
SELECT e.*, s.name as schedule_name
FROM schedule_executions e
JOIN schedules s ON e.schedule_id = s.id
WHERE e.schedule_id = ?
ORDER BY e.scheduled_time DESC
LIMIT ?
""", (schedule_id, limit))
else:
cursor.execute("""
SELECT e.*, s.name as schedule_name
FROM schedule_executions e
JOIN schedules s ON e.schedule_id = s.id
ORDER BY e.scheduled_time DESC
LIMIT ?
""", (limit,))
return [
{
"id": row["id"],
"schedule_id": row["schedule_id"],
"schedule_name": row["schedule_name"],
"scheduled_time": row["scheduled_time"],
"executed_at": row["executed_at"],
"status": row["status"],
"result_message": row["result_message"],
"starting_temp": row["starting_temp"],
}
for row in cursor.fetchall()
]
def cleanup_old_executions(self, days: int = 90) -> int:
"""
Delete execution history older than specified days.
Args:
days: Number of days to retain
Returns:
Number of rows deleted
"""
conn = self._get_connection()
cursor = conn.cursor()
cutoff = datetime.now() - timedelta(days=days)
cursor.execute(
"DELETE FROM schedule_executions WHERE scheduled_time < ?",
(cutoff.isoformat(),)
)
deleted = cursor.rowcount
conn.commit()
return deleted
# =========================================================================
# Command Queue Operations
# =========================================================================
def queue_command(
self,
command_type: str,
endpoint: str,
data: dict = None,
source: str = "user"
) -> int:
"""
Add a command to the queue for later execution.
Args:
command_type: Type of command (temperature, heat_mode, temp_range, pump, light, etc.)
endpoint: API endpoint the command targets
data: Command data/parameters
source: 'user' for manual commands, 'schedule' for scheduled commands
Returns:
Row ID of queued command
"""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("""
INSERT INTO command_queue (command_type, endpoint, data_json, source, created_at, status)
VALUES (?, ?, ?, ?, ?, 'pending')
""", (
command_type,
endpoint,
json.dumps(data) if data else None,
source,
datetime.now().isoformat(),
))
conn.commit()
return cursor.lastrowid
def get_pending_commands(self) -> list[dict]:
"""Get all pending commands in queue order."""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT id, command_type, endpoint, data_json, source, created_at
FROM command_queue
WHERE status = 'pending'
ORDER BY created_at ASC
""")
commands = []
for row in cursor.fetchall():
commands.append({
"id": row["id"],
"command_type": row["command_type"],
"endpoint": row["endpoint"],
"data": json.loads(row["data_json"]) if row["data_json"] else None,
"source": row["source"],
"created_at": row["created_at"],
})
return commands
def mark_command_executed(self, command_id: int):
"""Mark a queued command as executed."""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("""
UPDATE command_queue
SET status = 'executed', executed_at = ?
WHERE id = ?
""", (datetime.now().isoformat(), command_id))
conn.commit()
def mark_command_failed(self, command_id: int, error: str):
"""Mark a queued command as failed."""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("""
UPDATE command_queue
SET status = 'failed', executed_at = ?, error_message = ?
WHERE id = ?
""", (datetime.now().isoformat(), error, command_id))
conn.commit()
def cancel_command(self, command_id: int) -> bool:
"""Cancel a pending command. Returns True if cancelled, False if not found or not pending."""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("""
UPDATE command_queue
SET status = 'cancelled', executed_at = ?
WHERE id = ? AND status = 'pending'
""", (datetime.now().isoformat(), command_id))
conn.commit()
return cursor.rowcount > 0
def get_command_history(self, limit: int = 10) -> list[dict]:
"""Get recent command history for audit log."""
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT id, command_type, endpoint, data_json, source, created_at,
status, executed_at, error_message
FROM command_queue
ORDER BY created_at DESC
LIMIT ?
""", (limit,))
commands = []
for row in cursor.fetchall():
commands.append({
"id": row["id"],
"command_type": row["command_type"],
"endpoint": row["endpoint"],
"data": json.loads(row["data_json"]) if row["data_json"] else None,
"source": row["source"],
"created_at": row["created_at"],
"status": row["status"],
"executed_at": row["executed_at"],
"error_message": row["error_message"],
})
return commands
def cleanup_old_commands(self, days: int = 7) -> int:
"""Delete command history older than specified days."""
conn = self._get_connection()
cursor = conn.cursor()