Files
charging_station/backend/store.py
T
julian 8d8affe6ff feat(backend): capture voltage, current and sample context in meter samples
The charger sends Voltage/Current.Import in every MeterValues frame but
we only stored energy/power/SoC. samples now also record voltage_v,
current_a and the OCPP context (Sample.Periodic vs Transaction.Begin/End
snapshots, which are legitimately all-zero). Existing dbs migrate via
ALTER TABLE on open.
2026-07-12 09:32:32 +02:00

175 lines
6.0 KiB
Python

"""The one persistent store: SQLite (stdlib) in backend.db next to this module.
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
settings — the app state sections (users, allowlist, relays, chargers,
learn_mode, session_secret) as JSON blobs, one row per section.
Always whole-section reads/writes, so blobs beat normalized
tables here. Managed through config.py — see there.
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.
sqlite3 connections are cheap at household scale — one per call, no pooling.
BACKEND_DB env var overrides the path (used by tests to stay off the real db).
"""
import json
import os
import sqlite3
from contextlib import closing
from pathlib import Path
from typing import Optional
HERE = Path(__file__).resolve().parent
DB_PATH = Path(os.environ.get("BACKEND_DB", HERE / "backend.db"))
_SCHEMA = """
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
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,
method TEXT
);
CREATE TABLE IF NOT EXISTS samples (
tx INTEGER NOT NULL,
time TEXT NOT NULL,
energy_wh REAL,
power_w REAL,
soc REAL,
voltage_v REAL,
current_a REAL,
context TEXT
);
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)
# migrations for dbs created before later columns existed
cols = [row[1] for row in con.execute("PRAGMA table_info(sessions)")]
if "method" not in cols:
con.execute("ALTER TABLE sessions ADD COLUMN method TEXT")
sample_cols = [row[1] for row in con.execute("PRAGMA table_info(samples)")]
for col, ddl in (("voltage_v", "REAL"), ("current_a", "REAL"), ("context", "TEXT")):
if col not in sample_cols:
con.execute(f"ALTER TABLE samples ADD COLUMN {col} {ddl}")
return closing(con)
def load_settings() -> dict:
with _db() as con, con:
return {
row["key"]: json.loads(row["value"])
for row in con.execute("SELECT key, value FROM settings")
}
def save_settings(sections: dict) -> None:
with _db() as con, con:
con.executemany(
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
[(key, json.dumps(value, ensure_ascii=False)) for key, value in sections.items()],
)
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, method: str = "unknown") -> None:
with _db() as con, con:
con.execute(
"INSERT OR REPLACE INTO sessions"
" (tx, cp, connector, id_tag, who, started, meter_start, method)"
" VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(tx, cp, connector, id_tag, who, started, meter_start, method),
)
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] = None,
power_w: Optional[float] = None, soc: Optional[float] = None,
voltage_v: Optional[float] = None, current_a: Optional[float] = None,
context: Optional[str] = None) -> None:
with _db() as con, con:
con.execute(
"INSERT INTO samples (tx, time, energy_wh, power_w, soc, voltage_v, current_a, context)"
" VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(tx, time, energy_wh, power_w, soc, voltage_v, current_a, context),
)
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,))
]