Files
2026-07-12 10:32:57 +02:00

65 lines
7.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
type: entity
updated: 2026-07-12
tags: [software, csms, backend, relays, auth]
---
# Backend (`../backend/`)
The production successor to [[csms-toolkit|station.py]] (built 2026-07-11): one FastAPI/uvicorn process on **port 9000** that is both the private CSMS for the [[anfu-charger]] and the controller for the [[wifi-relays|Tuya WiFi relays]] — phases 1–2 of the [[architecture-plan]].
```
backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
├── main.py app assembly + entrypoint (uvicorn :9000), serves the panel
├── csms.py OCPP 1.6J ChargePoint handlers, decide() gate, remote start/stop
├── relays.py tinytuya local control of the SmartLife relays
├── routes.py REST under /api/* (login + per-scope permission checks)
├── users.py passwords (PBKDF2), sessions (HMAC), scope matcher, user CLI
├── store.py SQLite session store: who charged, when, how many kWh + meter samples
├── config.py app-state sections (users/allowlist/relays/chargers), db-backed
├── journal.py events.jsonl (raw ground truth)
└── backend.db THE one store (SQLite, gitignored): sessions + samples +
settings (users, allowlist, relays, chargers, session secret)
```
## Surfaces (all on :9000 — the touchscreen URL never changes)
- `ws://<host>:9000/<ChargerID>` — OCPP WebSocket (catch-all path, the JC-6620 dials in)
- `GET /` — **the [[frontend|React panel]]** served from `../frontend/dist/` with SPA fallback (deep links land on index.html; `/api/*` + `/docs` excluded; 503 with instructions if not built)
- `POST /api/login|logout`, `GET /api/me`, `POST /api/me/password` (self-service change, current password required) — username/password → 30-day session (cookie + bearer)
- `GET /api/sessions?limit&cp&connector` — **charging history: who / when / kWh** (visibility: PRIVATE — own sessions only, i.e. own app starts + own linked cards; admin sees all; gun scopes grant control, not visibility); `GET /api/sessions/{tx}/samples` — per-minute energy/power/SoC for charts
- `GET /api/status` — connected chargers, gun states, active transactions, auth events + pending-card count (admin), relays (filtered to what the caller may control)
- `GET /api/events?limit&event=` — tail the journal (admin)
- `POST /api/charger/start|stop[/{tx}]|unlock/{n}` — gun-scoped; `trigger/{...}|setconfig|probe` — admin
- `GET/PUT/DELETE /api/allowlist[/{idTag}]` — enrolled cards/tokens (admin)
- `GET /api/cards/pending` + `POST /api/cards/pending/{id}/approve|reject`, `GET/DELETE /api/cards/denied[/{id}]` — the **unknown-card review workflow** (admin); pending count rides `/api/status` as the notification signal
- `GET /api/permissions` — the grantable-permission catalog (chargers/guns/relays) that drives the panel's checkbox matrix (admin)
- `GET/PUT/DELETE /api/users[/{name}]` — user CRUD (admin), enables a PWA admin page later
- `GET /api/relays[?live=true]`, `GET /api/relays/{name}`, `POST /api/relays/{name}/on|off|toggle` — relay-scoped
- `/docs` — interactive OpenAPI docs
## Design facts
- Carried over from the proven discovery code: the `decide()` gate ([[authorization]]) — now with card→user linking (`"user"`) and charger-qualified gun restriction (`"guns": ["eu092025:2"]`, fnmatch) — the `_WSAdapter` WebSocket bridge, and the JSONL event journal. `DataTransfer` frames are journaled too (the VIN long-shot lead in [[authorization]]).
- **Multi-charger by design**: a second charger only needs the same URL with a unique ChargerID; scopes, sessions, card restrictions, and the panel are all keyed by charger id. Gun display names come from the `"chargers"` config section (not hardcoded).
- **Multi-user auth** (2026-07-11, replaced the interim `api_token`): username/password users with permission scopes — `charger:<cp>:<gun>`, `relay:<name>`, `admin` — full model in [[authorization]]. Stdlib crypto only (PBKDF2 + HMAC sessions). Zero users = open API (startup warns); bootstrap via `python -m backend.users add <name> --scopes admin`.
- Remote starts run under the calling user's own idTag (`app-<name>`) → per-person session attribution. Since 2026-07-12 these tags are **validated directly against the user record** (never enrolled in the allowlist — the old synthetic "app token of <name>" entries are auto-dropped on startup), and the charger-side gate enforces the user's `charger:<cp>:<gun>` scopes too.
- **Consumption tracking** (`store.py`, 2026-07-11): every `StartTransaction` opens a row in `backend.db` with a resolved "who" (allowlist name or username); `StopTransaction` closes it and computes Wh from the meter diff; `MeterValues` rows land in a `samples` table (energy/power/SoC, kW→W normalized). Transaction ids continue from `MAX(tx)` across restarts, and stop-by-tx falls back to the store so sessions running through a backend restart stay stoppable.
- **Live telemetry** (2026-07-12): the latest meter sample per active transaction (SoC, W, V, A, energy) rides `/api/status` as `active_transactions[tx].telemetry`; `Transaction.Begin` snapshots are skipped (taken before the car's BMS is read). The `samples` table stores energy/power/SoC/voltage/current + OCPP context per minute.
- Ctrl+C gotcha, fixed 2026-07-12: uvicorn's graceful shutdown waited forever for the charger's never-closing WebSocket — `timeout_graceful_shutdown=3` caps it; one Ctrl+C now exits in ~3 s and the charger redials.
- SPA cache headers: `index.html` is `no-cache` (phones must revalidate — stale builds plagued early testing), hashed `assets/*` cache forever. Remember: **`:9000` serves the last `npm run build`** — source edits are invisible until a build runs (`npm run dev` for live editing).
- Relay calls are blocking tinytuya I/O, run via `asyncio.to_thread` so the OCPP socket never stalls.
- Venv at repo root (`../venv/`, Python 3.13); deps pinned in `backend/requirements.txt` (fastapi, uvicorn, websockets, ocpp, tinytuya) — the auth system added none.
- Sessions record the **auth method** (`card` vs `app`) for the audit trail; unknown cards NEVER charge — they queue in `pending_cards` for admin approve/reject (learn mode is gone).
- ✅ Smoke-tested (65 checks as of 2026-07-12, isolated temp db via the `BACKEND_DB` env override): REST surface, allowlist CRUD incl. gun-restricted cards, login/sessions/scopes, user/relay/charger CRUD, the full consumption pipeline (start → meter sample → stop → kWh → visibility filtering), static panel serving, and a fake charge point over the real WS route. Lives in the repo (`backend/smoke_test.py`) since 2026-07-12 — it's the CI gate in [[deployment]].
- **Container-ready** (2026-07-12, [[deployment]]): `BACKEND_EVENTS` env override relocates `events.jsonl` (mirrors `BACKEND_DB`), and unauthenticated `GET /api/health` serves Docker/Traefik/Komodo probes.
- ✅ **Live charger connected** (2026-07-11 evening): `eu092025` dials the backend (events.jsonl). ⚠️ Panel not yet exercised from a real phone; relays unconfigured until the [[wifi-relays|key extraction]] is done.
## Web panel
See [[frontend]] — React/Vite app, built to `frontend/dist/` and served by this process.
## Deliberately deferred
SSE live push (the panel polls), per-session charts from the `samples` table (data is already collected), auto-interrogation on connect (manual `POST /api/charger/probe`).