"""Charging-session store — who charged, when, and how many kWh. SQLite (stdlib) in sessions.db next to this module. Two tables: sessions — one row per transaction: cp, connector, idTag, resolved "who", start/end timestamps (charger-reported), meter readings, Wh, reason samples — per-minute MeterValues while charging (energy/power/SoC) for later charts The events.jsonl journal (journal.py) stays the raw ground truth; this is the queryable view. Transaction ids come from MAX(tx)+1 here, so they survive backend restarts (the in-memory counter used to reset to 0). sqlite3 connections are cheap at household scale — one per call, no pooling. """ import sqlite3 from contextlib import closing from pathlib import Path from typing import Optional HERE = Path(__file__).resolve().parent DB_PATH = HERE / "sessions.db" _SCHEMA = """ CREATE TABLE IF NOT EXISTS sessions ( tx INTEGER PRIMARY KEY, cp TEXT NOT NULL, connector INTEGER NOT NULL, id_tag TEXT NOT NULL, who TEXT, started TEXT NOT NULL, ended TEXT, meter_start REAL NOT NULL, meter_stop REAL, wh REAL, reason TEXT ); CREATE TABLE IF NOT EXISTS samples ( tx INTEGER NOT NULL, time TEXT NOT NULL, energy_wh REAL, power_w REAL, soc REAL ); CREATE INDEX IF NOT EXISTS idx_samples_tx ON samples (tx); CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions (started); """ def _db(): """Context manager: commits on success AND closes (a bare `with sqlite3 .connect(...)` only commits — the handle would leak).""" con = sqlite3.connect(DB_PATH) con.row_factory = sqlite3.Row con.executescript(_SCHEMA) return closing(con) def max_tx() -> int: with _db() as con, con: row = con.execute("SELECT MAX(tx) AS m FROM sessions").fetchone() return row["m"] or 0 def start_session(tx: int, cp: str, connector: int, id_tag: str, who: str, started: str, meter_start: float) -> None: with _db() as con, con: con.execute( "INSERT OR REPLACE INTO sessions (tx, cp, connector, id_tag, who, started, meter_start)" " VALUES (?, ?, ?, ?, ?, ?, ?)", (tx, cp, connector, id_tag, who, started, meter_start), ) def end_session(tx: int, ended: str, meter_stop: float, reason: Optional[str] = None) -> None: with _db() as con, con: con.execute( "UPDATE sessions SET ended = ?, meter_stop = ?, reason = ?," " wh = ? - meter_start WHERE tx = ?", (ended, meter_stop, reason, meter_stop, tx), ) def add_sample(tx: int, time: str, energy_wh: Optional[float], power_w: Optional[float], soc: Optional[float]) -> None: with _db() as con, con: con.execute( "INSERT INTO samples (tx, time, energy_wh, power_w, soc) VALUES (?, ?, ?, ?, ?)", (tx, time, energy_wh, power_w, soc), ) def get_session(tx: int) -> Optional[dict]: with _db() as con, con: row = con.execute("SELECT * FROM sessions WHERE tx = ?", (tx,)).fetchone() return dict(row) if row else None def open_session(tx: int) -> Optional[dict]: """An unfinished session (e.g. still running after a backend restart).""" with _db() as con, con: row = con.execute( "SELECT * FROM sessions WHERE tx = ? AND ended IS NULL", (tx,) ).fetchone() return dict(row) if row else None def query_sessions(limit: int = 50, cp: Optional[str] = None, connector: Optional[int] = None) -> list: sql, args = "SELECT * FROM sessions", [] where = [] if cp is not None: where.append("cp = ?") args.append(cp) if connector is not None: where.append("connector = ?") args.append(connector) if where: sql += " WHERE " + " AND ".join(where) sql += " ORDER BY tx DESC LIMIT ?" args.append(limit) with _db() as con, con: return [dict(row) for row in con.execute(sql, args)] def samples_for(tx: int) -> list: with _db() as con, con: return [ dict(row) for row in con.execute("SELECT * FROM samples WHERE tx = ? ORDER BY time", (tx,)) ]