docs(wiki): discovery results, architecture, auth model, backend + relay pages

Ingests the 2026-07-09 live session (source page + raw GetConfiguration
dump): charger identified as SimpleCharge MultiSocketCharger, 60 kW DC
dual-standard (gun 1 EU/CCS, gun 2 GB/T); RFID and remote start/stop
verified; by-vehicle auth closed as not supported (three escalating tests
incl. MacEnabled=true after power-cycle); touchscreen-shows-VIN observation
with the DataTransferVendorId long-shot lead.

Adds/updates: architecture plan (FastAPI + PWA, phases 1-3 done), backend
entity, wifi-relays entity (Tuya local-control path + key extraction steps),
authorization concept (API user/scope model, per-gun cards), overview,
runbook, index, log.
This commit is contained in:
2026-07-11 18:58:20 +02:00
parent d7b17d9cb2
commit 3326c8d16c
12 changed files with 713 additions and 31 deletions
+13 -4
View File
@@ -6,7 +6,9 @@ tags: [hardware]
# Anfu Home Charger (charging pile)
The physical home EV charger this whole project revolves around. It is not a single device but a small network of three, behind its own Four-Faith router (see [[network-topology]]). Per [[2026-07-09-findings-and-requirements]]:
The physical home EV charger this whole project revolves around. Identity per the live probe ([[2026-07-09-discovery-eu092025]]): **SimpleCharge "MultiSocketCharger"**, serial `24310588`, firmware `1.24.0620.1`, OCPP ID **`eu092025`** — with **two guns** (connectors 1 and 2).
It is not a single device but a small network of three, behind its own Four-Faith router (see [[network-topology]]). Per [[2026-07-09-findings-and-requirements]]:
- **[[jc-6620|JC-6620]]** (`192.168.2.228`) — OCPP communication controller; the OCPP client that dials the CSMS
- **EV charging controller** (`192.168.2.118`, DHCP) — the main control board that actually manages charging; the JC-6620 talks to it on port 2403
@@ -25,8 +27,15 @@ The physical home EV charger this whole project revolves around. It is not a sin
> [!warning] Power-cycle required
> URL or network changes only take effect after power-cycling the pile.
## Capabilities in question
## Capabilities (per the live probe, [[2026-07-09-discovery-eu092025]], and the live charging test)
> [!warning] Superseded: "basic AC unit" (assumed in [[2026-07-09-findings-and-requirements]])
> The first live charging session (2026-07-09) showed gun 2 delivering **30.6 kW at 309.6 V / 98.8 A with SoC reporting** — that's **DC fast charging**, not AC. This is a DC-capable multi-standard charger.
- ✅ OCPP 1.6J over WebSocket — verified working
- ⚠️ Autocharge (per-vehicle idTag on plug-in) — needs a physical test; see [[authorization]]
- ❌ True ISO 15118 Plug & Charge — unlikely on a basic AC unit
- ✅ **DC fast charger, 60 kW** (owner-confirmed) with **two guns** — `NumberOfConnectors=2`: **gun 1 = EU standard (CCS), gun 2 = Chinese standard (GB/T)**; 30.6 kW observed on gun 2 while both guns charged simultaneously
- ⚠️ Telemetry quirk: while charging, gun 1's periodic samples read 0 W / 0 V (though SoC updated and energy was delivered — 349 Wh per Transaction.End); gun 2's samples looked sane. Watch whether gun 1 metering is lazy/lagged.
- ✅ Feature profiles: Core, **RemoteTrigger** (verified), **SmartCharging** (Power-based profiles, max 3 periods), Reservation, LocalAuthListManagement (max **6** entries), FirmwareManagement
- ✅ Meter data every 60 s while charging: Energy, Power, **SoC**, Voltage, Current
- ❌ Autocharge / vehicle ID over OCPP — **tested and closed 2026-07-09**: no idTag ever forwarded, even with `MacEnabled=true` after a power-cycle ([[authorization]]); the charger clearly holds the DC handshake (reports SoC) but firmware `1.24.0620.1` keeps the vehicle identity to itself
- ❌ True ISO 15118 Plug & Charge — nothing in the config suggests it
+57
View File
@@ -0,0 +1,57 @@
---
type: entity
updated: 2026-07-11
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 config.json load/save
├── journal.py events.jsonl + seen_tags.json (raw ground truth)
├── static/ the web panel PWA (index.html, manifest, service worker, icon)
├── config.json users + allowlist + relay registry — GITIGNORED (password
│ hashes, session secret, Tuya local keys); see config.example.json
└── sessions.db SQLite (gitignored, auto-created)
```
## 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 web panel** (mobile-first PWA, vanilla JS, self-contained; login → tabs Control / History / Admin, buttons filtered by the user's scopes; polls `/api/status` every 5 s)
- `POST /api/login|logout`, `GET /api/me` — username/password → 30-day session (cookie + bearer)
- `GET /api/sessions?limit&cp&connector` — **charging history: who / when / kWh** (visibility: own sessions + guns within scope; admin sees all); `GET /api/sessions/{tx}/samples` — per-minute energy/power/SoC for charts
- `GET /api/status` — mode, connected chargers, gun states, active transactions, auth events, 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}]` + `POST /api/mode?learn=` — admin; **learn mode flips at runtime, no restart**
- `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 optional per-gun card restriction (`"connectors": [2]`) — the `_WSAdapter` WebSocket bridge, learn mode, the JSONL event journal. `DataTransfer` frames are journaled too (the VIN long-shot lead in [[authorization]]).
- **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>`, auto-enrolled) → per-person session attribution.
- **Consumption tracking** (`store.py`, 2026-07-11): every `StartTransaction` opens a row in `sessions.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.
- 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.
- ✅ Smoke-tested 2026-07-11 (37 checks): REST surface, allowlist CRUD incl. gun-restricted cards, login/sessions/scopes, user 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. ⚠️ Not yet run against the live charger or a real phone browser; relays unconfigured until the [[wifi-relays|key extraction]] is done.
## Web panel notes
Vanilla JS on purpose (no framework, no CDN — the panel must work with NetBird-only reachability). Start button enables only when the gun reports `Preparing`/`Available` **and** the user holds that gun's scope. Gun cards show who is charging and since when; History tab lists who/when/kWh; Admin tab (admin scope only) manages allowlist (incl. per-gun cards + "seen but not enrolled" quick-enroll), users, and the learn/enforce toggle. Trivial service worker = installable ("add to home screen") without cache-staleness risk.
## 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`).
+14 -3
View File
@@ -1,6 +1,6 @@
---
type: entity
updated: 2026-07-09
updated: 2026-07-11
tags: [software, csms]
---
@@ -8,6 +8,8 @@ tags: [software, csms]
The Python scripts that play the CSMS (backend) side of the [[ocpp|OCPP]] link. Currently discovery/tester-grade; `station.py` is the seed of the real controller. Per [[2026-07-09-findings-and-requirements]]:
> [!warning] Superseded for production (2026-07-11): `station.py` was ported into the [[backend]] package (`../backend/`), which adds allowlist CRUD, optional API token auth, and [[wifi-relays|Tuya relay]] control. `discovering/` stays as the discovery/diagnostic toolkit (`csms.py`, `rawlisten.py`, fake charge point) — don't run `station.py` and the backend at the same time; both bind port 9000.
| File | Purpose |
|---|---|
| `csms.py` | Minimal OCPP 1.6J server — accepts everything, logs raw frames. Discovery/tester. |
@@ -16,10 +18,19 @@ The Python scripts that play the CSMS (backend) side of the [[ocpp|OCPP]] link.
| `station_config.json` | `{ "learn_mode": bool, "authorized": { "<idTag>": {name, kind} } }` |
| `seen_tags.json` | Auto-recorded log of every idTag observed (discovery / Autocharge testing). |
- **Runtime:** Python venv with `websockets` 16.0 + `ocpp`; listens on `ws://0.0.0.0:9000/<chargePointId>`.
- **Runtime:** Python venv with `fastapi` + `uvicorn` + `ocpp` (2026-07-09: `station.py` moved from raw `websockets` to a single FastAPI/uvicorn process — the phase-1 shape from [[architecture-plan]]).
- **Single port 9000:** the OCPP WebSocket (`ws://0.0.0.0:9000/<chargePointId>`, any path) *and* the discovery HTTP API share it, so the hardcoded touchscreen URL never changes.
- **The one gate:** every [[authorization]] method funnels through `decide(id_tag)` in `station.py` — Accepted/Rejected against the allowlist.
- **Host requirements:** inbound TCP 9000 open (Windows firewall silently drops otherwise — see [[troubleshooting]]) and a stable IP, since the [[anfu-charger|charger touchscreen]] URL is hardcoded.
## Discovery API (in `station.py`, docs at `http://<host>:9000/docs`)
- Auto-interrogation on every charger connect: `GetConfiguration` (all keys) + `TriggerMessage(StatusNotification)` → saved to `discovery_<id>.json` (first real capture: [[2026-07-09-discovery-eu092025]])
- **Event journal:** every OCPP event (connect/disconnect, boot, status, authorize, start/stop transaction, meter values) is appended as one JSON line to `events.jsonl` — permanent, restart-proof, greppable; tail it via `GET /events?limit=N&event=<kind>`
- `GET /status` (chargers, guns, transactions, auth events) · `GET /tags` (seen + authorized)
- `POST /probe` · `/start` · `/stop[/{tx}]` · `/trigger/{status|meter|heartbeat|boot}` · `/unlock/{connector}` · `/setconfig?key=&value=`
- With one charger connected, `?cp=` may be omitted. ✅ Verified end-to-end against both a fake charge point and the real charger.
## Still to build
The web control panel (remote start/stop, live status, allowlist management) served behind [[netbird|NetBird]] — see [[overview]] for the plan and open host decision.
The web control panel (remote start/stop, live status, allowlist management) served behind [[netbird|NetBird]] — now on the [[backend]], see [[overview]] for the plan and open host decision.
+28
View File
@@ -0,0 +1,28 @@
---
type: entity
updated: 2026-07-11
tags: [hardware, relays, tuya]
---
# WiFi Relays (SmartLife / Tuya)
Several WiFi relays scattered around the property, currently driven by the **SmartLife app** (owner report, 2026-07-11). Scope expansion: the [[backend]] should control them too, so one self-hosted system runs both the [[anfu-charger|charger]] and the relays.
## What they are
SmartLife = Tuya's consumer app, so these are **Tuya WiFi devices**. The "discovered by Bluetooth at first" behavior the owner observed is Tuya's standard BLE-assisted *pairing* (the phone passes WiFi credentials over BLE once); after provisioning the relays live on WiFi and speak **Tuya's local protocol on TCP 6668**, which the `tinytuya` library drives directly — **no Tuya cloud in the loop** for day-to-day control. SmartLife keeps working in parallel; local and app control don't conflict.
## Control path (implemented in `backend/relays.py`, ⚠️ awaiting keys)
Local control needs each device's **id + local key**, extracted once via Tuya's own API:
1. Create a (free) account at `iot.tuya.com` → Cloud → create a project (data center matching the SmartLife account region).
2. Link the SmartLife app account to the project (Devices → Link App Account → scan QR in SmartLife).
3. From the repo root: `venv\Scripts\python -m tinytuya wizard` — enter the project's API id/secret; it dumps every paired device's `id`, `key`, `ip`, and protocol `version`.
4. Copy each relay into `backend/config.json` → `"relays"` (shape in `config.example.json`). The Tuya cloud account is never needed again unless a device is re-paired (**re-pairing regenerates the local key**).
Recommended: DHCP reservations for the relays and pinned `"ip"` entries in the config — `"ip": "auto"` works via UDP broadcast discovery but is slower and only finds relays on the same L2 segment as the backend host (❓ verify which subnet the relays are on vs. the future always-on host, see [[network-topology]]).
## API (see [[backend]])
`GET /api/relays?live=true` (poll all), `GET /api/relays/{name}`, `POST /api/relays/{name}/on|off|toggle`. ⚠️ Untested against the physical relays until the keys are in the config.