feat: React control panel; pending-card review workflow; auth-method audit

Frontend rewrite (frontend/, replacing backend/static/):
- Vite + TypeScript + React 19, React Router 7, zustand, TanStack Query 5
- dev: vite proxy /api -> :9000; prod: npm run build -> dist/, served by
  the backend with SPA fallback
- pages: Control (gun bays w/ scope+readiness-gated start/stop, relays),
  History (who/via/gun/when/duration/kWh audit), Cards (pending review,
  enrolled, rejected), Users (permission checkbox matrix)
- self-contained: fonts bundled, no CDN; light/dark; reduced-motion safe

Backend:
- learn mode removed: unknown cards are always refused and queued in
  pending_cards; admin approves (name + owner + gun restrictions in one
  step) or rejects (denied_cards, silent, un-rejectable); pending count
  rides /api/status as the notification signal
- sessions record the auth method (card tap vs in-app button) for audit
- GET /api/permissions: grantable-permission catalog driving the UI matrix
- SPA static serving with path-traversal guard; 503 hint when not built

Smoke test: 54 checks incl. approve/reject round-trips over a fake charge
point and method audit assertions.
This commit is contained in:
2026-07-11 20:52:20 +02:00
parent 56c9020d9f
commit 75869364b0
41 changed files with 4057 additions and 610 deletions
+4 -2
View File
@@ -1,6 +1,8 @@
# Charging Station Project # Charging Station Project
Two parts: Four parts:
- **`backend/`** — the production FastAPI backend: private OCPP 1.6J CSMS + REST API + Tuya relay control on port 9000. All state in `backend/backend.db` (SQLite, gitignored). Run from the repo root: `venv\Scripts\python -m backend.main`. Documented at `wiki/entities/backend.md`.
- **`frontend/`** — the React control panel (Vite + TypeScript + React Router + zustand + TanStack Query). Dev: `npm run dev` (proxies `/api` to :9000). Prod: `npm run build` → `frontend/dist/`, served statically by the backend. Documented at `wiki/entities/frontend.md`.
- **`wiki/`** — an LLM-maintained knowledge base about the Anfu home charger OCPP integration. **Read `wiki/CLAUDE.md` before touching anything in it** — it defines the schema, conventions, and ingest/query/lint workflows. `wiki/raw/` is immutable source material; never edit it. - **`wiki/`** — an LLM-maintained knowledge base about the Anfu home charger OCPP integration. **Read `wiki/CLAUDE.md` before touching anything in it** — it defines the schema, conventions, and ingest/query/lint workflows. `wiki/raw/` is immutable source material; never edit it.
- **`discovering/`** — throwaway-ish Python scripts to test the charging station connection and watch WebSocket payloads in realtime (`csms.py`, `rawlisten.py`, `station.py`). Documented in the wiki at `wiki/entities/csms-toolkit.md`. - **`discovering/`** — throwaway-ish Python scripts used during discovery (`csms.py`, `rawlisten.py`, `station.py`). Superseded by `backend/` for production; kept as diagnostics. Documented at `wiki/entities/csms-toolkit.md`.
+10 -2
View File
@@ -7,13 +7,19 @@ semantics. A legacy config.json (pre-2026-07-11 layout) is imported into the
database once on startup and renamed to config.json.migrated. database once on startup and renamed to config.json.migrated.
Sections: Sections:
learn_mode accept-and-record unknown idTags vs enforce the allowlist
users name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag"} users name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag"}
authorized idTag -> {"name", "kind": "card|app|car", authorized idTag -> {"name", "kind": "card|app|car",
optional "user": owner, "guns": ["eu092025:2"]} optional "user": owner, "guns": ["eu092025:2"]}
pending_cards unknown idTags tapped on a charger, awaiting the admin's
approve (-> authorized, linked to a user) or reject decision;
idTag -> {"first_seen", "last_seen", "count", "cp", "connector"}
denied_cards rejected idTags; silently refused, never re-pend
relays name -> {"id", "key", "ip", "version", "switch", "label"} relays name -> {"id", "key", "ip", "version", "switch", "label"}
chargers cp_id -> {"label", "guns": {"1": "display name"}} (UI only) chargers cp_id -> {"label", "guns": {"1": "display name"}} (UI only)
session_secret signs login sessions; auto-generated once session_secret signs login sessions; auto-generated once
There is no learn mode anymore: an unknown card is ALWAYS refused, but lands
in pending_cards for the admin to approve or reject from the panel.
""" """
import json import json
@@ -29,9 +35,10 @@ LEGACY_CONFIG = HERE / "config.json"
log = logging.getLogger("config") log = logging.getLogger("config")
DEFAULTS = { DEFAULTS = {
"learn_mode": True,
"users": {}, "users": {},
"authorized": {}, "authorized": {},
"pending_cards": {},
"denied_cards": {},
"relays": {}, "relays": {},
"chargers": {}, "chargers": {},
} }
@@ -46,6 +53,7 @@ def _load() -> dict:
"config.json.migrated)", store.DB_PATH.name) "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))
cfg.pop("learn_mode", None) # superseded by the pending-cards workflow
if not cfg.get("session_secret"): if not cfg.get("session_secret"):
cfg["session_secret"] = secrets.token_hex(32) cfg["session_secret"] = secrets.token_hex(32)
return cfg return cfg
+28 -11
View File
@@ -27,8 +27,8 @@ from ocpp.v16.enums import (
) )
from . import store from . import store
from .config import CONFIG, HERE from .config import CONFIG, HERE, save
from .journal import now, record_event, record_seen from .journal import now, record_event
log = logging.getLogger("csms") log = logging.getLogger("csms")
@@ -47,6 +47,16 @@ TRIGGERABLE = {
} }
def _record_pending(id_tag: str, cp: Optional[str], connector: Optional[int]) -> None:
"""An unknown card was tapped: queue it for the admin to approve or reject."""
entry = CONFIG["pending_cards"].get(
id_tag, {"first_seen": now(), "count": 0}
)
entry.update(last_seen=now(), count=entry["count"] + 1, cp=cp, connector=connector)
CONFIG["pending_cards"][id_tag] = entry
save()
def decide(id_tag: str, context: str, connector: Optional[int] = None, def decide(id_tag: str, context: str, connector: Optional[int] = None,
cp: Optional[str] = None) -> AuthorizationStatus: cp: Optional[str] = None) -> AuthorizationStatus:
"""The one gate every auth method flows through: is this idTag allowed? """The one gate every auth method flows through: is this idTag allowed?
@@ -57,6 +67,9 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
fires there; a plain Authorize (card tap) still accepts a known card — fires there; a plain Authorize (card tap) still accepts a known card —
which matches this charger, since AuthorizeRemoteTxRequests=false means which matches this charger, since AuthorizeRemoteTxRequests=false means
StartTransaction is the decisive call anyway. StartTransaction is the decisive call anyway.
Unknown idTags are always refused: silently if the admin already rejected
the card, otherwise they land in pending_cards for the admin to decide.
""" """
entry = CONFIG["authorized"].get(id_tag) entry = CONFIG["authorized"].get(id_tag)
known = entry is not None known = entry is not None
@@ -70,13 +83,13 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
name = entry.get("name", "?") name = entry.get("name", "?")
log.info("[OK] AUTHORIZED idTag=%r (%s) via %s", id_tag, name, context) log.info("[OK] AUTHORIZED idTag=%r (%s) via %s", id_tag, name, context)
status = AuthorizationStatus.accepted status = AuthorizationStatus.accepted
elif CONFIG.get("learn_mode"): elif id_tag in CONFIG["denied_cards"]:
log.warning("[LEARN] NEW idTag=%r via %s -> accepting & recording.", id_tag, context) log.warning("[NO] DENIED idTag=%r (admin-rejected card) via %s", id_tag, context)
record_seen(id_tag, context) status = AuthorizationStatus.invalid
status = AuthorizationStatus.accepted
else: else:
log.warning("[NO] REJECTED unknown idTag=%r via %s", id_tag, context) log.warning("[??] UNKNOWN idTag=%r via %s -> refused, queued for admin approval",
record_seen(id_tag, context) id_tag, context)
_record_pending(id_tag, cp, connector)
status = AuthorizationStatus.invalid status = AuthorizationStatus.invalid
AUTH_EVENTS.append( AUTH_EVENTS.append(
{"time": now(), "id_tag": id_tag, "context": context, {"time": now(), "id_tag": id_tag, "context": context,
@@ -126,7 +139,7 @@ class ChargePoint(OcppChargePoint):
@on(Action.authorize) @on(Action.authorize)
async def on_authorize(self, id_tag, **kwargs): async def on_authorize(self, id_tag, **kwargs):
status = decide(id_tag, "Authorize (card/app)") status = decide(id_tag, "Authorize (card/app)", cp=self.id)
record_event("Authorize", self.id, id_tag=id_tag, result=status.value) record_event("Authorize", self.id, id_tag=id_tag, result=status.value)
return call_result.Authorize(id_tag_info={"status": status}) return call_result.Authorize(id_tag_info={"status": status})
@@ -138,12 +151,16 @@ class ChargePoint(OcppChargePoint):
_tx_counter["n"] += 1 _tx_counter["n"] += 1
tx = _tx_counter["n"] tx = _tx_counter["n"]
who = resolve_who(id_tag) who = resolve_who(id_tag)
# audit: HOW was this session authorized? kind of the allowlist
# entry -> "card" (physical tap) or "app" (in-app button press)
method = CONFIG["authorized"].get(id_tag, {}).get("kind", "unknown")
ACTIVE_TX[tx] = { ACTIVE_TX[tx] = {
"cp": self.id, "connector": connector_id, "id_tag": id_tag, "cp": self.id, "connector": connector_id, "id_tag": id_tag,
"who": who, "meter_start": meter_start, "started": now(), "who": who, "method": method,
"meter_start": meter_start, "started": now(),
} }
store.start_session(tx, self.id, connector_id, id_tag, who, store.start_session(tx, self.id, connector_id, id_tag, who,
timestamp, meter_start) timestamp, meter_start, method=method)
log.info("Transaction %s STARTED on connector %s by %s (meter_start=%s)", log.info("Transaction %s STARTED on connector %s by %s (meter_start=%s)",
tx, connector_id, who, meter_start) tx, connector_id, who, meter_start)
else: else:
+3 -26
View File
@@ -1,8 +1,6 @@
"""Durable journals: events.jsonl (everything the charger tells us) and """Durable journal: events.jsonl — everything the charger tells us (and what
seen_tags.json (unknown idTags captured in learn mode). we told it), one JSON line per event. Append-only, crash-safe, greppable; the
raw ground truth behind the queryable store (store.py).
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 json
@@ -13,7 +11,6 @@ from typing import Optional
HERE = Path(__file__).resolve().parent HERE = Path(__file__).resolve().parent
EVENTS_PATH = HERE / "events.jsonl" EVENTS_PATH = HERE / "events.jsonl"
SEEN_PATH = HERE / "seen_tags.json"
log = logging.getLogger("journal") log = logging.getLogger("journal")
@@ -39,23 +36,3 @@ def read_events(limit: int = 100, event: Optional[str] = None) -> list:
if event is not None: if event is not None:
entries = [e for e in entries if e.get("event") == event] entries = [e for e in entries if e.get("event") == event]
return entries[-limit:] 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"))
+23 -17
View File
@@ -17,13 +17,13 @@ from pathlib import Path
import uvicorn import uvicorn
from fastapi import FastAPI, WebSocket from fastapi import FastAPI, WebSocket
from fastapi.responses import FileResponse from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from . import csms, routes from . import csms, routes
from .config import CONFIG from .config import CONFIG
STATIC = Path(__file__).resolve().parent / "static" # the built React app (frontend/: `npm run build` -> dist/)
DIST = Path(__file__).resolve().parent.parent / "frontend" / "dist"
logging.basicConfig( logging.basicConfig(
level=logging.INFO, level=logging.INFO,
@@ -37,18 +37,23 @@ app = FastAPI(
"ws://<host>:9000/<id>; everything else lives under /api/*.", "ws://<host>:9000/<id>; everything else lives under /api/*.",
) )
app.include_router(routes.router) app.include_router(routes.router)
app.mount("/static", StaticFiles(directory=STATIC), name="static")
@app.get("/") # SPA serving: exact files from frontend/dist, anything else falls back to
async def index_page(): # index.html so React Router owns the URL space. Registered after the API
return FileResponse(STATIC / "index.html") # router, so /api/* and /docs keep winning.
@app.get("/{full_path:path}", include_in_schema=False)
async def spa(full_path: str):
# the service worker must be served from / so its scope covers the whole app if not DIST.exists():
@app.get("/sw.js") return JSONResponse(
async def service_worker(): {"detail": "frontend not built — run `npm run build` in frontend/ "
return FileResponse(STATIC / "sw.js", media_type="application/javascript") "(or use the Vite dev server, which proxies /api here)"},
status_code=503,
)
candidate = (DIST / full_path).resolve() if full_path else None
if candidate and candidate.is_file() and candidate.is_relative_to(DIST.resolve()):
return FileResponse(candidate)
return FileResponse(DIST / "index.html")
# Catch-all WS route so the charger may dial any path (it uses /<ChargerID>). # Catch-all WS route so the charger may dial any path (it uses /<ChargerID>).
@@ -59,11 +64,12 @@ async def ocpp_websocket(ws: WebSocket, cp_path: str):
async def main(): async def main():
mode = "LEARN (accepting & recording new ids)" if CONFIG["learn_mode"] else "ENFORCING allowlist"
log.info( log.info(
"CSMS ws://0.0.0.0:9000/<id> | API http://0.0.0.0:9000/docs | mode: %s | " "CSMS ws://0.0.0.0:9000/<id> | API http://0.0.0.0:9000/docs | "
"%d authorized id(s) | %d user(s) | %d relay(s) configured", "%d authorized id(s) | %d pending card(s) | %d user(s) | %d relay(s) | panel %s",
mode, len(CONFIG["authorized"]), len(CONFIG["users"]), len(CONFIG["relays"]), len(CONFIG["authorized"]), len(CONFIG["pending_cards"]),
len(CONFIG["users"]), len(CONFIG["relays"]),
"ready" if DIST.exists() else "NOT BUILT (frontend/: npm run build)",
) )
if not CONFIG["users"]: if not CONFIG["users"]:
log.warning( log.warning(
+85 -14
View File
@@ -17,7 +17,7 @@ from pydantic import BaseModel
from . import csms, relays, store, users from . import csms, relays, store, users
from .config import CONFIG, save from .config import CONFIG, save
from .journal import read_events, read_seen from .journal import now, read_events
from ocpp.v16 import call from ocpp.v16 import call
log = logging.getLogger("api") log = logging.getLogger("api")
@@ -110,16 +110,18 @@ async def me(user: dict = Depends(current_user)):
# ---- status & journals ---- # ---- status & journals ----
@router.get("/status") @router.get("/status")
async def api_status(user: dict = Depends(current_user)): async def api_status(user: dict = Depends(current_user)):
is_admin = users.allowed(user["scopes"], "admin")
return { return {
"mode": "learn" if CONFIG.get("learn_mode") else "enforce",
"connected": { "connected": {
cp_id: getattr(cp, "boot_info", None) for cp_id, cp in csms.CONNECTED.items() 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()}, "connectors": {f"{cp_id}/{conn}": s for (cp_id, conn), s in csms.CONNECTORS.items()},
"active_transactions": csms.ACTIVE_TX, "active_transactions": csms.ACTIVE_TX,
"recent_auth_events": list(csms.AUTH_EVENTS), "recent_auth_events": list(csms.AUTH_EVENTS) if is_admin else [],
"relays": _visible_relays(user), "relays": _visible_relays(user),
"chargers": CONFIG["chargers"], # display labels for the panel "chargers": CONFIG["chargers"], # display labels for the panel
# the admin's notification bell: unknown cards awaiting a decision
"pending_cards": len(CONFIG["pending_cards"]) if is_admin else 0,
} }
@@ -238,11 +240,7 @@ class AllowlistEntry(BaseModel):
@router.get("/allowlist") @router.get("/allowlist")
async def allowlist_get(user: dict = Depends(current_user)): async def allowlist_get(user: dict = Depends(current_user)):
need(user, "admin") need(user, "admin")
return { return {"authorized": CONFIG["authorized"]}
"learn_mode": CONFIG["learn_mode"],
"authorized": CONFIG["authorized"],
"seen": read_seen(),
}
@router.put("/allowlist/{id_tag}") @router.put("/allowlist/{id_tag}")
@@ -267,14 +265,87 @@ async def allowlist_delete(id_tag: str, user: dict = Depends(current_user)):
return {"authorized": CONFIG["authorized"]} return {"authorized": CONFIG["authorized"]}
@router.post("/mode") # ---- pending cards: unknown taps awaiting the admin's decision ----
async def set_mode(learn: bool, user: dict = Depends(current_user)): class ApproveBody(BaseModel):
"""Flip learn mode at runtime — no restart needed; decide() reads CONFIG live.""" name: str
user: Optional[str] = None # link the card to its owner right here
guns: Optional[list[str]] = None
kind: str = "card"
@router.get("/cards/pending")
async def pending_list(user: dict = Depends(current_user)):
need(user, "admin") need(user, "admin")
CONFIG["learn_mode"] = learn return CONFIG["pending_cards"]
@router.post("/cards/pending/{id_tag}/approve")
async def pending_approve(id_tag: str, body: ApproveBody,
user: dict = Depends(current_user)):
need(user, "admin")
if id_tag not in CONFIG["pending_cards"]:
raise HTTPException(404, f"{id_tag!r} is not pending")
if body.user is not None and body.user not in CONFIG["users"]:
raise HTTPException(400, f"cannot link card to unknown user {body.user!r}")
CONFIG["pending_cards"].pop(id_tag)
CONFIG["authorized"][id_tag] = body.model_dump(exclude_none=True)
save() save()
log.warning("mode changed: %s", "LEARN" if learn else "ENFORCE") log.info("pending card %r APPROVED by %r as %r (user=%s)",
return {"mode": "learn" if learn else "enforce"} id_tag, user["name"], body.name, body.user)
return {"approved": id_tag, "authorized": CONFIG["authorized"]}
@router.post("/cards/pending/{id_tag}/reject")
async def pending_reject(id_tag: str, user: dict = Depends(current_user)):
need(user, "admin")
meta = CONFIG["pending_cards"].pop(id_tag, None)
if meta is None:
raise HTTPException(404, f"{id_tag!r} is not pending")
CONFIG["denied_cards"][id_tag] = {
"rejected_at": now(), "by": user["name"],
**{k: meta[k] for k in ("first_seen", "count") if k in meta},
}
save()
log.warning("pending card %r REJECTED by %r", id_tag, user["name"])
return {"rejected": id_tag}
@router.get("/cards/denied")
async def denied_list(user: dict = Depends(current_user)):
need(user, "admin")
return CONFIG["denied_cards"]
@router.delete("/cards/denied/{id_tag}")
async def denied_delete(id_tag: str, user: dict = Depends(current_user)):
"""Un-reject: the card pends again on its next tap."""
need(user, "admin")
if CONFIG["denied_cards"].pop(id_tag, None) is None:
raise HTTPException(404, f"{id_tag!r} is not denied")
save()
return {"undenied": id_tag}
# ---- permission catalog: what CAN be granted (drives the UI matrix) ----
@router.get("/permissions")
async def permissions_catalog(user: dict = Depends(current_user)):
"""Everything a scope could refer to, so the panel renders checkboxes
instead of asking admins to type raw scope strings."""
need(user, "admin")
chargers = {}
for cp_id, meta in CONFIG["chargers"].items():
chargers[cp_id] = {"label": meta.get("label", cp_id),
"guns": dict(meta.get("guns", {}))}
# chargers that connected but were never given display labels
for (cp_id, conn) in csms.CONNECTORS:
if conn > 0:
entry = chargers.setdefault(cp_id, {"label": cp_id, "guns": {}})
entry["guns"].setdefault(str(conn), f"Gun {conn}")
return {
"chargers": chargers, # scope per gun: charger:<cp>:<conn>
"relays": relays.configured(), # scope per relay: relay:<name>
"admin_scope": "admin",
}
# ---- user management (admin) ---- # ---- user management (admin) ----
-4
View File
@@ -1,4 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<rect width="100" height="100" rx="22" fill="#0f172a"/>
<path d="M55 12 L28 56 L46 56 L41 88 L72 42 L52 42 Z" fill="#facc15"/>
</svg>

Before

Width:  |  Height:  |  Size: 201 B

-493
View File
@@ -1,493 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#0f172a">
<title>Home Energy</title>
<link rel="manifest" href="/static/manifest.json">
<link rel="icon" href="/static/icon.svg">
<style>
:root {
--bg: #f1f5f9; --card: #ffffff; --text: #0f172a; --muted: #64748b;
--line: #e2e8f0; --accent: #2563eb; --ok: #16a34a; --warn: #d97706;
--bad: #dc2626; --chip: #e2e8f0;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0f172a; --card: #1e293b; --text: #e2e8f0; --muted: #94a3b8;
--line: #334155; --chip: #334155;
}
}
* { box-sizing: border-box; margin: 0; }
body {
background: var(--bg); color: var(--text);
font: 16px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
padding-bottom: 76px;
}
header {
display: flex; align-items: center; gap: 8px;
padding: 14px 16px 10px;
}
header h1 { font-size: 20px; flex: 1; }
header .who { color: var(--muted); font-size: 14px; }
main { max-width: 640px; margin: 0 auto; padding: 0 12px; }
.card {
background: var(--card); border: 1px solid var(--line);
border-radius: 14px; padding: 14px 16px; margin-bottom: 12px;
}
.card h2 { font-size: 15px; color: var(--muted); margin-bottom: 10px; font-weight: 600; }
.row { display: flex; align-items: center; gap: 10px; }
.row .grow { flex: 1; min-width: 0; }
.title { font-weight: 600; }
.sub { color: var(--muted); font-size: 13px; }
.chip {
display: inline-block; padding: 2px 10px; border-radius: 999px;
background: var(--chip); font-size: 13px; font-weight: 600;
}
.chip.ok { background: color-mix(in srgb, var(--ok) 18%, transparent); color: var(--ok); }
.chip.warn { background: color-mix(in srgb, var(--warn) 18%, transparent); color: var(--warn); }
.chip.bad { background: color-mix(in srgb, var(--bad) 18%, transparent); color: var(--bad); }
.chip.accent { background: color-mix(in srgb, var(--accent) 15%, transparent); color: var(--accent); }
button {
font: inherit; font-weight: 600; border: 0; border-radius: 10px;
padding: 10px 16px; cursor: pointer; background: var(--accent); color: #fff;
}
button.secondary { background: var(--chip); color: var(--text); }
button.danger { background: var(--bad); }
button.small { padding: 6px 10px; font-size: 13px; border-radius: 8px; }
button:disabled { opacity: .45; cursor: default; }
input, select {
font: inherit; color: var(--text); background: var(--bg);
border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; width: 100%;
}
form .row { margin-bottom: 8px; }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
th, td { text-align: left; padding: 7px 6px; border-bottom: 1px solid var(--line); }
th { color: var(--muted); font-weight: 600; font-size: 12px; text-transform: uppercase; }
td.num, th.num { text-align: right; }
.scroll { overflow-x: auto; }
nav {
position: fixed; bottom: 0; left: 0; right: 0;
display: flex; background: var(--card); border-top: 1px solid var(--line);
padding-bottom: env(safe-area-inset-bottom);
}
nav button {
flex: 1; background: none; color: var(--muted); border-radius: 0;
padding: 12px 0 10px; font-size: 13px;
}
nav button.active { color: var(--accent); }
#toast {
position: fixed; left: 50%; bottom: 86px; transform: translateX(-50%);
background: var(--text); color: var(--bg); padding: 10px 18px;
border-radius: 10px; font-size: 14px; opacity: 0; transition: opacity .25s;
pointer-events: none; max-width: 90vw;
}
#toast.show { opacity: 1; }
#login { max-width: 360px; margin: 12vh auto 0; padding: 0 16px; }
#login .card { padding: 22px; }
#login h1 { font-size: 22px; margin-bottom: 16px; text-align: center; }
#login button { width: 100%; margin-top: 6px; }
.hidden { display: none !important; }
.offline { text-align: center; color: var(--muted); padding: 18px 0; }
</style>
</head>
<body>
<div id="login" class="hidden">
<div class="card">
<h1>&#9889; Home Energy</h1>
<form onsubmit="return doLogin(event)">
<div class="row"><input id="l-user" placeholder="Username" autocomplete="username" required></div>
<div class="row"><input id="l-pass" type="password" placeholder="Password" autocomplete="current-password" required></div>
<button>Log in</button>
</form>
</div>
</div>
<div id="app" class="hidden">
<header>
<h1>&#9889; Home Energy</h1>
<span class="who" id="whoami"></span>
<button class="secondary small" id="logout-btn" onclick="doLogout()">Log out</button>
</header>
<main>
<section id="tab-control">
<div id="guns"></div>
<div class="card" id="relays-card">
<h2>Relays</h2>
<div id="relays"></div>
<div class="row" style="margin-top:8px">
<button class="secondary small" onclick="refreshRelaysLive()">Refresh live states</button>
</div>
</div>
</section>
<section id="tab-history" class="hidden">
<div class="card">
<h2>Charging sessions</h2>
<div class="scroll"><table>
<thead><tr><th>Who</th><th>Gun</th><th>Started</th><th class="num">kWh</th><th></th></tr></thead>
<tbody id="sessions"></tbody>
</table></div>
</div>
</section>
<section id="tab-admin" class="hidden">
<div class="card">
<h2>Mode</h2>
<div class="row">
<div class="grow"><span class="title" id="mode-label"></span>
<div class="sub">Learn mode accepts and records unknown cards; enforce rejects them.</div></div>
<button class="small" id="mode-btn" onclick="toggleMode()"></button>
</div>
</div>
<div class="card">
<h2>Cards &amp; tags</h2>
<div class="scroll"><table>
<thead><tr><th>idTag</th><th>Name</th><th>User</th><th>Guns</th><th></th></tr></thead>
<tbody id="allowlist"></tbody>
</table></div>
<div id="seen-tags"></div>
<form onsubmit="return addAllowlist(event)" style="margin-top:10px">
<div class="row"><input id="a-tag" placeholder="idTag" required></div>
<div class="row">
<input id="a-name" placeholder="Name (e.g. Card blue)" required>
<select id="a-kind" style="width:110px"><option>card</option><option>app</option><option>car</option></select>
</div>
<div class="row">
<select id="a-user"><option value="">No user linked</option></select>
<input id="a-guns" placeholder="Guns, e.g. eu092025:2 — empty = all">
</div>
<div class="row"><button class="small">Save card</button></div>
</form>
</div>
<div class="card">
<h2>Users</h2>
<div class="scroll"><table>
<thead><tr><th>User</th><th>Scopes</th><th></th></tr></thead>
<tbody id="users"></tbody>
</table></div>
<form onsubmit="return addUser(event)" style="margin-top:10px">
<div class="row"><input id="u-name" placeholder="Username" required></div>
<div class="row"><input id="u-pass" type="password" placeholder="Password (empty = keep current)"></div>
<div class="row">
<input id="u-scopes" placeholder='Scopes, e.g. admin or charger:eu092025:1 relay:*'>
<button class="small">Save</button>
</div>
</form>
</div>
</section>
</main>
<nav>
<button data-tab="control" class="active" onclick="showTab('control')">&#9889; Control</button>
<button data-tab="history" onclick="showTab('history')">&#128202; History</button>
<button data-tab="admin" class="hidden" onclick="showTab('admin')">&#9881; Admin</button>
</nav>
</div>
<div id="toast"></div>
<script>
"use strict";
let me = null, status = null, pollTimer = null;
// ---- tiny helpers ----
const $ = (id) => document.getElementById(id);
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
function toast(msg) {
const t = $("toast");
t.textContent = msg;
t.classList.add("show");
clearTimeout(t._h);
t._h = setTimeout(() => t.classList.remove("show"), 3000);
}
async function api(path, opts = {}) {
const r = await fetch("/api" + path, {
headers: { "Content-Type": "application/json" }, ...opts,
});
if (r.status === 401 && path !== "/login") { showLogin(); throw new Error("not logged in"); }
if (!r.ok) {
let detail = r.statusText;
try { detail = (await r.json()).detail || detail; } catch {}
throw new Error(detail);
}
return r.json();
}
// fnmatch-style scope check, mirroring backend/users.py
function scopeOk(needed) {
if (!me) return false;
return me.scopes.some(g => {
if (g === "*" || g === "admin") return true;
const re = new RegExp("^" + g.split("*").map(p => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$");
return re.test(needed);
});
}
const isAdmin = () => me && me.scopes.some(g => g === "admin" || g === "*");
// ---- login flow ----
function showLogin() {
clearInterval(pollTimer);
$("app").classList.add("hidden");
$("login").classList.remove("hidden");
}
async function doLogin(ev) {
ev.preventDefault();
try {
await api("/login", { method: "POST", body: JSON.stringify({
username: $("l-user").value.trim(), password: $("l-pass").value }) });
$("l-pass").value = "";
await boot();
} catch (e) { toast(e.message); }
return false;
}
async function doLogout() {
await api("/logout", { method: "POST" }).catch(() => {});
me = null;
showLogin();
}
async function boot() {
try { me = await api("/me"); } catch { return; } // api() already showed login
$("login").classList.add("hidden");
$("app").classList.remove("hidden");
$("whoami").textContent = me.name === "anonymous" ? "open mode" : me.name;
$("logout-btn").classList.toggle("hidden", me.name === "anonymous");
document.querySelector('nav [data-tab="admin"]').classList.toggle("hidden", !isAdmin());
await refreshStatus();
clearInterval(pollTimer);
pollTimer = setInterval(() => {
if (!document.hidden && !$("tab-control").classList.contains("hidden")) refreshStatus();
}, 5000);
}
// ---- tabs ----
function showTab(name) {
for (const t of ["control", "history", "admin"]) {
$("tab-" + t).classList.toggle("hidden", t !== name);
document.querySelector(`nav [data-tab="${t}"]`).classList.toggle("active", t === name);
}
if (name === "history") loadSessions();
if (name === "admin") loadAdmin();
if (name === "control") refreshStatus();
}
// ---- control tab ----
const STATUS_CHIP = {
Available: "", Preparing: "accent", Charging: "ok", SuspendedEV: "warn",
SuspendedEVSE: "warn", Finishing: "", Faulted: "bad", Unavailable: "bad", Reserved: "warn",
};
async function refreshStatus() {
try { status = await api("/status"); } catch { return; }
renderGuns();
renderRelays(null);
}
function renderGuns() {
const box = $("guns");
const cps = Object.keys(status.connected);
if (!cps.length) {
box.innerHTML = `<div class="card"><div class="offline">Charger offline — waiting for it to dial in&hellip;</div></div>`;
return;
}
// active transaction per (cp, connector)
const txByGun = {};
for (const [tx, info] of Object.entries(status.active_transactions))
txByGun[`${info.cp}/${info.connector}`] = { tx, ...info };
let html = "";
for (const cp of cps) {
const conns = Object.entries(status.connectors)
.map(([key, st]) => ({ key, st, conn: +key.split("/")[1], cpId: key.split("/")[0] }))
.filter(c => c.cpId === cp && c.conn > 0)
.sort((a, b) => a.conn - b.conn);
if (!conns.length)
html += `<div class="card"><div class="sub">${esc(cp)} connected — no gun status yet</div></div>`;
const cpCfg = (status.chargers || {})[cp] || {};
for (const { conn, st } of conns) {
let gunName = (cpCfg.guns || {})[conn] || `Gun ${conn}`;
if (cps.length > 1) gunName = `${cpCfg.label || cp} · ${gunName}`;
const active = txByGun[`${cp}/${conn}`];
const may = scopeOk(`charger:${cp}:${conn}`);
const canStart = may && !active && (st === "Preparing" || st === "Available");
let action = "";
if (active && may)
action = `<button class="danger" onclick="stopTx(${active.tx})">Stop</button>`;
else if (!active)
action = `<button ${canStart ? "" : "disabled"} onclick="startGun('${esc(cp)}',${conn})">Start</button>`;
let sub = st === "Preparing" && !active ? "Cable plugged — ready to start" : "";
if (active) sub = `${esc(active.who || active.id_tag)} · since ${fmtTime(active.started)}`;
if (!may) sub = "No permission for this gun";
html += `<div class="card"><div class="row">
<div class="grow"><div class="title">${gunName}</div><div class="sub">${sub || "&nbsp;"}</div></div>
<span class="chip ${STATUS_CHIP[st] || ""}">${esc(st)}</span>${action}
</div></div>`;
}
}
box.innerHTML = html;
}
async function startGun(cp, conn) {
try {
const r = await api(`/charger/start?connector=${conn}&cp=${encodeURIComponent(cp)}`, { method: "POST" });
toast(`Start: ${r.remote_start}`);
setTimeout(refreshStatus, 1500);
} catch (e) { toast(e.message); }
}
async function stopTx(tx) {
try {
const r = await api(`/charger/stop/${tx}`, { method: "POST" });
toast(`Stop: ${r.remote_stop}`);
setTimeout(refreshStatus, 1500);
} catch (e) { toast(e.message); }
}
// ---- relays ----
let relayLive = {}; // name -> true/false/undefined, from the last live poll/switch
function renderRelays(_) {
const names = Object.keys(status.relays || {});
$("relays-card").classList.toggle("hidden", !names.length);
$("relays").innerHTML = names.map(name => {
const label = status.relays[name].label || name;
const on = relayLive[name];
const chip = on === undefined ? `<span class="chip">?</span>`
: `<span class="chip ${on ? "ok" : ""}">${on ? "ON" : "OFF"}</span>`;
return `<div class="row" style="padding:6px 0">
<div class="grow title">${esc(label)}</div>${chip}
<button class="small" onclick="toggleRelay('${esc(name)}')">Toggle</button>
</div>`;
}).join("");
}
async function toggleRelay(name) {
try {
const r = await api(`/relays/${encodeURIComponent(name)}/toggle`, { method: "POST" });
relayLive[name] = r.on;
renderRelays();
toast(`${name}: ${r.on ? "ON" : "OFF"}`);
} catch (e) { toast(e.message); }
}
async function refreshRelaysLive() {
try {
const live = await api("/relays?live=true");
for (const [name, st] of Object.entries(live))
relayLive[name] = "on" in st ? st.on : undefined;
renderRelays();
} catch (e) { toast(e.message); }
}
// ---- history tab ----
const fmtTime = (iso) => iso ? new Date(iso).toLocaleString([], { dateStyle: "short", timeStyle: "short" }) : "";
const fmtKwh = (wh) => wh == null ? "…" : (wh / 1000).toFixed(2);
function fmtDuration(a, b) {
if (!a || !b) return "";
const mins = Math.max(0, Math.round((new Date(b) - new Date(a)) / 60000));
return mins >= 60 ? `${Math.floor(mins / 60)}h${String(mins % 60).padStart(2, "0")}` : `${mins}m`;
}
async function loadSessions() {
try {
const rows = await api("/sessions?limit=100");
$("sessions").innerHTML = rows.map(s => `<tr>
<td>${esc(s.who || s.id_tag)}</td>
<td>${s.connector}</td>
<td>${fmtTime(s.started)}</td>
<td class="num"><b>${fmtKwh(s.wh)}</b></td>
<td class="sub">${s.ended ? fmtDuration(s.started, s.ended) : '<span class="chip ok">live</span>'}</td>
</tr>`).join("") || `<tr><td colspan="5" class="sub">No sessions yet</td></tr>`;
} catch (e) { toast(e.message); }
}
// ---- admin tab ----
async function loadAdmin() {
try {
const [al, users] = await Promise.all([api("/allowlist"), api("/users")]);
$("mode-label").textContent = al.learn_mode ? "Learn mode" : "Enforcing allowlist";
$("mode-btn").textContent = al.learn_mode ? "Enforce" : "Back to learn";
$("mode-btn").dataset.learn = al.learn_mode;
$("allowlist").innerHTML = Object.entries(al.authorized).map(([tag, e]) => `<tr>
<td class="sub">${esc(tag)}</td><td>${esc(e.name)}</td>
<td>${e.user ? esc(e.user) : '<span class="sub">—</span>'}</td>
<td class="sub">${e.guns ? esc(e.guns.join(", ")) : "all"}</td>
<td><button class="danger small" onclick="delAllowlist('${esc(tag)}')">&#10005;</button></td>
</tr>`).join("");
$("a-user").innerHTML = `<option value="">No user linked</option>` +
users.map(u => `<option value="${esc(u.name)}">${esc(u.name)}</option>`).join("");
const seen = Object.entries(al.seen || {}).filter(([tag]) => !(tag in al.authorized));
$("seen-tags").innerHTML = seen.length
? `<div class="sub" style="margin-top:8px">Seen but not enrolled:</div>` + seen.map(([tag, s]) =>
`<div class="row" style="padding:4px 0"><div class="grow sub">${esc(tag)} (&times;${s.count})</div>
<button class="small secondary" onclick="$('a-tag').value='${esc(tag)}';$('a-name').focus()">Enroll</button></div>`).join("")
: "";
$("users").innerHTML = users.map(u => `<tr>
<td>${esc(u.name)}</td><td class="sub">${esc(u.scopes.join(" "))}</td>
<td><button class="danger small" onclick="delUser('${esc(u.name)}')">&#10005;</button></td>
</tr>`).join("") || `<tr><td colspan="3" class="sub">No users — API is open</td></tr>`;
} catch (e) { toast(e.message); }
}
async function toggleMode() {
const toLearn = $("mode-btn").dataset.learn !== "true";
if (!toLearn && !confirm("Enforce the allowlist? Unknown cards will be rejected.")) return;
try { await api(`/mode?learn=${toLearn}`, { method: "POST" }); loadAdmin(); }
catch (e) { toast(e.message); }
}
async function addAllowlist(ev) {
ev.preventDefault();
const body = { name: $("a-name").value.trim(), kind: $("a-kind").value };
if ($("a-user").value) body.user = $("a-user").value;
const guns = $("a-guns").value.trim();
if (guns) body.guns = guns.split(",").map(s => s.trim()).filter(Boolean);
try {
await api(`/allowlist/${encodeURIComponent($("a-tag").value.trim())}`,
{ method: "PUT", body: JSON.stringify(body) });
$("a-tag").value = $("a-name").value = $("a-guns").value = "";
$("a-user").value = "";
loadAdmin();
} catch (e) { toast(e.message); }
return false;
}
async function delAllowlist(tag) {
if (!confirm(`Remove ${tag} from the allowlist?`)) return;
try { await api(`/allowlist/${encodeURIComponent(tag)}`, { method: "DELETE" }); loadAdmin(); }
catch (e) { toast(e.message); }
}
async function addUser(ev) {
ev.preventDefault();
const body = {};
if ($("u-pass").value) body.password = $("u-pass").value;
if ($("u-scopes").value.trim()) body.scopes = $("u-scopes").value.trim().split(/\s+/);
try {
await api(`/users/${encodeURIComponent($("u-name").value.trim())}`,
{ method: "PUT", body: JSON.stringify(body) });
$("u-name").value = $("u-pass").value = $("u-scopes").value = "";
loadAdmin();
} catch (e) { toast(e.message); }
return false;
}
async function delUser(name) {
if (!confirm(`Delete user ${name}?`)) return;
try { await api(`/users/${encodeURIComponent(name)}`, { method: "DELETE" }); loadAdmin(); }
catch (e) { toast(e.message); }
}
// ---- go ----
if ("serviceWorker" in navigator) navigator.serviceWorker.register("/sw.js").catch(() => {});
boot();
</script>
</body>
</html>
-12
View File
@@ -1,12 +0,0 @@
{
"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" }
]
}
-6
View File
@@ -1,6 +0,0 @@
// 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", () => {});
+11 -5
View File
@@ -43,7 +43,8 @@ CREATE TABLE IF NOT EXISTS sessions (
meter_start REAL NOT NULL, meter_start REAL NOT NULL,
meter_stop REAL, meter_stop REAL,
wh REAL, wh REAL,
reason TEXT reason TEXT,
method TEXT
); );
CREATE TABLE IF NOT EXISTS samples ( CREATE TABLE IF NOT EXISTS samples (
tx INTEGER NOT NULL, tx INTEGER NOT NULL,
@@ -63,6 +64,10 @@ def _db():
con = sqlite3.connect(DB_PATH) con = sqlite3.connect(DB_PATH)
con.row_factory = sqlite3.Row con.row_factory = sqlite3.Row
con.executescript(_SCHEMA) con.executescript(_SCHEMA)
# migration for dbs created before the audit column existed
cols = [row[1] for row in con.execute("PRAGMA table_info(sessions)")]
if "method" not in cols:
con.execute("ALTER TABLE sessions ADD COLUMN method TEXT")
return closing(con) return closing(con)
@@ -89,12 +94,13 @@ def max_tx() -> int:
def start_session(tx: int, cp: str, connector: int, id_tag: str, who: str, def start_session(tx: int, cp: str, connector: int, id_tag: str, who: str,
started: str, meter_start: float) -> None: started: str, meter_start: float, method: str = "unknown") -> None:
with _db() as con, con: with _db() as con, con:
con.execute( con.execute(
"INSERT OR REPLACE INTO sessions (tx, cp, connector, id_tag, who, started, meter_start)" "INSERT OR REPLACE INTO sessions"
" VALUES (?, ?, ?, ?, ?, ?, ?)", " (tx, cp, connector, id_tag, who, started, meter_start, method)"
(tx, cp, connector, id_tag, who, started, meter_start), " VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(tx, cp, connector, id_tag, who, started, meter_start, method),
) )
+2
View File
@@ -0,0 +1,2 @@
node_modules/
dist/
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#171d1b" />
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
<link rel="manifest" href="/manifest.json" />
<title>Charge Control</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1958
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "charging-station-panel",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"@fontsource/archivo": "^5.1.0",
"@fontsource/ibm-plex-mono": "^5.1.0",
"@tanstack/react-query": "^5.62.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.1.0",
"zustand": "^5.0.2"
},
"devDependencies": {
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.7.2",
"vite": "^6.0.5"
}
}
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<rect width="100" height="100" rx="22" fill="#171d1b"/>
<path d="M55 12 L28 56 L46 56 L41 88 L72 42 L52 42 Z" fill="#c9773d"/>
</svg>

After

Width:  |  Height:  |  Size: 201 B

+12
View File
@@ -0,0 +1,12 @@
{
"name": "Charge Control",
"short_name": "Charge",
"description": "Home EV charger and relay control",
"start_url": "/",
"display": "standalone",
"background_color": "#171d1b",
"theme_color": "#171d1b",
"icons": [
{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }
]
}
+55
View File
@@ -0,0 +1,55 @@
import { useEffect } from "react";
import { Navigate, Route, Routes, useLocation } from "react-router-dom";
import { api, ApiError, isAdmin } from "./api";
import { useApp } from "./store";
import type { Me } from "./types";
import Layout from "./components/Layout";
import Login from "./pages/Login";
import Dashboard from "./pages/Dashboard";
import History from "./pages/History";
import Cards from "./pages/Cards";
import Users from "./pages/Users";
export default function App() {
const { me, authChecked, setMe } = useApp();
const location = useLocation();
useEffect(() => {
api
.get<Me>("/me")
.then(setMe)
.catch((e) => {
if (e instanceof ApiError && e.status === 401) setMe(null);
else setMe(null);
});
}, [setMe]);
if (!authChecked) {
return (
<div className="boot">
<span className="lamp lamp--amber" /> Connecting…
</div>
);
}
if (!me) {
return (
<Routes>
<Route path="*" element={<Login />} />
</Routes>
);
}
const admin = isAdmin(me.scopes);
return (
<Routes>
<Route element={<Layout />}>
<Route path="/" element={<Dashboard />} />
<Route path="/history" element={<History />} />
{admin && <Route path="/cards" element={<Cards />} />}
{admin && <Route path="/users" element={<Users />} />}
<Route path="*" element={<Navigate to="/" replace state={{ from: location }} />} />
</Route>
</Routes>
);
}
+52
View File
@@ -0,0 +1,52 @@
export class ApiError extends Error {
status: number;
constructor(status: number, detail: string) {
super(detail);
this.status = status;
}
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`/api${path}`, {
headers: init?.body ? { "Content-Type": "application/json" } : undefined,
...init,
});
if (!res.ok) {
let detail = res.statusText;
try {
detail = (await res.json()).detail ?? detail;
} catch {
/* non-JSON error body */
}
throw new ApiError(res.status, detail);
}
return res.json() as Promise<T>;
}
export const api = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, body?: unknown) =>
request<T>(path, { method: "POST", body: body ? JSON.stringify(body) : undefined }),
put: <T>(path: string, body: unknown) =>
request<T>(path, { method: "PUT", body: JSON.stringify(body) }),
delete: <T>(path: string) => request<T>(path, { method: "DELETE" }),
};
/** Mirrors backend/users.py `allowed()` — fnmatch-lite scope check. */
export function scopeAllowed(scopes: string[], needed: string): boolean {
return scopes.some((grant) => {
if (grant === "*" || grant === "admin") return true;
const re = new RegExp(
"^" +
grant
.split("*")
.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
.join(".*") +
"$",
);
return re.test(needed);
});
}
export const isAdmin = (scopes: string[]) =>
scopes.some((s) => s === "admin" || s === "*");
+34
View File
@@ -0,0 +1,34 @@
/** The signature element: a physical indicator lamp, like the ones on the
* charger cabinet itself. Tone encodes state everywhere in the app. */
export type LampTone = "off" | "green" | "amber" | "red" | "pulse";
const TONE_CLASS: Record<LampTone, string> = {
off: "lamp",
green: "lamp lamp--green",
amber: "lamp lamp--amber",
red: "lamp lamp--red",
pulse: "lamp lamp--green lamp--pulse",
};
export function Lamp({ tone, title }: { tone: LampTone; title?: string }) {
return <span className={TONE_CLASS[tone]} title={title} aria-hidden />;
}
export function statusTone(ocppStatus: string, charging: boolean): LampTone {
if (charging) return "pulse";
switch (ocppStatus) {
case "Charging":
return "pulse";
case "Preparing":
case "Finishing":
case "Reserved":
return "amber";
case "Available":
return "green";
case "Faulted":
case "Unavailable":
return "red";
default:
return "off";
}
}
+86
View File
@@ -0,0 +1,86 @@
import { NavLink, Outlet } from "react-router-dom";
import { api, isAdmin } from "../api";
import { useApp } from "../store";
import { useStatus } from "../queries";
const NAV = [
{ to: "/", label: "Control", exact: true },
{ to: "/history", label: "History" },
];
const ADMIN_NAV = [
{ to: "/cards", label: "Cards" },
{ to: "/users", label: "Users" },
];
export default function Layout() {
const { me, setMe, toasts } = useApp();
const { data: status } = useStatus();
const admin = me ? isAdmin(me.scopes) : false;
const pending = status?.pending_cards ?? 0;
async function logout() {
await api.post("/logout").catch(() => undefined);
setMe(null);
}
return (
<div className="shell">
<header className="topbar">
<div className="brand">
<svg viewBox="0 0 100 100" className="brand__mark" aria-hidden>
<path d="M55 12 L28 56 L46 56 L41 88 L72 42 L52 42 Z" />
</svg>
<div>
<span className="brand__name">Charge Control</span>
<span className="brand__sub">private CSMS</span>
</div>
</div>
<nav className="nav" aria-label="Main">
{NAV.map((n) => (
<NavLink key={n.to} to={n.to} end={n.exact} className="nav__link">
{n.label}
</NavLink>
))}
{admin &&
ADMIN_NAV.map((n) => (
<NavLink key={n.to} to={n.to} className="nav__link">
{n.label}
{n.to === "/cards" && pending > 0 && (
<span className="badge" title={`${pending} card(s) awaiting review`}>
{pending}
</span>
)}
</NavLink>
))}
</nav>
<div className="topbar__user">
<span className="topbar__who">{me?.name}</span>
<button className="btn btn--ghost btn--sm" onClick={logout}>
Log out
</button>
</div>
</header>
{admin && pending > 0 && (
<NavLink to="/cards" className="alert">
<span className="lamp lamp--amber" />
{pending === 1 ? "An unknown card was presented" : `${pending} unknown cards were presented`}
&nbsp;— review and approve or reject.
</NavLink>
)}
<main className="content">
<Outlet />
</main>
<div className="toasts" role="status">
{toasts.map((t) => (
<div key={t.id} className={`toast toast--${t.tone}`}>
{t.text}
</div>
))}
</div>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App";
import "@fontsource/archivo/400.css";
import "@fontsource/archivo/500.css";
import "@fontsource/archivo/600.css";
import "@fontsource/archivo/700.css";
import "@fontsource/ibm-plex-mono/400.css";
import "@fontsource/ibm-plex-mono/500.css";
import "@fontsource/ibm-plex-mono/600.css";
import "./styles.css";
const queryClient = new QueryClient({
defaultOptions: {
queries: { staleTime: 3000, refetchOnWindowFocus: true },
},
});
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<App />
</BrowserRouter>
</QueryClientProvider>
</React.StrictMode>,
);
+318
View File
@@ -0,0 +1,318 @@
import { useState } from "react";
import { api } from "../api";
import { Lamp } from "../components/Lamp";
import {
useAction,
useAllowlist,
useDenied,
usePending,
usePermissions,
useUsers,
} from "../queries";
import { useApp } from "../store";
import type { CardEntry, PermissionCatalog } from "../types";
const fmtTime = (iso?: string | null) =>
iso ? new Date(iso).toLocaleString([], { dateStyle: "medium", timeStyle: "short" }) : "—";
/** Checkbox list of every gun in the system -> ["eu092025:2", ...]; empty = all guns. */
function GunPicker({
catalog,
value,
onChange,
}: {
catalog: PermissionCatalog | undefined;
value: string[];
onChange: (guns: string[]) => void;
}) {
if (!catalog) return null;
const toggle = (gun: string) =>
onChange(value.includes(gun) ? value.filter((g) => g !== gun) : [...value, gun]);
return (
<div className="gunpicker">
<span className="field__label">Allowed guns (none checked = all)</span>
{Object.entries(catalog.chargers).map(([cp, meta]) => (
<div key={cp} className="gunpicker__charger">
{Object.entries(meta.guns).map(([conn, label]) => {
const gun = `${cp}:${conn}`;
return (
<label key={gun} className="check">
<input
type="checkbox"
checked={value.includes(gun)}
onChange={() => toggle(gun)}
/>
<span>
{meta.label} — {label}
</span>
</label>
);
})}
</div>
))}
</div>
);
}
function CardForm({
initial,
submitLabel,
busy,
onSubmit,
onCancel,
}: {
initial: CardEntry;
submitLabel: string;
busy: boolean;
onSubmit: (entry: CardEntry) => void;
onCancel?: () => void;
}) {
const { data: users } = useUsers();
const { data: catalog } = usePermissions();
const [name, setName] = useState(initial.name);
const [owner, setOwner] = useState(initial.user ?? "");
const [guns, setGuns] = useState<string[]>(initial.guns ?? []);
return (
<form
className="cardform"
onSubmit={(e) => {
e.preventDefault();
onSubmit({
name: name.trim(),
kind: initial.kind || "card",
...(owner ? { user: owner } : {}),
...(guns.length ? { guns } : {}),
});
}}
>
<label className="field">
<span>Card name</span>
<input value={name} onChange={(e) => setName(e.target.value)} required placeholder="e.g. Blue keyfob" />
</label>
<label className="field">
<span>Belongs to</span>
<select value={owner} onChange={(e) => setOwner(e.target.value)}>
<option value="">Nobody (unassigned)</option>
{users?.map((u) => (
<option key={u.name} value={u.name}>
{u.name}
</option>
))}
</select>
</label>
<GunPicker catalog={catalog} value={guns} onChange={setGuns} />
<div className="cardform__actions">
<button className="btn btn--primary btn--sm" disabled={busy}>
{submitLabel}
</button>
{onCancel && (
<button type="button" className="btn btn--ghost btn--sm" onClick={onCancel}>
Cancel
</button>
)}
</div>
</form>
);
}
function PendingSection() {
const toast = useApp((s) => s.toast);
const { data: pending } = usePending();
const [open, setOpen] = useState<string | null>(null);
const approve = useAction(
({ tag, entry }: { tag: string; entry: CardEntry }) =>
api.post(`/cards/pending/${encodeURIComponent(tag)}/approve`, entry),
[["pending"], ["allowlist"], ["status"]],
() => {
toast("Card approved and enrolled");
setOpen(null);
},
);
const reject = useAction(
(tag: string) => api.post(`/cards/pending/${encodeURIComponent(tag)}/reject`),
[["pending"], ["denied"], ["status"]],
() => toast("Card rejected — it will be silently refused from now on"),
);
const entries = Object.entries(pending ?? {});
if (!entries.length) return null;
return (
<section className="panel panel--attention">
<header className="panel__head">
<h2>
<Lamp tone="amber" /> Awaiting review
</h2>
<span className="panel__meta">
unknown cards presented at a charger — approve to enroll, reject to silence
</span>
</header>
<ul className="pending-list">
{entries.map(([tag, meta]) => (
<li key={tag} className="pending">
<div className="pending__row">
<div>
<span className="mono strong">{tag}</span>
<span className="pending__meta">
tapped ×{meta.count} · last {fmtTime(meta.last_seen)}
{meta.cp ? ` · at ${meta.cp}${meta.connector ? ` gun ${meta.connector}` : ""}` : ""}
</span>
</div>
<div className="pending__actions">
<button
className="btn btn--primary btn--sm"
onClick={() => setOpen(open === tag ? null : tag)}
>
Approve…
</button>
<button
className="btn btn--danger btn--sm"
disabled={reject.isPending}
onClick={() => reject.mutate(tag)}
>
Reject
</button>
</div>
</div>
{open === tag && (
<CardForm
initial={{ name: "", kind: "card" }}
submitLabel="Approve & enroll"
busy={approve.isPending}
onSubmit={(entry) => approve.mutate({ tag, entry })}
onCancel={() => setOpen(null)}
/>
)}
</li>
))}
</ul>
</section>
);
}
function AuthorizedSection() {
const toast = useApp((s) => s.toast);
const { data } = useAllowlist();
const [editing, setEditing] = useState<string | null>(null);
const save = useAction(
({ tag, entry }: { tag: string; entry: CardEntry }) =>
api.put(`/allowlist/${encodeURIComponent(tag)}`, entry),
[["allowlist"]],
() => {
toast("Card updated");
setEditing(null);
},
);
const remove = useAction(
(tag: string) => api.delete(`/allowlist/${encodeURIComponent(tag)}`),
[["allowlist"]],
() => toast("Card removed"),
);
const entries = Object.entries(data?.authorized ?? {});
return (
<section className="panel">
<header className="panel__head">
<h2>Enrolled cards &amp; tokens</h2>
<span className="panel__meta">what may authorize a charge, and who it belongs to</span>
</header>
{!entries.length && <p className="empty">Nothing enrolled yet.</p>}
<div className="table-wrap">
<table className="table">
<tbody>
{entries.map(([tag, entry]) => (
<tr key={tag}>
<td className="mono">{tag}</td>
<td className="strong">{entry.name}</td>
<td>
<span className={`chip chip--${entry.kind === "app" ? "app" : "card"}`}>
{entry.kind}
</span>
</td>
<td>{entry.user ?? <span className="dim">unassigned</span>}</td>
<td className="dim">{entry.guns?.join(", ") ?? "all guns"}</td>
<td className="num">
<button className="btn btn--ghost btn--sm" onClick={() => setEditing(tag)}>
Edit
</button>
<button
className="btn btn--ghost btn--sm btn--dangertext"
onClick={() => {
if (confirm(`Remove ${entry.name} (${tag})?`)) remove.mutate(tag);
}}
>
Remove
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{editing && data?.authorized[editing] && (
<div className="panel__inset">
<h3 className="mono">{editing}</h3>
<CardForm
initial={data.authorized[editing]}
submitLabel="Save changes"
busy={save.isPending}
onSubmit={(entry) =>
save.mutate({ tag: editing, entry: { ...entry, kind: data.authorized[editing].kind } })
}
onCancel={() => setEditing(null)}
/>
</div>
)}
</section>
);
}
function DeniedSection() {
const toast = useApp((s) => s.toast);
const { data: denied } = useDenied();
const undeny = useAction(
(tag: string) => api.delete(`/cards/denied/${encodeURIComponent(tag)}`),
[["denied"]],
() => toast("Card un-rejected — it pends again on its next tap"),
);
const entries = Object.entries(denied ?? {});
if (!entries.length) return null;
return (
<section className="panel">
<header className="panel__head">
<h2>Rejected cards</h2>
<span className="panel__meta">silently refused; un-reject to reconsider</span>
</header>
<ul className="relay-list">
{entries.map(([tag, meta]) => (
<li key={tag} className="relay">
<Lamp tone="red" />
<span className="mono relay__label">{tag}</span>
<span className="relay__state">
by {meta.by} · {fmtTime(meta.rejected_at)}
</span>
<button className="btn btn--ghost btn--sm" onClick={() => undeny.mutate(tag)}>
Un-reject
</button>
</li>
))}
</ul>
</section>
);
}
export default function Cards() {
return (
<>
<PendingSection />
<AuthorizedSection />
<DeniedSection />
</>
);
}
+199
View File
@@ -0,0 +1,199 @@
import { api, scopeAllowed } from "../api";
import { Lamp, statusTone } from "../components/Lamp";
import { useAction, useLiveRelays, useStatus } from "../queries";
import { useApp } from "../store";
import type { ActiveTx, Status } from "../types";
function fmtSince(iso: string): string {
const mins = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 60000));
return mins >= 60 ? `${Math.floor(mins / 60)} h ${mins % 60} min` : `${mins} min`;
}
interface Gun {
cp: string;
connector: number;
label: string;
chargerLabel: string;
ocppStatus: string;
tx: (ActiveTx & { txId: string }) | null;
}
function gunsFrom(status: Status): Gun[] {
const txByGun = new Map<string, ActiveTx & { txId: string }>();
for (const [txId, tx] of Object.entries(status.active_transactions))
txByGun.set(`${tx.cp}/${tx.connector}`, { ...tx, txId });
return Object.entries(status.connectors)
.map(([key, ocppStatus]) => {
const [cp, conn] = [key.slice(0, key.lastIndexOf("/")), key.slice(key.lastIndexOf("/") + 1)];
return { cp, connector: Number(conn), ocppStatus };
})
.filter((g) => g.connector > 0)
.sort((a, b) => a.cp.localeCompare(b.cp) || a.connector - b.connector)
.map((g) => {
const meta = status.chargers[g.cp] ?? {};
return {
...g,
label: meta.guns?.[String(g.connector)] ?? `Gun ${g.connector}`,
chargerLabel: meta.label ?? g.cp,
tx: txByGun.get(`${g.cp}/${g.connector}`) ?? null,
};
});
}
function GunBay({ gun, scopes }: { gun: Gun; scopes: string[] }) {
const toast = useApp((s) => s.toast);
const may = scopeAllowed(scopes, `charger:${gun.cp}:${gun.connector}`);
const ready = !gun.tx && (gun.ocppStatus === "Preparing" || gun.ocppStatus === "Available");
const start = useAction(
() =>
api.post<{ remote_start: string }>(
`/charger/start?connector=${gun.connector}&cp=${encodeURIComponent(gun.cp)}`,
),
[["status"], ["sessions"]],
(r) => toast(`Start command: ${r.remote_start}`),
);
const stop = useAction(
() => api.post<{ remote_stop: string }>(`/charger/stop/${gun.tx!.txId}`),
[["status"], ["sessions"]],
(r) => toast(`Stop command: ${r.remote_stop}`),
);
return (
<article className="bay">
<header className="bay__head">
<span className="bay__eyebrow">{gun.chargerLabel}</span>
<Lamp tone={statusTone(gun.ocppStatus, !!gun.tx)} title={gun.ocppStatus} />
</header>
<h2 className="bay__title">{gun.label}</h2>
<div className="bay__status">
<span className={`chip chip--${gun.tx ? "live" : gun.ocppStatus.toLowerCase()}`}>
{gun.tx ? "Charging" : gun.ocppStatus}
</span>
{gun.ocppStatus === "Preparing" && !gun.tx && (
<span className="bay__hint">cable plugged — ready to start</span>
)}
</div>
{gun.tx && (
<dl className="bay__telemetry">
<div>
<dt>By</dt>
<dd>{gun.tx.who || gun.tx.id_tag}</dd>
</div>
<div>
<dt>Via</dt>
<dd>{gun.tx.method === "app" ? "In-app" : gun.tx.method === "card" ? "Card" : gun.tx.method}</dd>
</div>
<div>
<dt>Running</dt>
<dd>{fmtSince(gun.tx.started)}</dd>
</div>
</dl>
)}
<footer className="bay__actions">
{gun.tx ? (
<button
className="btn btn--danger"
disabled={!may || stop.isPending}
onClick={() => stop.mutate()}
>
{stop.isPending ? "Stopping…" : "Stop charging"}
</button>
) : (
<button
className="btn btn--primary"
disabled={!may || !ready || start.isPending}
onClick={() => start.mutate()}
>
{start.isPending ? "Starting…" : "Start charging"}
</button>
)}
{!may && <span className="bay__hint">no permission for this gun</span>}
</footer>
</article>
);
}
function Relays({ status, scopes }: { status: Status; scopes: string[] }) {
const toast = useApp((s) => s.toast);
const live = useLiveRelays();
const names = Object.keys(status.relays);
const toggle = useAction(
(name: string) => api.post<{ relay: string; on: boolean }>(`/relays/${encodeURIComponent(name)}/toggle`),
[["relays-live"]],
(r) => toast(`${r.relay}: ${r.on ? "on" : "off"}`),
);
if (!names.length) return null;
return (
<section className="panel">
<header className="panel__head">
<h2>Relays</h2>
<button
className="btn btn--ghost btn--sm"
onClick={() => live.refetch()}
disabled={live.isFetching}
>
{live.isFetching ? "Reading…" : "Read states"}
</button>
</header>
<ul className="relay-list">
{names.map((name) => {
const state = live.data?.[name];
const on = state && "on" in state ? state.on : undefined;
return (
<li key={name} className="relay">
<Lamp tone={on === undefined ? "off" : on ? "green" : "off"} />
<span className="relay__label">{status.relays[name].label}</span>
<span className="relay__state">
{state?.error ? "unreachable" : on === undefined ? "—" : on ? "on" : "off"}
</span>
<button
className="btn btn--ghost btn--sm"
disabled={!scopeAllowed(scopes, `relay:${name}`) || toggle.isPending}
onClick={() => toggle.mutate(name)}
>
Toggle
</button>
</li>
);
})}
</ul>
</section>
);
}
export default function Dashboard() {
const me = useApp((s) => s.me)!;
const { data: status, isLoading, error } = useStatus();
if (isLoading) return <p className="empty">Reading charger status…</p>;
if (error || !status) return <p className="empty">Status unavailable: {(error as Error)?.message}</p>;
const guns = gunsFrom(status);
const offline = Object.keys(status.connected).length === 0;
return (
<>
{offline && (
<div className="panel panel--offline">
<Lamp tone="red" />
<div>
<h2>Charger offline</h2>
<p>Waiting for the charge point to dial in. Guns appear here as soon as it connects.</p>
</div>
</div>
)}
<div className="bays">
{guns.map((g) => (
<GunBay key={`${g.cp}/${g.connector}`} gun={g} scopes={me.scopes} />
))}
</div>
<Relays status={status} scopes={me.scopes} />
</>
);
}
+85
View File
@@ -0,0 +1,85 @@
import { useSessions, useStatus } from "../queries";
import type { Session } from "../types";
const fmtKwh = (wh: number | null) => (wh == null ? "—" : (wh / 1000).toFixed(2));
const fmtTime = (iso: string | null) =>
iso ? new Date(iso).toLocaleString([], { dateStyle: "medium", timeStyle: "short" }) : "—";
function fmtDuration(a: string, b: string | null): string {
if (!b) return "";
const mins = Math.max(0, Math.round((new Date(b).getTime() - new Date(a).getTime()) / 60000));
return mins >= 60 ? `${Math.floor(mins / 60)} h ${String(mins % 60).padStart(2, "0")} min` : `${mins} min`;
}
function MethodChip({ method }: { method: string | null }) {
if (method === "card") return <span className="chip chip--card">Card</span>;
if (method === "app") return <span className="chip chip--app">In-app</span>;
return <span className="chip">{method ?? "—"}</span>;
}
function gunLabel(s: Session, chargers: Record<string, { label?: string; guns?: Record<string, string> }>) {
const meta = chargers[s.cp];
return meta?.guns?.[String(s.connector)] ?? `${s.cp} · gun ${s.connector}`;
}
export default function History() {
const { data: sessions, isLoading } = useSessions();
const { data: status } = useStatus();
if (isLoading) return <p className="empty">Loading history…</p>;
if (!sessions?.length)
return (
<p className="empty">
No charging sessions yet. The first card tap or in-app start will appear here with who,
when, how, and how many kWh.
</p>
);
const totalKwh = sessions.reduce((acc, s) => acc + (s.wh ?? 0), 0) / 1000;
return (
<section className="panel">
<header className="panel__head">
<h2>Charging sessions</h2>
<span className="panel__meta">
{sessions.length} session{sessions.length === 1 ? "" : "s"} ·{" "}
<strong className="mono">{totalKwh.toFixed(1)} kWh</strong> total
</span>
</header>
<div className="table-wrap">
<table className="table">
<thead>
<tr>
<th>Who</th>
<th>Via</th>
<th>Gun</th>
<th>Started</th>
<th>Duration</th>
<th className="num">kWh</th>
</tr>
</thead>
<tbody>
{sessions.map((s) => (
<tr key={s.tx}>
<td className="strong">{s.who || s.id_tag}</td>
<td>
<MethodChip method={s.method} />
</td>
<td>{gunLabel(s, status?.chargers ?? {})}</td>
<td className="mono">{fmtTime(s.started)}</td>
<td>
{s.ended ? (
fmtDuration(s.started, s.ended)
) : (
<span className="chip chip--live">charging</span>
)}
</td>
<td className="num mono strong">{fmtKwh(s.wh)}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { FormEvent, useState } from "react";
import { api } from "../api";
import { useApp } from "../store";
import type { Me } from "../types";
export default function Login() {
const setMe = useApp((s) => s.setMe);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function submit(e: FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
const r = await api.post<{ user: Me }>("/login", { username, password });
setMe(r.user);
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}
return (
<div className="login">
<form className="login__panel" onSubmit={submit}>
<div className="login__head">
<svg viewBox="0 0 100 100" className="login__mark" aria-hidden>
<path d="M55 12 L28 56 L46 56 L41 88 L72 42 L52 42 Z" />
</svg>
<h1>Charge Control</h1>
<p>Private charging backend — sign in to operate.</p>
</div>
<label className="field">
<span>Username</span>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
autoComplete="username"
autoFocus
required
/>
</label>
<label className="field">
<span>Password</span>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
required
/>
</label>
{error && <p className="field-error">{error}</p>}
<button className="btn btn--primary btn--block" disabled={busy}>
{busy ? "Signing in…" : "Sign in"}
</button>
</form>
</div>
);
}
+275
View File
@@ -0,0 +1,275 @@
import { useMemo, useState } from "react";
import { api, isAdmin, scopeAllowed } from "../api";
import { useAction, usePermissions, useUsers } from "../queries";
import { useApp } from "../store";
import type { Me, PermissionCatalog } from "../types";
/** The permission matrix: scopes rendered as checkboxes instead of raw strings. */
interface Matrix {
admin: boolean;
guns: string[]; // "cp:conn"
allRelays: boolean;
relays: string[];
}
function toMatrix(scopes: string[], catalog: PermissionCatalog): Matrix {
const nonAdmin = scopes.filter((s) => s !== "admin" && s !== "*");
const guns: string[] = [];
for (const [cp, meta] of Object.entries(catalog.chargers))
for (const conn of Object.keys(meta.guns))
if (scopeAllowed(nonAdmin, `charger:${cp}:${conn}`)) guns.push(`${cp}:${conn}`);
const allRelays = nonAdmin.includes("relay:*");
const relays = allRelays
? []
: Object.keys(catalog.relays).filter((r) => scopeAllowed(nonAdmin, `relay:${r}`));
return { admin: isAdmin(scopes), guns, allRelays, relays };
}
function toScopes(m: Matrix): string[] {
if (m.admin) return ["admin"];
return [
...m.guns.map((g) => `charger:${g}`),
...(m.allRelays ? ["relay:*"] : m.relays.map((r) => `relay:${r}`)),
];
}
function MatrixEditor({
catalog,
value,
onChange,
}: {
catalog: PermissionCatalog;
value: Matrix;
onChange: (m: Matrix) => void;
}) {
const toggleList = (list: string[], item: string) =>
list.includes(item) ? list.filter((x) => x !== item) : [...list, item];
return (
<div className="matrix">
<label className="check check--strong">
<input
type="checkbox"
checked={value.admin}
onChange={() => onChange({ ...value, admin: !value.admin })}
/>
<span>Administrator — everything, including cards, users and settings</span>
</label>
{!value.admin && (
<>
<div className="matrix__group">
<span className="field__label">Charging guns</span>
{Object.entries(catalog.chargers).map(([cp, meta]) =>
Object.entries(meta.guns).map(([conn, label]) => {
const gun = `${cp}:${conn}`;
return (
<label key={gun} className="check">
<input
type="checkbox"
checked={value.guns.includes(gun)}
onChange={() => onChange({ ...value, guns: toggleList(value.guns, gun) })}
/>
<span>
{meta.label} — {label}
</span>
</label>
);
}),
)}
{!Object.keys(catalog.chargers).length && (
<span className="dim">no chargers known yet</span>
)}
</div>
<div className="matrix__group">
<span className="field__label">Relays</span>
<label className="check">
<input
type="checkbox"
checked={value.allRelays}
onChange={() => onChange({ ...value, allRelays: !value.allRelays })}
/>
<span>All relays (including future ones)</span>
</label>
{!value.allRelays &&
Object.entries(catalog.relays).map(([name, meta]) => (
<label key={name} className="check">
<input
type="checkbox"
checked={value.relays.includes(name)}
onChange={() =>
onChange({ ...value, relays: toggleList(value.relays, name) })
}
/>
<span>{meta.label}</span>
</label>
))}
{!value.allRelays && !Object.keys(catalog.relays).length && (
<span className="dim">no relays registered yet</span>
)}
</div>
</>
)}
</div>
);
}
function UserEditor({
user,
catalog,
onClose,
}: {
user: Me | null; // null = create new
catalog: PermissionCatalog;
onClose: () => void;
}) {
const toast = useApp((s) => s.toast);
const [name, setName] = useState(user?.name ?? "");
const [password, setPassword] = useState("");
const [matrix, setMatrix] = useState<Matrix>(() =>
user ? toMatrix(user.scopes, catalog) : { admin: false, guns: [], allRelays: false, relays: [] },
);
const save = useAction(
() =>
api.put(`/users/${encodeURIComponent(name.trim())}`, {
...(password ? { password } : {}),
scopes: toScopes(matrix),
}),
[["users"]],
() => {
toast(user ? "User updated" : "User created");
onClose();
},
);
return (
<form
className="panel__inset"
onSubmit={(e) => {
e.preventDefault();
save.mutate();
}}
>
<h3>{user ? `Edit ${user.name}` : "New user"}</h3>
<div className="formrow">
<label className="field">
<span>Username</span>
<input
value={name}
onChange={(e) => setName(e.target.value)}
disabled={!!user}
required
placeholder="e.g. maria"
/>
</label>
<label className="field">
<span>{user ? "New password (empty = keep)" : "Password"}</span>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required={!user}
autoComplete="new-password"
/>
</label>
</div>
<MatrixEditor catalog={catalog} value={matrix} onChange={setMatrix} />
<div className="cardform__actions">
<button className="btn btn--primary btn--sm" disabled={save.isPending}>
{user ? "Save changes" : "Create user"}
</button>
<button type="button" className="btn btn--ghost btn--sm" onClick={onClose}>
Cancel
</button>
</div>
</form>
);
}
function describeScopes(scopes: string[], catalog: PermissionCatalog): string {
if (isAdmin(scopes)) return "Administrator";
const m = toMatrix(scopes, catalog);
const parts: string[] = [];
for (const gun of m.guns) {
const [cp, conn] = gun.split(":");
const meta = catalog.chargers[cp];
parts.push(meta ? `${meta.label} ${meta.guns[conn] ?? `gun ${conn}`}` : gun);
}
if (m.allRelays) parts.push("all relays");
else parts.push(...m.relays.map((r) => catalog.relays[r]?.label ?? r));
return parts.length ? parts.join(" · ") : "No permissions";
}
export default function Users() {
const me = useApp((s) => s.me)!;
const toast = useApp((s) => s.toast);
const { data: users } = useUsers();
const { data: catalog } = usePermissions();
const [editing, setEditing] = useState<Me | null | "new">(null);
const remove = useAction(
(name: string) => api.delete(`/users/${encodeURIComponent(name)}`),
[["users"]],
() => toast("User deleted (their sessions are now invalid)"),
);
const sorted = useMemo(
() => [...(users ?? [])].sort((a, b) => a.name.localeCompare(b.name)),
[users],
);
if (!catalog) return <p className="empty">Loading permission catalog…</p>;
return (
<section className="panel">
<header className="panel__head">
<h2>Users</h2>
<button className="btn btn--primary btn--sm" onClick={() => setEditing("new")}>
Add user
</button>
</header>
{!sorted.length && (
<p className="empty">
No users yet — the API is open until the first account exists. Create the admin account
now.
</p>
)}
<div className="table-wrap">
<table className="table">
<tbody>
{sorted.map((u) => (
<tr key={u.name}>
<td className="strong">{u.name}</td>
<td className="dim">{describeScopes(u.scopes, catalog)}</td>
<td className="num">
<button className="btn btn--ghost btn--sm" onClick={() => setEditing(u)}>
Edit
</button>
<button
className="btn btn--ghost btn--sm btn--dangertext"
disabled={u.name === me.name}
title={u.name === me.name ? "You cannot delete your own account" : undefined}
onClick={() => {
if (confirm(`Delete user ${u.name}?`)) remove.mutate(u.name);
}}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{editing !== null && (
<UserEditor
user={editing === "new" ? null : editing}
catalog={catalog}
onClose={() => setEditing(null)}
/>
)}
</section>
);
}
+95
View File
@@ -0,0 +1,95 @@
import {
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import { api, ApiError } from "./api";
import { useApp } from "./store";
import type {
CardEntry,
DeniedCard,
Me,
PendingCard,
PermissionCatalog,
RelayState,
Session,
Status,
} from "./types";
export function useStatus() {
const setMe = useApp((s) => s.setMe);
return useQuery({
queryKey: ["status"],
queryFn: async () => {
try {
return await api.get<Status>("/status");
} catch (e) {
if (e instanceof ApiError && e.status === 401) setMe(null);
throw e;
}
},
refetchInterval: 5000,
retry: false,
});
}
export const useSessions = () =>
useQuery({
queryKey: ["sessions"],
queryFn: () => api.get<Session[]>("/sessions?limit=200"),
refetchInterval: 15000,
});
export const usePending = () =>
useQuery({
queryKey: ["pending"],
queryFn: () => api.get<Record<string, PendingCard>>("/cards/pending"),
refetchInterval: 10000,
});
export const useDenied = () =>
useQuery({
queryKey: ["denied"],
queryFn: () => api.get<Record<string, DeniedCard>>("/cards/denied"),
});
export const useAllowlist = () =>
useQuery({
queryKey: ["allowlist"],
queryFn: () => api.get<{ authorized: Record<string, CardEntry> }>("/allowlist"),
});
export const useUsers = () =>
useQuery({ queryKey: ["users"], queryFn: () => api.get<Me[]>("/users") });
export const usePermissions = () =>
useQuery({
queryKey: ["permissions"],
queryFn: () => api.get<PermissionCatalog>("/permissions"),
});
export const useLiveRelays = () =>
useQuery({
queryKey: ["relays-live"],
queryFn: () => api.get<Record<string, RelayState>>("/relays?live=true"),
enabled: false, // fetched on demand (each poll talks to real hardware)
retry: false,
});
/** Mutation wrapper: toast on error, invalidate the given query keys on success. */
export function useAction<TArgs = void, TResult = unknown>(
fn: (args: TArgs) => Promise<TResult>,
invalidate: string[][],
onDone?: (result: TResult) => void,
) {
const qc = useQueryClient();
const toast = useApp((s) => s.toast);
return useMutation({
mutationFn: fn,
onSuccess: (result) => {
for (const key of invalidate) qc.invalidateQueries({ queryKey: key });
onDone?.(result);
},
onError: (e: Error) => toast(e.message, "error"),
});
}
+31
View File
@@ -0,0 +1,31 @@
import { create } from "zustand";
import type { Me } from "./types";
/** Auth + app-shell state (zustand). Server data lives in TanStack Query. */
interface AppState {
me: Me | null;
authChecked: boolean; // finished the initial /api/me probe
setMe: (me: Me | null) => void;
toasts: { id: number; text: string; tone: "info" | "error" }[];
toast: (text: string, tone?: "info" | "error") => void;
dismissToast: (id: number) => void;
}
let toastId = 0;
export const useApp = create<AppState>((set) => ({
me: null,
authChecked: false,
setMe: (me) => set({ me, authChecked: true }),
toasts: [],
toast: (text, tone = "info") => {
const id = ++toastId;
set((s) => ({ toasts: [...s.toasts, { id, text, tone }] }));
setTimeout(
() => set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })),
4000,
);
},
dismissToast: (id) =>
set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })),
}));
+368
View File
@@ -0,0 +1,368 @@
/* ============================================================
Charge Control — instrument-panel design system
Surfaces like enameled switchgear, copper-busbar accent,
indicator lamps as the signature element.
Type: Archivo (UI) + IBM Plex Mono (telemetry & identifiers).
============================================================ */
:root {
--paper: #eef0ef; /* porcelain enamel */
--panel: #f9faf9;
--panel-inset: #f1f3f2;
--ink: #1d2523; /* deep green-black, like cabinet paint */
--ink-dim: #5d6b67;
--line: #d8ddda;
--copper: #b25c28; /* busbar copper — the accent */
--copper-deep: #8f4a20;
--live: #178a5c; /* DC-on green */
--amber: #c07f00;
--red: #bf3527;
--lamp-off: #c4ccc8;
--shadow: 0 1px 2px rgb(29 37 35 / 0.06), 0 4px 16px rgb(29 37 35 / 0.05);
--radius: 10px;
--font-ui: "Archivo", "Segoe UI", system-ui, sans-serif;
--font-mono: "IBM Plex Mono", ui-monospace, Consolas, monospace;
}
@media (prefers-color-scheme: dark) {
:root {
--paper: #131816;
--panel: #1b211f;
--panel-inset: #161c1a;
--ink: #e4e9e7;
--ink-dim: #93a09b;
--line: #2c3531;
--copper: #d07a3e;
--copper-deep: #b25c28;
--live: #2fae7c;
--amber: #d99a1b;
--red: #d8503f;
--lamp-off: #39433f;
--shadow: 0 1px 2px rgb(0 0 0 / 0.4), 0 4px 18px rgb(0 0 0 / 0.35);
}
}
* { box-sizing: border-box; margin: 0; }
html { color-scheme: light dark; }
body {
background: var(--paper);
color: var(--ink);
font-family: var(--font-ui);
font-size: 15.5px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
button, input, select { font: inherit; color: inherit; }
:focus-visible {
outline: 2px solid var(--copper);
outline-offset: 2px;
border-radius: 4px;
}
.mono { font-family: var(--font-mono); font-size: 0.92em; }
.strong { font-weight: 600; }
.dim { color: var(--ink-dim); }
.num { text-align: right; }
/* ---------- indicator lamp (signature element) ---------- */
.lamp {
display: inline-block;
width: 11px; height: 11px;
border-radius: 50%;
background: radial-gradient(circle at 35% 30%, color-mix(in srgb, var(--lamp-off) 60%, white 25%), var(--lamp-off) 70%);
box-shadow: inset 0 0 2px rgb(0 0 0 / 0.35);
vertical-align: baseline;
flex: none;
}
.lamp--green {
background: radial-gradient(circle at 35% 30%, #8fe8c2, var(--live) 70%);
box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 8px color-mix(in srgb, var(--live) 55%, transparent);
}
.lamp--amber {
background: radial-gradient(circle at 35% 30%, #ffd98a, var(--amber) 70%);
box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 8px color-mix(in srgb, var(--amber) 55%, transparent);
}
.lamp--red {
background: radial-gradient(circle at 35% 30%, #ff9d8f, var(--red) 70%);
box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 8px color-mix(in srgb, var(--red) 55%, transparent);
}
.lamp--pulse { animation: lamp-pulse 1.6s ease-in-out infinite; }
@keyframes lamp-pulse {
0%, 100% { box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 4px color-mix(in srgb, var(--live) 40%, transparent); }
50% { box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 14px color-mix(in srgb, var(--live) 85%, transparent); }
}
@media (prefers-reduced-motion: reduce) {
.lamp--pulse { animation: none; }
* { transition: none !important; }
}
/* ---------- app shell ---------- */
.shell { min-height: 100dvh; display: flex; flex-direction: column; }
.topbar {
display: flex; align-items: center; gap: 20px;
padding: 10px clamp(14px, 4vw, 32px);
background: var(--panel);
border-bottom: 1px solid var(--line);
position: sticky; top: 0; z-index: 10;
}
.brand { display: flex; align-items: center; gap: 10px; }
.brand__mark { width: 30px; height: 30px; }
.brand__mark path { fill: var(--copper); }
.brand__name { display: block; font-weight: 700; letter-spacing: 0.01em; line-height: 1.15; }
.brand__sub {
display: block; font-family: var(--font-mono); font-size: 10.5px;
text-transform: uppercase; letter-spacing: 0.14em; color: var(--ink-dim);
}
.nav { display: flex; gap: 4px; flex: 1; overflow-x: auto; }
.nav__link {
display: inline-flex; align-items: center; gap: 7px;
padding: 7px 13px;
border-radius: 8px;
color: var(--ink-dim);
text-decoration: none;
font-weight: 500;
white-space: nowrap;
}
.nav__link:hover { color: var(--ink); background: var(--panel-inset); }
.nav__link.active { color: var(--copper-deep); background: color-mix(in srgb, var(--copper) 12%, transparent); font-weight: 600; }
.badge {
background: var(--amber); color: #fff;
font-family: var(--font-mono); font-size: 11px; font-weight: 600;
border-radius: 999px; padding: 1px 7px;
}
.topbar__user { display: flex; align-items: center; gap: 10px; }
.topbar__who { font-family: var(--font-mono); font-size: 13px; color: var(--ink-dim); }
.alert {
display: flex; align-items: center; gap: 10px;
margin: 14px clamp(14px, 4vw, 32px) 0;
padding: 11px 16px;
border: 1px solid color-mix(in srgb, var(--amber) 45%, var(--line));
background: color-mix(in srgb, var(--amber) 9%, var(--panel));
border-radius: var(--radius);
color: var(--ink);
text-decoration: none;
font-weight: 500;
}
.alert:hover { border-color: var(--amber); }
.content {
width: min(1060px, 100%);
margin: 0 auto;
padding: 22px clamp(14px, 4vw, 32px) 60px;
display: flex; flex-direction: column; gap: 18px;
}
.boot, .empty {
display: flex; align-items: center; justify-content: center; gap: 10px;
padding: 48px 20px; color: var(--ink-dim); text-align: center;
}
/* ---------- login ---------- */
.login {
min-height: 100dvh; display: grid; place-items: center;
padding: 20px;
background:
radial-gradient(800px 400px at 80% -10%, color-mix(in srgb, var(--copper) 9%, transparent), transparent),
var(--paper);
}
.login__panel {
width: min(380px, 100%);
background: var(--panel);
border: 1px solid var(--line);
border-radius: 14px;
box-shadow: var(--shadow);
padding: 30px 28px;
display: flex; flex-direction: column; gap: 14px;
}
.login__head { text-align: center; margin-bottom: 6px; }
.login__mark { width: 44px; height: 44px; margin-bottom: 10px; }
.login__mark path { fill: var(--copper); }
.login__head h1 { font-size: 22px; font-weight: 700; letter-spacing: -0.01em; }
.login__head p { color: var(--ink-dim); font-size: 13.5px; margin-top: 4px; }
/* ---------- panels & bays ---------- */
.panel {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 18px 20px;
}
.panel--attention { border-color: color-mix(in srgb, var(--amber) 50%, var(--line)); }
.panel--offline { display: flex; gap: 14px; align-items: center; }
.panel--offline p { color: var(--ink-dim); font-size: 14px; }
.panel__head {
display: flex; align-items: baseline; justify-content: space-between; gap: 12px;
margin-bottom: 12px; flex-wrap: wrap;
}
.panel__head h2 { font-size: 16px; font-weight: 700; display: flex; align-items: center; gap: 9px; }
.panel__meta { color: var(--ink-dim); font-size: 13px; }
.panel__inset {
margin-top: 14px; padding: 16px;
background: var(--panel-inset);
border: 1px solid var(--line);
border-radius: 8px;
}
.panel__inset h3 { font-size: 14px; margin-bottom: 10px; }
.bays {
display: grid; gap: 18px;
grid-template-columns: repeat(auto-fit, minmax(290px, 1fr));
}
.bay {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 18px 20px;
display: flex; flex-direction: column; gap: 10px;
border-top: 3px solid var(--copper);
}
.bay__head { display: flex; justify-content: space-between; align-items: center; }
.bay__eyebrow {
font-family: var(--font-mono); font-size: 11px;
text-transform: uppercase; letter-spacing: 0.14em; color: var(--ink-dim);
}
.bay__title { font-size: 21px; font-weight: 700; letter-spacing: -0.01em; }
.bay__status { display: flex; align-items: center; gap: 10px; min-height: 26px; }
.bay__hint { color: var(--ink-dim); font-size: 13px; }
.bay__telemetry {
display: flex; gap: 22px;
padding: 10px 12px;
background: var(--panel-inset);
border-radius: 8px;
}
.bay__telemetry dt {
font-family: var(--font-mono); font-size: 10.5px;
text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-dim);
}
.bay__telemetry dd { font-weight: 600; font-size: 14px; }
.bay__actions { display: flex; align-items: center; gap: 12px; margin-top: 2px; }
/* ---------- chips ---------- */
.chip {
display: inline-block;
font-family: var(--font-mono); font-size: 11.5px; font-weight: 600;
text-transform: uppercase; letter-spacing: 0.07em;
padding: 3px 9px; border-radius: 999px;
background: var(--panel-inset); color: var(--ink-dim);
border: 1px solid var(--line);
}
.chip--live, .chip--charging { background: color-mix(in srgb, var(--live) 14%, transparent); color: var(--live); border-color: color-mix(in srgb, var(--live) 40%, transparent); }
.chip--preparing, .chip--finishing { background: color-mix(in srgb, var(--amber) 14%, transparent); color: var(--amber); border-color: color-mix(in srgb, var(--amber) 40%, transparent); }
.chip--faulted, .chip--unavailable { background: color-mix(in srgb, var(--red) 12%, transparent); color: var(--red); border-color: color-mix(in srgb, var(--red) 40%, transparent); }
.chip--card { background: color-mix(in srgb, var(--copper) 13%, transparent); color: var(--copper-deep); border-color: color-mix(in srgb, var(--copper) 40%, transparent); }
.chip--app { background: color-mix(in srgb, var(--live) 12%, transparent); color: var(--live); border-color: color-mix(in srgb, var(--live) 35%, transparent); }
/* ---------- buttons ---------- */
.btn {
border: 1px solid transparent;
border-radius: 8px;
padding: 9px 18px;
font-weight: 600;
cursor: pointer;
background: var(--panel-inset);
transition: background 0.15s, border-color 0.15s, transform 0.05s;
}
.btn:active:not(:disabled) { transform: translateY(1px); }
.btn:disabled { opacity: 0.45; cursor: default; }
.btn--primary { background: var(--copper); color: #fff; }
.btn--primary:hover:not(:disabled) { background: var(--copper-deep); }
.btn--danger { background: var(--red); color: #fff; }
.btn--danger:hover:not(:disabled) { background: color-mix(in srgb, var(--red) 85%, black); }
.btn--ghost { background: transparent; border-color: var(--line); color: var(--ink); }
.btn--ghost:hover:not(:disabled) { background: var(--panel-inset); }
.btn--sm { padding: 5px 12px; font-size: 13.5px; }
.btn--block { width: 100%; }
.btn--dangertext { color: var(--red); }
/* ---------- forms ---------- */
.field { display: flex; flex-direction: column; gap: 5px; }
.field > span, .field__label {
font-family: var(--font-mono); font-size: 11px;
text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-dim);
}
.field input, .field select {
background: var(--paper);
border: 1px solid var(--line);
border-radius: 8px;
padding: 9px 12px;
width: 100%;
}
.field input:focus, .field select:focus { border-color: var(--copper); outline: none; }
.field-error { color: var(--red); font-size: 13.5px; }
.formrow { display: grid; gap: 12px; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); margin-bottom: 12px; }
.check { display: flex; align-items: center; gap: 9px; padding: 4px 0; cursor: pointer; }
.check input { accent-color: var(--copper); width: 16px; height: 16px; }
.check--strong { font-weight: 600; }
.cardform { display: flex; flex-direction: column; gap: 12px; margin-top: 12px; }
.cardform__actions { display: flex; gap: 10px; }
.gunpicker, .matrix { display: flex; flex-direction: column; gap: 6px; }
.matrix__group { margin-top: 8px; }
/* ---------- tables & lists ---------- */
.table-wrap { overflow-x: auto; }
.table { width: 100%; border-collapse: collapse; font-size: 14px; }
.table th {
text-align: left; padding: 8px 10px;
font-family: var(--font-mono); font-size: 10.5px;
text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-dim);
border-bottom: 1px solid var(--line);
}
.table th.num { text-align: right; }
.table td { padding: 9px 10px; border-bottom: 1px solid var(--line); vertical-align: middle; }
.table tr:last-child td { border-bottom: none; }
.relay-list, .pending-list { list-style: none; padding: 0; display: flex; flex-direction: column; }
.relay {
display: flex; align-items: center; gap: 12px;
padding: 10px 2px; border-bottom: 1px solid var(--line);
}
.relay:last-child { border-bottom: none; }
.relay__label { font-weight: 600; flex: 1; min-width: 0; }
.relay__state { font-family: var(--font-mono); font-size: 12.5px; color: var(--ink-dim); }
.pending { padding: 12px 2px; border-bottom: 1px solid var(--line); }
.pending:last-child { border-bottom: none; }
.pending__row { display: flex; justify-content: space-between; gap: 12px; align-items: center; flex-wrap: wrap; }
.pending__meta { display: block; color: var(--ink-dim); font-size: 13px; }
.pending__actions { display: flex; gap: 8px; }
/* ---------- toasts ---------- */
.toasts {
position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%);
display: flex; flex-direction: column; gap: 8px; z-index: 50;
width: min(480px, calc(100vw - 28px));
}
.toast {
background: var(--ink); color: var(--paper);
border-radius: 9px; padding: 11px 16px;
font-size: 14px; box-shadow: var(--shadow);
}
.toast--error { background: var(--red); color: #fff; }
/* ---------- responsive ---------- */
@media (max-width: 640px) {
.topbar { flex-wrap: wrap; row-gap: 6px; }
.nav { order: 3; width: 100%; }
.bay__telemetry { flex-wrap: wrap; gap: 12px 20px; }
.content { padding-top: 14px; }
}
+89
View File
@@ -0,0 +1,89 @@
export interface Me {
name: string;
scopes: string[];
id_tag: string | null;
}
export interface ActiveTx {
cp: string;
connector: number;
id_tag: string;
who: string;
method: string;
meter_start: number;
started: string;
}
export interface ChargerMeta {
label?: string;
guns?: Record<string, string>;
}
export interface Status {
connected: Record<string, Record<string, unknown> | null>;
connectors: Record<string, string>; // "cpId/connector" -> OCPP status
active_transactions: Record<string, ActiveTx>;
recent_auth_events: AuthEvent[];
relays: Record<string, { label: string; ip: string }>;
chargers: Record<string, ChargerMeta>;
pending_cards: number;
}
export interface AuthEvent {
time: string;
id_tag: string;
context: string;
connector: number | null;
result: string;
known: boolean;
}
export interface Session {
tx: number;
cp: string;
connector: number;
id_tag: string;
who: string | null;
started: string;
ended: string | null;
meter_start: number;
meter_stop: number | null;
wh: number | null;
reason: string | null;
method: string | null;
}
export interface CardEntry {
name: string;
kind: string;
user?: string;
guns?: string[];
}
export interface PendingCard {
first_seen: string;
last_seen: string;
count: number;
cp: string | null;
connector: number | null;
}
export interface DeniedCard {
rejected_at: string;
by: string;
first_seen?: string;
count?: number;
}
export interface PermissionCatalog {
chargers: Record<string, { label: string; guns: Record<string, string> }>;
relays: Record<string, { label: string; ip: string }>;
admin_scope: string;
}
export interface RelayState {
relay: string;
on?: boolean;
error?: string;
label?: string;
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"isolatedModules": true,
"noEmit": true,
"useDefineForClassFields": true
},
"include": ["src"]
}
+1
View File
@@ -0,0 +1 @@
{"root":["./src/app.tsx","./src/api.ts","./src/main.tsx","./src/queries.ts","./src/store.ts","./src/types.ts","./src/components/lamp.tsx","./src/components/layout.tsx","./src/pages/cards.tsx","./src/pages/dashboard.tsx","./src/pages/history.tsx","./src/pages/login.tsx","./src/pages/users.tsx"],"version":"5.9.3"}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// Dev: `npm run dev` serves on :5173 and proxies /api to the running backend.
// Prod: `npm run build` -> dist/, served as static files by the backend on :9000.
export default defineConfig({
plugins: [react()],
server: {
proxy: {
"/api": "http://localhost:9000",
},
},
});
+10 -4
View File
@@ -10,12 +10,13 @@ The three planned ways to authorize a charging session. Architecturally they all
## 1. RFID cards — ✅ verified live (2026-07-09) ## 1. RFID cards — ✅ verified live (2026-07-09)
First card tapped on the real charger: idTag `1000000000000393` → Authorize → StartTransaction on gun 2 → **actual charging session started** (tx 1, meter_start 3,513.857 kWh). Enrolled as "RFID card A". Second card captured the same session: `1000000000000395` → "RFID card B". The ids are sequential — the cards ship as a numbered batch. Remaining: tap any further cards, then set `learn_mode=false` to enforce. First card tapped on the real charger: idTag `1000000000000393` → Authorize → StartTransaction on gun 2 → **actual charging session started** (tx 1, meter_start 3,513.857 kWh). Enrolled as "RFID card A". Second card captured the same session: `1000000000000395` → "RFID card B". The ids are sequential — the cards ship as a numbered batch.
> [!warning] Session restarted after remote stop (❓ verify mechanism) > [!warning] Session restarted after remote stop (❓ verify mechanism)
> ~65 s after a RemoteStop on gun 2 (cable left plugged), a **new** transaction began with the same card id. Either the owner re-tapped, or the charger auto-restarts from its authorization cache (`AuthorizationCacheEnabled=true`). Matters for app UX: "stop" may not stick while the cable stays in. Test: remote-stop and touch nothing for 5 min. > ~65 s after a RemoteStop on gun 2 (cable left plugged), a **new** transaction began with the same card id. Either the owner re-tapped, or the charger auto-restarts from its authorization cache (`AuthorizationCacheEnabled=true`). Matters for app UX: "stop" may not stick while the cable stays in. Test: remote-stop and touch nothing for 5 min.
Flow for each new card: tap once in learn mode → harvest its idTag from `seen_tags.json` / `GET /api/allowlist` → add to `authorized` with a name (`kind: "card"`). > [!warning] Superseded (2026-07-11): learn mode removed — replaced by the **pending-card review workflow**
> An unknown card is now ALWAYS refused, but lands in `pending_cards`. The admin gets a notification (banner + badge in the [[frontend|panel]]) and decides: **approve** (name it, link it to a user, optionally restrict guns — one step) or **reject** (goes to `denied_cards`, silently refused, never re-pends; un-rejectable). New-card flow: tap once on the charger → review in the panel’s Cards page. ✅ smoke-verified: unknown tap → Invalid + pending; approved card authorizes on next tap; rejected card stays silent.
Since 2026-07-11 a card can be **linked to a user and restricted per gun**: Since 2026-07-11 a card can be **linked to a user and restricted per gun**:
@@ -64,13 +65,18 @@ The [[backend]] now has real multi-user authorization on top of the three method
| `charger:eu092025:1` | start/stop/unlock gun 1 | | `charger:eu092025:1` | start/stop/unlock gun 1 |
| `charger:eu092025:2` | same for gun 2 | | `charger:eu092025:2` | same for gun 2 |
| `relay:<name>` / `relay:*` | switch those relays (others are invisible to the user) | | `relay:<name>` / `relay:*` | switch those relays (others are invisible to the user) |
| `admin` | everything, incl. allowlist/user CRUD, learn-mode flip, setconfig, events | | `admin` | everything, incl. cards (pending review, allowlist), user CRUD, relay/charger registry, 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 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. - Admins grant permissions in the panel’s Users page as a **checkbox matrix** (per gun, per relay, admin) rendered from `GET /api/permissions` — nobody types raw scope strings.
- ✅ Verified by the 54-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.
## Audit: who charged, and how
Every session row records the **method**: `card` (physical RFID tap) or `app` (in-app button press), derived from the allowlist entry’s kind at StartTransaction, plus the resolved **who** (card owner / username). The panel’s History tab shows Who · Via · Gun · When · Duration · kWh. (2026-07-11, owner requirement.)
## Facts from the live probe that shape this design ## Facts from the live probe that shape this design
Per [[2026-07-09-discovery-eu092025]]: `AuthorizeRemoteTxRequests=false`, so remote starts don't trigger a separate Authorize — the `decide()` gate fires when the charger sends `StartTransaction`. The on-charger offline allowlist (`LocalAuthList`) holds max **6 idTags** and is currently disabled; enough for a household if we ever want tap-to-charge to survive CSMS downtime. Per [[2026-07-09-discovery-eu092025]]: `AuthorizeRemoteTxRequests=false`, so remote starts don't trigger a separate Authorize — the `decide()` gate fires when the charger sends `StartTransaction`. The on-charger offline allowlist (`LocalAuthList`) holds max **6 idTags** and is currently disabled; enough for a household if we ever want tap-to-charge to survive CSMS downtime.
+11 -9
View File
@@ -17,8 +17,7 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
├── 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 app-state sections (users/allowlist/relays/chargers), db-backed ├── 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 (raw ground truth)
├── static/ the web panel PWA (index.html, manifest, service worker, icon)
└── backend.db THE one store (SQLite, gitignored): sessions + samples + └── backend.db THE one store (SQLite, gitignored): sessions + samples +
settings (users, allowlist, relays, chargers, session secret) settings (users, allowlist, relays, chargers, session secret)
``` ```
@@ -26,32 +25,35 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
## Surfaces (all on :9000 — the touchscreen URL never changes) ## Surfaces (all on :9000 — the touchscreen URL never changes)
- `ws://<host>:9000/<ChargerID>` — OCPP WebSocket (catch-all path, the JC-6620 dials in) - `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) - `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` — username/password → 30-day session (cookie + bearer) - `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/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/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) - `GET /api/events?limit&event=` — tail the journal (admin)
- `POST /api/charger/start|stop[/{tx}]|unlock/{n}` — gun-scoped; `trigger/{...}|setconfig|probe` — 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/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/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 - `GET /api/relays[?live=true]`, `GET /api/relays/{name}`, `POST /api/relays/{name}/on|off|toggle` — relay-scoped
- `/docs` — interactive OpenAPI docs - `/docs` — interactive OpenAPI docs
## Design facts ## 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, learn mode, the JSONL event journal. `DataTransfer` frames are journaled too (the VIN long-shot lead in [[authorization]]). - 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-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 `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. - **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 (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. - 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 2026-07-11 (54 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. - ✅ **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
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. See [[frontend]] — React/Vite app, built to `frontend/dist/` and served by this process.
## Deliberately deferred ## Deliberately deferred
+30
View File
@@ -0,0 +1,30 @@
---
type: entity
updated: 2026-07-11
tags: [software, frontend, react]
---
# Frontend (`../frontend/`)
The React control panel (built 2026-07-11, replacing the single-file vanilla-JS panel at the owner's request). Stack per the owner's spec: **Vite + TypeScript + React 19, React Router 7 (routing), zustand (auth/UI state), TanStack Query 5 (server state, polling)**.
## Dev / prod workflow
- **Dev**: `npm run dev` in `frontend/` → Vite on `:5173`, **proxies `/api` to the backend on `:9000`** (`vite.config.ts`), so the session cookie flows normally.
- **Prod**: `npm run build` → `frontend/dist/`; the [[backend]] serves it statically with an SPA fallback (exact files win, everything else gets `index.html`, `/api/*` and `/docs` excluded). No separate web server.
- Fully self-contained: fonts (Archivo + IBM Plex Mono via Fontsource) are bundled into `dist/` — nothing loads from a CDN, so it works over [[netbird|NetBird]] without internet. ~94 kB gzipped JS.
## Pages
| Route | Who | What |
|---|---|---|
| `/` (Control) | all | one "bay" card per gun (labels from the chargers registry): status lamp, Start/Stop gated by scope **and** gun readiness; live session shows who/via/duration; relay toggles with on-demand live read |
| `/history` | all (filtered by scope) | the audit table: **who charged, via Card or In-app, which gun, when, duration, kWh**; total kWh; live sessions flagged |
| `/cards` | admin | **pending cards awaiting review** (approve → name + owner + gun restrictions in one step; reject → silenced), enrolled cards with owner/guns editing, rejected list with un-reject |
| `/users` | admin | user CRUD with the **permission matrix** — admin toggle, per-gun and per-relay checkboxes rendered from `GET /api/permissions` (no raw scope strings in the UI) |
An amber **notification banner + nav badge** appears for admins whenever unknown cards are pending (count polled via `/api/status` every 5 s).
## Design
Instrument-panel direction grounded in the hardware: porcelain/graphite surfaces (light + dark via `prefers-color-scheme`), **copper-busbar accent**, IBM Plex Mono for telemetry/identifiers, Archivo for UI. Signature element: the **indicator lamp** (radial LED with glow) encoding state everywhere — green=available, pulsing green=charging, amber=preparing/pending, red=fault/denied. Reduced motion respected; keyboard focus visible.
+2 -1
View File
@@ -16,7 +16,8 @@ Catalog of every wiki page. Updated on every ingest. (Schema/conventions live in
- [[anfu-charger]] — the charging pile: its three internal devices + working touchscreen config - [[anfu-charger]] — the charging pile: its three internal devices + working touchscreen config
- [[jc-6620]] — the OCPP communication controller / client; its IPs and shipped-gateway gotcha - [[jc-6620]] — the OCPP communication controller / client; its IPs and shipped-gateway gotcha
- [[backend]] — the production backend in `../backend/`: CSMS + REST API + relay control + user auth + consumption store + web panel, all on :9000 - [[backend]] — the production backend in `../backend/`: CSMS + REST API + relay control + user auth + consumption store, all on :9000
- [[frontend]] — the React control panel in `../frontend/`: Vite/TS, React Router, zustand, TanStack Query; served by the backend
- [[csms-toolkit]] — the Python CSMS scripts in `../discovering/`; discovery/diagnostic tooling (production role superseded by [[backend]]) - [[csms-toolkit]] — the Python CSMS scripts in `../discovering/`; discovery/diagnostic tooling (production role superseded by [[backend]])
- [[wifi-relays]] — the Tuya/SmartLife WiFi relays; local tinytuya control path + key-extraction steps - [[wifi-relays]] — the Tuya/SmartLife WiFi relays; local tinytuya control path + key-extraction steps
- [[netbird]] — the private overlay network; security boundary for the future web panel - [[netbird]] — the private overlay network; security boundary for the future web panel
+4
View File
@@ -79,3 +79,7 @@ Owner requirements: cards must belong to a person (not float around as "RFID car
## [2026-07-11] meta | config.json eliminated — one SQLite store (backend.db) ## [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]]. 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]].
## [2026-07-11] meta | React frontend; pending-card review workflow; auth-method audit
Owner: full frontend revision (React + routing + zustand + TanStack Query, Vite proxy in dev, static build served by backend, professional look) and backend fixes: permissions must be understandable, cards must connect to users, unknown card taps must notify the admin for approve/reject, and sessions must audit HOW authorization happened. Backend: learn mode REMOVED -> pending_cards/denied_cards workflow (unknown taps always refused, queued for review; pending count on /api/status as notification); sessions.method column (card|app); GET /api/permissions catalog. Frontend: new ../frontend/ (React 19, instrument-panel design, copper accent, indicator-lamp signature, bundled fonts); pages Control/History/Cards/Users; permission checkbox matrix; approve-with-owner-link in one step. Old backend/static vanilla panel deleted; seen_tags.json gone. Smoke: 54 checks. Created [[frontend]]; updated [[backend]], [[authorization]], [[overview]], [[architecture-plan]], [[index]], root CLAUDE.md.
+3 -1
View File
@@ -30,6 +30,8 @@ FastAPI app (uvicorn, :9000, on the always-on host)
**Web frontend: mobile-first PWA, no build pipeline — decided.** **Web frontend: mobile-first PWA, no build pipeline — decided.**
Plain HTML/JS (Alpine.js or htmx + SSE), served by FastAPI. Features: status card, start/stop, allowlist management, session history. PWA manifest → "add to home screen". Reached only over [[netbird|NetBird]]. Plain HTML/JS (Alpine.js or htmx + SSE), served by FastAPI. Features: status card, start/stop, allowlist management, session history. PWA manifest → "add to home screen". Reached only over [[netbird|NetBird]].
> [!warning] Superseded (2026-07-11): owner opted for a real build pipeline after seeing v1 — React/Vite stack, see [[frontend]]. "Served by FastAPI on :9000" and "NetBird-only" still hold.
**Flutter mobile app: phase 2, optional.** **Flutter mobile app: phase 2, optional.**
The PWA covers ~95% of the value. Flutter earns its keep only for push notifications ("charging complete") or as a learning project. It would consume the same REST API (FastAPI's OpenAPI spec → typed Dart client codegen), so nothing built now is wasted. Phone needs the NetBird client either way. The PWA covers ~95% of the value. Flutter earns its keep only for push notifications ("charging complete") or as a learning project. It would consume the same REST API (FastAPI's OpenAPI spec → typed Dart client codegen), so nothing built now is wasted. Phone needs the NetBird client either way.
@@ -39,7 +41,7 @@ The PWA covers ~95% of the value. Flutter earns its keep only for push notificat
1. **Productionize the CSMS** — ✅ done 2026-07-11 as the [[backend]] package (`../backend/`); SQLite session store added same day (JSONL journal stays as raw ground truth). 1. **Productionize the CSMS** — ✅ done 2026-07-11 as the [[backend]] package (`../backend/`); SQLite session store added same day (JSONL journal stays as raw ground truth).
2. **REST API** — ✅ done 2026-07-11: status, remote start/stop, allowlist CRUD, runtime learn-mode flip, **relay on/off/toggle**, multi-user login with permission scopes, **session history (who/when/kWh)**. ⚠️ Relay half awaits the [[wifi-relays|local-key extraction]]. 2. **REST API** — ✅ done 2026-07-11: status, remote start/stop, allowlist CRUD, runtime learn-mode flip, **relay on/off/toggle**, multi-user login with permission scopes, **session history (who/when/kWh)**. ⚠️ Relay half awaits the [[wifi-relays|local-key extraction]].
3. **Web panel (PWA)** — ✅ built 2026-07-11 (`backend/static/`, vanilla JS instead of Alpine — zero dependencies): login, per-gun status + start/stop gated by scopes and gun readiness, relay toggles, consumption history, admin tab. ⚠️ Untested on a real phone. 3. **Web panel** — ✅ built 2026-07-11, then **rebuilt the same day as a React app at the owner's request** ([[frontend]]: Vite + TS + React Router + zustand + TanStack Query; dev proxy to :9000, prod build served by the backend). The interim vanilla-JS panel is gone. ⚠️ Untested on a real phone.
4. **Deploy** — pick the always-on host (❓ open, [[overview]]), run as a service (systemd or NSSM on Windows), static IP / DHCP reservation, firewall rule for :9000, joined to NetBird. 4. **Deploy** — pick the always-on host (❓ open, [[overview]]), run as a service (systemd or NSSM on Windows), static IP / DHCP reservation, firewall rule for :9000, joined to NetBird.
5. **Hardware tasks** — RFID enrollment via learn mode; the Autocharge plug-in test ([[authorization]]) to settle "by vehicle". 5. **Hardware tasks** — RFID enrollment via learn mode; the Autocharge plug-in test ([[authorization]]) to settle "by vehicle".
6. **(Optional) Flutter app** — consumes the same API; adds push notifications. 6. **(Optional) Flutter app** — consumes the same API; adds push notifications.
+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 (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. **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 (54 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. **Late 2026-07-11:** learn mode replaced by the **pending-card review workflow** (unknown taps refused + queued for admin approve/reject), sessions audit the **auth method** (card vs in-app), and the panel was rebuilt as a **React app** ([[frontend]]). 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]]).
@@ -28,8 +28,8 @@ Hardware surprise: this is a **DC-capable multi-standard charger** (gun 1 EU, gu
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. 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 register them via `PUT /api/relays/<name>` → 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. **Restart the backend once** to pick up the React panel + pending-card workflow (state changes never need restarts; code updates do).
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** — `http://<host>:9000/`; verify login, a real button-push start on a ready gun, the pending-card banner (tap an unenrolled card), 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]]).
## Open decisions ❓ ## Open decisions ❓