wallmonitor 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wallmonitor/db.py ADDED
@@ -0,0 +1,675 @@
1
+ """SQLite storage for wallmonitor.
2
+
3
+ Every poll response is stored twice over: the complete raw JSON body from the
4
+ Wall Connector (full fidelity — nothing the device said is ever discarded) and
5
+ a set of extracted columns for fast querying/charting. All timestamps are a
6
+ single clock: host UTC epoch seconds captured the moment the response arrived.
7
+
8
+ sqlite3 is synchronous; call sites in async code wrap these methods in
9
+ asyncio.to_thread. A lock serializes access to the shared connection.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import sqlite3
16
+ import threading
17
+ from typing import Any
18
+
19
+ SCHEMA = """
20
+ CREATE TABLE IF NOT EXISTS vitals_samples (
21
+ id INTEGER PRIMARY KEY,
22
+ ts REAL NOT NULL,
23
+ session_id INTEGER,
24
+ vehicle_connected INTEGER,
25
+ contactor_closed INTEGER,
26
+ session_s INTEGER,
27
+ session_energy_wh REAL,
28
+ grid_v REAL,
29
+ grid_hz REAL,
30
+ vehicle_current_a REAL,
31
+ current_a_a REAL,
32
+ current_b_a REAL,
33
+ current_c_a REAL,
34
+ current_n_a REAL,
35
+ voltage_a_v REAL,
36
+ voltage_b_v REAL,
37
+ voltage_c_v REAL,
38
+ pcba_temp_c REAL,
39
+ handle_temp_c REAL,
40
+ mcu_temp_c REAL,
41
+ evse_state INTEGER,
42
+ config_status INTEGER,
43
+ uptime_s INTEGER,
44
+ total_power_w REAL,
45
+ raw TEXT NOT NULL
46
+ );
47
+ CREATE INDEX IF NOT EXISTS idx_vitals_ts ON vitals_samples(ts);
48
+ CREATE INDEX IF NOT EXISTS idx_vitals_session ON vitals_samples(session_id);
49
+
50
+ CREATE TABLE IF NOT EXISTS wifi_samples (
51
+ id INTEGER PRIMARY KEY,
52
+ ts REAL NOT NULL,
53
+ connected INTEGER,
54
+ internet INTEGER,
55
+ signal_strength INTEGER,
56
+ rssi INTEGER,
57
+ snr INTEGER,
58
+ infra_ip TEXT,
59
+ ssid TEXT,
60
+ mac TEXT,
61
+ raw TEXT NOT NULL
62
+ );
63
+ CREATE INDEX IF NOT EXISTS idx_wifi_ts ON wifi_samples(ts);
64
+
65
+ CREATE TABLE IF NOT EXISTS lifetime_samples (
66
+ id INTEGER PRIMARY KEY,
67
+ ts REAL NOT NULL,
68
+ energy_wh REAL,
69
+ charge_starts INTEGER,
70
+ charging_time_s INTEGER,
71
+ contactor_cycles INTEGER,
72
+ contactor_cycles_loaded INTEGER,
73
+ connector_cycles INTEGER,
74
+ alert_count INTEGER,
75
+ thermal_foldbacks INTEGER,
76
+ avg_startup_temp REAL,
77
+ uptime_s INTEGER,
78
+ raw TEXT NOT NULL
79
+ );
80
+ CREATE INDEX IF NOT EXISTS idx_lifetime_ts ON lifetime_samples(ts);
81
+
82
+ CREATE TABLE IF NOT EXISTS version_info (
83
+ id INTEGER PRIMARY KEY,
84
+ ts REAL NOT NULL,
85
+ firmware_version TEXT,
86
+ part_number TEXT,
87
+ serial_number TEXT,
88
+ git_branch TEXT,
89
+ web_service TEXT,
90
+ raw TEXT NOT NULL
91
+ );
92
+
93
+ CREATE TABLE IF NOT EXISTS sessions (
94
+ id INTEGER PRIMARY KEY,
95
+ start_ts REAL NOT NULL,
96
+ end_ts REAL,
97
+ energy_wh REAL,
98
+ max_power_w REAL,
99
+ avg_power_w REAL,
100
+ charging_s REAL,
101
+ sample_count INTEGER,
102
+ end_reason TEXT
103
+ );
104
+ CREATE INDEX IF NOT EXISTS idx_sessions_start ON sessions(start_ts);
105
+
106
+ CREATE TABLE IF NOT EXISTS alerts (
107
+ id INTEGER PRIMARY KEY,
108
+ alert TEXT NOT NULL,
109
+ source TEXT NOT NULL,
110
+ first_ts REAL NOT NULL,
111
+ last_ts REAL NOT NULL,
112
+ cleared_ts REAL,
113
+ active INTEGER NOT NULL DEFAULT 1
114
+ );
115
+ CREATE INDEX IF NOT EXISTS idx_alerts_active ON alerts(active);
116
+
117
+ CREATE TABLE IF NOT EXISTS events (
118
+ id INTEGER PRIMARY KEY,
119
+ ts REAL NOT NULL,
120
+ kind TEXT NOT NULL,
121
+ detail TEXT
122
+ );
123
+ CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts);
124
+
125
+ CREATE TABLE IF NOT EXISTS settings (
126
+ key TEXT PRIMARY KEY,
127
+ value TEXT NOT NULL
128
+ );
129
+
130
+ CREATE TABLE IF NOT EXISTS forecast_samples (
131
+ id INTEGER PRIMARY KEY,
132
+ ts REAL NOT NULL,
133
+ session_id INTEGER,
134
+ basis TEXT,
135
+ steady_state_c REAL,
136
+ will_trip INTEGER,
137
+ minutes_to_trip REAL,
138
+ trip_ts REAL,
139
+ suggested_max_a REAL,
140
+ handle_c REAL,
141
+ current_a REAL,
142
+ tau_min REAL,
143
+ fit_rmse_c REAL,
144
+ trip_c REAL,
145
+ raw TEXT NOT NULL
146
+ );
147
+ CREATE INDEX IF NOT EXISTS idx_forecast_ts ON forecast_samples(ts);
148
+
149
+ CREATE TABLE IF NOT EXISTS ambient_samples (
150
+ id INTEGER PRIMARY KEY,
151
+ ts REAL NOT NULL,
152
+ temp_c REAL NOT NULL,
153
+ humidity_pct REAL,
154
+ pressure_hpa REAL,
155
+ source TEXT,
156
+ raw TEXT
157
+ );
158
+ CREATE INDEX IF NOT EXISTS idx_ambient_ts ON ambient_samples(ts);
159
+ """
160
+
161
+ VITALS_COLUMNS = {
162
+ # db column -> key in the vitals JSON
163
+ "vehicle_connected": "vehicle_connected",
164
+ "contactor_closed": "contactor_closed",
165
+ "session_s": "session_s",
166
+ "session_energy_wh": "session_energy_wh",
167
+ "grid_v": "grid_v",
168
+ "grid_hz": "grid_hz",
169
+ "vehicle_current_a": "vehicle_current_a",
170
+ "current_a_a": "currentA_a",
171
+ "current_b_a": "currentB_a",
172
+ "current_c_a": "currentC_a",
173
+ "current_n_a": "currentN_a",
174
+ "voltage_a_v": "voltageA_v",
175
+ "voltage_b_v": "voltageB_v",
176
+ "voltage_c_v": "voltageC_v",
177
+ "pcba_temp_c": "pcba_temp_c",
178
+ "handle_temp_c": "handle_temp_c",
179
+ "mcu_temp_c": "mcu_temp_c",
180
+ "evse_state": "evse_state",
181
+ "config_status": "config_status",
182
+ "uptime_s": "uptime_s",
183
+ }
184
+
185
+
186
+ class Database:
187
+ """Thread-safe wrapper around a single SQLite connection."""
188
+
189
+ def __init__(self, path: str):
190
+ """Open (creating if needed) the database and apply the schema.
191
+
192
+ WAL journaling lets the web layer read while the poller writes
193
+ without either blocking; synchronous=NORMAL is durable against an
194
+ app crash (not an OS/power loss mid-checkpoint — acceptable for
195
+ telemetry). The schema is pure CREATE IF NOT EXISTS, re-run on
196
+ every startup: "migrations" are additive statements appended here.
197
+ """
198
+ self._conn = sqlite3.connect(path, check_same_thread=False)
199
+ self._conn.row_factory = sqlite3.Row
200
+ self._lock = threading.Lock()
201
+ with self._lock:
202
+ self._conn.executescript(
203
+ "PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON;"
204
+ )
205
+ self._conn.executescript(SCHEMA)
206
+ self._conn.commit()
207
+
208
+ def close(self) -> None:
209
+ """Close the shared connection. Owner-only: called once at process
210
+ shutdown (__main__, after every writer has stopped) and by test
211
+ fixtures — nothing else should ever call it."""
212
+ with self._lock:
213
+ self._conn.close()
214
+
215
+ def _execute(self, sql: str, params: tuple = ()) -> sqlite3.Cursor:
216
+ """Execute one write statement and commit immediately.
217
+
218
+ The caller must already hold self._lock. Committing per statement
219
+ means every insert is durable before its method returns — there is
220
+ no batching layer to lose samples in."""
221
+ cur = self._conn.execute(sql, params)
222
+ self._conn.commit()
223
+ return cur
224
+
225
+ # ---------- writes ----------
226
+
227
+ def insert_vitals(self, ts: float, raw: dict, session_id: int | None, total_power_w: float | None) -> int:
228
+ """Store one vitals poll: extracted columns (via VITALS_COLUMNS) plus
229
+ the complete raw JSON. Returns the new row id (the SSE frame carries
230
+ it so clients can de-duplicate)."""
231
+ cols = {col: raw.get(json_key) for col, json_key in VITALS_COLUMNS.items()}
232
+ with self._lock:
233
+ cur = self._execute(
234
+ f"""INSERT INTO vitals_samples
235
+ (ts, session_id, total_power_w, raw, {", ".join(cols)})
236
+ VALUES (?, ?, ?, ?, {", ".join("?" for _ in cols)})""",
237
+ (ts, session_id, total_power_w, json.dumps(raw), *cols.values()),
238
+ )
239
+ return cur.lastrowid or 0
240
+
241
+ def insert_wifi(self, ts: float, raw: dict, ssid: str | None = None) -> int:
242
+ """Store a Wi-Fi status sample. Pass ssid to override the column with
243
+ a decoded value (firmware reports it base64-encoded); the raw JSON
244
+ keeps the original either way."""
245
+ with self._lock:
246
+ cur = self._execute(
247
+ """INSERT INTO wifi_samples
248
+ (ts, connected, internet, signal_strength, rssi, snr, infra_ip, ssid, mac, raw)
249
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
250
+ (
251
+ ts,
252
+ raw.get("wifi_connected"),
253
+ raw.get("internet"),
254
+ raw.get("wifi_signal_strength"),
255
+ raw.get("wifi_rssi"),
256
+ raw.get("wifi_snr"),
257
+ raw.get("wifi_infra_ip"),
258
+ ssid if ssid is not None else raw.get("wifi_ssid"),
259
+ raw.get("wifi_mac"),
260
+ json.dumps(raw),
261
+ ),
262
+ )
263
+ return cur.lastrowid or 0
264
+
265
+ def insert_lifetime(self, ts: float, raw: dict) -> int:
266
+ with self._lock:
267
+ cur = self._execute(
268
+ """INSERT INTO lifetime_samples
269
+ (ts, energy_wh, charge_starts, charging_time_s, contactor_cycles,
270
+ contactor_cycles_loaded, connector_cycles, alert_count, thermal_foldbacks,
271
+ avg_startup_temp, uptime_s, raw)
272
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
273
+ (
274
+ ts,
275
+ raw.get("energy_wh"),
276
+ raw.get("charge_starts"),
277
+ raw.get("charging_time_s"),
278
+ raw.get("contactor_cycles"),
279
+ raw.get("contactor_cycles_loaded"),
280
+ raw.get("connector_cycles"),
281
+ raw.get("alert_count"),
282
+ raw.get("thermal_foldbacks"),
283
+ raw.get("avg_startup_temp"),
284
+ raw.get("uptime_s"),
285
+ json.dumps(raw),
286
+ ),
287
+ )
288
+ return cur.lastrowid or 0
289
+
290
+ def insert_version(self, ts: float, raw: dict) -> int:
291
+ with self._lock:
292
+ cur = self._execute(
293
+ """INSERT INTO version_info
294
+ (ts, firmware_version, part_number, serial_number, git_branch, web_service, raw)
295
+ VALUES (?, ?, ?, ?, ?, ?, ?)""",
296
+ (
297
+ ts,
298
+ raw.get("firmware_version"),
299
+ raw.get("part_number"),
300
+ raw.get("serial_number"),
301
+ raw.get("git_branch"),
302
+ raw.get("web_service"),
303
+ json.dumps(raw),
304
+ ),
305
+ )
306
+ return cur.lastrowid or 0
307
+
308
+ def add_event(self, ts: float, kind: str, detail: dict | None = None) -> int:
309
+ """Append to the event log. detail is stored as JSON text; an empty
310
+ dict stores NULL. Writers: the poller (via _event), the web layer's
311
+ amp-controller ingest, and startup/shutdown bookkeeping."""
312
+ with self._lock:
313
+ cur = self._execute(
314
+ "INSERT INTO events (ts, kind, detail) VALUES (?, ?, ?)",
315
+ (ts, kind, json.dumps(detail) if detail else None),
316
+ )
317
+ return cur.lastrowid or 0
318
+
319
+ def start_session(self, start_ts: float) -> int:
320
+ """Open a charging session (plug-in detected). start_ts may predate
321
+ 'now': the poller backdates it from the charger's own session timer
322
+ when monitoring begins mid-session. Aggregates stay NULL until
323
+ close_session computes them."""
324
+ with self._lock:
325
+ cur = self._execute("INSERT INTO sessions (start_ts) VALUES (?)", (start_ts,))
326
+ return cur.lastrowid or 0
327
+
328
+ def close_session(self, session_id: int, end_ts: float, end_reason: str) -> None:
329
+ """Close a session and compute its aggregates from recorded samples."""
330
+ with self._lock:
331
+ agg = self._conn.execute(
332
+ """SELECT COUNT(*) AS n, MAX(total_power_w) AS max_p, AVG(total_power_w) AS avg_p,
333
+ MAX(session_energy_wh) AS energy
334
+ FROM vitals_samples WHERE session_id = ?""",
335
+ (session_id,),
336
+ ).fetchone()
337
+ charging = self._conn.execute(
338
+ """SELECT COALESCE(SUM(dt), 0) AS s FROM (
339
+ SELECT ts - LAG(ts) OVER (ORDER BY ts) AS dt,
340
+ LAG(contactor_closed) OVER (ORDER BY ts) AS prev_cc
341
+ FROM vitals_samples WHERE session_id = ?
342
+ ) WHERE prev_cc = 1 AND dt IS NOT NULL AND dt < 120""",
343
+ (session_id,),
344
+ ).fetchone()
345
+ self._execute(
346
+ """UPDATE sessions SET end_ts = ?, end_reason = ?, sample_count = ?,
347
+ max_power_w = ?, avg_power_w = ?, energy_wh = ?, charging_s = ?
348
+ WHERE id = ?""",
349
+ (
350
+ end_ts,
351
+ end_reason,
352
+ agg["n"],
353
+ agg["max_p"],
354
+ agg["avg_p"],
355
+ agg["energy"],
356
+ charging["s"],
357
+ session_id,
358
+ ),
359
+ )
360
+
361
+ def open_session_id(self) -> int | None:
362
+ """Newest session with no end_ts, if any — how a restart discovers a
363
+ session the previous run left open."""
364
+ with self._lock:
365
+ row = self._conn.execute("SELECT id FROM sessions WHERE end_ts IS NULL ORDER BY id DESC LIMIT 1").fetchone()
366
+ return row["id"] if row else None
367
+
368
+ def raise_alert(self, ts: float, alert: str, source: str) -> tuple[int, bool]:
369
+ """Mark an alert active. Returns (alert_id, newly_raised)."""
370
+ with self._lock:
371
+ row = self._conn.execute(
372
+ "SELECT id FROM alerts WHERE alert = ? AND source = ? AND active = 1", (alert, source)
373
+ ).fetchone()
374
+ if row:
375
+ self._execute("UPDATE alerts SET last_ts = ? WHERE id = ?", (ts, row["id"]))
376
+ return row["id"], False
377
+ cur = self._execute(
378
+ "INSERT INTO alerts (alert, source, first_ts, last_ts, active) VALUES (?, ?, ?, ?, 1)",
379
+ (alert, source, ts, ts),
380
+ )
381
+ return cur.lastrowid or 0, True
382
+
383
+ def clear_alert(self, ts: float, alert: str, source: str) -> bool:
384
+ """Deactivate an alert. Returns True only if an active row was
385
+ actually cleared — callers use that edge to fire *_cleared events
386
+ exactly once instead of on every poll."""
387
+ with self._lock:
388
+ cur = self._execute(
389
+ "UPDATE alerts SET active = 0, cleared_ts = ?, last_ts = ? WHERE alert = ? AND source = ? AND active = 1",
390
+ (ts, ts, alert, source),
391
+ )
392
+ return cur.rowcount > 0
393
+
394
+ def insert_forecast(self, ts: float, out: dict, session_id: int | None = None) -> int:
395
+ """Store one computed derate forecast (the poller's 30 s tick while
396
+ charging) — the same values the amp controller acts on. Extracted
397
+ columns plus the complete payload as raw JSON, like every other
398
+ sample table."""
399
+ forecast = out.get("forecast") or {}
400
+ model = out.get("model") or {}
401
+ will_trip = forecast.get("will_trip")
402
+ with self._lock:
403
+ cur = self._execute(
404
+ """INSERT INTO forecast_samples
405
+ (ts, session_id, basis, steady_state_c, will_trip, minutes_to_trip,
406
+ trip_ts, suggested_max_a, handle_c, current_a, tau_min, fit_rmse_c, trip_c, raw)
407
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
408
+ (
409
+ ts,
410
+ session_id,
411
+ forecast.get("basis"),
412
+ forecast.get("steady_state_c"),
413
+ None if will_trip is None else int(will_trip),
414
+ forecast.get("minutes_to_trip"),
415
+ forecast.get("trip_ts"),
416
+ forecast.get("suggested_max_a"),
417
+ out.get("handle_c"),
418
+ out.get("current_a"),
419
+ model.get("tau_min"),
420
+ model.get("fit_rmse_c"),
421
+ model.get("trip_c"),
422
+ json.dumps(out),
423
+ ),
424
+ )
425
+ return cur.lastrowid or 0
426
+
427
+ def forecast_range(self, t_from: float, t_to: float, limit: int = 2000) -> list[dict]:
428
+ """Forecast snapshots in a window, oldest first, columns only (the
429
+ raw payload stays queryable but is not shipped to the chart)."""
430
+ return self._rows(
431
+ """SELECT ts, session_id, basis, steady_state_c, will_trip, minutes_to_trip,
432
+ trip_ts, suggested_max_a, handle_c, current_a, tau_min, fit_rmse_c, trip_c
433
+ FROM forecast_samples WHERE ts >= ? AND ts <= ? ORDER BY ts LIMIT ?""",
434
+ (t_from, t_to, limit),
435
+ )
436
+
437
+ def insert_ambient(self, ts: float, temp_c: float, humidity_pct: float | None = None,
438
+ pressure_hpa: float | None = None, raw: dict | None = None,
439
+ source: str | None = None) -> int:
440
+ with self._lock:
441
+ cur = self._execute(
442
+ "INSERT INTO ambient_samples (ts, temp_c, humidity_pct, pressure_hpa, raw, source) "
443
+ "VALUES (?, ?, ?, ?, ?, ?)",
444
+ (ts, temp_c, humidity_pct, pressure_hpa, json.dumps(raw) if raw else None, source),
445
+ )
446
+ return cur.lastrowid
447
+
448
+ def ambient_range(self, t_from: float, t_to: float, limit: int = 5000) -> list[dict]:
449
+ """Ambient samples in a window, oldest first. Caveat: a window with
450
+ more rows than limit keeps the *oldest* rows and silently drops the
451
+ newest (ORDER BY ts + LIMIT) — harmless at the 1/min sensor cadence
452
+ (5000 ≈ 3.5 days) but wrong for a naive "latest" query; use
453
+ latest_ambient for that."""
454
+ return self._rows(
455
+ "SELECT ts, temp_c, humidity_pct, pressure_hpa, source FROM ambient_samples "
456
+ "WHERE ts >= ? AND ts <= ? ORDER BY ts LIMIT ?",
457
+ (t_from, t_to, limit),
458
+ )
459
+
460
+ def latest_ambient(self) -> dict | None:
461
+ """Newest ambient row regardless of source — no stationary-beats-car
462
+ tiering here; callers that need the tier use thermal's readers."""
463
+ rows = self._rows(
464
+ "SELECT ts, temp_c, humidity_pct, pressure_hpa, source FROM ambient_samples "
465
+ "ORDER BY ts DESC LIMIT 1"
466
+ )
467
+ return rows[0] if rows else None
468
+
469
+ def set_setting(self, key: str, value: str) -> None:
470
+ """Upsert into the string key/value settings table (currently only
471
+ the thermal baseline anchor lives here)."""
472
+ with self._lock:
473
+ self._execute(
474
+ "INSERT INTO settings(key, value) VALUES (?, ?) "
475
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
476
+ (key, value),
477
+ )
478
+
479
+ def get_setting(self, key: str) -> str | None:
480
+ rows = self._rows("SELECT value FROM settings WHERE key = ?", (key,))
481
+ return rows[0]["value"] if rows else None
482
+
483
+ def delete_setting(self, key: str) -> None:
484
+ with self._lock:
485
+ self._execute("DELETE FROM settings WHERE key = ?", (key,))
486
+
487
+ def active_alerts(self) -> list[dict]:
488
+ with self._lock:
489
+ rows = self._conn.execute(
490
+ "SELECT * FROM alerts WHERE active = 1 ORDER BY first_ts DESC"
491
+ ).fetchall()
492
+ return [dict(row) for row in rows]
493
+
494
+ # ---------- reads ----------
495
+
496
+ def _rows(self, sql: str, params: tuple = ()) -> list[dict]:
497
+ """Run a read query under the lock, returning plain dicts — detached
498
+ from the cursor and directly JSON-serializable by the web layer."""
499
+ with self._lock:
500
+ return [dict(row) for row in self._conn.execute(sql, params).fetchall()]
501
+
502
+ def latest_vitals(self) -> dict | None:
503
+ rows = self._rows("SELECT * FROM vitals_samples ORDER BY ts DESC LIMIT 1")
504
+ return rows[0] if rows else None
505
+
506
+ def latest_wifi(self) -> dict | None:
507
+ rows = self._rows("SELECT * FROM wifi_samples ORDER BY ts DESC LIMIT 1")
508
+ return rows[0] if rows else None
509
+
510
+ def latest_lifetime(self) -> dict | None:
511
+ rows = self._rows("SELECT * FROM lifetime_samples ORDER BY ts DESC LIMIT 1")
512
+ return rows[0] if rows else None
513
+
514
+ def latest_version(self) -> dict | None:
515
+ rows = self._rows("SELECT * FROM version_info ORDER BY ts DESC LIMIT 1")
516
+ return rows[0] if rows else None
517
+
518
+ def vitals_range(self, t_from: float, t_to: float, max_points: int = 1500) -> list[dict]:
519
+ """Vitals samples in a range, bucket-averaged down to at most max_points."""
520
+ sample_count = self._rows(
521
+ "SELECT COUNT(*) AS n FROM vitals_samples WHERE ts >= ? AND ts <= ?", (t_from, t_to)
522
+ )[0]["n"]
523
+ # The device reports 255 (0xFF) for a temperature when the sensor read
524
+ # is momentarily invalid (seen on the handle during connector state
525
+ # transitions). Raw JSON keeps the sentinel; interpreted queries
526
+ # return NULL instead so charts and averages are never poisoned.
527
+ temp = "CASE WHEN {col} >= 255 THEN NULL ELSE {col} END"
528
+ t_pcba, t_handle, t_mcu = (
529
+ temp.format(col=col) for col in ("pcba_temp_c", "handle_temp_c", "mcu_temp_c")
530
+ )
531
+ # Handshake diagnostics live only in the raw JSON; json_extract makes
532
+ # them chartable retroactively for every sample ever recorded.
533
+ diag = """json_extract(raw, '$.pilot_high_v') AS pilot_high_v,
534
+ json_extract(raw, '$.pilot_low_v') AS pilot_low_v,
535
+ json_extract(raw, '$.prox_v') AS prox_v,
536
+ COALESCE(json_extract(raw, '$.relay_k1_v'), json_extract(raw, '$.relay_coil_v')) AS relay_k1_v,
537
+ json_extract(raw, '$.relay_k2_v') AS relay_k2_v"""
538
+ if sample_count <= max_points:
539
+ return self._rows(
540
+ f"""SELECT ts, total_power_w, vehicle_current_a, current_a_a, current_b_a, current_c_a,
541
+ voltage_a_v, voltage_b_v, voltage_c_v, grid_v, grid_hz,
542
+ {t_pcba} AS pcba_temp_c, {t_handle} AS handle_temp_c, {t_mcu} AS mcu_temp_c,
543
+ session_energy_wh,
544
+ vehicle_connected, contactor_closed, evse_state, session_id,
545
+ {diag}
546
+ FROM vitals_samples WHERE ts >= ? AND ts <= ? ORDER BY ts""",
547
+ (t_from, t_to),
548
+ )
549
+ width = (t_to - t_from) / max_points
550
+ return self._rows(
551
+ f"""SELECT MIN(ts) AS ts, AVG(total_power_w) AS total_power_w, MAX(total_power_w) AS max_power_w,
552
+ AVG(vehicle_current_a) AS vehicle_current_a,
553
+ AVG(current_a_a) AS current_a_a, AVG(current_b_a) AS current_b_a,
554
+ AVG(current_c_a) AS current_c_a,
555
+ AVG(voltage_a_v) AS voltage_a_v, AVG(voltage_b_v) AS voltage_b_v,
556
+ AVG(voltage_c_v) AS voltage_c_v,
557
+ AVG(grid_v) AS grid_v, AVG(grid_hz) AS grid_hz,
558
+ AVG({t_pcba}) AS pcba_temp_c, AVG({t_handle}) AS handle_temp_c,
559
+ AVG({t_mcu}) AS mcu_temp_c,
560
+ MAX(session_energy_wh) AS session_energy_wh,
561
+ MAX(vehicle_connected) AS vehicle_connected,
562
+ MAX(contactor_closed) AS contactor_closed,
563
+ MAX(evse_state) AS evse_state, MAX(session_id) AS session_id,
564
+ AVG(json_extract(raw, '$.pilot_high_v')) AS pilot_high_v,
565
+ AVG(json_extract(raw, '$.pilot_low_v')) AS pilot_low_v,
566
+ AVG(json_extract(raw, '$.prox_v')) AS prox_v,
567
+ AVG(COALESCE(json_extract(raw, '$.relay_k1_v'), json_extract(raw, '$.relay_coil_v'))) AS relay_k1_v,
568
+ AVG(json_extract(raw, '$.relay_k2_v')) AS relay_k2_v
569
+ FROM vitals_samples WHERE ts >= ? AND ts <= ?
570
+ GROUP BY CAST((ts - ?) / ? AS INTEGER) ORDER BY ts""",
571
+ (t_from, t_to, t_from, width),
572
+ )
573
+
574
+ def lifetime_range(self, t_from: float, t_to: float, max_points: int = 3000) -> list[dict]:
575
+ """Lifetime counter samples in a range (counters are monotonic, so
576
+ buckets keep the last/max value)."""
577
+ sample_count = self._rows(
578
+ "SELECT COUNT(*) AS n FROM lifetime_samples WHERE ts >= ? AND ts <= ?", (t_from, t_to)
579
+ )[0]["n"]
580
+ if sample_count <= max_points:
581
+ return self._rows(
582
+ """SELECT ts, energy_wh, charge_starts, charging_time_s
583
+ FROM lifetime_samples WHERE ts >= ? AND ts <= ? ORDER BY ts""",
584
+ (t_from, t_to),
585
+ )
586
+ width = (t_to - t_from) / max_points
587
+ return self._rows(
588
+ """SELECT MAX(ts) AS ts, MAX(energy_wh) AS energy_wh,
589
+ MAX(charge_starts) AS charge_starts, MAX(charging_time_s) AS charging_time_s
590
+ FROM lifetime_samples WHERE ts >= ? AND ts <= ?
591
+ GROUP BY CAST((ts - ?) / ? AS INTEGER) ORDER BY ts""",
592
+ (t_from, t_to, t_from, width),
593
+ )
594
+
595
+ def wifi_range(self, t_from: float, t_to: float, max_points: int = 1000) -> list[dict]:
596
+ """Wi-Fi samples in a range, bucket-averaged down to max_points.
597
+ Buckets take MIN(connected)/MIN(internet) so a dropout anywhere in a
598
+ bucket stays visible instead of averaging away."""
599
+ sample_count = self._rows(
600
+ "SELECT COUNT(*) AS n FROM wifi_samples WHERE ts >= ? AND ts <= ?", (t_from, t_to)
601
+ )[0]["n"]
602
+ if sample_count <= max_points:
603
+ return self._rows(
604
+ """SELECT ts, connected, internet, signal_strength, rssi, snr
605
+ FROM wifi_samples WHERE ts >= ? AND ts <= ? ORDER BY ts""",
606
+ (t_from, t_to),
607
+ )
608
+ width = (t_to - t_from) / max_points
609
+ return self._rows(
610
+ """SELECT MIN(ts) AS ts, MIN(connected) AS connected, MIN(internet) AS internet,
611
+ AVG(signal_strength) AS signal_strength, AVG(rssi) AS rssi, AVG(snr) AS snr
612
+ FROM wifi_samples WHERE ts >= ? AND ts <= ?
613
+ GROUP BY CAST((ts - ?) / ? AS INTEGER) ORDER BY ts""",
614
+ (t_from, t_to, t_from, width),
615
+ )
616
+
617
+ def sessions_range(self, t_from: float, t_to: float) -> list[dict]:
618
+ """Sessions overlapping [t_from, t_to], newest first. A still-open
619
+ session (end_ts NULL) is treated as extending to t_to, so a live
620
+ session always shows in a "recent" query."""
621
+ return self._rows(
622
+ """SELECT * FROM sessions
623
+ WHERE start_ts <= ? AND COALESCE(end_ts, ?) >= ?
624
+ ORDER BY start_ts DESC""",
625
+ (t_to, t_to, t_from),
626
+ )
627
+
628
+ def session(self, session_id: int) -> dict | None:
629
+ rows = self._rows("SELECT * FROM sessions WHERE id = ?", (session_id,))
630
+ return rows[0] if rows else None
631
+
632
+ def alerts_range(self, t_from: float, t_to: float) -> list[dict]:
633
+ """Alerts whose active span [first_ts, last_ts] overlaps the window,
634
+ active ones first, then newest first."""
635
+ return self._rows(
636
+ """SELECT * FROM alerts WHERE last_ts >= ? AND first_ts <= ?
637
+ ORDER BY active DESC, first_ts DESC""",
638
+ (t_from, t_to),
639
+ )
640
+
641
+ def events_range(self, t_from: float, t_to: float, kinds: list[str] | None = None, limit: int = 2000) -> list[dict]:
642
+ """Events in a window, newest first, optionally filtered to specific
643
+ kinds. Unlike ambient_range, the limit here keeps the *newest* rows
644
+ (DESC order), which is what a timeline wants."""
645
+ if kinds:
646
+ marks = ",".join("?" for _ in kinds)
647
+ return self._rows(
648
+ f"SELECT * FROM events WHERE ts >= ? AND ts <= ? AND kind IN ({marks}) ORDER BY ts DESC LIMIT ?",
649
+ (t_from, t_to, *kinds, limit),
650
+ )
651
+ return self._rows(
652
+ "SELECT * FROM events WHERE ts >= ? AND ts <= ? ORDER BY ts DESC LIMIT ?",
653
+ (t_from, t_to, limit),
654
+ )
655
+
656
+ def last_activity_ts(self) -> float | None:
657
+ """Timestamp of the most recent recorded sample or event, if any."""
658
+ rows = self._rows(
659
+ """SELECT MAX(ts) AS ts FROM (
660
+ SELECT MAX(ts) AS ts FROM vitals_samples
661
+ UNION ALL SELECT MAX(ts) FROM events
662
+ )"""
663
+ )
664
+ return rows[0]["ts"] if rows and rows[0]["ts"] is not None else None
665
+
666
+ def counts(self) -> dict[str, Any]:
667
+ """Row counts for the dashboard footer ("N vitals samples · …")."""
668
+ return {
669
+ "vitals_samples": self._rows("SELECT COUNT(*) AS n FROM vitals_samples")[0]["n"],
670
+ "wifi_samples": self._rows("SELECT COUNT(*) AS n FROM wifi_samples")[0]["n"],
671
+ "lifetime_samples": self._rows("SELECT COUNT(*) AS n FROM lifetime_samples")[0]["n"],
672
+ "sessions": self._rows("SELECT COUNT(*) AS n FROM sessions")[0]["n"],
673
+ "events": self._rows("SELECT COUNT(*) AS n FROM events")[0]["n"],
674
+ "alerts": self._rows("SELECT COUNT(*) AS n FROM alerts")[0]["n"],
675
+ }