refactor(backend): single SQLite store — config.json eliminated

backend.db (renamed from sessions.db) now holds everything: the sessions
and samples tables plus a settings table with the app-state sections
(users, allowlist, relays, chargers, learn_mode, session_secret) as JSON
blobs. All mutations go through the API/panel and take effect immediately;
there is no config file and no hand-edit-then-restart ambiguity.

- legacy config.json auto-imports into the db on first start (renamed to
  config.json.migrated as a backup)
- new admin endpoints: PUT/DELETE /api/relays/{name} (how tinytuya wizard
  results are registered now) and PUT /api/chargers/{cp_id} (panel labels)
- BACKEND_DB env override so tests run on an isolated temp database
- smoke test: 45 checks, real db verified untouched
This commit is contained in:
2026-07-11 20:15:38 +02:00
parent 70c2fe1210
commit 56c9020d9f
10 changed files with 132 additions and 96 deletions
+3 -1
View File
@@ -1,5 +1,7 @@
# Runtime state + secrets (Tuya local keys live in config.json) # Runtime state + secrets (users, Tuya local keys, session secret live in backend.db)
backend.db
config.json config.json
config.json.migrated
events.jsonl events.jsonl
seen_tags.json seen_tags.json
sessions.db sessions.db
-51
View File
@@ -1,51 +0,0 @@
{
"learn_mode": true,
"session_secret": "<auto-generated on first run — signs login sessions>",
"users": {
"admin-user": {
"password": "<pbkdf2 hash — create users with: python -m backend.users add <name>>",
"scopes": ["admin"],
"id_tag": "app-admin-user"
},
"gun1-only-user": {
"password": "<pbkdf2 hash>",
"scopes": ["charger:eu092025:1", "relay:garden-lights"],
"id_tag": "app-gun1-only-user"
},
"relays-only-user": {
"password": "<pbkdf2 hash>",
"scopes": ["relay:*"],
"id_tag": "app-relays-only-user"
}
},
"authorized": {
"1000000000000000": {
"name": "Card linked to a user, works everywhere",
"kind": "card",
"user": "admin-user"
},
"1000000000000001": {
"name": "Card restricted to gun 2 of one charger",
"kind": "card",
"user": "gun1-only-user",
"guns": ["eu092025:2"]
},
"app-remote": { "name": "Web/app remote start token", "kind": "app" }
},
"chargers": {
"eu092025": {
"label": "Anfu 60kW",
"guns": { "1": "Gun 1 · EU (CCS)", "2": "Gun 2 · GB/T" }
}
},
"relays": {
"example-relay": {
"id": "<tuya device id from tinytuya wizard>",
"key": "<tuya local key from tinytuya wizard>",
"ip": "auto",
"version": 3.3,
"switch": 1,
"label": "Garden lights"
}
}
}
+39 -27
View File
@@ -1,49 +1,61 @@
"""Backend configuration — one JSON file, config.json, next to this module. """App state sections, backed by the settings table in backend.db (store.py).
Holds the charger allowlist (learn_mode + authorized idTags, same shape the CONFIG is the in-memory runtime state; save() persists it. Every mutation goes
discovery phase used), the user accounts with their permission scopes, and the through the API/panel (or the backend.users CLI), takes effect immediately,
Tuya relay registry. config.json is gitignored because it contains secrets and is durable — there is no config file to hand-edit and no restart-to-apply
(password hashes, the session-signing secret, Tuya local keys); semantics. A legacy config.json (pre-2026-07-11 layout) is imported into the
config.example.json documents the shape. database once on startup and renamed to config.json.migrated.
Sections:
learn_mode accept-and-record unknown idTags vs enforce the allowlist
users name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag"}
authorized idTag -> {"name", "kind": "card|app|car",
optional "user": owner, "guns": ["eu092025:2"]}
relays name -> {"id", "key", "ip", "version", "switch", "label"}
chargers cp_id -> {"label", "guns": {"1": "display name"}} (UI only)
session_secret signs login sessions; auto-generated once
""" """
import json import json
import logging
import secrets import secrets
from pathlib import Path from pathlib import Path
from . import store
HERE = Path(__file__).resolve().parent HERE = Path(__file__).resolve().parent
CONFIG_PATH = HERE / "config.json" LEGACY_CONFIG = HERE / "config.json"
log = logging.getLogger("config")
DEFAULTS = { DEFAULTS = {
"learn_mode": True, "learn_mode": True,
"users": {}, # name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag": ...} "users": {},
"authorized": {}, # idTag -> {"name", "kind": "card|app|car", "authorized": {},
# optional "user": owner, "guns": ["eu092025:2"]} "relays": {},
"relays": {}, # name -> {"id", "key", "ip", "version", "switch", "label"} "chargers": {},
"chargers": {}, # cp_id -> {"label", "guns": {"1": "display name", ...}} (UI only)
} }
def load() -> dict: def _load() -> dict:
if CONFIG_PATH.exists(): cfg = store.load_settings()
cfg = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) if not cfg and LEGACY_CONFIG.exists():
else: cfg = json.loads(LEGACY_CONFIG.read_text(encoding="utf-8"))
cfg = {} LEGACY_CONFIG.rename(LEGACY_CONFIG.with_suffix(".json.migrated"))
log.warning("imported legacy config.json into %s (file kept as "
"config.json.migrated)", store.DB_PATH.name)
for key, default in DEFAULTS.items(): for key, default in DEFAULTS.items():
cfg.setdefault(key, default if not isinstance(default, dict) else dict(default)) cfg.setdefault(key, default if not isinstance(default, dict) else dict(default))
if not cfg.get("session_secret"):
cfg["session_secret"] = secrets.token_hex(32)
return cfg return cfg
CONFIG = load() 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: def save() -> None:
CONFIG_PATH.write_text( store.save_settings(CONFIG)
json.dumps(CONFIG, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)
save() # persist migration / generated defaults immediately
+43
View File
@@ -313,6 +313,49 @@ async def users_delete(name: str, user: dict = Depends(current_user)):
return {"removed": name} return {"removed": name}
# ---- relay & charger registry (admin; how tinytuya wizard results get in) ----
class RelayBody(BaseModel):
id: str # tuya device id (from tinytuya wizard)
key: str # tuya local key (from tinytuya wizard)
ip: str = "auto" # pin the LAN IP once known (faster than discovery)
version: float = 3.3
switch: int = 1
label: Optional[str] = None
@router.put("/relays/{name}")
async def relay_put(name: str, body: RelayBody, user: dict = Depends(current_user)):
need(user, "admin")
entry = body.model_dump()
entry["label"] = entry["label"] or name
CONFIG["relays"][name] = entry
save()
log.info("relays: %r set by %r", name, user["name"])
return {"relays": relays.configured()}
@router.delete("/relays/{name}")
async def relay_delete(name: str, user: dict = Depends(current_user)):
need(user, "admin")
if CONFIG["relays"].pop(name, None) is None:
raise HTTPException(404, f"no relay {name!r}")
save()
return {"relays": relays.configured()}
class ChargerBody(BaseModel):
label: Optional[str] = None
guns: Optional[dict[str, str]] = None # {"1": "Gun 1 · EU (CCS)"}
@router.put("/chargers/{cp_id}")
async def charger_put(cp_id: str, body: ChargerBody, user: dict = Depends(current_user)):
need(user, "admin")
CONFIG["chargers"][cp_id] = body.model_dump(exclude_none=True)
save()
return {"chargers": CONFIG["chargers"]}
# ---- relays (scope: relay:<name>) ---- # ---- relays (scope: relay:<name>) ----
@router.get("/relays") @router.get("/relays")
async def relays_list(live: bool = False, user: dict = Depends(current_user)): async def relays_list(live: bool = False, user: dict = Depends(current_user)):
+30 -4
View File
@@ -1,27 +1,37 @@
"""Charging-session store — who charged, when, and how many kWh. """The one persistent store: SQLite (stdlib) in backend.db next to this module.
SQLite (stdlib) in sessions.db next to this module. Two tables:
sessions — one row per transaction: cp, connector, idTag, resolved "who", sessions — one row per transaction: cp, connector, idTag, resolved "who",
start/end timestamps (charger-reported), meter readings, Wh, reason start/end timestamps (charger-reported), meter readings, Wh, reason
samples — per-minute MeterValues while charging (energy/power/SoC) for samples — per-minute MeterValues while charging (energy/power/SoC) for
later charts later charts
settings — the app state sections (users, allowlist, relays, chargers,
learn_mode, session_secret) as JSON blobs, one row per section.
Always whole-section reads/writes, so blobs beat normalized
tables here. Managed through config.py — see there.
The events.jsonl journal (journal.py) stays the raw ground truth; this is the 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 queryable view. Transaction ids come from MAX(tx)+1 here, so they survive
backend restarts (the in-memory counter used to reset to 0). backend restarts.
sqlite3 connections are cheap at household scale — one per call, no pooling. sqlite3 connections are cheap at household scale — one per call, no pooling.
BACKEND_DB env var overrides the path (used by tests to stay off the real db).
""" """
import json
import os
import sqlite3 import sqlite3
from contextlib import closing from contextlib import closing
from pathlib import Path from pathlib import Path
from typing import Optional from typing import Optional
HERE = Path(__file__).resolve().parent HERE = Path(__file__).resolve().parent
DB_PATH = HERE / "sessions.db" DB_PATH = Path(os.environ.get("BACKEND_DB", HERE / "backend.db"))
_SCHEMA = """ _SCHEMA = """
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions ( CREATE TABLE IF NOT EXISTS sessions (
tx INTEGER PRIMARY KEY, tx INTEGER PRIMARY KEY,
cp TEXT NOT NULL, cp TEXT NOT NULL,
@@ -56,6 +66,22 @@ def _db():
return closing(con) return closing(con)
def load_settings() -> dict:
with _db() as con, con:
return {
row["key"]: json.loads(row["value"])
for row in con.execute("SELECT key, value FROM settings")
}
def save_settings(sections: dict) -> None:
with _db() as con, con:
con.executemany(
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
[(key, json.dumps(value, ensure_ascii=False)) for key, value in sections.items()],
)
def max_tx() -> int: def max_tx() -> int:
with _db() as con, con: with _db() as con, con:
row = con.execute("SELECT MAX(tx) AS m FROM sessions").fetchone() row = con.execute("SELECT MAX(tx) AS m FROM sessions").fetchone()
+3 -3
View File
@@ -6,7 +6,7 @@ tags: [auth, requirements]
# Authorization Methods # Authorization Methods
The three planned ways to authorize a charging session. Architecturally they all collapse to one gate: **`decide(id_tag, connector)` in the [[backend]]** (`backend/csms.py`; formerly `station.py` in [[csms-toolkit]]) returns Accepted/Rejected against the allowlist in `backend/config.json`. Per [[2026-07-09-findings-and-requirements]]. On top of these charger-side methods sits the **per-user API permission system** (last section). The three planned ways to authorize a charging session. Architecturally they all collapse to one gate: **`decide(id_tag, connector)` in the [[backend]]** (`backend/csms.py`; formerly `station.py` in [[csms-toolkit]]) returns Accepted/Rejected against the allowlist in `backend.db`. Per [[2026-07-09-findings-and-requirements]]. On top of these charger-side methods sits the **per-user API permission system** (last section).
## 1. RFID cards — ✅ verified live (2026-07-09) ## 1. RFID cards — ✅ verified live (2026-07-09)
@@ -55,7 +55,7 @@ A mobile-friendly web control panel (no app store):
The [[backend]] now has real multi-user authorization on top of the three methods above, because not every household member may control everything. Requirement (owner, 2026-07-11): some users control gun 1 only, some gun 2, some only certain [[wifi-relays|relays]]. The [[backend]] now has real multi-user authorization on top of the three methods above, because not every household member may control everything. Requirement (owner, 2026-07-11): some users control gun 1 only, some gun 2, some only certain [[wifi-relays|relays]].
- **Users** live in `backend/config.json` → `"users"`: username + PBKDF2 password hash + scope list + a personal `id_tag` (`app-<name>`) used for their remote starts, so charging sessions are **attributable per person**. - **Users** live in the `settings` table of `backend.db`: username + PBKDF2 password hash + scope list + a personal `id_tag` (`app-<name>`) used for their remote starts, so charging sessions are **attributable per person**.
- **Login**: `POST /api/login` (username/password) → 30-day HMAC-signed session, delivered as an HttpOnly cookie (for the PWA) and as a bearer token (for curl). Stateless — survives backend restarts; deleting a user kills their sessions. - **Login**: `POST /api/login` (username/password) → 30-day HMAC-signed session, delivered as an HttpOnly cookie (for the PWA) and as a bearer token (for curl). Stateless — survives backend restarts; deleting a user kills their sessions.
- **Scopes** (fnmatch wildcards work): - **Scopes** (fnmatch wildcards work):
@@ -67,7 +67,7 @@ The [[backend]] now has real multi-user authorization on top of the three method
| `admin` | everything, incl. allowlist/user CRUD, learn-mode flip, setconfig, events | | `admin` | everything, incl. allowlist/user CRUD, learn-mode flip, setconfig, events |
- **Bootstrap**: zero users = open API (startup warns loudly). First user: `venv\Scripts\python -m backend.users add <name> --scopes admin`. - **Bootstrap**: zero users = open API (startup warns loudly). First user: `venv\Scripts\python -m backend.users add <name> --scopes admin`.
- ✅ Verified by the 28-check smoke test (login, wrong password, cookie + bearer, per-scope 403s, relay visibility filtering, user CRUD, session invalidation on delete). ⚠️ Not yet exercised from a real browser/PWA (doesn't exist yet). - ✅ Verified by the 45-check smoke test (login, wrong password, cookie + bearer, per-scope 403s, relay visibility filtering, user CRUD, session invalidation on delete). ⚠️ Not yet exercised from a real phone browser.
This resolves the ❓ "web app auth" open decision in [[overview]]: username+password with per-resource scopes, chosen over plain tokens by the owner. This resolves the ❓ "web app auth" open decision in [[overview]]: username+password with per-resource scopes, chosen over plain tokens by the owner.
+6 -6
View File
@@ -16,12 +16,11 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
├── routes.py REST under /api/* (login + per-scope permission checks) ├── routes.py REST under /api/* (login + per-scope permission checks)
├── users.py passwords (PBKDF2), sessions (HMAC), scope matcher, user CLI ├── users.py passwords (PBKDF2), sessions (HMAC), scope matcher, user CLI
├── store.py SQLite session store: who charged, when, how many kWh + meter samples ├── store.py SQLite session store: who charged, when, how many kWh + meter samples
├── config.py config.json load/save ├── config.py app-state sections (users/allowlist/relays/chargers), db-backed
├── journal.py events.jsonl + seen_tags.json (raw ground truth) ├── journal.py events.jsonl + seen_tags.json (raw ground truth)
├── static/ the web panel PWA (index.html, manifest, service worker, icon) ├── static/ the web panel PWA (index.html, manifest, service worker, icon)
├── config.json users + allowlist + relay registry — GITIGNORED (password └── backend.db THE one store (SQLite, gitignored): sessions + samples +
│ hashes, session secret, Tuya local keys); see config.example.json settings (users, allowlist, relays, chargers, session secret)
└── sessions.db SQLite (gitignored, auto-created)
``` ```
## Surfaces (all on :9000 — the touchscreen URL never changes) ## Surfaces (all on :9000 — the touchscreen URL never changes)
@@ -44,10 +43,11 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
- **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-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`. - **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. - 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. - **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.
- Relay calls are blocking tinytuya I/O, run via `asyncio.to_thread` so the OCPP socket never stalls. - 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. - 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. - ✅ Smoke-tested 2026-07-11 (45 checks, 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.
- ✅ **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 notes ## Web panel notes
+1 -1
View File
@@ -19,7 +19,7 @@ Local control needs each device's **id + local key**, extracted once via Tuya's
1. Create a (free) account at `iot.tuya.com` → Cloud → create a project (data center matching the SmartLife account region). 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). 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`. 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**). 4. Register each relay via `PUT /api/relays/<name>` (admin; interactive form at `/docs`) with its `id`, `key`, `ip`, `version`. 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]]). 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]]).
+4
View File
@@ -75,3 +75,7 @@ Owner requirement: button-push start when a gun is ready (and permitted) + "who
## [2026-07-11] meta | Cards linked to users; multi-charger gaps closed ## [2026-07-11] meta | Cards linked to users; multi-charger gaps closed
Owner requirements: cards must belong to a person (not float around as "RFID card A (tapped first...)"), and adding a second charger must be clean. Allowlist entries now take "user" (sessions attribute to the person; owner sees their card's history) and charger-qualified "guns": ["eu092025:2"] (fnmatch; replaces the charger-blind "connectors" field). Gun display names moved from hardcoded panel JS to a "chargers" config section served via /api/status. Adding a charger = point it at the same URL with a unique ChargerID + grant charger:<id>:<gun> scopes. Panel admin tab: owner dropdown + guns field. Smoke test 37 -> 42 checks. Updated [[authorization]], [[backend]]. Owner requirements: cards must belong to a person (not float around as "RFID card A (tapped first...)"), and adding a second charger must be clean. Allowlist entries now take "user" (sessions attribute to the person; owner sees their card's history) and charger-qualified "guns": ["eu092025:2"] (fnmatch; replaces the charger-blind "connectors" field). Gun display names moved from hardcoded panel JS to a "chargers" config section served via /api/status. Adding a charger = point it at the same URL with a unique ChargerID + grant charger:<id>:<gun> scopes. Panel admin tab: owner dropdown + guns field. Smoke test 37 -> 42 checks. Updated [[authorization]], [[backend]].
## [2026-07-11] meta | config.json eliminated — one SQLite store (backend.db)
Owner pushback: two persistence stores (sessions.db + a config.json that doubled as a mutable datastore) was one too many, with confusing hand-edit-needs-restart semantics. Now everything lives in backend.db (renamed from sessions.db): sessions + samples tables plus a settings table holding the app-state sections (users, allowlist, relays, chargers, learn_mode, session_secret) as JSON blobs. All changes go through the API/panel and apply immediately; nothing to hand-edit. Legacy config.json auto-imports on first start (kept as config.json.migrated) — julian + cards + charger labels migrated. New admin endpoints PUT/DELETE /api/relays/{name} and PUT /api/chargers/{id} replace file editing (tinytuya wizard results now enter via /docs). Smoke test isolated via BACKEND_DB env override; 45 checks. Also: live cutover confirmed — eu092025 connected to the backend this evening. Updated [[backend]], [[authorization]], [[wifi-relays]], [[overview]].
+3 -3
View File
@@ -12,7 +12,7 @@ tags: [synthesis]
**Connectivity: ✅ solved.** The [[jc-6620|JC-6620]] controller inside the [[anfu-charger|charging pile]] reliably dials out to the CSMS — verified both on the charger's own LAN (`192.168.2.114:9000`) and across the NAT boundary on the WAN subnet (`10.0.10.203:9000`). Getting here required the fixes catalogued in [[troubleshooting]]; the network layout is in [[network-topology]]. **Connectivity: ✅ solved.** The [[jc-6620|JC-6620]] controller inside the [[anfu-charger|charging pile]] reliably dials out to the CSMS — verified both on the charger's own LAN (`192.168.2.114:9000`) and across the NAT boundary on the WAN subnet (`10.0.10.203:9000`). Getting here required the fixes catalogued in [[troubleshooting]]; the network layout is in [[network-topology]].
**Software: production [[backend]] built (2026-07-11), including the web panel.** `station.py` was ported into the `../backend/` package: one FastAPI process on port 9000 = CSMS WebSocket + `/api/*` (charger control, allowlist CRUD, runtime learn-mode flip) + [[wifi-relays|Tuya relay]] on/off/toggle + **multi-user auth** (username/password, per-resource scopes: gun 1 / gun 2 / per-relay / admin, per-gun-restrictable RFID cards — [[authorization]]) + **consumption tracking** (SQLite: who charged, when, how many kWh, per-minute meter samples) + the **PWA control panel** at `/` (login, scope-filtered start/stop buttons, relay toggles, history, admin). Smoke-tested (37 checks incl. a fake charge point over the real WS route); ⚠️ not yet run against the live charger or a real phone. The [[csms-toolkit]] (`../discovering/`) remains as diagnostic tooling. **Software: production [[backend]] built (2026-07-11), including the web panel.** `station.py` was ported into the `../backend/` package: one FastAPI process on port 9000 = CSMS WebSocket + `/api/*` (charger control, allowlist CRUD, runtime learn-mode flip) + [[wifi-relays|Tuya relay]] on/off/toggle + **multi-user auth** (username/password, per-resource scopes: gun 1 / gun 2 / per-relay / admin, per-gun-restrictable RFID cards — [[authorization]]) + **consumption tracking** (SQLite: who charged, when, how many kWh, per-minute meter samples) + the **PWA control panel** at `/` (login, scope-filtered start/stop buttons, relay toggles, history, admin). Smoke-tested (45 checks incl. a fake charge point over the real WS route); ✅ live charger connects to it since 2026-07-11 evening; ⚠️ panel untested from a real phone. All state lives in one SQLite file (`backend.db`) — no config file, every change via API/panel takes effect immediately. The [[csms-toolkit]] (`../discovering/`) remains as diagnostic tooling.
**Capabilities: ✅ known.** The live probe ([[2026-07-09-discovery-eu092025]]) identified the pile as SimpleCharge "MultiSocketCharger" (fw 1.24.0620.1, OCPP ID `eu092025`) with **two guns**, RemoteTrigger (verified), SmartCharging, Reservation, a 6-entry local auth list, and per-minute meter data including SoC. Only Autocharge remains unknown (physical test pending; `MacEnabled` is a lead — [[authorization]]). **Capabilities: ✅ known.** The live probe ([[2026-07-09-discovery-eu092025]]) identified the pile as SimpleCharge "MultiSocketCharger" (fw 1.24.0620.1, OCPP ID `eu092025`) with **two guns**, RemoteTrigger (verified), SmartCharging, Reservation, a 6-entry local auth list, and per-minute meter data including SoC. Only Autocharge remains unknown (physical test pending; `MacEnabled` is a lead — [[authorization]]).
@@ -25,9 +25,9 @@ Hardware surprise: this is a **DC-capable multi-standard charger** (gun 1 EU, gu
## What's next ## What's next
1. **Cut the live charger over to the [[backend]]** — stop `station.py`, run `python -m backend.main` from the repo root, verify the JC-6620 reconnects and a card tap still authorizes (allowlist already migrated to `backend/config.json`). 1. ~~Cut the live charger over to the backend~~ — ✅ done 2026-07-11 evening: `eu092025` connects to `python -m backend.main` (verified in events.jsonl). Remaining: a card tap + a panel button-push on the live charger.
2. **Create the real users** — `python -m backend.users add <name> --scopes ...` for each household member (the API stays open until the first user exists). 2. **Create the real users** — `python -m backend.users add <name> --scopes ...` for each household member (the API stays open until the first user exists).
3. **Extract the Tuya local keys** (`tinytuya wizard` — steps in [[wifi-relays]]) and fill `backend/config.json` → relays become controllable. 3. **Extract the Tuya local keys** (`tinytuya wizard` — steps in [[wifi-relays]]) and register them via `PUT /api/relays/<name>` → relays become controllable.
4. **Flip learn mode off** — both cards + the app token are enrolled; switchable from the panel's Admin tab or `POST /api/mode?learn=false`, no restart. (Only wait if more cards need tapping.) 4. **Flip learn mode off** — both cards + the app token are enrolled; switchable from the panel's Admin tab or `POST /api/mode?learn=false`, no restart. (Only wait if more cards need tapping.)
5. **Test the panel from a phone** — it's built and serving at `http://<host>:9000/`; verify login, a real button-push start on a ready gun, and add-to-home-screen over [[netbird|NetBird]]. 5. **Test the panel from a phone** — it's built and serving at `http://<host>:9000/`; verify login, a real button-push start on a ready gun, and add-to-home-screen over [[netbird|NetBird]].
6. **Resolve the ❓ remote-stop restart question** — did the gun-2 session auto-restart from auth cache after RemoteStop, or was the card re-tapped? Affects the app's Stop button UX ([[authorization]]). 6. **Resolve the ❓ remote-stop restart question** — did the gun-2 session auto-restart from auth cache after RemoteStop, or was the card re-tapped? Affects the app's Stop button UX ([[authorization]]).