feat(backend): production backend — CSMS, multi-user auth, relays, session store, web panel
One FastAPI process on port 9000 (the charger's hardcoded URL), replacing
discovering/station.py for production:
- csms.py: OCPP 1.6J handlers ported from the proven discovery code; the
decide() gate now supports per-gun RFID restriction ("connectors": [2])
enforced at StartTransaction
- users.py: username/password auth (PBKDF2), stateless HMAC sessions
(cookie + bearer, 30 days), fnmatch permission scopes
(charger:<cp>:<gun>, relay:<name>, admin) and a user CLI
- relays.py: local tinytuya control of the SmartLife/Tuya WiFi relays
(no cloud; needs one-time id/local-key extraction via tinytuya wizard)
- store.py: SQLite consumption tracking — who charged, when, how many kWh,
per-minute energy/power/SoC samples; tx ids survive restarts
- routes.py: /api/* with per-scope checks, allowlist/user CRUD, runtime
learn-mode flip, session history with visibility rules
- static/: self-contained vanilla-JS PWA — login, per-gun start/stop gated
by scope + gun readiness, relay toggles, history, admin tab
config.json (password hashes, session secret, Tuya keys) and sessions.db
are gitignored; config.example.json documents the shape. Covered by a
37-check smoke test incl. a fake charge point over the real WS route.
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
"""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,))
|
||||
]
|
||||
Reference in New Issue
Block a user