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:
2026-07-11 18:58:09 +02:00
parent 5c88e8fa3c
commit d7b17d9cb2
16 changed files with 1794 additions and 0 deletions
+61
View File
@@ -0,0 +1,61 @@
"""Durable journals: events.jsonl (everything the charger tells us) and
seen_tags.json (unknown idTags captured in learn mode).
JSONL now, SQLite later — the append-only line format survives crashes and is
trivially greppable/ingestable, which is all the current phase needs.
"""
import json
import logging
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
HERE = Path(__file__).resolve().parent
EVENTS_PATH = HERE / "events.jsonl"
SEEN_PATH = HERE / "seen_tags.json"
log = logging.getLogger("journal")
def now() -> str:
return datetime.now(timezone.utc).isoformat()
def record_event(event: str, cp_id: str, **data) -> None:
entry = {"time": now(), "event": event, "cp": cp_id, **data}
try:
with EVENTS_PATH.open("a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n")
except Exception:
log.exception("failed to journal event %r", event)
def read_events(limit: int = 100, event: Optional[str] = None) -> list:
if not EVENTS_PATH.exists():
return []
lines = EVENTS_PATH.read_text(encoding="utf-8").splitlines()
entries = [json.loads(line) for line in lines if line.strip()]
if event is not None:
entries = [e for e in entries if e.get("event") == event]
return entries[-limit:]
def record_seen(id_tag: str, context: str) -> None:
try:
seen = json.loads(SEEN_PATH.read_text(encoding="utf-8")) if SEEN_PATH.exists() else {}
except Exception:
seen = {}
entry = seen.get(id_tag, {"count": 0, "first_seen": now(), "contexts": []})
entry["count"] += 1
entry["last_seen"] = now()
if context not in entry["contexts"]:
entry["contexts"].append(context)
seen[id_tag] = entry
SEEN_PATH.write_text(json.dumps(seen, indent=2), encoding="utf-8")
def read_seen() -> dict:
if not SEEN_PATH.exists():
return {}
return json.loads(SEEN_PATH.read_text(encoding="utf-8"))