From d7b17d9cb2d4dfe4f22560006989958475183024 Mon Sep 17 00:00:00 2001 From: Julian Cuni Date: Sat, 11 Jul 2026 18:58:09 +0200 Subject: [PATCH] =?UTF-8?q?feat(backend):=20production=20backend=20?= =?UTF-8?q?=E2=80=94=20CSMS,=20multi-user=20auth,=20relays,=20session=20st?= =?UTF-8?q?ore,=20web=20panel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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::, relay:, 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. --- backend/.gitignore | 10 + backend/__init__.py | 0 backend/config.example.json | 40 +++ backend/config.py | 47 ++++ backend/csms.py | 313 ++++++++++++++++++++++ backend/journal.py | 61 +++++ backend/main.py | 79 ++++++ backend/relays.py | 103 ++++++++ backend/requirements.txt | 5 + backend/routes.py | 339 ++++++++++++++++++++++++ backend/static/icon.svg | 4 + backend/static/index.html | 486 +++++++++++++++++++++++++++++++++++ backend/static/manifest.json | 12 + backend/static/sw.js | 6 + backend/store.py | 132 ++++++++++ backend/users.py | 157 +++++++++++ 16 files changed, 1794 insertions(+) create mode 100644 backend/.gitignore create mode 100644 backend/__init__.py create mode 100644 backend/config.example.json create mode 100644 backend/config.py create mode 100644 backend/csms.py create mode 100644 backend/journal.py create mode 100644 backend/main.py create mode 100644 backend/relays.py create mode 100644 backend/requirements.txt create mode 100644 backend/routes.py create mode 100644 backend/static/icon.svg create mode 100644 backend/static/index.html create mode 100644 backend/static/manifest.json create mode 100644 backend/static/sw.js create mode 100644 backend/store.py create mode 100644 backend/users.py diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..c4f24e3 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,10 @@ +# Runtime state + secrets (Tuya local keys live in config.json) +config.json +events.jsonl +seen_tags.json +sessions.db +discovery_*.json +snapshot.json +tinytuya.json +devices.json +tuya-raw.json diff --git a/backend/__init__.py b/backend/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/config.example.json b/backend/config.example.json new file mode 100644 index 0000000..6ea3244 --- /dev/null +++ b/backend/config.example.json @@ -0,0 +1,40 @@ +{ + "learn_mode": true, + "session_secret": "", + "users": { + "admin-user": { + "password": ">", + "scopes": ["admin"], + "id_tag": "app-admin-user" + }, + "gun1-only-user": { + "password": "", + "scopes": ["charger:eu092025:1", "relay:garden-lights"], + "id_tag": "app-gun1-only-user" + }, + "relays-only-user": { + "password": "", + "scopes": ["relay:*"], + "id_tag": "app-relays-only-user" + } + }, + "authorized": { + "1000000000000000": { "name": "Example RFID card, works on both guns", "kind": "card" }, + "1000000000000001": { + "name": "Example RFID card restricted to gun 2", + "kind": "card", + "connectors": [2] + }, + "app-remote": { "name": "Web/app remote start token", "kind": "app" } + }, + "relays": { + "example-relay": { + "id": "", + "key": "", + "ip": "auto", + "version": 3.3, + "switch": 1, + "label": "Garden lights" + } + } +} diff --git a/backend/config.py b/backend/config.py new file mode 100644 index 0000000..6822ef9 --- /dev/null +++ b/backend/config.py @@ -0,0 +1,47 @@ +"""Backend configuration — one JSON file, config.json, next to this module. + +Holds the charger allowlist (learn_mode + authorized idTags, same shape the +discovery phase used), the user accounts with their permission scopes, and the +Tuya relay registry. config.json is gitignored because it contains secrets +(password hashes, the session-signing secret, Tuya local keys); +config.example.json documents the shape. +""" + +import json +import secrets +from pathlib import Path + +HERE = Path(__file__).resolve().parent +CONFIG_PATH = HERE / "config.json" + +DEFAULTS = { + "learn_mode": True, + "users": {}, # name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag": ...} + "authorized": {}, # idTag -> {"name", "kind": "card|app|car", optional "connectors": [1]} + "relays": {}, # name -> {"id", "key", "ip", "version", "switch", "label"} +} + + +def load() -> dict: + if CONFIG_PATH.exists(): + cfg = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) + else: + cfg = {} + for key, default in DEFAULTS.items(): + cfg.setdefault(key, default if not isinstance(default, dict) else dict(default)) + return cfg + + +CONFIG = load() + +if not CONFIG.get("session_secret"): + CONFIG["session_secret"] = secrets.token_hex(32) + CONFIG_PATH.write_text( + json.dumps(CONFIG, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + + +def save() -> None: + CONFIG_PATH.write_text( + json.dumps(CONFIG, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) diff --git a/backend/csms.py b/backend/csms.py new file mode 100644 index 0000000..4ebab78 --- /dev/null +++ b/backend/csms.py @@ -0,0 +1,313 @@ +"""OCPP 1.6J charge-point side of the backend (the CSMS). + +Ported from the proven discovery code (../discovering/station.py) with the +same core design: the API server IS the CSMS, because RemoteStart/Stop can +only travel down the live WebSocket the charger holds open. Every auth method +(RFID tap, app remote start) flows through the single decide() gate. +""" + +import asyncio +import json +import logging +from collections import deque +from typing import Optional + +from fastapi import WebSocket, WebSocketDisconnect + +from ocpp.routing import on +from ocpp.v16 import ChargePoint as OcppChargePoint +from ocpp.v16 import call, call_result +from ocpp.v16.enums import ( + Action, + AuthorizationStatus, + DataTransferStatus, + MessageTrigger, + RegistrationStatus, +) + +from . import store +from .config import CONFIG, HERE +from .journal import now, record_event, record_seen + +log = logging.getLogger("csms") + +# ---- shared runtime state (the REST routes read/drive these) ---- +CONNECTED: dict = {} # cp_id -> ChargePoint instance +CONNECTORS: dict = {} # (cp_id, connector_id) -> latest status string +ACTIVE_TX: dict = {} # transaction_id -> {cp, connector, id_tag, meter_start, started} +AUTH_EVENTS = deque(maxlen=50) # recent authorization attempts (for the panel UI) +_tx_counter = {"n": store.max_tx()} # tx ids continue across restarts + +TRIGGERABLE = { + "status": MessageTrigger.status_notification, + "meter": MessageTrigger.meter_values, + "heartbeat": MessageTrigger.heartbeat, + "boot": MessageTrigger.boot_notification, +} + + +def decide(id_tag: str, context: str, connector: Optional[int] = None) -> AuthorizationStatus: + """The one gate every auth method flows through: is this idTag allowed? + + An allowlist entry may carry "connectors": [1] to restrict a card to + specific guns. Only StartTransaction knows the connector, so the per-gun + check fires there; a plain Authorize (card tap) still accepts a known card + — which matches this charger, since AuthorizeRemoteTxRequests=false means + StartTransaction is the decisive call anyway. + """ + entry = CONFIG["authorized"].get(id_tag) + known = entry is not None + if known and connector is not None and entry.get("connectors") \ + and connector not in entry["connectors"]: + log.warning("[NO] REJECTED idTag=%r (%s) not allowed on connector %s (allowed: %s)", + id_tag, entry.get("name", "?"), connector, entry["connectors"]) + status = AuthorizationStatus.invalid + elif known: + name = entry.get("name", "?") + log.info("[OK] AUTHORIZED idTag=%r (%s) via %s", id_tag, name, context) + status = AuthorizationStatus.accepted + elif CONFIG.get("learn_mode"): + log.warning("[LEARN] NEW idTag=%r via %s -> accepting & recording.", id_tag, context) + record_seen(id_tag, context) + status = AuthorizationStatus.accepted + else: + log.warning("[NO] REJECTED unknown idTag=%r via %s", id_tag, context) + record_seen(id_tag, context) + status = AuthorizationStatus.invalid + AUTH_EVENTS.append( + {"time": now(), "id_tag": id_tag, "context": context, + "connector": connector, "result": status.value, "known": known} + ) + return status + + +def resolve_who(id_tag: str) -> str: + """Human label for a session: allowlist entry name, username, or the raw tag.""" + entry = CONFIG["authorized"].get(id_tag) + if entry and entry.get("name"): + return entry["name"] + for username, user in CONFIG["users"].items(): + if user.get("id_tag") == id_tag: + return username + return id_tag + + +class ChargePoint(OcppChargePoint): + @on(Action.boot_notification) + async def on_boot_notification(self, charge_point_vendor, charge_point_model, **kwargs): + self.boot_info = {"vendor": charge_point_vendor, "model": charge_point_model, **kwargs} + record_event("BootNotification", self.id, **self.boot_info) + log.info("BootNotification: vendor=%r model=%r extra=%r", + charge_point_vendor, charge_point_model, kwargs) + return call_result.BootNotification( + current_time=now(), interval=30, status=RegistrationStatus.accepted + ) + + @on(Action.heartbeat) + async def on_heartbeat(self): + return call_result.Heartbeat(current_time=now()) + + @on(Action.status_notification) + async def on_status_notification(self, connector_id, error_code, status, **kwargs): + CONNECTORS[(self.id, connector_id)] = status + record_event("StatusNotification", self.id, + connector=connector_id, status=status, error=error_code) + log.info("StatusNotification: connector=%s status=%s error=%s", + connector_id, status, error_code) + return call_result.StatusNotification() + + @on(Action.authorize) + async def on_authorize(self, id_tag, **kwargs): + status = decide(id_tag, "Authorize (card/app)") + record_event("Authorize", self.id, id_tag=id_tag, result=status.value) + return call_result.Authorize(id_tag_info={"status": status}) + + @on(Action.start_transaction) + async def on_start_transaction(self, connector_id, id_tag, meter_start, timestamp, **kwargs): + status = decide(id_tag, f"StartTransaction (connector {connector_id})", + connector=connector_id) + if status == AuthorizationStatus.accepted: + _tx_counter["n"] += 1 + tx = _tx_counter["n"] + who = resolve_who(id_tag) + ACTIVE_TX[tx] = { + "cp": self.id, "connector": connector_id, "id_tag": id_tag, + "who": who, "meter_start": meter_start, "started": now(), + } + store.start_session(tx, self.id, connector_id, id_tag, who, + timestamp, meter_start) + log.info("Transaction %s STARTED on connector %s by %s (meter_start=%s)", + tx, connector_id, who, meter_start) + else: + tx = 0 # 0 tells the charger the transaction is not authorized + record_event("StartTransaction", self.id, connector=connector_id, + id_tag=id_tag, meter_start=meter_start, result=status.value, tx=tx) + return call_result.StartTransaction( + transaction_id=tx, id_tag_info={"status": status} + ) + + @on(Action.stop_transaction) + async def on_stop_transaction(self, meter_stop, timestamp, transaction_id, **kwargs): + info = ACTIVE_TX.pop(transaction_id, None) + used = (meter_stop - info["meter_start"]) if info else "?" + store.end_session(transaction_id, timestamp, meter_stop, + reason=kwargs.get("reason")) + record_event("StopTransaction", self.id, tx=transaction_id, + meter_stop=meter_stop, delivered_wh=used, **kwargs) + log.info("Transaction %s STOPPED (meter_stop=%s, delivered=%s Wh)", + transaction_id, meter_stop, used) + return call_result.StopTransaction( + id_tag_info={"status": AuthorizationStatus.accepted} + ) + + @on(Action.meter_values) + async def on_meter_values(self, connector_id, meter_value, **kwargs): + record_event("MeterValues", self.id, connector=connector_id, + values=meter_value, **kwargs) + tx = kwargs.get("transaction_id") + if tx is not None: + for entry in meter_value or []: + reading = {} + for sv in entry.get("sampled_value") or []: + # measurand defaults to the energy register when omitted + measurand = sv.get("measurand", "Energy.Active.Import.Register") + try: + value = float(sv.get("value")) + except (TypeError, ValueError): + continue + if measurand == "Energy.Active.Import.Register": + # some firmwares report kWh; normalize to Wh + reading["energy_wh"] = value * 1000 if sv.get("unit") == "kWh" else value + elif measurand == "Power.Active.Import": + reading["power_w"] = value * 1000 if sv.get("unit") == "kW" else value + elif measurand == "SoC": + reading["soc"] = value + if reading: + store.add_sample(tx, entry.get("timestamp", now()), + reading.get("energy_wh"), reading.get("power_w"), + reading.get("soc")) + log.info("MeterValues: connector=%s values=%r", connector_id, meter_value) + return call_result.MeterValues() + + @on(Action.data_transfer) + async def on_data_transfer(self, vendor_id, **kwargs): + # Journaled because a vendor DataTransfer frame is the long-shot lead + # for the charger ever surfacing the vehicle VIN (wiki: authorization). + record_event("DataTransfer", self.id, vendor_id=vendor_id, **kwargs) + log.info("DataTransfer: vendor_id=%r extra=%r", vendor_id, kwargs) + return call_result.DataTransfer(status=DataTransferStatus.accepted) + + @on(Action.firmware_status_notification) + async def on_firmware_status(self, status, **kwargs): + log.info("FirmwareStatusNotification: %s", status) + return call_result.FirmwareStatusNotification() + + @on(Action.diagnostics_status_notification) + async def on_diagnostics_status(self, status, **kwargs): + log.info("DiagnosticsStatusNotification: %s", status) + return call_result.DiagnosticsStatusNotification() + + +# ---- outbound OCPP commands (called by the REST routes) ---- +async def remote_start(cp_id: str, id_tag: str, connector_id: int = 1) -> str: + cp = CONNECTED.get(cp_id) + if cp is None: + raise RuntimeError(f"charge point {cp_id!r} is not connected") + resp = await cp.call(call.RemoteStartTransaction(id_tag=id_tag, connector_id=connector_id)) + log.info("RemoteStartTransaction(%s, connector=%s) -> %s", id_tag, connector_id, resp.status) + return resp.status + + +async def remote_stop(transaction_id: int) -> str: + # fall back to the store so sessions still running after a backend restart + # (charger keeps them alive) remain stoppable + info = ACTIVE_TX.get(transaction_id) or store.open_session(transaction_id) + if info is None: + raise RuntimeError(f"no active transaction {transaction_id}") + cp = CONNECTED.get(info["cp"]) + if cp is None: + raise RuntimeError("charge point is not connected") + resp = await cp.call(call.RemoteStopTransaction(transaction_id=transaction_id)) + log.info("RemoteStopTransaction(%s) -> %s", transaction_id, resp.status) + return resp.status + + +async def interrogate(cp: ChargePoint) -> dict: + """GetConfiguration + trigger a StatusNotification; save to discovery_.json.""" + report = { + "charge_point": cp.id, + "probed_at": now(), + "boot_info": getattr(cp, "boot_info", None), + } + try: + resp = await cp.call(call.GetConfiguration()) + report["configuration"] = resp.configuration_key + report["unknown_keys"] = resp.unknown_key + except Exception as exc: + report["configuration_error"] = repr(exc) + try: + resp = await cp.call( + call.TriggerMessage(requested_message=MessageTrigger.status_notification) + ) + report["trigger_status_notification"] = resp.status + await asyncio.sleep(2) # give the triggered StatusNotifications time to arrive + except Exception as exc: + report["trigger_error"] = repr(exc) + report["connectors_seen"] = { + str(conn): status for (cp_id, conn), status in CONNECTORS.items() if cp_id == cp.id + } + path = HERE / f"discovery_{cp.id}.json" + path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8") + return report + + +class _WSAdapter: + """Bridge a Starlette WebSocket to the recv()/send() interface the ocpp lib expects.""" + + def __init__(self, ws: WebSocket): + self._ws = ws + + async def recv(self) -> str: + return await self._ws.receive_text() + + async def send(self, message: str) -> None: + await self._ws.send_text(message) + + async def close(self, code: int = 1000, reason: str = "") -> None: + await self._ws.close(code=code) + + +async def ocpp_socket(ws: WebSocket, cp_path: str) -> None: + """The OCPP endpoint the JC-6620 dials: ws://:9000/.""" + cp_id = cp_path.strip("/").split("/")[-1] or "unknown" + offered = [ + p.strip() + for p in ws.headers.get("sec-websocket-protocol", "").split(",") + if p.strip() + ] + await ws.accept(subprotocol="ocpp1.6" if "ocpp1.6" in offered else None) + log.info("Charger connected: id=%r from %s subprotocols=%r", cp_id, ws.client, offered) + record_event("connected", cp_id, client=str(ws.client), subprotocols=offered) + cp = ChargePoint(cp_id, _WSAdapter(ws)) + CONNECTED[cp_id] = cp + try: + await cp.start() + except WebSocketDisconnect: + log.info("Charger %r disconnected", cp_id) + finally: + record_event("disconnected", cp_id) + CONNECTED.pop(cp_id, None) + for key in [k for k in CONNECTORS if k[0] == cp_id]: + CONNECTORS.pop(key, None) + + +def pick_cp(cp_id: Optional[str]) -> ChargePoint: + """Resolve which charger a REST call targets; auto-select when only one is connected.""" + if cp_id is not None: + cp = CONNECTED.get(cp_id) + if cp is None: + raise KeyError(f"charge point {cp_id!r} is not connected") + return cp + if len(CONNECTED) == 1: + return next(iter(CONNECTED.values())) + raise KeyError(f"specify ?cp=; currently connected: {list(CONNECTED)}") diff --git a/backend/journal.py b/backend/journal.py new file mode 100644 index 0000000..4abe8b0 --- /dev/null +++ b/backend/journal.py @@ -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")) diff --git a/backend/main.py b/backend/main.py new file mode 100644 index 0000000..96fa6a8 --- /dev/null +++ b/backend/main.py @@ -0,0 +1,79 @@ +"""Home energy backend — private CSMS for the Anfu charger + local control of +the Tuya/SmartLife WiFi relays. One uvicorn process, one port: + + ws://:9000/ OCPP 1.6J (the JC-6620 dials in here) + http://:9000/api/* REST for the web panel / curl + http://:9000/docs interactive API docs + +Port 9000 is load-bearing: it's hardcoded in the charger's touchscreen URL and +changing it there requires a power-cycle (wiki: troubleshooting #4). + +Run: venv\\Scripts\\python -m backend.main (from the repo root) +""" + +import asyncio +import logging +from pathlib import Path + +import uvicorn +from fastapi import FastAPI, WebSocket +from fastapi.responses import FileResponse +from fastapi.staticfiles import StaticFiles + +from . import csms, routes +from .config import CONFIG + +STATIC = Path(__file__).resolve().parent / "static" + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s | %(message)s", +) +log = logging.getLogger("backend") + +app = FastAPI( + title="Home Energy Backend", + description="Private OCPP CSMS + WiFi relay control. The charger dials " + "ws://:9000/; everything else lives under /api/*.", +) +app.include_router(routes.router) +app.mount("/static", StaticFiles(directory=STATIC), name="static") + + +@app.get("/") +async def index_page(): + return FileResponse(STATIC / "index.html") + + +# the service worker must be served from / so its scope covers the whole app +@app.get("/sw.js") +async def service_worker(): + return FileResponse(STATIC / "sw.js", media_type="application/javascript") + + +# Catch-all WS route so the charger may dial any path (it uses /). +# WebSocket and HTTP routes match independently, so this never shadows /api/*. +@app.websocket("/{cp_path:path}") +async def ocpp_websocket(ws: WebSocket, cp_path: str): + await csms.ocpp_socket(ws, cp_path) + + +async def main(): + mode = "LEARN (accepting & recording new ids)" if CONFIG["learn_mode"] else "ENFORCING allowlist" + log.info( + "CSMS ws://0.0.0.0:9000/ | API http://0.0.0.0:9000/docs | mode: %s | " + "%d authorized id(s) | %d user(s) | %d relay(s) configured", + mode, len(CONFIG["authorized"]), len(CONFIG["users"]), len(CONFIG["relays"]), + ) + if not CONFIG["users"]: + log.warning( + "NO USERS CONFIGURED — the API is OPEN (anonymous admin). " + "Create one: venv\\Scripts\\python -m backend.users add --scopes admin" + ) + await uvicorn.Server( + uvicorn.Config(app, host="0.0.0.0", port=9000, log_config=None) + ).serve() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/relays.py b/backend/relays.py new file mode 100644 index 0000000..6f483a7 --- /dev/null +++ b/backend/relays.py @@ -0,0 +1,103 @@ +"""Local control of the Tuya/SmartLife WiFi relays — no Tuya cloud in the loop. + +The relays pair via the SmartLife app (BLE-assisted onboarding) but once on +WiFi they speak Tuya's local protocol on TCP 6668, which tinytuya drives +directly. Each relay needs its device id + LOCAL KEY in config.json under +"relays" — extracted once with `tinytuya wizard` (see the wiki: wifi-relays). + +tinytuya is synchronous/blocking, so every call runs in a worker thread via +asyncio.to_thread to keep the OCPP socket responsive. +""" + +import asyncio +import logging + +try: + import tinytuya +except ImportError: # backend still runs (charger-only) without it + tinytuya = None + +from .config import CONFIG + +log = logging.getLogger("relays") + + +class RelayError(RuntimeError): + pass + + +def configured() -> dict: + """The relay registry without secrets — safe to return over the API.""" + return { + name: {"label": cfg.get("label", name), "ip": cfg.get("ip", "auto")} + for name, cfg in CONFIG["relays"].items() + } + + +def _device(name: str): + if tinytuya is None: + raise RelayError("tinytuya is not installed (pip install tinytuya)") + cfg = CONFIG["relays"].get(name) + if cfg is None: + raise RelayError(f"unknown relay {name!r}; configured: {list(CONFIG['relays'])}") + ip = cfg.get("ip", "auto") + # "Auto" makes tinytuya find the device via its UDP broadcast (slower); + # pin the IP in config.json (with a DHCP reservation) once known. + dev = tinytuya.OutletDevice( + cfg["id"], ip if ip and ip != "auto" else "Auto", cfg["key"] + ) + dev.set_version(float(cfg.get("version", 3.3))) + dev.set_socketTimeout(5) + return dev, str(cfg.get("switch", 1)) + + +def _check(name: str, result) -> dict: + if not isinstance(result, dict) or "dps" not in result: + raise RelayError(f"relay {name!r} did not answer: {result!r}") + return result["dps"] + + +def _status_sync(name: str) -> dict: + dev, sw = _device(name) + dps = _check(name, dev.status()) + return {"relay": name, "on": bool(dps.get(sw)), "dps": dps} + + +def _switch_sync(name: str, on: bool) -> dict: + dev, sw = _device(name) + result = dev.set_status(on, int(sw)) + # some firmwares reply with the new dps, some with an empty ack — verify + if not (isinstance(result, dict) and "dps" in result): + result = dev.status() + dps = _check(name, result) + actual = bool(dps.get(sw, on)) + if actual != on: + raise RelayError(f"relay {name!r} did not switch (wanted {on}, reads {actual})") + return {"relay": name, "on": actual} + + +async def status(name: str) -> dict: + return await asyncio.to_thread(_status_sync, name) + + +async def switch(name: str, on: bool) -> dict: + return await asyncio.to_thread(_switch_sync, name, on) + + +async def toggle(name: str) -> dict: + current = await status(name) + return await switch(name, not current["on"]) + + +async def status_all() -> dict: + """Poll every configured relay concurrently; errors become per-relay strings.""" + names = list(CONFIG["relays"]) + results = await asyncio.gather(*(status(n) for n in names), return_exceptions=True) + out = {} + for name, res in zip(names, results): + if isinstance(res, BaseException): + out[name] = {"relay": name, "error": str(res)} + else: + out[name] = res + out[name]["label"] = CONFIG["relays"][name].get("label", name) + return out diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..39b9e31 --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,5 @@ +fastapi==0.139.0 +uvicorn==0.51.0 +websockets==16.0 +ocpp==2.1.0 +tinytuya==1.20.0 diff --git a/backend/routes.py b/backend/routes.py new file mode 100644 index 0000000..7b9e89b --- /dev/null +++ b/backend/routes.py @@ -0,0 +1,339 @@ +"""REST API — everything under /api/*, for the web panel (and curl). + +Authorization model (see backend/users.py): + * POST /api/login {username, password} -> HMAC session token, set as an + HttpOnly cookie AND returned in the body (usable as a Bearer token). + * Every endpoint resolves the caller to a user and checks a permission + scope: charger::, relay:, or admin (implies everything). + * With ZERO users configured the API is open (anonymous admin) so nothing + breaks before the first `python -m backend.users add` — main.py warns. +""" + +import logging +from typing import Optional + +from fastapi import APIRouter, Depends, HTTPException, Request, Response +from pydantic import BaseModel + +from . import csms, relays, store, users +from .config import CONFIG, save +from .journal import read_events, read_seen +from ocpp.v16 import call + +log = logging.getLogger("api") + +SESSION_COOKIE = "session" + + +def current_user(request: Request) -> dict: + """Resolve the session cookie or Bearer token to a user dict.""" + if not CONFIG["users"]: + return {"name": "anonymous", "scopes": ["admin"], "id_tag": "app-remote"} + token = request.cookies.get(SESSION_COOKIE) or ( + request.headers.get("authorization") or "" + ).removeprefix("Bearer ").strip() + username = users.verify_session(token) if token else None + if username is None: + raise HTTPException(401, "not logged in (or session expired)") + return {"name": username, **CONFIG["users"][username]} + + +def need(user: dict, scope: str) -> None: + if not users.allowed(user["scopes"], scope): + raise HTTPException(403, f"user {user['name']!r} lacks permission {scope!r}") + + +router = APIRouter(prefix="/api") + + +def _cp(cp_id: Optional[str]) -> csms.ChargePoint: + try: + return csms.pick_cp(cp_id) + except KeyError as exc: + raise HTTPException(409, str(exc.args[0])) + + +async def _ocpp(coro): + """Run an OCPP call for an HTTP handler, mapping failures to HTTP errors.""" + try: + return await coro + except HTTPException: + raise + except Exception as exc: + raise HTTPException(502, f"OCPP call failed: {exc!r}") + + +def _visible_relays(user: dict) -> dict: + return { + name: info + for name, info in relays.configured().items() + if users.allowed(user["scopes"], f"relay:{name}") + } + + +# ---- login / identity ---- +class LoginBody(BaseModel): + username: str + password: str + + +@router.post("/login") +async def login(body: LoginBody, response: Response): + entry = CONFIG["users"].get(body.username) + if not CONFIG["users"]: + raise HTTPException(409, "no users configured — the API is open; log in is pointless " + "until `python -m backend.users add` creates one") + if entry is None or not users.verify_password(body.password, entry.get("password", "")): + log.warning("failed login for %r", body.username) + raise HTTPException(401, "wrong username or password") + token = users.mint_session(body.username) + response.set_cookie( + SESSION_COOKIE, token, max_age=users.SESSION_TTL, + httponly=True, samesite="lax", # no `secure`: plain http inside NetBird + ) + log.info("login: %r", body.username) + return {"token": token, "user": users.public_view(body.username, entry)} + + +@router.post("/logout") +async def logout(response: Response): + # sessions are stateless — logout just clears the cookie on this client + response.delete_cookie(SESSION_COOKIE) + return {"logged_out": True} + + +@router.get("/me") +async def me(user: dict = Depends(current_user)): + return users.public_view(user["name"], user) + + +# ---- status & journals ---- +@router.get("/status") +async def api_status(user: dict = Depends(current_user)): + return { + "mode": "learn" if CONFIG.get("learn_mode") else "enforce", + "connected": { + cp_id: getattr(cp, "boot_info", None) for cp_id, cp in csms.CONNECTED.items() + }, + "connectors": {f"{cp_id}/{conn}": s for (cp_id, conn), s in csms.CONNECTORS.items()}, + "active_transactions": csms.ACTIVE_TX, + "recent_auth_events": list(csms.AUTH_EVENTS), + "relays": _visible_relays(user), + } + + +@router.get("/events") +async def api_events(limit: int = 100, event: Optional[str] = None, + user: dict = Depends(current_user)): + need(user, "admin") + return read_events(limit=limit, event=event) + + +# ---- charger control (scope: charger::) ---- +@router.post("/charger/start") +async def charger_start(connector: int = 1, cp: Optional[str] = None, + user: dict = Depends(current_user)): + target = _cp(cp) + need(user, f"charger:{target.id}:{connector}") + # remote starts run under the caller's own idTag so sessions are attributable + id_tag = user.get("id_tag") or f"app-{user['name']}" + if id_tag not in CONFIG["authorized"]: + CONFIG["authorized"][id_tag] = {"name": f"app token of {user['name']}", "kind": "app"} + save() + status = await _ocpp(csms.remote_start(target.id, id_tag, connector)) + return {"remote_start": status, "id_tag": id_tag} + + +@router.post("/charger/stop") +@router.post("/charger/stop/{tx}") +async def charger_stop(tx: Optional[int] = None, user: dict = Depends(current_user)): + if tx is None: + if len(csms.ACTIVE_TX) != 1: + raise HTTPException(409, f"specify /stop/; active: {list(csms.ACTIVE_TX)}") + tx = next(iter(csms.ACTIVE_TX)) + info = csms.ACTIVE_TX.get(tx) or store.open_session(tx) + if info is None: + raise HTTPException(409, f"no active transaction {tx}") + need(user, f"charger:{info['cp']}:{info['connector']}") + status = await _ocpp(csms.remote_stop(tx)) + return {"remote_stop": status, "transaction": tx} + + +@router.post("/charger/unlock/{connector}") +async def charger_unlock(connector: int, cp: Optional[str] = None, + user: dict = Depends(current_user)): + target = _cp(cp) + need(user, f"charger:{target.id}:{connector}") + resp = await _ocpp(target.call(call.UnlockConnector(connector_id=connector))) + return {"unlock": connector, "status": resp.status} + + +@router.post("/charger/trigger/{what}") +async def charger_trigger(what: str, connector: Optional[int] = None, + cp: Optional[str] = None, user: dict = Depends(current_user)): + need(user, "admin") + if what not in csms.TRIGGERABLE: + raise HTTPException(400, f"unknown trigger {what!r}; options: {list(csms.TRIGGERABLE)}") + payload = call.TriggerMessage( + requested_message=csms.TRIGGERABLE[what], connector_id=connector + ) + resp = await _ocpp(_cp(cp).call(payload)) + return {"trigger": what, "status": resp.status} + + +@router.post("/charger/setconfig") +async def charger_setconfig(key: str, value: str, cp: Optional[str] = None, + user: dict = Depends(current_user)): + need(user, "admin") + resp = await _ocpp(_cp(cp).call(call.ChangeConfiguration(key=key, value=value))) + return {"key": key, "value": value, "status": resp.status} + + +@router.post("/charger/probe") +async def charger_probe(cp: Optional[str] = None, user: dict = Depends(current_user)): + need(user, "admin") + return await _ocpp(csms.interrogate(_cp(cp))) + + +# ---- session history: who charged when and how many kWh ---- +def _may_see_session(user: dict, s: dict) -> bool: + """Own sessions, sessions on guns you control, or everything for admin.""" + return ( + s["id_tag"] == user.get("id_tag") + or users.allowed(user["scopes"], f"charger:{s['cp']}:{s['connector']}") + ) + + +@router.get("/sessions") +async def sessions_list(limit: int = 50, cp: Optional[str] = None, + connector: Optional[int] = None, + user: dict = Depends(current_user)): + rows = store.query_sessions(limit=limit, cp=cp, connector=connector) + return [s for s in rows if _may_see_session(user, s)] + + +@router.get("/sessions/{tx}/samples") +async def session_samples(tx: int, user: dict = Depends(current_user)): + session = store.get_session(tx) + if session is None: + raise HTTPException(404, f"no session {tx}") + if not _may_see_session(user, session): + raise HTTPException(403, f"user {user['name']!r} may not view session {tx}") + return {"session": session, "samples": store.samples_for(tx)} + + +# ---- allowlist management (admin) ---- +class AllowlistEntry(BaseModel): + name: str + kind: str = "card" # card | app | car + connectors: Optional[list[int]] = None # e.g. [2] = this card only works on gun 2 + + +@router.get("/allowlist") +async def allowlist_get(user: dict = Depends(current_user)): + need(user, "admin") + return { + "learn_mode": CONFIG["learn_mode"], + "authorized": CONFIG["authorized"], + "seen": read_seen(), + } + + +@router.put("/allowlist/{id_tag}") +async def allowlist_put(id_tag: str, entry: AllowlistEntry, + user: dict = Depends(current_user)): + need(user, "admin") + CONFIG["authorized"][id_tag] = entry.model_dump(exclude_none=True) + save() + log.info("allowlist: added/updated %r (%s)", id_tag, entry.name) + return {"authorized": CONFIG["authorized"]} + + +@router.delete("/allowlist/{id_tag}") +async def allowlist_delete(id_tag: str, user: dict = Depends(current_user)): + need(user, "admin") + if CONFIG["authorized"].pop(id_tag, None) is None: + raise HTTPException(404, f"idTag {id_tag!r} is not in the allowlist") + save() + log.info("allowlist: removed %r", id_tag) + return {"authorized": CONFIG["authorized"]} + + +@router.post("/mode") +async def set_mode(learn: bool, user: dict = Depends(current_user)): + """Flip learn mode at runtime — no restart needed; decide() reads CONFIG live.""" + need(user, "admin") + CONFIG["learn_mode"] = learn + save() + log.warning("mode changed: %s", "LEARN" if learn else "ENFORCE") + return {"mode": "learn" if learn else "enforce"} + + +# ---- user management (admin) ---- +class UserBody(BaseModel): + password: Optional[str] = None + scopes: Optional[list[str]] = None + + +@router.get("/users") +async def users_list(user: dict = Depends(current_user)): + need(user, "admin") + return [users.public_view(name, u) for name, u in CONFIG["users"].items()] + + +@router.put("/users/{name}") +async def users_put(name: str, body: UserBody, user: dict = Depends(current_user)): + need(user, "admin") + try: + updated = users.set_user(name, password=body.password, scopes=body.scopes) + except ValueError as exc: + raise HTTPException(400, str(exc)) + log.info("users: %r set by %r (scopes=%s)", name, user["name"], updated["scopes"]) + return users.public_view(name, updated) + + +@router.delete("/users/{name}") +async def users_delete(name: str, user: dict = Depends(current_user)): + need(user, "admin") + if name == user["name"]: + raise HTTPException(400, "refusing to delete the account you are logged in as") + try: + users.remove_user(name) + except KeyError: + raise HTTPException(404, f"no user {name!r}") + log.info("users: %r removed by %r", name, user["name"]) + return {"removed": name} + + +# ---- relays (scope: relay:) ---- +@router.get("/relays") +async def relays_list(live: bool = False, user: dict = Depends(current_user)): + """Relays the caller may control; ?live=true polls each for its actual state.""" + visible = _visible_relays(user) + if not live: + return visible + polled = await relays.status_all() + return {name: polled[name] for name in visible if name in polled} + + +@router.get("/relays/{name}") +async def relay_status(name: str, user: dict = Depends(current_user)): + need(user, f"relay:{name}") + try: + return await relays.status(name) + except relays.RelayError as exc: + raise HTTPException(502, str(exc)) + + +@router.post("/relays/{name}/{verb}") +async def relay_switch(name: str, verb: str, user: dict = Depends(current_user)): + need(user, f"relay:{name}") + actions = {"on": True, "off": False} + try: + if verb == "toggle": + return await relays.toggle(name) + if verb in actions: + return await relays.switch(name, actions[verb]) + except relays.RelayError as exc: + raise HTTPException(502, str(exc)) + raise HTTPException(400, f"unknown verb {verb!r}; use on, off or toggle") diff --git a/backend/static/icon.svg b/backend/static/icon.svg new file mode 100644 index 0000000..f5b044c --- /dev/null +++ b/backend/static/icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/backend/static/index.html b/backend/static/index.html new file mode 100644 index 0000000..485c710 --- /dev/null +++ b/backend/static/index.html @@ -0,0 +1,486 @@ + + + + + + +Home Energy + + + + + + + + + + +
+ + + + diff --git a/backend/static/manifest.json b/backend/static/manifest.json new file mode 100644 index 0000000..7783726 --- /dev/null +++ b/backend/static/manifest.json @@ -0,0 +1,12 @@ +{ + "name": "Home Energy", + "short_name": "Energy", + "description": "Home EV charger and relay control", + "start_url": "/", + "display": "standalone", + "background_color": "#0f172a", + "theme_color": "#0f172a", + "icons": [ + { "src": "/static/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" } + ] +} diff --git a/backend/static/sw.js b/backend/static/sw.js new file mode 100644 index 0000000..517ea7b --- /dev/null +++ b/backend/static/sw.js @@ -0,0 +1,6 @@ +// Minimal service worker: required for "add to home screen" installability. +// No caching — the panel is only reachable over NetBird/LAN anyway, and a +// stale cached UI causes more confusion than a brief offline error. +self.addEventListener("install", () => self.skipWaiting()); +self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim())); +self.addEventListener("fetch", () => {}); diff --git a/backend/store.py b/backend/store.py new file mode 100644 index 0000000..87399dd --- /dev/null +++ b/backend/store.py @@ -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,)) + ] diff --git a/backend/users.py b/backend/users.py new file mode 100644 index 0000000..7d3ad62 --- /dev/null +++ b/backend/users.py @@ -0,0 +1,157 @@ +"""User accounts, password hashing, sessions, and the scope matcher. + +Everything is stdlib crypto: PBKDF2-HMAC-SHA256 for passwords, HMAC-signed +stateless tokens for sessions (they survive backend restarts; "logout" is the +client dropping its cookie). Users live in config.json -> "users": + + "julian": { + "password": "pbkdf2$600000$$", + "scopes": ["admin"], # or charger::, relay: + "id_tag": "app-julian" # idTag used for their remote starts + } + +Scopes are matched with fnmatch, so "relay:*" or "charger:eu092025:*" work. +"admin" implies every scope and is required for management endpoints. + +CLI (from the repo root): + venv\\Scripts\\python -m backend.users add --scopes admin + venv\\Scripts\\python -m backend.users list + venv\\Scripts\\python -m backend.users remove +""" + +import base64 +import hashlib +import hmac +import secrets +import time +from fnmatch import fnmatch + +from .config import CONFIG, save + +PBKDF2_ITERATIONS = 600_000 +SESSION_TTL = 30 * 24 * 3600 # 30 days + + +# ---- passwords ---- +def hash_password(password: str) -> str: + salt = secrets.token_hex(16) + digest = hashlib.pbkdf2_hmac( + "sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS + ) + return f"pbkdf2${PBKDF2_ITERATIONS}${salt}${digest.hex()}" + + +def verify_password(password: str, stored: str) -> bool: + try: + scheme, iterations, salt, expected = stored.split("$") + if scheme != "pbkdf2": + return False + digest = hashlib.pbkdf2_hmac( + "sha256", password.encode(), bytes.fromhex(salt), int(iterations) + ) + return hmac.compare_digest(digest.hex(), expected) + except (ValueError, AttributeError): + return False + + +# ---- sessions (stateless HMAC tokens) ---- +def _secret() -> bytes: + return CONFIG["session_secret"].encode() + + +def _sign(payload: str) -> str: + return hmac.new(_secret(), payload.encode(), hashlib.sha256).hexdigest() + + +def mint_session(username: str) -> str: + payload = f"{username}|{int(time.time()) + SESSION_TTL}" + token = f"{payload}|{_sign(payload)}" + return base64.urlsafe_b64encode(token.encode()).decode() + + +def verify_session(token: str) -> str | None: + """Return the username for a valid, unexpired token; None otherwise.""" + try: + username, expires, signature = ( + base64.urlsafe_b64decode(token.encode()).decode().split("|") + ) + except Exception: + return None + if not hmac.compare_digest(_sign(f"{username}|{expires}"), signature): + return None + if int(expires) < time.time(): + return None + if username not in CONFIG["users"]: + return None # deleted users lose their sessions + return username + + +# ---- scopes ---- +def allowed(scopes: list, needed: str) -> bool: + return any( + grant in ("*", "admin") or fnmatch(needed, grant) for grant in scopes + ) + + +# ---- user management (used by the CLI and the admin API) ---- +def set_user(name: str, password: str | None = None, scopes: list | None = None) -> dict: + user = CONFIG["users"].get(name, {"scopes": [], "id_tag": f"app-{name}"}) + if password is not None: + user["password"] = hash_password(password) + if scopes is not None: + user["scopes"] = scopes + user.setdefault("id_tag", f"app-{name}") + if "password" not in user: + raise ValueError(f"new user {name!r} needs a password") + CONFIG["users"][name] = user + save() + return user + + +def remove_user(name: str) -> None: + if CONFIG["users"].pop(name, None) is None: + raise KeyError(name) + save() + + +def public_view(name: str, user: dict) -> dict: + """A user entry without the password hash — safe for /api/me and /api/users.""" + return {"name": name, "scopes": user["scopes"], "id_tag": user.get("id_tag")} + + +def _cli() -> None: + import argparse + import getpass + + parser = argparse.ArgumentParser(prog="backend.users", description=__doc__) + sub = parser.add_subparsers(dest="cmd", required=True) + p_add = sub.add_parser("add", help="add a user or update an existing one") + p_add.add_argument("name") + p_add.add_argument("--scopes", nargs="+", default=None, + help='e.g. admin, "charger:eu092025:1", "relay:*"') + sub.add_parser("list", help="list users and their scopes") + p_rm = sub.add_parser("remove", help="delete a user") + p_rm.add_argument("name") + args = parser.parse_args() + + if args.cmd == "list": + for name, user in CONFIG["users"].items(): + print(f"{name:20} scopes={user['scopes']} id_tag={user.get('id_tag')}") + if not CONFIG["users"]: + print("no users configured — the API is OPEN (anonymous admin)") + elif args.cmd == "add": + existing = args.name in CONFIG["users"] + password = getpass.getpass(f"{'New ' if not existing else ''}password for {args.name!r}: ") + if not existing or password: + confirm = getpass.getpass("Repeat password: ") + if password != confirm: + raise SystemExit("passwords do not match") + user = set_user(args.name, password=password or None, scopes=args.scopes) + print(f"{'updated' if existing else 'created'} {args.name!r}: scopes={user['scopes']}") + elif args.cmd == "remove": + remove_user(args.name) + print(f"removed {args.name!r}") + + +if __name__ == "__main__": + _cli()