Compare commits
23 Commits
2e5960fae3
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 272a6ad97d | |||
| 96ea568e53 | |||
| 9eaacf5eeb | |||
| d7264a758a | |||
| dbc4a477cb | |||
| 086b799158 | |||
| 268bed5d92 | |||
| 5f33eedbb1 | |||
| 12db2e719d | |||
| d285a32829 | |||
| 11e467a576 | |||
| a9b8436f2c | |||
| 25fa1f9fc5 | |||
| 8d8affe6ff | |||
| 9562fdaf6b | |||
| 069d544bb5 | |||
| 3387f8689e | |||
| 75869364b0 | |||
| 56c9020d9f | |||
| 70c2fe1210 | |||
| 3326c8d16c | |||
| d7b17d9cb2 | |||
| 5c88e8fa3c |
@@ -0,0 +1,20 @@
|
||||
# keep the build context lean — only backend/ and frontend/ sources matter
|
||||
.git/
|
||||
.gitea/
|
||||
venv/
|
||||
wiki/
|
||||
discovering/
|
||||
log.json
|
||||
CLAUDE.md
|
||||
compose.yaml
|
||||
|
||||
# built/installed inside the image, never copied in
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/tsconfig.tsbuildinfo
|
||||
|
||||
# runtime state — must never leak into an image
|
||||
backend/backend.db
|
||||
backend/events.jsonl
|
||||
backend/config.json*
|
||||
**/__pycache__/
|
||||
@@ -0,0 +1,95 @@
|
||||
name: Build Art IoT image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'backend/**'
|
||||
- 'frontend/**'
|
||||
- 'Dockerfile'
|
||||
- '.dockerignore'
|
||||
- 'compose.yaml'
|
||||
- '.gitea/workflows/build.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-and-publish:
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Plain `docker build` (not buildx) so the image is visible to `docker run`
|
||||
# for the smoke test below — buildx's docker-container driver exports to a
|
||||
# separate buildkitd cache that `docker run` can't see.
|
||||
# -------------------------------------------------------------------------
|
||||
- name: Build image
|
||||
run: docker build -t artiot:ci .
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Smoke test gate: 65 checks against the freshly built image — REST auth/
|
||||
# scopes, per-gun cards, pending-card workflow, OCPP WS round-trips via a
|
||||
# fake charge point, session store, SPA serving. All in-process (fastapi
|
||||
# TestClient) against a temp db; no network listeners needed.
|
||||
#
|
||||
# --user root only because httpx (TestClient's transport, test-only dep)
|
||||
# isn't shipped in the runtime image and uid 1000 can't pip-install.
|
||||
# If this fails, the workflow halts and the broken image is never pushed.
|
||||
# -------------------------------------------------------------------------
|
||||
- name: Smoke test
|
||||
timeout-minutes: 3
|
||||
run: |
|
||||
docker run --rm --user root artiot:ci sh -c \
|
||||
"pip install --no-cache-dir -q httpx && python -m backend.smoke_test"
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Registry login — only runs if the smoke test passed.
|
||||
# -------------------------------------------------------------------------
|
||||
- name: Login to Gitea registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.infra.msai.al
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Two tags:
|
||||
# :<branch> — mutable; the compose stack's default (ARTIOT_TAG=main).
|
||||
# :<sha> — immutable; set ARTIOT_TAG=<sha> in Komodo for a pinned
|
||||
# rollback.
|
||||
# -------------------------------------------------------------------------
|
||||
- name: Tag and push image
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
SHA: ${{ github.sha }}
|
||||
IMG: git.infra.msai.al/art/charging_station
|
||||
run: |
|
||||
docker tag artiot:ci $IMG:$BRANCH
|
||||
docker tag artiot:ci $IMG:$SHA
|
||||
docker push $IMG:$BRANCH
|
||||
docker push $IMG:$SHA
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Trigger the Komodo Stack redeploy. HMAC-validated webhook — same pattern
|
||||
# as the polymarket-bot repo. Both secrets must be set on this repo:
|
||||
# KOMODO_STACK_WEBHOOK_URL, KOMODO_WEBHOOK_SECRET
|
||||
# -------------------------------------------------------------------------
|
||||
- name: Trigger Komodo Stack redeploy
|
||||
if: success()
|
||||
env:
|
||||
URL: ${{ secrets.KOMODO_STACK_WEBHOOK_URL }}
|
||||
SECRET: ${{ secrets.KOMODO_WEBHOOK_SECRET }}
|
||||
run: |
|
||||
if [ -z "$URL" ] || [ -z "$SECRET" ]; then
|
||||
echo "Komodo webhook secrets not set — skipping redeploy trigger."
|
||||
exit 0
|
||||
fi
|
||||
body='{"ref":"refs/heads/${{ github.ref_name }}"}'
|
||||
sig=$(printf '%s' "$body" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $2}')
|
||||
curl -fsS -X POST \
|
||||
-H 'Content-Type: application/json' \
|
||||
-H "X-Hub-Signature-256: sha256=$sig" \
|
||||
-d "$body" \
|
||||
"$URL"
|
||||
@@ -1,6 +1,10 @@
|
||||
# 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.
|
||||
- **`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`.
|
||||
|
||||
Deployment: `Dockerfile` (node builds the panel, python serves it) + `compose.yaml` (Komodo stack, Traefik labels, raw :9000 for the charger) + `.gitea/workflows/build.yml` (build → smoke gate → push to `git.infra.msai.al` → Komodo redeploy). Documented at `wiki/entities/deployment.md`. Smoke test: `venv\Scripts\python -m backend.smoke_test` (65 checks, isolated temp DB — safe to run anytime).
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
# ----------------------------------------------------------------------------
|
||||
# Art IoT — one image: OCPP 1.6J CSMS + REST API + Tuya relay control, serving
|
||||
# the built React panel. Two stages:
|
||||
# 1. node builds frontend/ -> dist/
|
||||
# 2. python:slim runs `python -m backend.main` on :9000, with dist/ where
|
||||
# backend/main.py expects it (/app/frontend/dist).
|
||||
#
|
||||
# All mutable state (backend.db, events.jsonl) lives on the /data volume via
|
||||
# the BACKEND_DB / BACKEND_EVENTS env overrides — the container is disposable.
|
||||
#
|
||||
# Build: docker build -t artiot:dev .
|
||||
# Run: docker run -p 9000:9000 -v artiot-data:/data artiot:dev
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
FROM node:24-alpine AS panel
|
||||
WORKDIR /build
|
||||
# deps first — separate layer so source edits don't bust the npm cache
|
||||
COPY frontend/package.json frontend/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
|
||||
FROM python:3.13-slim
|
||||
|
||||
# curl for the compose healthcheck; tini reaps zombies and forwards SIGTERM so
|
||||
# `docker stop` shuts uvicorn down cleanly (capped at 3s by main.py, because
|
||||
# the charger holds its WebSocket open forever).
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
ca-certificates \
|
||||
curl \
|
||||
tini \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Python deps first — separate layer, pinned exactly to requirements.txt.
|
||||
COPY backend/requirements.txt /app/backend/requirements.txt
|
||||
RUN pip install --no-cache-dir --upgrade pip && \
|
||||
pip install --no-cache-dir -r /app/backend/requirements.txt
|
||||
|
||||
COPY backend/ /app/backend/
|
||||
COPY --from=panel /build/dist/ /app/frontend/dist/
|
||||
|
||||
# Persistent state. Owned by UID 1000 so the non-root process can write it.
|
||||
RUN mkdir -p /data && chown -R 1000:1000 /data
|
||||
ENV BACKEND_DB=/data/backend.db \
|
||||
BACKEND_EVENTS=/data/events.jsonl \
|
||||
PYTHONUNBUFFERED=1
|
||||
VOLUME ["/data"]
|
||||
|
||||
# 9000 is load-bearing: hardcoded in the charger's touchscreen URL.
|
||||
EXPOSE 9000
|
||||
|
||||
USER 1000:1000
|
||||
ENTRYPOINT ["/usr/bin/tini", "--"]
|
||||
CMD ["python", "-m", "backend.main"]
|
||||
@@ -0,0 +1,12 @@
|
||||
# Runtime state + secrets (users, Tuya local keys, session secret live in backend.db)
|
||||
backend.db
|
||||
config.json
|
||||
config.json.migrated
|
||||
events.jsonl
|
||||
seen_tags.json
|
||||
sessions.db
|
||||
discovery_*.json
|
||||
snapshot.json
|
||||
tinytuya.json
|
||||
devices.json
|
||||
tuya-raw.json
|
||||
@@ -0,0 +1,75 @@
|
||||
"""App state sections, backed by the settings table in backend.db (store.py).
|
||||
|
||||
CONFIG is the in-memory runtime state; save() persists it. Every mutation goes
|
||||
through the API/panel (or the backend.users CLI), takes effect immediately,
|
||||
and is durable — there is no config file to hand-edit and no restart-to-apply
|
||||
semantics. A legacy config.json (pre-2026-07-11 layout) is imported into the
|
||||
database once on startup and renamed to config.json.migrated.
|
||||
|
||||
Sections:
|
||||
users name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag"}
|
||||
authorized idTag -> {"name", "kind": "card|app|car",
|
||||
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"}
|
||||
chargers cp_id -> {"label", "guns": {"1": "display name"}} (UI only)
|
||||
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 logging
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
from . import store
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
LEGACY_CONFIG = HERE / "config.json"
|
||||
|
||||
log = logging.getLogger("config")
|
||||
|
||||
DEFAULTS = {
|
||||
"users": {},
|
||||
"authorized": {},
|
||||
"pending_cards": {},
|
||||
"denied_cards": {},
|
||||
"relays": {},
|
||||
"chargers": {},
|
||||
}
|
||||
|
||||
|
||||
def _load() -> dict:
|
||||
cfg = store.load_settings()
|
||||
if not cfg and LEGACY_CONFIG.exists():
|
||||
cfg = json.loads(LEGACY_CONFIG.read_text(encoding="utf-8"))
|
||||
LEGACY_CONFIG.rename(LEGACY_CONFIG.with_suffix(".json.migrated"))
|
||||
log.warning("imported legacy config.json into %s (file kept as "
|
||||
"config.json.migrated)", store.DB_PATH.name)
|
||||
for key, default in DEFAULTS.items():
|
||||
cfg.setdefault(key, default if not isinstance(default, dict) else dict(default))
|
||||
cfg.pop("learn_mode", None) # superseded by the pending-cards workflow
|
||||
# users' app idTags used to be auto-enrolled as "app token of <name>"
|
||||
# allowlist entries; they now authorize via the user record directly
|
||||
user_tags = {u.get("id_tag") for u in cfg["users"].values()}
|
||||
for tag in [t for t in cfg["authorized"] if t in user_tags]:
|
||||
del cfg["authorized"][tag]
|
||||
log.info("dropped redundant allowlist entry %r (a user's app token)", tag)
|
||||
if not cfg.get("session_secret"):
|
||||
cfg["session_secret"] = secrets.token_hex(32)
|
||||
return cfg
|
||||
|
||||
|
||||
CONFIG = _load()
|
||||
|
||||
|
||||
def save() -> None:
|
||||
store.save_settings(CONFIG)
|
||||
|
||||
|
||||
save() # persist migration / generated defaults immediately
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
"""OCPP 1.6J charge-point side of the backend (the CSMS).
|
||||
|
||||
Ported from the proven discovery code (../discovering/station.py) with the
|
||||
same core design: the API server IS the CSMS, because RemoteStart/Stop can
|
||||
only travel down the live WebSocket the charger holds open. Every auth method
|
||||
(RFID tap, app remote start) flows through the single decide() gate.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from collections import deque
|
||||
from fnmatch import fnmatch
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import WebSocket, WebSocketDisconnect
|
||||
|
||||
from ocpp.routing import on
|
||||
from ocpp.v16 import ChargePoint as OcppChargePoint
|
||||
from ocpp.v16 import call, call_result
|
||||
from ocpp.v16.enums import (
|
||||
Action,
|
||||
AuthorizationStatus,
|
||||
DataTransferStatus,
|
||||
MessageTrigger,
|
||||
RegistrationStatus,
|
||||
)
|
||||
|
||||
from . import store, users
|
||||
from .config import CONFIG, HERE, save
|
||||
from .journal import now, record_event
|
||||
|
||||
log = logging.getLogger("csms")
|
||||
|
||||
# ---- shared runtime state (the REST routes read/drive these) ----
|
||||
CONNECTED: dict = {} # cp_id -> ChargePoint instance
|
||||
CONNECTORS: dict = {} # (cp_id, connector_id) -> latest status string
|
||||
ACTIVE_TX: dict = {} # transaction_id -> {cp, connector, id_tag, meter_start, started}
|
||||
AUTH_EVENTS = deque(maxlen=50) # recent authorization attempts (for the panel UI)
|
||||
_tx_counter = {"n": store.max_tx()} # tx ids continue across restarts
|
||||
|
||||
TRIGGERABLE = {
|
||||
"status": MessageTrigger.status_notification,
|
||||
"meter": MessageTrigger.meter_values,
|
||||
"heartbeat": MessageTrigger.heartbeat,
|
||||
"boot": MessageTrigger.boot_notification,
|
||||
}
|
||||
|
||||
|
||||
def _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,
|
||||
cp: Optional[str] = None) -> AuthorizationStatus:
|
||||
"""The one gate every auth method flows through: is this idTag allowed?
|
||||
|
||||
An allowlist entry may carry "guns": ["eu092025:2"] to restrict a card to
|
||||
specific guns of specific chargers (fnmatch patterns, so "eu092025:*"
|
||||
works). Only StartTransaction knows the connector, so the per-gun check
|
||||
fires there; a plain Authorize (card tap) still accepts a known card —
|
||||
which matches this charger, since AuthorizeRemoteTxRequests=false means
|
||||
StartTransaction is the decisive call anyway.
|
||||
|
||||
A user's app idTag (users.<name>.id_tag, used for their in-app starts) is
|
||||
validated directly against the user record — it is NOT an allowlist entry,
|
||||
and it must satisfy the user's own charger:<cp>:<gun> scopes.
|
||||
|
||||
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)
|
||||
known = entry is not None
|
||||
app_user = user_for_tag(id_tag)
|
||||
gun = f"{cp}:{connector}" if cp and connector is not None else None
|
||||
if known and gun and entry.get("guns") \
|
||||
and not any(fnmatch(gun, pat) for pat in entry["guns"]):
|
||||
log.warning("[NO] REJECTED idTag=%r (%s) not allowed on %s (allowed: %s)",
|
||||
id_tag, entry.get("name", "?"), gun, entry["guns"])
|
||||
status = AuthorizationStatus.invalid
|
||||
elif known:
|
||||
name = entry.get("name", "?")
|
||||
log.info("[OK] AUTHORIZED idTag=%r (%s) via %s", id_tag, name, context)
|
||||
status = AuthorizationStatus.accepted
|
||||
elif app_user is not None:
|
||||
known = True
|
||||
scopes = CONFIG["users"][app_user].get("scopes", [])
|
||||
if gun and not users.allowed(scopes, f"charger:{cp}:{connector}"):
|
||||
log.warning("[NO] REJECTED app idTag of %r on %s (no permission)",
|
||||
app_user, gun)
|
||||
status = AuthorizationStatus.invalid
|
||||
else:
|
||||
log.info("[OK] AUTHORIZED app start by user %r via %s", app_user, context)
|
||||
status = AuthorizationStatus.accepted
|
||||
elif id_tag == "app-remote" and not CONFIG["users"]:
|
||||
# bootstrap: with zero users the API is open and starts run as "app-remote"
|
||||
log.info("[OK] AUTHORIZED app-remote (open mode, no users yet)")
|
||||
status = AuthorizationStatus.accepted
|
||||
elif id_tag in CONFIG["denied_cards"]:
|
||||
log.warning("[NO] DENIED idTag=%r (admin-rejected card) via %s", id_tag, context)
|
||||
status = AuthorizationStatus.invalid
|
||||
else:
|
||||
log.warning("[??] UNKNOWN idTag=%r via %s -> refused, queued for admin approval",
|
||||
id_tag, context)
|
||||
_record_pending(id_tag, cp, connector)
|
||||
status = AuthorizationStatus.invalid
|
||||
AUTH_EVENTS.append(
|
||||
{"time": now(), "id_tag": id_tag, "context": context,
|
||||
"connector": connector, "result": status.value, "known": known}
|
||||
)
|
||||
return status
|
||||
|
||||
|
||||
def user_for_tag(id_tag: str) -> Optional[str]:
|
||||
"""Username whose personal app idTag this is, if any."""
|
||||
for username, user in CONFIG["users"].items():
|
||||
if user.get("id_tag") == id_tag:
|
||||
return username
|
||||
return None
|
||||
|
||||
|
||||
def resolve_who(id_tag: str) -> str:
|
||||
"""Human label for a session: the card's owning user, the allowlist entry
|
||||
name, the username behind an app idTag, or the raw tag — in that order."""
|
||||
entry = CONFIG["authorized"].get(id_tag)
|
||||
if entry:
|
||||
if entry.get("user"):
|
||||
return entry["user"]
|
||||
if entry.get("name"):
|
||||
return entry["name"]
|
||||
for username, user in CONFIG["users"].items():
|
||||
if user.get("id_tag") == id_tag:
|
||||
return username
|
||||
return id_tag
|
||||
|
||||
|
||||
class ChargePoint(OcppChargePoint):
|
||||
@on(Action.boot_notification)
|
||||
async def on_boot_notification(self, charge_point_vendor, charge_point_model, **kwargs):
|
||||
self.boot_info = {"vendor": charge_point_vendor, "model": charge_point_model, **kwargs}
|
||||
record_event("BootNotification", self.id, **self.boot_info)
|
||||
log.info("BootNotification: vendor=%r model=%r extra=%r",
|
||||
charge_point_vendor, charge_point_model, kwargs)
|
||||
return call_result.BootNotification(
|
||||
current_time=now(), interval=30, status=RegistrationStatus.accepted
|
||||
)
|
||||
|
||||
@on(Action.heartbeat)
|
||||
async def on_heartbeat(self):
|
||||
return call_result.Heartbeat(current_time=now())
|
||||
|
||||
@on(Action.status_notification)
|
||||
async def on_status_notification(self, connector_id, error_code, status, **kwargs):
|
||||
CONNECTORS[(self.id, connector_id)] = status
|
||||
record_event("StatusNotification", self.id,
|
||||
connector=connector_id, status=status, error=error_code)
|
||||
log.info("StatusNotification: connector=%s status=%s error=%s",
|
||||
connector_id, status, error_code)
|
||||
return call_result.StatusNotification()
|
||||
|
||||
@on(Action.authorize)
|
||||
async def on_authorize(self, id_tag, **kwargs):
|
||||
status = decide(id_tag, "Authorize (card/app)", cp=self.id)
|
||||
record_event("Authorize", self.id, id_tag=id_tag, result=status.value)
|
||||
return call_result.Authorize(id_tag_info={"status": status})
|
||||
|
||||
@on(Action.start_transaction)
|
||||
async def on_start_transaction(self, connector_id, id_tag, meter_start, timestamp, **kwargs):
|
||||
status = decide(id_tag, f"StartTransaction (connector {connector_id})",
|
||||
connector=connector_id, cp=self.id)
|
||||
if status == AuthorizationStatus.accepted:
|
||||
_tx_counter["n"] += 1
|
||||
tx = _tx_counter["n"]
|
||||
who = resolve_who(id_tag)
|
||||
# audit: HOW was this session authorized? allowlist kind ->
|
||||
# "card" (physical tap); a user's app idTag -> "app" (in-app button)
|
||||
entry = CONFIG["authorized"].get(id_tag)
|
||||
if entry is not None:
|
||||
method = entry.get("kind", "unknown")
|
||||
elif user_for_tag(id_tag) or id_tag == "app-remote":
|
||||
method = "app"
|
||||
else:
|
||||
method = "unknown"
|
||||
ACTIVE_TX[tx] = {
|
||||
"cp": self.id, "connector": connector_id, "id_tag": id_tag,
|
||||
"who": who, "method": method,
|
||||
"meter_start": meter_start, "started": now(),
|
||||
}
|
||||
store.start_session(tx, self.id, connector_id, id_tag, who,
|
||||
timestamp, meter_start, method=method)
|
||||
log.info("Transaction %s STARTED on connector %s by %s (meter_start=%s)",
|
||||
tx, connector_id, who, meter_start)
|
||||
else:
|
||||
tx = 0 # 0 tells the charger the transaction is not authorized
|
||||
record_event("StartTransaction", self.id, connector=connector_id,
|
||||
id_tag=id_tag, meter_start=meter_start, result=status.value, tx=tx)
|
||||
return call_result.StartTransaction(
|
||||
transaction_id=tx, id_tag_info={"status": status}
|
||||
)
|
||||
|
||||
@on(Action.stop_transaction)
|
||||
async def on_stop_transaction(self, meter_stop, timestamp, transaction_id, **kwargs):
|
||||
info = ACTIVE_TX.pop(transaction_id, None)
|
||||
used = (meter_stop - info["meter_start"]) if info else "?"
|
||||
store.end_session(transaction_id, timestamp, meter_stop,
|
||||
reason=kwargs.get("reason"))
|
||||
record_event("StopTransaction", self.id, tx=transaction_id,
|
||||
meter_stop=meter_stop, delivered_wh=used, **kwargs)
|
||||
log.info("Transaction %s STOPPED (meter_stop=%s, delivered=%s Wh)",
|
||||
transaction_id, meter_stop, used)
|
||||
return call_result.StopTransaction(
|
||||
id_tag_info={"status": AuthorizationStatus.accepted}
|
||||
)
|
||||
|
||||
@on(Action.meter_values)
|
||||
async def on_meter_values(self, connector_id, meter_value, **kwargs):
|
||||
record_event("MeterValues", self.id, connector=connector_id,
|
||||
values=meter_value, **kwargs)
|
||||
tx = kwargs.get("transaction_id")
|
||||
if tx is not None:
|
||||
for entry in meter_value or []:
|
||||
reading, context = {}, None
|
||||
for sv in entry.get("sampled_value") or []:
|
||||
# measurand defaults to the energy register when omitted
|
||||
measurand = sv.get("measurand", "Energy.Active.Import.Register")
|
||||
context = sv.get("context", context) # Sample.Periodic / Transaction.Begin / .End
|
||||
try:
|
||||
value = float(sv.get("value"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if measurand == "Energy.Active.Import.Register":
|
||||
# some firmwares report kWh; normalize to Wh
|
||||
reading["energy_wh"] = value * 1000 if sv.get("unit") == "kWh" else value
|
||||
elif measurand == "Power.Active.Import":
|
||||
reading["power_w"] = value * 1000 if sv.get("unit") == "kW" else value
|
||||
elif measurand == "SoC":
|
||||
reading["soc"] = value
|
||||
elif measurand == "Voltage":
|
||||
reading["voltage_v"] = value * 1000 if sv.get("unit") == "kV" else value
|
||||
elif measurand == "Current.Import":
|
||||
reading["current_a"] = value
|
||||
if reading:
|
||||
store.add_sample(tx, entry.get("timestamp", now()),
|
||||
context=context, **reading)
|
||||
# live telemetry for the panel: latest sample rides
|
||||
# /api/status. Transaction.Begin is skipped — it's taken
|
||||
# before the car's BMS is read (SoC 0, all zeros).
|
||||
if context != "Transaction.Begin" and tx in ACTIVE_TX:
|
||||
ACTIVE_TX[tx].setdefault("telemetry", {}).update(
|
||||
{**reading, "time": entry.get("timestamp")}
|
||||
)
|
||||
log.info("MeterValues: connector=%s values=%r", connector_id, meter_value)
|
||||
return call_result.MeterValues()
|
||||
|
||||
@on(Action.data_transfer)
|
||||
async def on_data_transfer(self, vendor_id, **kwargs):
|
||||
# Journaled because a vendor DataTransfer frame is the long-shot lead
|
||||
# for the charger ever surfacing the vehicle VIN (wiki: authorization).
|
||||
record_event("DataTransfer", self.id, vendor_id=vendor_id, **kwargs)
|
||||
log.info("DataTransfer: vendor_id=%r extra=%r", vendor_id, kwargs)
|
||||
return call_result.DataTransfer(status=DataTransferStatus.accepted)
|
||||
|
||||
@on(Action.firmware_status_notification)
|
||||
async def on_firmware_status(self, status, **kwargs):
|
||||
log.info("FirmwareStatusNotification: %s", status)
|
||||
return call_result.FirmwareStatusNotification()
|
||||
|
||||
@on(Action.diagnostics_status_notification)
|
||||
async def on_diagnostics_status(self, status, **kwargs):
|
||||
log.info("DiagnosticsStatusNotification: %s", status)
|
||||
return call_result.DiagnosticsStatusNotification()
|
||||
|
||||
|
||||
# ---- outbound OCPP commands (called by the REST routes) ----
|
||||
async def remote_start(cp_id: str, id_tag: str, connector_id: int = 1) -> str:
|
||||
cp = CONNECTED.get(cp_id)
|
||||
if cp is None:
|
||||
raise RuntimeError(f"charge point {cp_id!r} is not connected")
|
||||
resp = await cp.call(call.RemoteStartTransaction(id_tag=id_tag, connector_id=connector_id))
|
||||
log.info("RemoteStartTransaction(%s, connector=%s) -> %s", id_tag, connector_id, resp.status)
|
||||
return resp.status
|
||||
|
||||
|
||||
async def remote_stop(transaction_id: int) -> str:
|
||||
# fall back to the store so sessions still running after a backend restart
|
||||
# (charger keeps them alive) remain stoppable
|
||||
info = ACTIVE_TX.get(transaction_id) or store.open_session(transaction_id)
|
||||
if info is None:
|
||||
raise RuntimeError(f"no active transaction {transaction_id}")
|
||||
cp = CONNECTED.get(info["cp"])
|
||||
if cp is None:
|
||||
raise RuntimeError("charge point is not connected")
|
||||
resp = await cp.call(call.RemoteStopTransaction(transaction_id=transaction_id))
|
||||
log.info("RemoteStopTransaction(%s) -> %s", transaction_id, resp.status)
|
||||
return resp.status
|
||||
|
||||
|
||||
async def interrogate(cp: ChargePoint) -> dict:
|
||||
"""GetConfiguration + trigger a StatusNotification; save to discovery_<id>.json."""
|
||||
report = {
|
||||
"charge_point": cp.id,
|
||||
"probed_at": now(),
|
||||
"boot_info": getattr(cp, "boot_info", None),
|
||||
}
|
||||
try:
|
||||
resp = await cp.call(call.GetConfiguration())
|
||||
report["configuration"] = resp.configuration_key
|
||||
report["unknown_keys"] = resp.unknown_key
|
||||
except Exception as exc:
|
||||
report["configuration_error"] = repr(exc)
|
||||
try:
|
||||
resp = await cp.call(
|
||||
call.TriggerMessage(requested_message=MessageTrigger.status_notification)
|
||||
)
|
||||
report["trigger_status_notification"] = resp.status
|
||||
await asyncio.sleep(2) # give the triggered StatusNotifications time to arrive
|
||||
except Exception as exc:
|
||||
report["trigger_error"] = repr(exc)
|
||||
report["connectors_seen"] = {
|
||||
str(conn): status for (cp_id, conn), status in CONNECTORS.items() if cp_id == cp.id
|
||||
}
|
||||
path = HERE / f"discovery_{cp.id}.json"
|
||||
path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
return report
|
||||
|
||||
|
||||
class _WSAdapter:
|
||||
"""Bridge a Starlette WebSocket to the recv()/send() interface the ocpp lib expects."""
|
||||
|
||||
def __init__(self, ws: WebSocket):
|
||||
self._ws = ws
|
||||
|
||||
async def recv(self) -> str:
|
||||
return await self._ws.receive_text()
|
||||
|
||||
async def send(self, message: str) -> None:
|
||||
await self._ws.send_text(message)
|
||||
|
||||
async def close(self, code: int = 1000, reason: str = "") -> None:
|
||||
await self._ws.close(code=code)
|
||||
|
||||
|
||||
async def ocpp_socket(ws: WebSocket, cp_path: str) -> None:
|
||||
"""The OCPP endpoint the JC-6620 dials: ws://<host>:9000/<ChargerID>."""
|
||||
cp_id = cp_path.strip("/").split("/")[-1] or "unknown"
|
||||
offered = [
|
||||
p.strip()
|
||||
for p in ws.headers.get("sec-websocket-protocol", "").split(",")
|
||||
if p.strip()
|
||||
]
|
||||
await ws.accept(subprotocol="ocpp1.6" if "ocpp1.6" in offered else None)
|
||||
log.info("Charger connected: id=%r from %s subprotocols=%r", cp_id, ws.client, offered)
|
||||
record_event("connected", cp_id, client=str(ws.client), subprotocols=offered)
|
||||
cp = ChargePoint(cp_id, _WSAdapter(ws))
|
||||
CONNECTED[cp_id] = cp
|
||||
try:
|
||||
await cp.start()
|
||||
except WebSocketDisconnect:
|
||||
log.info("Charger %r disconnected", cp_id)
|
||||
finally:
|
||||
record_event("disconnected", cp_id)
|
||||
CONNECTED.pop(cp_id, None)
|
||||
for key in [k for k in CONNECTORS if k[0] == cp_id]:
|
||||
CONNECTORS.pop(key, None)
|
||||
|
||||
|
||||
def pick_cp(cp_id: Optional[str]) -> ChargePoint:
|
||||
"""Resolve which charger a REST call targets; auto-select when only one is connected."""
|
||||
if cp_id is not None:
|
||||
cp = CONNECTED.get(cp_id)
|
||||
if cp is None:
|
||||
raise KeyError(f"charge point {cp_id!r} is not connected")
|
||||
return cp
|
||||
if len(CONNECTED) == 1:
|
||||
return next(iter(CONNECTED.values()))
|
||||
raise KeyError(f"specify ?cp=<id>; currently connected: {list(CONNECTED)}")
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Durable journal: events.jsonl — everything the charger tells us (and what
|
||||
we told it), one JSON line per event. Append-only, crash-safe, greppable; the
|
||||
raw ground truth behind the queryable store (store.py).
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
# BACKEND_EVENTS: in containers the journal must land on the data volume, not
|
||||
# in the ephemeral image layer. Mirrors the BACKEND_DB override in store.py.
|
||||
EVENTS_PATH = Path(os.environ.get("BACKEND_EVENTS", HERE / "events.jsonl"))
|
||||
|
||||
log = logging.getLogger("journal")
|
||||
|
||||
|
||||
def now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def record_event(event: str, cp_id: str, **data) -> None:
|
||||
entry = {"time": now(), "event": event, "cp": cp_id, **data}
|
||||
try:
|
||||
with EVENTS_PATH.open("a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n")
|
||||
except Exception:
|
||||
log.exception("failed to journal event %r", event)
|
||||
|
||||
|
||||
def read_events(limit: int = 100, event: Optional[str] = None) -> list:
|
||||
if not EVENTS_PATH.exists():
|
||||
return []
|
||||
lines = EVENTS_PATH.read_text(encoding="utf-8").splitlines()
|
||||
entries = [json.loads(line) for line in lines if line.strip()]
|
||||
if event is not None:
|
||||
entries = [e for e in entries if e.get("event") == event]
|
||||
return entries[-limit:]
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Home energy backend — private CSMS for the Anfu charger + local control of
|
||||
the Tuya/SmartLife WiFi relays. One uvicorn process, one port:
|
||||
|
||||
ws://<host>:9000/<ChargerID> OCPP 1.6J (the JC-6620 dials in here)
|
||||
http://<host>:9000/api/* REST for the web panel / curl
|
||||
http://<host>:9000/docs interactive API docs
|
||||
|
||||
Port 9000 is load-bearing: it's hardcoded in the charger's touchscreen URL and
|
||||
changing it there requires a power-cycle (wiki: troubleshooting #4).
|
||||
|
||||
Run: venv\\Scripts\\python -m backend.main (from the repo root)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
import uvicorn
|
||||
from fastapi import FastAPI, WebSocket
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
||||
from . import csms, routes
|
||||
from .config import CONFIG
|
||||
|
||||
# the built React app (frontend/: `npm run build` -> dist/)
|
||||
DIST = Path(__file__).resolve().parent.parent / "frontend" / "dist"
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s | %(message)s",
|
||||
)
|
||||
log = logging.getLogger("backend")
|
||||
|
||||
app = FastAPI(
|
||||
title="Home Energy Backend",
|
||||
description="Private OCPP CSMS + WiFi relay control. The charger dials "
|
||||
"ws://<host>:9000/<id>; everything else lives under /api/*.",
|
||||
)
|
||||
app.include_router(routes.router)
|
||||
|
||||
|
||||
# SPA serving: exact files from frontend/dist, anything else falls back to
|
||||
# index.html so React Router owns the URL space. Registered after the API
|
||||
# router, so /api/* and /docs keep winning.
|
||||
@app.get("/{full_path:path}", include_in_schema=False)
|
||||
async def spa(full_path: str):
|
||||
if not DIST.exists():
|
||||
return JSONResponse(
|
||||
{"detail": "frontend not built — run `npm run build` in frontend/ "
|
||||
"(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()):
|
||||
# hashed assets are immutable; cache them hard
|
||||
headers = {"Cache-Control": "public, max-age=31536000, immutable"} \
|
||||
if full_path.startswith("assets/") else {"Cache-Control": "no-cache"}
|
||||
return FileResponse(candidate, headers=headers)
|
||||
# index.html must always revalidate, or phones keep showing stale builds
|
||||
return FileResponse(DIST / "index.html", headers={"Cache-Control": "no-cache"})
|
||||
|
||||
|
||||
# Catch-all WS route so the charger may dial any path (it uses /<ChargerID>).
|
||||
# WebSocket and HTTP routes match independently, so this never shadows /api/*.
|
||||
@app.websocket("/{cp_path:path}")
|
||||
async def ocpp_websocket(ws: WebSocket, cp_path: str):
|
||||
await csms.ocpp_socket(ws, cp_path)
|
||||
|
||||
|
||||
async def main():
|
||||
log.info(
|
||||
"CSMS ws://0.0.0.0:9000/<id> | API http://0.0.0.0:9000/docs | "
|
||||
"%d authorized id(s) | %d pending card(s) | %d user(s) | %d relay(s) | panel %s",
|
||||
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"]:
|
||||
log.warning(
|
||||
"NO USERS CONFIGURED — the API is OPEN (anonymous admin). "
|
||||
"Create one: venv\\Scripts\\python -m backend.users add <name> --scopes admin"
|
||||
)
|
||||
# timeout_graceful_shutdown: the charger holds its WebSocket open FOREVER,
|
||||
# so a graceful "wait for connections to drain" would hang Ctrl+C — cap it.
|
||||
# The charger reconnects within seconds after a restart anyway.
|
||||
await uvicorn.Server(
|
||||
uvicorn.Config(app, host="0.0.0.0", port=9000, log_config=None,
|
||||
timeout_graceful_shutdown=3)
|
||||
).serve()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Local control of the Tuya/SmartLife WiFi relays — no Tuya cloud in the loop.
|
||||
|
||||
The relays pair via the SmartLife app (BLE-assisted onboarding) but once on
|
||||
WiFi they speak Tuya's local protocol on TCP 6668, which tinytuya drives
|
||||
directly. Each relay needs its device id + LOCAL KEY in config.json under
|
||||
"relays" — extracted once with `tinytuya wizard` (see the wiki: wifi-relays).
|
||||
|
||||
tinytuya is synchronous/blocking, so every call runs in a worker thread via
|
||||
asyncio.to_thread to keep the OCPP socket responsive.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
try:
|
||||
import tinytuya
|
||||
except ImportError: # backend still runs (charger-only) without it
|
||||
tinytuya = None
|
||||
|
||||
from .config import CONFIG
|
||||
|
||||
log = logging.getLogger("relays")
|
||||
|
||||
|
||||
class RelayError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def configured() -> dict:
|
||||
"""The relay registry without secrets — safe to return over the API."""
|
||||
return {
|
||||
name: {"label": cfg.get("label", name), "ip": cfg.get("ip", "auto")}
|
||||
for name, cfg in CONFIG["relays"].items()
|
||||
}
|
||||
|
||||
|
||||
def _device(name: str):
|
||||
if tinytuya is None:
|
||||
raise RelayError("tinytuya is not installed (pip install tinytuya)")
|
||||
cfg = CONFIG["relays"].get(name)
|
||||
if cfg is None:
|
||||
raise RelayError(f"unknown relay {name!r}; configured: {list(CONFIG['relays'])}")
|
||||
ip = cfg.get("ip", "auto")
|
||||
# "Auto" makes tinytuya find the device via its UDP broadcast (slower);
|
||||
# pin the IP in config.json (with a DHCP reservation) once known.
|
||||
dev = tinytuya.OutletDevice(
|
||||
cfg["id"], ip if ip and ip != "auto" else "Auto", cfg["key"]
|
||||
)
|
||||
dev.set_version(float(cfg.get("version", 3.3)))
|
||||
dev.set_socketTimeout(5)
|
||||
return dev, str(cfg.get("switch", 1))
|
||||
|
||||
|
||||
def _check(name: str, result) -> dict:
|
||||
if not isinstance(result, dict) or "dps" not in result:
|
||||
raise RelayError(f"relay {name!r} did not answer: {result!r}")
|
||||
return result["dps"]
|
||||
|
||||
|
||||
def _status_sync(name: str) -> dict:
|
||||
dev, sw = _device(name)
|
||||
dps = _check(name, dev.status())
|
||||
return {"relay": name, "on": bool(dps.get(sw)), "dps": dps}
|
||||
|
||||
|
||||
def _switch_sync(name: str, on: bool) -> dict:
|
||||
dev, sw = _device(name)
|
||||
result = dev.set_status(on, int(sw))
|
||||
# some firmwares reply with the new dps, some with an empty ack — verify
|
||||
if not (isinstance(result, dict) and "dps" in result):
|
||||
result = dev.status()
|
||||
dps = _check(name, result)
|
||||
actual = bool(dps.get(sw, on))
|
||||
if actual != on:
|
||||
raise RelayError(f"relay {name!r} did not switch (wanted {on}, reads {actual})")
|
||||
return {"relay": name, "on": actual}
|
||||
|
||||
|
||||
async def status(name: str) -> dict:
|
||||
return await asyncio.to_thread(_status_sync, name)
|
||||
|
||||
|
||||
async def switch(name: str, on: bool) -> dict:
|
||||
return await asyncio.to_thread(_switch_sync, name, on)
|
||||
|
||||
|
||||
async def toggle(name: str) -> dict:
|
||||
current = await status(name)
|
||||
return await switch(name, not current["on"])
|
||||
|
||||
|
||||
async def status_all() -> dict:
|
||||
"""Poll every configured relay concurrently; errors become per-relay strings."""
|
||||
names = list(CONFIG["relays"])
|
||||
results = await asyncio.gather(*(status(n) for n in names), return_exceptions=True)
|
||||
out = {}
|
||||
for name, res in zip(names, results):
|
||||
if isinstance(res, BaseException):
|
||||
out[name] = {"relay": name, "error": str(res)}
|
||||
else:
|
||||
out[name] = res
|
||||
out[name]["label"] = CONFIG["relays"][name].get("label", name)
|
||||
return out
|
||||
@@ -0,0 +1,5 @@
|
||||
fastapi==0.139.0
|
||||
uvicorn==0.51.0
|
||||
websockets==16.0
|
||||
ocpp==2.1.0
|
||||
tinytuya==1.20.0
|
||||
@@ -0,0 +1,492 @@
|
||||
"""REST API — everything under /api/*, for the web panel (and curl).
|
||||
|
||||
Authorization model (see backend/users.py):
|
||||
* POST /api/login {username, password} -> HMAC session token, set as an
|
||||
HttpOnly cookie AND returned in the body (usable as a Bearer token).
|
||||
* Every endpoint resolves the caller to a user and checks a permission
|
||||
scope: charger:<cp>:<gun>, relay:<name>, or admin (implies everything).
|
||||
* With ZERO users configured the API is open (anonymous admin) so nothing
|
||||
breaks before the first `python -m backend.users add` — main.py warns.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from . import csms, relays, store, users
|
||||
from .config import CONFIG, save
|
||||
from .journal import now, read_events
|
||||
from ocpp.v16 import call
|
||||
|
||||
log = logging.getLogger("api")
|
||||
|
||||
SESSION_COOKIE = "session"
|
||||
|
||||
|
||||
def current_user(request: Request) -> dict:
|
||||
"""Resolve the session cookie or Bearer token to a user dict."""
|
||||
if not CONFIG["users"]:
|
||||
return {"name": "anonymous", "scopes": ["admin"], "id_tag": "app-remote"}
|
||||
token = request.cookies.get(SESSION_COOKIE) or (
|
||||
request.headers.get("authorization") or ""
|
||||
).removeprefix("Bearer ").strip()
|
||||
username = users.verify_session(token) if token else None
|
||||
if username is None:
|
||||
raise HTTPException(401, "not logged in (or session expired)")
|
||||
return {"name": username, **CONFIG["users"][username]}
|
||||
|
||||
|
||||
def need(user: dict, scope: str) -> None:
|
||||
if not users.allowed(user["scopes"], scope):
|
||||
raise HTTPException(403, f"user {user['name']!r} lacks permission {scope!r}")
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api")
|
||||
|
||||
|
||||
def _cp(cp_id: Optional[str]) -> csms.ChargePoint:
|
||||
try:
|
||||
return csms.pick_cp(cp_id)
|
||||
except KeyError as exc:
|
||||
raise HTTPException(409, str(exc.args[0]))
|
||||
|
||||
|
||||
async def _ocpp(coro):
|
||||
"""Run an OCPP call for an HTTP handler, mapping failures to HTTP errors."""
|
||||
try:
|
||||
return await coro
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise HTTPException(502, f"OCPP call failed: {exc!r}")
|
||||
|
||||
|
||||
def _visible_relays(user: dict) -> dict:
|
||||
return {
|
||||
name: info
|
||||
for name, info in relays.configured().items()
|
||||
if users.allowed(user["scopes"], f"relay:{name}")
|
||||
}
|
||||
|
||||
|
||||
# ---- health ----
|
||||
@router.get("/health")
|
||||
def health():
|
||||
"""Unauthenticated liveness probe — Docker healthcheck, Traefik, Komodo."""
|
||||
return {"ok": True, "chargers_connected": len(csms.CONNECTED)}
|
||||
|
||||
|
||||
# ---- login / identity ----
|
||||
class LoginBody(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login(body: LoginBody, response: Response):
|
||||
entry = CONFIG["users"].get(body.username)
|
||||
if not CONFIG["users"]:
|
||||
raise HTTPException(409, "no users configured — the API is open; log in is pointless "
|
||||
"until `python -m backend.users add` creates one")
|
||||
if entry is None or not users.verify_password(body.password, entry.get("password", "")):
|
||||
log.warning("failed login for %r", body.username)
|
||||
raise HTTPException(401, "wrong username or password")
|
||||
token = users.mint_session(body.username)
|
||||
response.set_cookie(
|
||||
SESSION_COOKIE, token, max_age=users.SESSION_TTL,
|
||||
httponly=True, samesite="lax", # no `secure`: plain http inside NetBird
|
||||
)
|
||||
log.info("login: %r", body.username)
|
||||
return {"token": token, "user": users.public_view(body.username, entry)}
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout(response: Response):
|
||||
# sessions are stateless — logout just clears the cookie on this client
|
||||
response.delete_cookie(SESSION_COOKIE)
|
||||
return {"logged_out": True}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def me(user: dict = Depends(current_user)):
|
||||
return users.public_view(user["name"], user)
|
||||
|
||||
|
||||
class PasswordBody(BaseModel):
|
||||
current_password: str
|
||||
new_password: str
|
||||
|
||||
|
||||
@router.post("/me/password")
|
||||
async def change_own_password(body: PasswordBody, user: dict = Depends(current_user)):
|
||||
"""Self-service password change — requires the current password.
|
||||
(Admins can still reset anyone's via PUT /api/users/<name>.)"""
|
||||
entry = CONFIG["users"].get(user["name"])
|
||||
if entry is None:
|
||||
raise HTTPException(409, "no user account — the API is in open mode")
|
||||
if not users.verify_password(body.current_password, entry.get("password", "")):
|
||||
raise HTTPException(403, "current password is wrong")
|
||||
if len(body.new_password) < 4:
|
||||
raise HTTPException(400, "new password must be at least 4 characters")
|
||||
users.set_user(user["name"], password=body.new_password)
|
||||
log.info("password changed by %r", user["name"])
|
||||
return {"changed": True}
|
||||
|
||||
|
||||
# ---- status & journals ----
|
||||
@router.get("/status")
|
||||
async def api_status(user: dict = Depends(current_user)):
|
||||
is_admin = users.allowed(user["scopes"], "admin")
|
||||
return {
|
||||
"connected": {
|
||||
cp_id: getattr(cp, "boot_info", None) for cp_id, cp in csms.CONNECTED.items()
|
||||
},
|
||||
"connectors": {f"{cp_id}/{conn}": s for (cp_id, conn), s in csms.CONNECTORS.items()},
|
||||
"active_transactions": csms.ACTIVE_TX,
|
||||
"recent_auth_events": list(csms.AUTH_EVENTS) if is_admin else [],
|
||||
"relays": _visible_relays(user),
|
||||
"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,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/events")
|
||||
async def api_events(limit: int = 100, event: Optional[str] = None,
|
||||
user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
return read_events(limit=limit, event=event)
|
||||
|
||||
|
||||
# ---- charger control (scope: charger:<cp>:<gun>) ----
|
||||
@router.post("/charger/start")
|
||||
async def charger_start(connector: int = 1, cp: Optional[str] = None,
|
||||
user: dict = Depends(current_user)):
|
||||
target = _cp(cp)
|
||||
need(user, f"charger:{target.id}:{connector}")
|
||||
# remote starts run under the caller's own idTag so sessions are
|
||||
# attributable; decide() validates it directly against the user record
|
||||
id_tag = user.get("id_tag") or f"app-{user['name']}"
|
||||
status = await _ocpp(csms.remote_start(target.id, id_tag, connector))
|
||||
return {"remote_start": status, "id_tag": id_tag}
|
||||
|
||||
|
||||
@router.post("/charger/stop")
|
||||
@router.post("/charger/stop/{tx}")
|
||||
async def charger_stop(tx: Optional[int] = None, user: dict = Depends(current_user)):
|
||||
if tx is None:
|
||||
if len(csms.ACTIVE_TX) != 1:
|
||||
raise HTTPException(409, f"specify /stop/<tx>; active: {list(csms.ACTIVE_TX)}")
|
||||
tx = next(iter(csms.ACTIVE_TX))
|
||||
info = csms.ACTIVE_TX.get(tx) or store.open_session(tx)
|
||||
if info is None:
|
||||
raise HTTPException(409, f"no active transaction {tx}")
|
||||
need(user, f"charger:{info['cp']}:{info['connector']}")
|
||||
status = await _ocpp(csms.remote_stop(tx))
|
||||
return {"remote_stop": status, "transaction": tx}
|
||||
|
||||
|
||||
@router.post("/charger/unlock/{connector}")
|
||||
async def charger_unlock(connector: int, cp: Optional[str] = None,
|
||||
user: dict = Depends(current_user)):
|
||||
target = _cp(cp)
|
||||
need(user, f"charger:{target.id}:{connector}")
|
||||
resp = await _ocpp(target.call(call.UnlockConnector(connector_id=connector)))
|
||||
return {"unlock": connector, "status": resp.status}
|
||||
|
||||
|
||||
@router.post("/charger/trigger/{what}")
|
||||
async def charger_trigger(what: str, connector: Optional[int] = None,
|
||||
cp: Optional[str] = None, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
if what not in csms.TRIGGERABLE:
|
||||
raise HTTPException(400, f"unknown trigger {what!r}; options: {list(csms.TRIGGERABLE)}")
|
||||
payload = call.TriggerMessage(
|
||||
requested_message=csms.TRIGGERABLE[what], connector_id=connector
|
||||
)
|
||||
resp = await _ocpp(_cp(cp).call(payload))
|
||||
return {"trigger": what, "status": resp.status}
|
||||
|
||||
|
||||
@router.post("/charger/setconfig")
|
||||
async def charger_setconfig(key: str, value: str, cp: Optional[str] = None,
|
||||
user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
resp = await _ocpp(_cp(cp).call(call.ChangeConfiguration(key=key, value=value)))
|
||||
return {"key": key, "value": value, "status": resp.status}
|
||||
|
||||
|
||||
@router.post("/charger/probe")
|
||||
async def charger_probe(cp: Optional[str] = None, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
return await _ocpp(csms.interrogate(_cp(cp)))
|
||||
|
||||
|
||||
# ---- session history: who charged when and how many kWh ----
|
||||
def _may_see_session(user: dict, s: dict) -> bool:
|
||||
"""Transactions are private: admins see everything, everyone else sees
|
||||
ONLY their own sessions (their app starts + their linked cards). Card
|
||||
ownership is looked up live, so linking a card to a user retroactively
|
||||
shows them its history. (Gun scopes grant CONTROL, not visibility —
|
||||
owner decision 2026-07-12.)"""
|
||||
if users.allowed(user["scopes"], "admin"):
|
||||
return True
|
||||
if s["id_tag"] == user.get("id_tag"):
|
||||
return True
|
||||
entry = CONFIG["authorized"].get(s["id_tag"])
|
||||
return bool(entry and entry.get("user") == user["name"])
|
||||
|
||||
|
||||
@router.get("/sessions")
|
||||
async def sessions_list(limit: int = 50, cp: Optional[str] = None,
|
||||
connector: Optional[int] = None,
|
||||
user: dict = Depends(current_user)):
|
||||
rows = store.query_sessions(limit=limit, cp=cp, connector=connector)
|
||||
return [s for s in rows if _may_see_session(user, s)]
|
||||
|
||||
|
||||
@router.get("/sessions/{tx}/samples")
|
||||
async def session_samples(tx: int, user: dict = Depends(current_user)):
|
||||
session = store.get_session(tx)
|
||||
if session is None:
|
||||
raise HTTPException(404, f"no session {tx}")
|
||||
if not _may_see_session(user, session):
|
||||
raise HTTPException(403, f"user {user['name']!r} may not view session {tx}")
|
||||
return {"session": session, "samples": store.samples_for(tx)}
|
||||
|
||||
|
||||
# ---- allowlist management (admin) ----
|
||||
class AllowlistEntry(BaseModel):
|
||||
name: str
|
||||
kind: str = "card" # card | app | car
|
||||
user: Optional[str] = None # owning username -> sessions attribute to them
|
||||
guns: Optional[list[str]] = None # e.g. ["eu092025:2"]; fnmatch, empty = all guns
|
||||
|
||||
|
||||
@router.get("/allowlist")
|
||||
async def allowlist_get(user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
return {"authorized": CONFIG["authorized"]}
|
||||
|
||||
|
||||
@router.put("/allowlist/{id_tag}")
|
||||
async def allowlist_put(id_tag: str, entry: AllowlistEntry,
|
||||
user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
if entry.user is not None and entry.user not in CONFIG["users"]:
|
||||
raise HTTPException(400, f"cannot link card to unknown user {entry.user!r}")
|
||||
if csms.user_for_tag(id_tag) is not None:
|
||||
raise HTTPException(400, f"{id_tag!r} is a user's app token — it authorizes "
|
||||
"through the user's own permissions, not the allowlist")
|
||||
CONFIG["authorized"][id_tag] = entry.model_dump(exclude_none=True)
|
||||
save()
|
||||
log.info("allowlist: added/updated %r (%s)", id_tag, entry.name)
|
||||
return {"authorized": CONFIG["authorized"]}
|
||||
|
||||
|
||||
@router.delete("/allowlist/{id_tag}")
|
||||
async def allowlist_delete(id_tag: str, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
if CONFIG["authorized"].pop(id_tag, None) is None:
|
||||
raise HTTPException(404, f"idTag {id_tag!r} is not in the allowlist")
|
||||
save()
|
||||
log.info("allowlist: removed %r", id_tag)
|
||||
return {"authorized": CONFIG["authorized"]}
|
||||
|
||||
|
||||
# ---- pending cards: unknown taps awaiting the admin's decision ----
|
||||
class ApproveBody(BaseModel):
|
||||
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")
|
||||
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()
|
||||
log.info("pending card %r APPROVED by %r as %r (user=%s)",
|
||||
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) ----
|
||||
class UserBody(BaseModel):
|
||||
password: Optional[str] = None
|
||||
scopes: Optional[list[str]] = None
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
async def users_list(user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
return [users.public_view(name, u) for name, u in CONFIG["users"].items()]
|
||||
|
||||
|
||||
@router.put("/users/{name}")
|
||||
async def users_put(name: str, body: UserBody, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
try:
|
||||
updated = users.set_user(name, password=body.password, scopes=body.scopes)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc))
|
||||
log.info("users: %r set by %r (scopes=%s)", name, user["name"], updated["scopes"])
|
||||
return users.public_view(name, updated)
|
||||
|
||||
|
||||
@router.delete("/users/{name}")
|
||||
async def users_delete(name: str, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
if name == user["name"]:
|
||||
raise HTTPException(400, "refusing to delete the account you are logged in as")
|
||||
try:
|
||||
users.remove_user(name)
|
||||
except KeyError:
|
||||
raise HTTPException(404, f"no user {name!r}")
|
||||
log.info("users: %r removed by %r", name, user["name"])
|
||||
return {"removed": name}
|
||||
|
||||
|
||||
# ---- relay & charger registry (admin; how tinytuya wizard results get in) ----
|
||||
class RelayBody(BaseModel):
|
||||
id: str # tuya device id (from tinytuya wizard)
|
||||
key: str # tuya local key (from tinytuya wizard)
|
||||
ip: str = "auto" # pin the LAN IP once known (faster than discovery)
|
||||
version: float = 3.3
|
||||
switch: int = 1
|
||||
label: Optional[str] = None
|
||||
|
||||
|
||||
@router.put("/relays/{name}")
|
||||
async def relay_put(name: str, body: RelayBody, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
entry = body.model_dump()
|
||||
entry["label"] = entry["label"] or name
|
||||
CONFIG["relays"][name] = entry
|
||||
save()
|
||||
log.info("relays: %r set by %r", name, user["name"])
|
||||
return {"relays": relays.configured()}
|
||||
|
||||
|
||||
@router.delete("/relays/{name}")
|
||||
async def relay_delete(name: str, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
if CONFIG["relays"].pop(name, None) is None:
|
||||
raise HTTPException(404, f"no relay {name!r}")
|
||||
save()
|
||||
return {"relays": relays.configured()}
|
||||
|
||||
|
||||
class ChargerBody(BaseModel):
|
||||
label: Optional[str] = None
|
||||
guns: Optional[dict[str, str]] = None # {"1": "Gun 1 · EU (CCS)"}
|
||||
|
||||
|
||||
@router.put("/chargers/{cp_id}")
|
||||
async def charger_put(cp_id: str, body: ChargerBody, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
CONFIG["chargers"][cp_id] = body.model_dump(exclude_none=True)
|
||||
save()
|
||||
return {"chargers": CONFIG["chargers"]}
|
||||
|
||||
|
||||
# ---- relays (scope: relay:<name>) ----
|
||||
@router.get("/relays")
|
||||
async def relays_list(live: bool = False, user: dict = Depends(current_user)):
|
||||
"""Relays the caller may control; ?live=true polls each for its actual state."""
|
||||
visible = _visible_relays(user)
|
||||
if not live:
|
||||
return visible
|
||||
polled = await relays.status_all()
|
||||
return {name: polled[name] for name in visible if name in polled}
|
||||
|
||||
|
||||
@router.get("/relays/{name}")
|
||||
async def relay_status(name: str, user: dict = Depends(current_user)):
|
||||
need(user, f"relay:{name}")
|
||||
try:
|
||||
return await relays.status(name)
|
||||
except relays.RelayError as exc:
|
||||
raise HTTPException(502, str(exc))
|
||||
|
||||
|
||||
@router.post("/relays/{name}/{verb}")
|
||||
async def relay_switch(name: str, verb: str, user: dict = Depends(current_user)):
|
||||
need(user, f"relay:{name}")
|
||||
actions = {"on": True, "off": False}
|
||||
try:
|
||||
if verb == "toggle":
|
||||
return await relays.toggle(name)
|
||||
if verb in actions:
|
||||
return await relays.switch(name, actions[verb])
|
||||
except relays.RelayError as exc:
|
||||
raise HTTPException(502, str(exc))
|
||||
raise HTTPException(400, f"unknown verb {verb!r}; use on, off or toggle")
|
||||
@@ -0,0 +1,305 @@
|
||||
"""Smoke test for the backend: REST surface, auth/scopes, OCPP WS round-trips,
|
||||
session store, static frontend. Runs against an isolated temp database via
|
||||
the BACKEND_DB env override — a real backend.db is never touched.
|
||||
|
||||
Needs httpx (fastapi TestClient dep, not shipped in the runtime image):
|
||||
pip install httpx && python -m backend.smoke_test
|
||||
CI runs exactly that inside the freshly built image (.gitea/workflows/build.yml)
|
||||
and refuses to push the image if any check fails.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
# must be set BEFORE any backend import — store.py/journal.py read these at import
|
||||
TMP = Path(tempfile.mkdtemp(prefix="artiot-smoke-"))
|
||||
DB = TMP / "smoke.db"
|
||||
os.environ["BACKEND_DB"] = str(DB)
|
||||
os.environ["BACKEND_EVENTS"] = str(TMP / "events.jsonl")
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
from backend.config import CONFIG, save
|
||||
from backend import csms, store, users
|
||||
|
||||
# display labels are app state (empty in a fresh db); seed what the checks expect
|
||||
CONFIG["chargers"]["eu092025"] = {"label": "Anfu 60kW", "guns": {"1": "Gun 1 (EU)"}}
|
||||
|
||||
ok = 0
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global ok
|
||||
status = "PASS" if cond else "FAIL"
|
||||
print(f"[{status}] {label} {detail}")
|
||||
if cond:
|
||||
ok += 1
|
||||
else:
|
||||
sys.exit(f"smoke test failed at: {label}")
|
||||
|
||||
anon = TestClient(app) # separate instances = separate cookie jars
|
||||
boss = TestClient(app)
|
||||
kid = TestClient(app)
|
||||
|
||||
# ---------- phase 0: SPA serving + health ----------
|
||||
r = anon.get("/api/health")
|
||||
check("GET /api/health is open", r.status_code == 200 and r.json()["ok"] is True)
|
||||
|
||||
DIST = Path(__file__).resolve().parent.parent / "frontend" / "dist"
|
||||
r = anon.get("/")
|
||||
if DIST.exists():
|
||||
check("GET / serves the built React app",
|
||||
r.status_code == 200 and "text/html" in r.headers["content-type"])
|
||||
r = anon.get("/some/deep/route")
|
||||
check("SPA fallback serves index.html for deep links",
|
||||
r.status_code == 200 and "text/html" in r.headers["content-type"])
|
||||
else:
|
||||
check("GET / explains the frontend is not built", r.status_code == 503)
|
||||
|
||||
# ---------- phase 1: zero users -> open API (anonymous admin) ----------
|
||||
r = anon.get("/api/status")
|
||||
check("open API: GET /api/status", r.status_code == 200 and "connected" in r.json())
|
||||
check("status carries charger display labels",
|
||||
r.json()["chargers"]["eu092025"]["guns"]["1"].startswith("Gun 1"))
|
||||
r = anon.get("/api/allowlist")
|
||||
check("open API: admin endpoint reachable", r.status_code == 200)
|
||||
r = anon.post("/api/login", json={"username": "x", "password": "y"})
|
||||
check("login with zero users -> 409", r.status_code == 409)
|
||||
|
||||
# allowlist CRUD: a gun-2-restricted card for the WS test below
|
||||
# (app-remote needs NO enrollment: open mode authorizes it directly)
|
||||
r = anon.put("/api/allowlist/smoke-gun2-card",
|
||||
json={"name": "smoke", "kind": "card", "guns": ["SMOKECP:2"]})
|
||||
check("PUT allowlist card with guns=[SMOKECP:2]",
|
||||
r.status_code == 200
|
||||
and r.json()["authorized"]["smoke-gun2-card"]["guns"] == ["SMOKECP:2"])
|
||||
r = anon.put("/api/allowlist/x", json={"name": "x", "user": "nobody"})
|
||||
check("linking card to unknown user -> 400", r.status_code == 400)
|
||||
|
||||
# relay + charger registry endpoints (replaces hand-editing the old config.json)
|
||||
r = anon.put("/api/relays/tmp-relay", json={"id": "devid", "key": "localkey"})
|
||||
check("PUT /api/relays creates entry with defaulted label",
|
||||
r.status_code == 200 and r.json()["relays"]["tmp-relay"]["label"] == "tmp-relay")
|
||||
r = anon.delete("/api/relays/tmp-relay")
|
||||
check("DELETE /api/relays", r.status_code == 200 and r.json()["relays"] == {})
|
||||
r = anon.put("/api/chargers/TESTCP2", json={"label": "Second charger"})
|
||||
check("PUT /api/chargers", r.status_code == 200
|
||||
and r.json()["chargers"]["TESTCP2"]["label"] == "Second charger")
|
||||
CONFIG["chargers"].pop("TESTCP2", None)
|
||||
|
||||
# relays: none visible, unknown -> 403 (scope check precedes existence)
|
||||
r = anon.get("/api/relays")
|
||||
check("GET /api/relays (anon admin, none configured)", r.status_code == 200 and r.json() == {})
|
||||
r = anon.post("/api/charger/start")
|
||||
check("start w/o charger -> 409", r.status_code == 409, r.json())
|
||||
|
||||
# ---------- phase 2: OCPP WS — boot, authorize, per-gun card ----------
|
||||
with anon.websocket_connect("/SMOKECP", subprotocols=["ocpp1.6"]) as ws:
|
||||
def rpc(msg_id, action, payload):
|
||||
ws.send_text(json.dumps([2, str(msg_id), action, payload]))
|
||||
return json.loads(ws.receive_text())
|
||||
|
||||
resp = rpc(1, "BootNotification", {"chargePointVendor": "Smoke", "chargePointModel": "Test"})
|
||||
check("BootNotification accepted", resp[0] == 3 and resp[2]["status"] == "Accepted")
|
||||
|
||||
resp = rpc(2, "Authorize", {"idTag": "app-remote"})
|
||||
check("open mode: app-remote authorizes without enrollment",
|
||||
resp[2]["idTagInfo"]["status"] == "Accepted")
|
||||
|
||||
# unknown card: refused + queued for the admin's approve/reject decision
|
||||
resp = rpc(20, "Authorize", {"idTag": "mystery-1"})
|
||||
check("unknown card tap -> Invalid", resp[2]["idTagInfo"]["status"] == "Invalid")
|
||||
r = anon.get("/api/cards/pending")
|
||||
check("unknown card lands in pending", "mystery-1" in r.json()
|
||||
and r.json()["mystery-1"]["count"] == 1, r.json())
|
||||
r = anon.get("/api/status")
|
||||
check("status shows the pending notification count", r.json()["pending_cards"] == 1)
|
||||
r = anon.post("/api/cards/pending/mystery-1/approve",
|
||||
json={"name": "Approved card"})
|
||||
check("admin approves pending card", r.status_code == 200
|
||||
and "mystery-1" in r.json()["authorized"])
|
||||
resp = rpc(21, "Authorize", {"idTag": "mystery-1"})
|
||||
check("approved card now authorizes", resp[2]["idTagInfo"]["status"] == "Accepted")
|
||||
CONFIG["authorized"].pop("mystery-1", None)
|
||||
|
||||
# rejection: card goes to denied and never re-pends
|
||||
rpc(22, "Authorize", {"idTag": "mystery-2"})
|
||||
r = anon.post("/api/cards/pending/mystery-2/reject")
|
||||
check("admin rejects pending card", r.status_code == 200)
|
||||
resp = rpc(23, "Authorize", {"idTag": "mystery-2"})
|
||||
r = anon.get("/api/cards/pending")
|
||||
check("rejected card refused and does NOT re-pend",
|
||||
resp[2]["idTagInfo"]["status"] == "Invalid" and r.json() == {})
|
||||
r = anon.delete("/api/cards/denied/mystery-2")
|
||||
check("un-reject removes from denied", r.status_code == 200)
|
||||
|
||||
# per-gun card: tap authorizes (no connector known yet)...
|
||||
resp = rpc(3, "Authorize", {"idTag": "smoke-gun2-card"})
|
||||
check("gun2 card: Authorize (tap) -> Accepted", resp[2]["idTagInfo"]["status"] == "Accepted")
|
||||
# ...but StartTransaction on gun 1 is rejected
|
||||
resp = rpc(4, "StartTransaction", {"connectorId": 1, "idTag": "smoke-gun2-card",
|
||||
"meterStart": 0, "timestamp": "2026-07-11T12:00:00Z"})
|
||||
check("gun2 card on gun 1 -> Invalid, tx=0",
|
||||
resp[2]["idTagInfo"]["status"] == "Invalid" and resp[2]["transactionId"] == 0, resp)
|
||||
# ...and accepted on gun 2
|
||||
resp = rpc(5, "StartTransaction", {"connectorId": 2, "idTag": "smoke-gun2-card",
|
||||
"meterStart": 1000, "timestamp": "2026-07-11T12:00:00Z"})
|
||||
tx = resp[2]["transactionId"]
|
||||
check("gun2 card on gun 2 -> Accepted, tx>0",
|
||||
resp[2]["idTagInfo"]["status"] == "Accepted" and tx > 0, resp)
|
||||
|
||||
# session store: open session with resolved who, meter sample, then close
|
||||
sess = store.get_session(tx)
|
||||
check("session recorded (who resolved from allowlist)",
|
||||
sess and sess["who"] == "smoke" and sess["ended"] is None, sess)
|
||||
check("session audits the auth method (physical card)", sess["method"] == "card")
|
||||
resp = rpc(6, "MeterValues", {"connectorId": 2, "transactionId": tx, "meterValue": [
|
||||
{"timestamp": "2026-07-11T12:03:00Z", "sampledValue": [
|
||||
{"value": "13500", "measurand": "Energy.Active.Import.Register", "unit": "Wh"},
|
||||
{"value": "30.58", "measurand": "Power.Active.Import", "unit": "kW"},
|
||||
{"value": "309.6", "measurand": "Voltage", "unit": "V", "context": "Sample.Periodic"},
|
||||
{"value": "98.8", "measurand": "Current.Import", "unit": "A"},
|
||||
{"value": "61", "measurand": "SoC", "unit": "Percent"}]}]})
|
||||
check("MeterValues acked", resp[0] == 3)
|
||||
samples = store.samples_for(tx)
|
||||
check("meter sample stored (kW->W, V, A, SoC, context)",
|
||||
len(samples) == 1 and samples[0]["power_w"] == 30580.0
|
||||
and samples[0]["energy_wh"] == 13500.0 and samples[0]["soc"] == 61.0
|
||||
and samples[0]["voltage_v"] == 309.6 and samples[0]["current_a"] == 98.8
|
||||
and samples[0]["context"] == "Sample.Periodic", samples)
|
||||
r = anon.get("/api/status")
|
||||
tele = r.json()["active_transactions"][str(tx)].get("telemetry")
|
||||
check("live telemetry rides /api/status",
|
||||
tele and tele["soc"] == 61.0 and tele["voltage_v"] == 309.6
|
||||
and tele["power_w"] == 30580.0, tele)
|
||||
resp = rpc(7, "StopTransaction", {"transactionId": tx, "meterStop": 26000, "reason": "Remote",
|
||||
"timestamp": "2026-07-11T12:30:00Z"})
|
||||
check("StopTransaction accepted", resp[2]["idTagInfo"]["status"] == "Accepted")
|
||||
sess = store.get_session(tx)
|
||||
check("session closed with Wh computed",
|
||||
sess["wh"] == 25000.0 and sess["reason"] == "Remote"
|
||||
and sess["ended"] == "2026-07-11T12:30:00Z", sess)
|
||||
|
||||
# ---------- phase 3: users + scopes (charger still connected) ----------
|
||||
users.set_user("smoke-boss", password="boss-pw", scopes=["admin"])
|
||||
users.set_user("smoke-kid", password="kid-pw",
|
||||
scopes=["charger:SMOKECP:1", "relay:smoke-garden"])
|
||||
CONFIG["relays"]["smoke-garden"] = {"id": "x", "key": "y", "label": "Garden"}
|
||||
CONFIG["relays"]["smoke-attic"] = {"id": "x", "key": "y", "label": "Attic"}
|
||||
|
||||
r = anon.get("/api/status")
|
||||
check("with users: anonymous -> 401", r.status_code == 401)
|
||||
r = anon.get("/api/health")
|
||||
check("health stays open with users configured", r.status_code == 200)
|
||||
r = boss.post("/api/login", json={"username": "smoke-boss", "password": "wrong"})
|
||||
check("wrong password -> 401", r.status_code == 401)
|
||||
|
||||
r = boss.post("/api/login", json={"username": "smoke-boss", "password": "boss-pw"})
|
||||
check("boss login ok + cookie set",
|
||||
r.status_code == 200 and "session" in r.cookies and r.json()["token"])
|
||||
boss_token = r.json()["token"]
|
||||
r = boss.get("/api/me")
|
||||
check("boss /api/me via cookie",
|
||||
r.status_code == 200 and r.json() == {"name": "smoke-boss", "scopes": ["admin"],
|
||||
"id_tag": "app-smoke-boss"}, r.json())
|
||||
r = anon.get("/api/me", headers={"Authorization": f"Bearer {boss_token}"})
|
||||
check("bearer token works too", r.status_code == 200 and r.json()["name"] == "smoke-boss")
|
||||
|
||||
kid.post("/api/login", json={"username": "smoke-kid", "password": "kid-pw"})
|
||||
r = kid.post("/api/charger/start?connector=2")
|
||||
check("kid start gun 2 -> 403", r.status_code == 403, r.json())
|
||||
r = kid.get("/api/allowlist")
|
||||
check("kid admin endpoint -> 403", r.status_code == 403)
|
||||
r = kid.post("/api/relays/smoke-attic/on")
|
||||
check("kid foreign relay -> 403", r.status_code == 403)
|
||||
r = kid.get("/api/status")
|
||||
check("kid sees only his relay",
|
||||
r.status_code == 200 and list(r.json()["relays"]) == ["smoke-garden"], r.json()["relays"])
|
||||
r = boss.get("/api/relays")
|
||||
check("boss sees all relays", sorted(r.json()) == ["smoke-attic", "smoke-garden"])
|
||||
|
||||
# self-service password change
|
||||
r = kid.post("/api/me/password",
|
||||
json={"current_password": "wrong", "new_password": "kid-pw2"})
|
||||
check("password change with wrong current -> 403", r.status_code == 403)
|
||||
r = kid.post("/api/me/password",
|
||||
json={"current_password": "kid-pw", "new_password": "kid-pw2"})
|
||||
check("password change ok", r.status_code == 200 and r.json()["changed"])
|
||||
r = TestClient(app).post("/api/login", json={"username": "smoke-kid", "password": "kid-pw"})
|
||||
check("old password no longer works", r.status_code == 401)
|
||||
r = TestClient(app).post("/api/login", json={"username": "smoke-kid", "password": "kid-pw2"})
|
||||
check("new password works", r.status_code == 200)
|
||||
|
||||
# user CRUD over the API
|
||||
r = boss.put("/api/users/smoke-temp", json={"password": "t", "scopes": ["relay:*"]})
|
||||
check("boss creates user via API", r.status_code == 200 and r.json()["scopes"] == ["relay:*"])
|
||||
temp_session = users.mint_session("smoke-temp")
|
||||
r = boss.delete("/api/users/smoke-boss")
|
||||
check("boss cannot delete own account", r.status_code == 400)
|
||||
r = boss.delete("/api/users/smoke-temp")
|
||||
check("boss deletes temp user", r.status_code == 200)
|
||||
r = anon.get("/api/me", headers={"Authorization": f"Bearer {temp_session}"})
|
||||
check("deleted user's session invalid", r.status_code == 401)
|
||||
r = boss.get("/api/users")
|
||||
check("GET /api/users lists remaining",
|
||||
sorted(u["name"] for u in r.json()) == ["smoke-boss", "smoke-kid"])
|
||||
|
||||
# session visibility: the gun-2 session is invisible to the gun-1-only kid
|
||||
r = boss.get("/api/sessions")
|
||||
check("boss sees the gun-2 session (kWh present)",
|
||||
len(r.json()) == 1 and r.json()[0]["wh"] == 25000.0, r.json())
|
||||
r = kid.get("/api/sessions")
|
||||
check("kid (gun 1 only) sees no sessions", r.json() == [])
|
||||
|
||||
# gun scope grants CONTROL, not visibility: a gun-2-scoped user still
|
||||
# cannot see someone else's gun-2 session
|
||||
users.set_user("smoke-viewer", password="v-pw", scopes=["charger:SMOKECP:2"])
|
||||
viewer = TestClient(app)
|
||||
viewer.post("/api/login", json={"username": "smoke-viewer", "password": "v-pw"})
|
||||
r = viewer.get("/api/sessions")
|
||||
check("gun-scoped user sees no foreign sessions", r.json() == [])
|
||||
CONFIG["users"].pop("smoke-viewer", None)
|
||||
|
||||
# link the card to kid: he now owns its history + future sessions attribute to him
|
||||
r = boss.put("/api/allowlist/smoke-gun2-card",
|
||||
json={"name": "smoke", "kind": "card", "user": "smoke-kid",
|
||||
"guns": ["SMOKECP:2"]})
|
||||
check("boss links card to smoke-kid", r.status_code == 200)
|
||||
check("who now resolves to the linked user",
|
||||
csms.resolve_who("smoke-gun2-card") == "smoke-kid")
|
||||
r = kid.get("/api/sessions")
|
||||
check("kid sees the session after his card is linked",
|
||||
len(r.json()) == 1 and r.json()[0]["id_tag"] == "smoke-gun2-card", r.json())
|
||||
|
||||
# user app idTags: validated against the user record, never enrolled
|
||||
r = boss.put("/api/allowlist/app-smoke-kid", json={"name": "x"})
|
||||
check("enrolling a user's app token -> 400", r.status_code == 400)
|
||||
resp = rpc(30, "StartTransaction", {"connectorId": 2, "idTag": "app-smoke-kid",
|
||||
"meterStart": 0, "timestamp": "2026-07-12T09:00:00Z"})
|
||||
check("kid's app tag on gun 2 (no scope) -> Invalid",
|
||||
resp[2]["idTagInfo"]["status"] == "Invalid" and resp[2]["transactionId"] == 0, resp)
|
||||
resp = rpc(31, "StartTransaction", {"connectorId": 1, "idTag": "app-smoke-kid",
|
||||
"meterStart": 0, "timestamp": "2026-07-12T09:00:01Z"})
|
||||
app_tx = resp[2]["transactionId"]
|
||||
check("kid's app tag on gun 1 (scoped) -> Accepted",
|
||||
resp[2]["idTagInfo"]["status"] == "Accepted" and app_tx > 0, resp)
|
||||
sess = store.get_session(app_tx)
|
||||
check("app session audited: who=user, method=app",
|
||||
sess["who"] == "smoke-kid" and sess["method"] == "app", sess)
|
||||
rpc(32, "StopTransaction", {"transactionId": app_tx, "meterStop": 500,
|
||||
"timestamp": "2026-07-12T09:05:00Z"})
|
||||
|
||||
# ---------- cleanup (temp db only; a real backend.db was never touched) ----------
|
||||
for name in ("smoke-boss", "smoke-kid"):
|
||||
CONFIG["users"].pop(name, None)
|
||||
for rl in ("smoke-garden", "smoke-attic"):
|
||||
CONFIG["relays"].pop(rl, None)
|
||||
CONFIG["authorized"].pop("smoke-gun2-card", None)
|
||||
|
||||
r = anon.get("/api/status")
|
||||
check("cleanup: API open again, SMOKECP pruned",
|
||||
r.status_code == 200 and "SMOKECP" not in r.json()["connected"])
|
||||
|
||||
print(f"\nall {ok} checks passed (isolated temp db at {TMP})")
|
||||
@@ -0,0 +1,174 @@
|
||||
"""The one persistent store: SQLite (stdlib) in backend.db next to this module.
|
||||
|
||||
sessions — one row per transaction: cp, connector, idTag, resolved "who",
|
||||
start/end timestamps (charger-reported), meter readings, Wh, reason
|
||||
samples — per-minute MeterValues while charging (energy/power/SoC) for
|
||||
later charts
|
||||
settings — the app state sections (users, allowlist, relays, chargers,
|
||||
learn_mode, session_secret) as JSON blobs, one row per section.
|
||||
Always whole-section reads/writes, so blobs beat normalized
|
||||
tables here. Managed through config.py — see there.
|
||||
|
||||
The events.jsonl journal (journal.py) stays the raw ground truth; this is the
|
||||
queryable view. Transaction ids come from MAX(tx)+1 here, so they survive
|
||||
backend restarts.
|
||||
|
||||
sqlite3 connections are cheap at household scale — one per call, no pooling.
|
||||
BACKEND_DB env var overrides the path (used by tests to stay off the real db).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
DB_PATH = Path(os.environ.get("BACKEND_DB", HERE / "backend.db"))
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
tx INTEGER PRIMARY KEY,
|
||||
cp TEXT NOT NULL,
|
||||
connector INTEGER NOT NULL,
|
||||
id_tag TEXT NOT NULL,
|
||||
who TEXT,
|
||||
started TEXT NOT NULL,
|
||||
ended TEXT,
|
||||
meter_start REAL NOT NULL,
|
||||
meter_stop REAL,
|
||||
wh REAL,
|
||||
reason TEXT,
|
||||
method TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS samples (
|
||||
tx INTEGER NOT NULL,
|
||||
time TEXT NOT NULL,
|
||||
energy_wh REAL,
|
||||
power_w REAL,
|
||||
soc REAL,
|
||||
voltage_v REAL,
|
||||
current_a REAL,
|
||||
context TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_samples_tx ON samples (tx);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions (started);
|
||||
"""
|
||||
|
||||
|
||||
def _db():
|
||||
"""Context manager: commits on success AND closes (a bare `with sqlite3
|
||||
.connect(...)` only commits — the handle would leak)."""
|
||||
con = sqlite3.connect(DB_PATH)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.executescript(_SCHEMA)
|
||||
# migrations for dbs created before later columns 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")
|
||||
sample_cols = [row[1] for row in con.execute("PRAGMA table_info(samples)")]
|
||||
for col, ddl in (("voltage_v", "REAL"), ("current_a", "REAL"), ("context", "TEXT")):
|
||||
if col not in sample_cols:
|
||||
con.execute(f"ALTER TABLE samples ADD COLUMN {col} {ddl}")
|
||||
return closing(con)
|
||||
|
||||
|
||||
def load_settings() -> dict:
|
||||
with _db() as con, con:
|
||||
return {
|
||||
row["key"]: json.loads(row["value"])
|
||||
for row in con.execute("SELECT key, value FROM settings")
|
||||
}
|
||||
|
||||
|
||||
def save_settings(sections: dict) -> None:
|
||||
with _db() as con, con:
|
||||
con.executemany(
|
||||
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
|
||||
[(key, json.dumps(value, ensure_ascii=False)) for key, value in sections.items()],
|
||||
)
|
||||
|
||||
|
||||
def max_tx() -> int:
|
||||
with _db() as con, con:
|
||||
row = con.execute("SELECT MAX(tx) AS m FROM sessions").fetchone()
|
||||
return row["m"] or 0
|
||||
|
||||
|
||||
def start_session(tx: int, cp: str, connector: int, id_tag: str, who: str,
|
||||
started: str, meter_start: float, method: str = "unknown") -> None:
|
||||
with _db() as con, con:
|
||||
con.execute(
|
||||
"INSERT OR REPLACE INTO sessions"
|
||||
" (tx, cp, connector, id_tag, who, started, meter_start, method)"
|
||||
" VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(tx, cp, connector, id_tag, who, started, meter_start, method),
|
||||
)
|
||||
|
||||
|
||||
def end_session(tx: int, ended: str, meter_stop: float,
|
||||
reason: Optional[str] = None) -> None:
|
||||
with _db() as con, con:
|
||||
con.execute(
|
||||
"UPDATE sessions SET ended = ?, meter_stop = ?, reason = ?,"
|
||||
" wh = ? - meter_start WHERE tx = ?",
|
||||
(ended, meter_stop, reason, meter_stop, tx),
|
||||
)
|
||||
|
||||
|
||||
def add_sample(tx: int, time: str, energy_wh: Optional[float] = None,
|
||||
power_w: Optional[float] = None, soc: Optional[float] = None,
|
||||
voltage_v: Optional[float] = None, current_a: Optional[float] = None,
|
||||
context: Optional[str] = None) -> None:
|
||||
with _db() as con, con:
|
||||
con.execute(
|
||||
"INSERT INTO samples (tx, time, energy_wh, power_w, soc, voltage_v, current_a, context)"
|
||||
" VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(tx, time, energy_wh, power_w, soc, voltage_v, current_a, context),
|
||||
)
|
||||
|
||||
|
||||
def get_session(tx: int) -> Optional[dict]:
|
||||
with _db() as con, con:
|
||||
row = con.execute("SELECT * FROM sessions WHERE tx = ?", (tx,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def open_session(tx: int) -> Optional[dict]:
|
||||
"""An unfinished session (e.g. still running after a backend restart)."""
|
||||
with _db() as con, con:
|
||||
row = con.execute(
|
||||
"SELECT * FROM sessions WHERE tx = ? AND ended IS NULL", (tx,)
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def query_sessions(limit: int = 50, cp: Optional[str] = None,
|
||||
connector: Optional[int] = None) -> list:
|
||||
sql, args = "SELECT * FROM sessions", []
|
||||
where = []
|
||||
if cp is not None:
|
||||
where.append("cp = ?")
|
||||
args.append(cp)
|
||||
if connector is not None:
|
||||
where.append("connector = ?")
|
||||
args.append(connector)
|
||||
if where:
|
||||
sql += " WHERE " + " AND ".join(where)
|
||||
sql += " ORDER BY tx DESC LIMIT ?"
|
||||
args.append(limit)
|
||||
with _db() as con, con:
|
||||
return [dict(row) for row in con.execute(sql, args)]
|
||||
|
||||
|
||||
def samples_for(tx: int) -> list:
|
||||
with _db() as con, con:
|
||||
return [
|
||||
dict(row) for row in
|
||||
con.execute("SELECT * FROM samples WHERE tx = ? ORDER BY time", (tx,))
|
||||
]
|
||||
@@ -0,0 +1,157 @@
|
||||
"""User accounts, password hashing, sessions, and the scope matcher.
|
||||
|
||||
Everything is stdlib crypto: PBKDF2-HMAC-SHA256 for passwords, HMAC-signed
|
||||
stateless tokens for sessions (they survive backend restarts; "logout" is the
|
||||
client dropping its cookie). Users live in config.json -> "users":
|
||||
|
||||
"julian": {
|
||||
"password": "pbkdf2$600000$<salt hex>$<hash hex>",
|
||||
"scopes": ["admin"], # or charger:<cp>:<gun>, relay:<name>
|
||||
"id_tag": "app-julian" # idTag used for their remote starts
|
||||
}
|
||||
|
||||
Scopes are matched with fnmatch, so "relay:*" or "charger:eu092025:*" work.
|
||||
"admin" implies every scope and is required for management endpoints.
|
||||
|
||||
CLI (from the repo root):
|
||||
venv\\Scripts\\python -m backend.users add <name> --scopes admin
|
||||
venv\\Scripts\\python -m backend.users list
|
||||
venv\\Scripts\\python -m backend.users remove <name>
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import time
|
||||
from fnmatch import fnmatch
|
||||
|
||||
from .config import CONFIG, save
|
||||
|
||||
PBKDF2_ITERATIONS = 600_000
|
||||
SESSION_TTL = 30 * 24 * 3600 # 30 days
|
||||
|
||||
|
||||
# ---- passwords ----
|
||||
def hash_password(password: str) -> str:
|
||||
salt = secrets.token_hex(16)
|
||||
digest = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
|
||||
)
|
||||
return f"pbkdf2${PBKDF2_ITERATIONS}${salt}${digest.hex()}"
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
scheme, iterations, salt, expected = stored.split("$")
|
||||
if scheme != "pbkdf2":
|
||||
return False
|
||||
digest = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode(), bytes.fromhex(salt), int(iterations)
|
||||
)
|
||||
return hmac.compare_digest(digest.hex(), expected)
|
||||
except (ValueError, AttributeError):
|
||||
return False
|
||||
|
||||
|
||||
# ---- sessions (stateless HMAC tokens) ----
|
||||
def _secret() -> bytes:
|
||||
return CONFIG["session_secret"].encode()
|
||||
|
||||
|
||||
def _sign(payload: str) -> str:
|
||||
return hmac.new(_secret(), payload.encode(), hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def mint_session(username: str) -> str:
|
||||
payload = f"{username}|{int(time.time()) + SESSION_TTL}"
|
||||
token = f"{payload}|{_sign(payload)}"
|
||||
return base64.urlsafe_b64encode(token.encode()).decode()
|
||||
|
||||
|
||||
def verify_session(token: str) -> str | None:
|
||||
"""Return the username for a valid, unexpired token; None otherwise."""
|
||||
try:
|
||||
username, expires, signature = (
|
||||
base64.urlsafe_b64decode(token.encode()).decode().split("|")
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
if not hmac.compare_digest(_sign(f"{username}|{expires}"), signature):
|
||||
return None
|
||||
if int(expires) < time.time():
|
||||
return None
|
||||
if username not in CONFIG["users"]:
|
||||
return None # deleted users lose their sessions
|
||||
return username
|
||||
|
||||
|
||||
# ---- scopes ----
|
||||
def allowed(scopes: list, needed: str) -> bool:
|
||||
return any(
|
||||
grant in ("*", "admin") or fnmatch(needed, grant) for grant in scopes
|
||||
)
|
||||
|
||||
|
||||
# ---- user management (used by the CLI and the admin API) ----
|
||||
def set_user(name: str, password: str | None = None, scopes: list | None = None) -> dict:
|
||||
user = CONFIG["users"].get(name, {"scopes": [], "id_tag": f"app-{name}"})
|
||||
if password is not None:
|
||||
user["password"] = hash_password(password)
|
||||
if scopes is not None:
|
||||
user["scopes"] = scopes
|
||||
user.setdefault("id_tag", f"app-{name}")
|
||||
if "password" not in user:
|
||||
raise ValueError(f"new user {name!r} needs a password")
|
||||
CONFIG["users"][name] = user
|
||||
save()
|
||||
return user
|
||||
|
||||
|
||||
def remove_user(name: str) -> None:
|
||||
if CONFIG["users"].pop(name, None) is None:
|
||||
raise KeyError(name)
|
||||
save()
|
||||
|
||||
|
||||
def public_view(name: str, user: dict) -> dict:
|
||||
"""A user entry without the password hash — safe for /api/me and /api/users."""
|
||||
return {"name": name, "scopes": user["scopes"], "id_tag": user.get("id_tag")}
|
||||
|
||||
|
||||
def _cli() -> None:
|
||||
import argparse
|
||||
import getpass
|
||||
|
||||
parser = argparse.ArgumentParser(prog="backend.users", description=__doc__)
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
p_add = sub.add_parser("add", help="add a user or update an existing one")
|
||||
p_add.add_argument("name")
|
||||
p_add.add_argument("--scopes", nargs="+", default=None,
|
||||
help='e.g. admin, "charger:eu092025:1", "relay:*"')
|
||||
sub.add_parser("list", help="list users and their scopes")
|
||||
p_rm = sub.add_parser("remove", help="delete a user")
|
||||
p_rm.add_argument("name")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.cmd == "list":
|
||||
for name, user in CONFIG["users"].items():
|
||||
print(f"{name:20} scopes={user['scopes']} id_tag={user.get('id_tag')}")
|
||||
if not CONFIG["users"]:
|
||||
print("no users configured — the API is OPEN (anonymous admin)")
|
||||
elif args.cmd == "add":
|
||||
existing = args.name in CONFIG["users"]
|
||||
password = getpass.getpass(f"{'New ' if not existing else ''}password for {args.name!r}: ")
|
||||
if not existing or password:
|
||||
confirm = getpass.getpass("Repeat password: ")
|
||||
if password != confirm:
|
||||
raise SystemExit("passwords do not match")
|
||||
user = set_user(args.name, password=password or None, scopes=args.scopes)
|
||||
print(f"{'updated' if existing else 'created'} {args.name!r}: scopes={user['scopes']}")
|
||||
elif args.cmd == "remove":
|
||||
remove_user(args.name)
|
||||
print(f"removed {args.name!r}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
_cli()
|
||||
@@ -0,0 +1,62 @@
|
||||
# ----------------------------------------------------------------------------
|
||||
# Art IoT production stack — one service, deployed by Komodo, panel routed
|
||||
# through Traefik.
|
||||
#
|
||||
# Two front doors, same container port:
|
||||
# * ws://<docker-host>:9000/<ChargerID> — the charger dials this DIRECTLY
|
||||
# (published port below). The URL is hardcoded in the charger's touch-
|
||||
# screen and changing it needs a power-cycle, so the Docker host must be
|
||||
# reachable at that exact IP:port (DHCP reservation!). No TLS — the
|
||||
# JC-6620 speaks plain ws://.
|
||||
# * https://${ARTIOT_HOST} — the human-facing panel via Traefik.
|
||||
#
|
||||
# Komodo env (all optional, defaults below):
|
||||
# ARTIOT_TAG image tag — `main` for rolling, a commit SHA to pin
|
||||
# ARTIOT_HOST panel hostname routed by Traefik
|
||||
# TRAEFIK_NETWORK name of the external Traefik docker network
|
||||
# ARTIOT_ENTRYPOINT Traefik entrypoint (default websecure)
|
||||
# ARTIOT_CERTRESOLVER Traefik cert resolver (default letsencrypt)
|
||||
#
|
||||
# First deploy on a new host: copy the existing backend.db into the volume —
|
||||
# docker compose cp ./backend/backend.db artiot:/data/backend.db (then restart)
|
||||
# or bootstrap fresh: docker compose exec artiot python -m backend.users add <name> --scopes admin
|
||||
#
|
||||
# The relays are controlled over the LAN (tinytuya, TCP to the device IPs) —
|
||||
# the Docker host must sit on a subnet that reaches them.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
services:
|
||||
artiot:
|
||||
image: ${ARTIOT_REGISTRY:-git.infra.msai.al/art/charging_station}:${ARTIOT_TAG:-main}
|
||||
container_name: artiot
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
# OCPP — the charger's hardcoded dial-in. Keep 9000:9000, always.
|
||||
- "9000:9000"
|
||||
volumes:
|
||||
# backend.db + events.jsonl; survives `docker compose down`, only
|
||||
# `down -v` wipes it.
|
||||
- artiot-data:/data
|
||||
networks:
|
||||
- traefik-net
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-fsS", "http://localhost:9000/api/health"]
|
||||
interval: 15s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.artiot.rule=Host(`${ARTIOT_HOST:-artiot.infra.msai.al}`)
|
||||
- traefik.http.routers.artiot.entrypoints=${ARTIOT_ENTRYPOINT:-websecure}
|
||||
- traefik.http.routers.artiot.tls.certresolver=le
|
||||
- traefik.http.services.artiot.loadbalancer.server.port=9000
|
||||
|
||||
volumes:
|
||||
artiot-data:
|
||||
name: artiot-data
|
||||
|
||||
networks:
|
||||
traefik-net:
|
||||
external: true
|
||||
name: ${TRAEFIK_NETWORK:-traefik}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"charge_point": "TESTCP",
|
||||
"probed_at": "2026-07-09T14:50:00.315598+00:00",
|
||||
"boot_info": {
|
||||
"vendor": "FakeVendor",
|
||||
"model": "FakeModel-7kW",
|
||||
"firmware_version": "0.0.1"
|
||||
},
|
||||
"configuration": [
|
||||
{
|
||||
"key": "NumberOfConnectors",
|
||||
"readonly": true,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "SupportedFeatureProfiles",
|
||||
"readonly": true,
|
||||
"value": "Core,RemoteTrigger,LocalAuthListManagement"
|
||||
},
|
||||
{
|
||||
"key": "MeterValueSampleInterval",
|
||||
"readonly": false,
|
||||
"value": "60"
|
||||
}
|
||||
],
|
||||
"unknown_keys": [],
|
||||
"trigger_status_notification": "Accepted",
|
||||
"connectors_seen": {
|
||||
"1": "Available"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
{
|
||||
"charge_point": "eu092025",
|
||||
"probed_at": "2026-07-09T15:33:50.788871+00:00",
|
||||
"boot_info": {
|
||||
"vendor": "SimpleCharge",
|
||||
"model": "MultiSocketCharger",
|
||||
"charge_point_serial_number": "24310588",
|
||||
"firmware_version": "1.24.0620.1",
|
||||
"iccid": "",
|
||||
"imsi": ""
|
||||
},
|
||||
"configuration": [
|
||||
{
|
||||
"key": "AllowOfflineTxForUnknownId",
|
||||
"readonly": false,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "AuthorizationCacheEnabled",
|
||||
"readonly": false,
|
||||
"value": "true"
|
||||
},
|
||||
{
|
||||
"key": "AuthorizeRemoteTxRequests",
|
||||
"readonly": false,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "ClockAlignedDataInterval",
|
||||
"readonly": false,
|
||||
"value": "0"
|
||||
},
|
||||
{
|
||||
"key": "ConnectorPhaseRotationMaxLength",
|
||||
"readonly": true,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "ConnectionTimeOut",
|
||||
"readonly": false,
|
||||
"value": "60"
|
||||
},
|
||||
{
|
||||
"key": "GetConfigurationMaxKeys",
|
||||
"readonly": true,
|
||||
"value": "30"
|
||||
},
|
||||
{
|
||||
"key": "HeartbeatInterval",
|
||||
"readonly": false,
|
||||
"value": "7200"
|
||||
},
|
||||
{
|
||||
"key": "LocalAuthorizeOffline",
|
||||
"readonly": false,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "LocalPreAuthorize",
|
||||
"readonly": false,
|
||||
"value": "0"
|
||||
},
|
||||
{
|
||||
"key": "MaxEnergyOnInvalidId",
|
||||
"readonly": false,
|
||||
"value": "0"
|
||||
},
|
||||
{
|
||||
"key": "MeterValueSampleInterval",
|
||||
"readonly": false,
|
||||
"value": "60"
|
||||
},
|
||||
{
|
||||
"key": "NumberOfConnectors",
|
||||
"readonly": true,
|
||||
"value": "2"
|
||||
},
|
||||
{
|
||||
"key": "ResetRetries",
|
||||
"readonly": false,
|
||||
"value": "0"
|
||||
},
|
||||
{
|
||||
"key": "StopTransactionOnEVSideDisconnect",
|
||||
"readonly": false,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "StopTransactionOnInvalidId",
|
||||
"readonly": false,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "TransactionMessageAttempts",
|
||||
"readonly": false,
|
||||
"value": "50"
|
||||
},
|
||||
{
|
||||
"key": "TransactionMessageRetryInterval",
|
||||
"readonly": false,
|
||||
"value": "60"
|
||||
},
|
||||
{
|
||||
"key": "WebSocketPingInterval",
|
||||
"readonly": false,
|
||||
"value": "60"
|
||||
},
|
||||
{
|
||||
"key": "LocalAuthListEnabled",
|
||||
"readonly": false,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "LocalAuthListMaxLength",
|
||||
"readonly": true,
|
||||
"value": "6"
|
||||
},
|
||||
{
|
||||
"key": "SendLocalListMaxLength",
|
||||
"readonly": true,
|
||||
"value": "6"
|
||||
},
|
||||
{
|
||||
"key": "ChargeProfileMaxStackLevel",
|
||||
"readonly": true,
|
||||
"value": "3"
|
||||
},
|
||||
{
|
||||
"key": "UnlockConnectorOnEVSideDisconnect",
|
||||
"readonly": false,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "SendJCMeterValuesType",
|
||||
"readonly": true,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "ChargingScheduleAllowedChargingRateUnit",
|
||||
"readonly": true,
|
||||
"value": "Power"
|
||||
},
|
||||
{
|
||||
"key": "ChargingScheduleMaxPeriods",
|
||||
"readonly": true,
|
||||
"value": "3"
|
||||
},
|
||||
{
|
||||
"key": "MaxChargingProfilesInstalled",
|
||||
"readonly": true,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "LocalListVersion",
|
||||
"readonly": true,
|
||||
"value": "-1"
|
||||
},
|
||||
{
|
||||
"key": "MeterValuesAlignedData",
|
||||
"readonly": false,
|
||||
"value": "Energy.Active.Import.Register,Power.Active.Import,SoC,Voltage,Current.Import"
|
||||
},
|
||||
{
|
||||
"key": "MeterValuesSampledData",
|
||||
"readonly": false,
|
||||
"value": "Energy.Active.Import.Register,Power.Active.Import,SoC,Voltage,Current.Import"
|
||||
},
|
||||
{
|
||||
"key": "StopTxnAlignedData",
|
||||
"readonly": false,
|
||||
"value": "SoC"
|
||||
},
|
||||
{
|
||||
"key": "StopTxnSampledData",
|
||||
"readonly": false,
|
||||
"value": "Energy.Active.Import.Register"
|
||||
},
|
||||
{
|
||||
"key": "ConnectorPhaseRotation",
|
||||
"readonly": false,
|
||||
"value": "RST"
|
||||
},
|
||||
{
|
||||
"key": "SupportedFeatureProfiles",
|
||||
"readonly": true,
|
||||
"value": "Core,FirmwareManagement,LocalAuthListManagement,Reservation,SmartCharging,RemoteTrigger"
|
||||
},
|
||||
{
|
||||
"key": "Url",
|
||||
"readonly": false,
|
||||
"value": "http://10.0.10.203:9000"
|
||||
},
|
||||
{
|
||||
"key": "Vendor",
|
||||
"readonly": true,
|
||||
"value": "JC"
|
||||
},
|
||||
{
|
||||
"key": "Model",
|
||||
"readonly": true,
|
||||
"value": "MultiSocketCharger"
|
||||
},
|
||||
{
|
||||
"key": "TimeZone",
|
||||
"readonly": false,
|
||||
"value": "0"
|
||||
},
|
||||
{
|
||||
"key": "ProtocolName",
|
||||
"readonly": true,
|
||||
"value": "ocpp1.6"
|
||||
},
|
||||
{
|
||||
"key": "QRCodeTextOfConnector-1",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "QRCodeTextOfConnector-2",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "QRCodeTextOfConnector-3",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "AuthorizationKey",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "AuthorizationUser",
|
||||
"readonly": true,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "CpoName",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "OutputLimitRate",
|
||||
"readonly": false,
|
||||
"value": "100"
|
||||
},
|
||||
{
|
||||
"key": "PeakPrice",
|
||||
"readonly": false,
|
||||
"value": "1.0000"
|
||||
},
|
||||
{
|
||||
"key": "OffPeakPrice",
|
||||
"readonly": false,
|
||||
"value": "0.5000"
|
||||
},
|
||||
{
|
||||
"key": "IdleFeePerMinute",
|
||||
"readonly": false,
|
||||
"value": "0.0100"
|
||||
},
|
||||
{
|
||||
"key": "IdleTime",
|
||||
"readonly": false,
|
||||
"value": "5"
|
||||
},
|
||||
{
|
||||
"key": "MacEnabled",
|
||||
"readonly": false,
|
||||
"value": "true"
|
||||
},
|
||||
{
|
||||
"key": "FreeChargeMode",
|
||||
"readonly": false,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "KeepConnectOTAServer",
|
||||
"readonly": false,
|
||||
"value": "true"
|
||||
},
|
||||
{
|
||||
"key": "DataTransferVendorId",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "MeterValuesAlignedDataMaxLength",
|
||||
"readonly": true,
|
||||
"value": "5"
|
||||
},
|
||||
{
|
||||
"key": "MeterValuesSampledDataMaxLength",
|
||||
"readonly": true,
|
||||
"value": "5"
|
||||
},
|
||||
{
|
||||
"key": "StopTxnAlignedDataMaxLength",
|
||||
"readonly": true,
|
||||
"value": "5"
|
||||
},
|
||||
{
|
||||
"key": "StopTxnSampledDataMaxLength",
|
||||
"readonly": true,
|
||||
"value": "5"
|
||||
},
|
||||
{
|
||||
"key": "SupportedFeatureProfilesMaxLength",
|
||||
"readonly": true,
|
||||
"value": "6"
|
||||
},
|
||||
{
|
||||
"key": "ReserveConnectorZeroSupported",
|
||||
"readonly": true,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "ConnectorSwitch3to1PhaseSupported",
|
||||
"readonly": true,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "ChargePointID",
|
||||
"readonly": false,
|
||||
"value": "eu092025"
|
||||
}
|
||||
],
|
||||
"unknown_keys": null,
|
||||
"trigger_status_notification": "Accepted",
|
||||
"connectors_seen": {
|
||||
"0": "Available",
|
||||
"1": "Preparing",
|
||||
"2": "Available"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
{"time": "2026-07-09T14:49:55.301899+00:00", "event": "connected", "cp": "TESTCP", "client": "Address(host='127.0.0.1', port=52661)", "subprotocols": ["ocpp1.6"]}
|
||||
{"time": "2026-07-09T14:49:55.311317+00:00", "event": "BootNotification", "cp": "TESTCP", "vendor": "FakeVendor", "model": "FakeModel-7kW", "firmware_version": "0.0.1"}
|
||||
{"time": "2026-07-09T14:49:55.318486+00:00", "event": "Authorize", "cp": "TESTCP", "id_tag": "CARD-TEST-123", "result": "Accepted"}
|
||||
{"time": "2026-07-09T14:50:00.334616+00:00", "event": "StatusNotification", "cp": "TESTCP", "connector": 1, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T14:50:03.389613+00:00", "event": "connected", "cp": "eu092025", "client": "Address(host='10.0.10.152', port=44810)", "subprotocols": ["ocpp1.6"]}
|
||||
{"time": "2026-07-09T14:50:08.719261+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 0, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T14:50:08.926940+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T14:50:09.132883+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T14:50:15.331029+00:00", "event": "disconnected", "cp": "TESTCP"}
|
||||
{"time": "2026-07-09T14:54:16.567013+00:00", "event": "connected", "cp": "eu092025", "client": "Address(host='10.0.10.152', port=43000)", "subprotocols": ["ocpp1.6"]}
|
||||
{"time": "2026-07-09T14:54:21.741178+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 0, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T14:54:21.903108+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T14:54:22.109657+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:02:59.819374+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Preparing", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:07:19.906156+00:00", "event": "Authorize", "cp": "eu092025", "id_tag": "1000000000000393", "result": "Accepted"}
|
||||
{"time": "2026-07-09T15:07:20.139915+00:00", "event": "StartTransaction", "cp": "eu092025", "connector": 2, "id_tag": "1000000000000393", "meter_start": 3513857, "result": "Accepted", "tx": 1}
|
||||
{"time": "2026-07-09T15:07:20.323299+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Charging", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:07:20.906172+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:07:19.445Z", "sampled_value": [{"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3513857", "context": "Transaction.Begin", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
|
||||
{"time": "2026-07-09T15:07:43.370964+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Preparing", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:08:21.093068+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:08:20.617277826Z", "sampled_value": [{"value": "98.8", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3514087", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "30580", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "61", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "309.6", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
|
||||
{"time": "2026-07-09T15:08:58.365193+00:00", "event": "StartTransaction", "cp": "eu092025", "connector": 1, "id_tag": "app-remote", "meter_start": 405382, "result": "Accepted", "tx": 2}
|
||||
{"time": "2026-07-09T15:08:58.668936+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Charging", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:08:59.044085+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 1, "values": [{"timestamp": "2026-07-09T15:08:57.720Z", "sampled_value": [{"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "405382", "context": "Transaction.Begin", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 2}
|
||||
{"time": "2026-07-09T15:09:21.178130+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:09:20.728656493Z", "sampled_value": [{"value": "98.6", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3514622", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "30660", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "62", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "311.0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
|
||||
{"time": "2026-07-09T15:09:59.338172+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 1, "values": [{"timestamp": "2026-07-09T15:09:58.900267471Z", "sampled_value": [{"value": "0.0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "405382", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "64", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 2}
|
||||
{"time": "2026-07-09T15:10:09.353518+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Finishing", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:10:10.392443+00:00", "event": "StopTransaction", "cp": "eu092025", "tx": 2, "meter_stop": 405731, "delivered_wh": 349, "id_tag": "app-remote", "reason": "Remote", "transaction_data": [{"timestamp": "2026-07-09T15:10:08.231Z", "sampled_value": [{"value": "405731", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}]}]}
|
||||
{"time": "2026-07-09T15:10:10.655340+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 1, "values": [{"timestamp": "2026-07-09T15:10:08.231Z", "sampled_value": [{"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "405731", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.End", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "64", "context": "Transaction.End", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 2}
|
||||
{"time": "2026-07-09T15:10:21.181272+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:10:20.751714927Z", "sampled_value": [{"value": "98.4", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3515115", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "30680", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "63", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "311.8", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
|
||||
{"time": "2026-07-09T15:11:21.161004+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:11:20.752496181Z", "sampled_value": [{"value": "98.3", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3515617", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "30640", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "65", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "311.8", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
|
||||
{"time": "2026-07-09T15:11:26.454939+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Finishing", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:11:27.967000+00:00", "event": "StopTransaction", "cp": "eu092025", "tx": 1, "meter_stop": 3515664, "delivered_wh": 1807, "id_tag": "1000000000000393", "reason": "Remote", "transaction_data": [{"timestamp": "2026-07-09T15:11:26.858Z", "sampled_value": [{"value": "3515664", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}]}]}
|
||||
{"time": "2026-07-09T15:11:28.173805+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:11:26.858Z", "sampled_value": [{"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3515664", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.End", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "65", "context": "Transaction.End", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
|
||||
{"time": "2026-07-09T15:12:06.504623+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:12:11.528746+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Preparing", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:12:31.966934+00:00", "event": "Authorize", "cp": "eu092025", "id_tag": "1000000000000393", "result": "Accepted"}
|
||||
{"time": "2026-07-09T15:12:32.272632+00:00", "event": "StartTransaction", "cp": "eu092025", "connector": 2, "id_tag": "1000000000000393", "meter_start": 3515664, "result": "Accepted", "tx": 3}
|
||||
{"time": "2026-07-09T15:12:32.450600+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Charging", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:12:33.053501+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:12:31.679Z", "sampled_value": [{"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3515664", "context": "Transaction.Begin", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 3}
|
||||
{"time": "2026-07-09T15:13:33.234090+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:13:32.875985191Z", "sampled_value": [{"value": "129.3", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3516035", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "40690", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "65", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "314.7", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 3}
|
||||
{"time": "2026-07-09T15:13:56.469910+00:00", "event": "Authorize", "cp": "eu092025", "id_tag": "1000000000000395", "result": "Accepted"}
|
||||
{"time": "2026-07-09T15:14:33.303145+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:14:32.970773241Z", "sampled_value": [{"value": "121.2", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3516671", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "38050", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "67", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "314.0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 3}
|
||||
{"time": "2026-07-09T15:14:38.019887+00:00", "event": "Authorize", "cp": "eu092025", "id_tag": "1000000000000395", "result": "Accepted"}
|
||||
{"time": "2026-07-09T15:15:33.369007+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:15:33.061647792Z", "sampled_value": [{"value": "121.2", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3517340", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "38050", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "68", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "314.0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 3}
|
||||
{"time": "2026-07-09T15:16:31.502080+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Finishing", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:16:32.612265+00:00", "event": "StopTransaction", "cp": "eu092025", "tx": 3, "meter_stop": 3517928, "delivered_wh": 2264, "id_tag": "1000000000000393", "reason": "Remote", "transaction_data": [{"timestamp": "2026-07-09T15:16:31.628Z", "sampled_value": [{"value": "3517928", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}]}]}
|
||||
{"time": "2026-07-09T15:16:32.739682+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:16:31.628Z", "sampled_value": [{"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3517928", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.End", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "69", "context": "Transaction.End", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 3}
|
||||
{"time": "2026-07-09T15:16:37.120878+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:22:11.084171+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:22:14.593031+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Preparing", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:32:56.678733+00:00", "event": "disconnected", "cp": "eu092025"}
|
||||
{"time": "2026-07-09T15:33:45.785808+00:00", "event": "connected", "cp": "eu092025", "client": "Address(host='10.0.10.152', port=33650)", "subprotocols": ["ocpp1.6"]}
|
||||
{"time": "2026-07-09T15:33:46.288738+00:00", "event": "BootNotification", "cp": "eu092025", "vendor": "SimpleCharge", "model": "MultiSocketCharger", "charge_point_serial_number": "24310588", "firmware_version": "1.24.0620.1", "iccid": "", "imsi": ""}
|
||||
{"time": "2026-07-09T15:33:47.696131+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 0, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:33:49.711246+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:33:49.921913+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:33:51.124034+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Preparing", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:33:51.234093+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 0, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T15:33:51.443211+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T16:56:22.781138+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Available", "error": "NoError"}
|
||||
{"time": "2026-07-09T17:45:22.815009+00:00", "event": "disconnected", "cp": "eu092025"}
|
||||
@@ -1,4 +1,6 @@
|
||||
attrs==26.1.0
|
||||
fastapi==0.139.0
|
||||
uvicorn==0.51.0
|
||||
jsonschema==4.26.0
|
||||
jsonschema-specifications==2025.9.1
|
||||
ocpp==2.1.0
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"CARD-TEST-123": {
|
||||
"count": 2,
|
||||
"first_seen": "2026-07-09T13:48:25.276914+00:00",
|
||||
"contexts": [
|
||||
"Authorize (card/app/autocharge)"
|
||||
],
|
||||
"last_seen": "2026-07-09T14:49:55.317640+00:00"
|
||||
},
|
||||
"1000000000000393": {
|
||||
"count": 4,
|
||||
"first_seen": "2026-07-09T15:07:19.905448+00:00",
|
||||
"contexts": [
|
||||
"Authorize (card/app/autocharge)",
|
||||
"StartTransaction (connector 2)"
|
||||
],
|
||||
"last_seen": "2026-07-09T15:12:32.270138+00:00"
|
||||
},
|
||||
"app-remote": {
|
||||
"count": 1,
|
||||
"first_seen": "2026-07-09T15:08:58.363084+00:00",
|
||||
"contexts": [
|
||||
"StartTransaction (connector 1)"
|
||||
],
|
||||
"last_seen": "2026-07-09T15:08:58.363112+00:00"
|
||||
},
|
||||
"1000000000000395": {
|
||||
"count": 2,
|
||||
"first_seen": "2026-07-09T15:13:56.468848+00:00",
|
||||
"contexts": [
|
||||
"Authorize (card/app/autocharge)"
|
||||
],
|
||||
"last_seen": "2026-07-09T15:14:38.018675+00:00"
|
||||
}
|
||||
}
|
||||
+241
-19
@@ -19,6 +19,18 @@ Workflow:
|
||||
3. Move the ones you want into "authorized" in station_config.json, name them.
|
||||
4. Set "learn_mode": false and restart -> only your ids are accepted.
|
||||
|
||||
Discovery API (same port 9000 the charger dials — http://<host>:9000, docs at /docs):
|
||||
GET /status connected chargers, guns, transactions, auth events
|
||||
GET /events?limit=100&event=X tail the permanent event journal (events.jsonl)
|
||||
GET /tags seen + authorized idTags
|
||||
POST /probe GetConfiguration + trigger StatusNotification,
|
||||
saved to discovery_<id>.json (also auto-runs on connect)
|
||||
POST /start?id_tag=X&connector=1 RemoteStartTransaction
|
||||
POST /stop/{tx} or POST /stop RemoteStopTransaction (no tx = the only active one)
|
||||
POST /trigger/{status|meter|heartbeat|boot}?connector=N
|
||||
POST /unlock/{connector} UnlockConnector
|
||||
POST /setconfig?key=K&value=V ChangeConfiguration (e.g. MeterValueSampleInterval)
|
||||
|
||||
Run: venv/Scripts/python station.py
|
||||
"""
|
||||
|
||||
@@ -28,8 +40,10 @@ import logging
|
||||
from collections import deque
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import websockets
|
||||
import uvicorn
|
||||
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
|
||||
|
||||
from ocpp.routing import on
|
||||
from ocpp.v16 import ChargePoint as OcppChargePoint
|
||||
@@ -38,12 +52,14 @@ from ocpp.v16.enums import (
|
||||
Action,
|
||||
AuthorizationStatus,
|
||||
DataTransferStatus,
|
||||
MessageTrigger,
|
||||
RegistrationStatus,
|
||||
)
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
CONFIG_PATH = HERE / "station_config.json"
|
||||
SEEN_PATH = HERE / "seen_tags.json"
|
||||
EVENTS_PATH = HERE / "events.jsonl"
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -79,6 +95,17 @@ def load_config() -> dict:
|
||||
CONFIG = load_config()
|
||||
|
||||
|
||||
def record_event(event: str, cp_id: str, **data) -> None:
|
||||
"""Append one JSON line to events.jsonl — the permanent journal of everything
|
||||
the charger tells us (and what we told it). Survives restarts; grep/ingest later."""
|
||||
entry = {"time": now(), "event": event, "cp": cp_id, **data}
|
||||
try:
|
||||
with EVENTS_PATH.open("a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n")
|
||||
except Exception:
|
||||
log.exception("failed to journal event %r", event)
|
||||
|
||||
|
||||
def record_seen(id_tag: str, context: str) -> None:
|
||||
"""Append/refresh an entry in seen_tags.json so you can harvest ids later."""
|
||||
try:
|
||||
@@ -123,6 +150,8 @@ def decide(id_tag: str, context: str) -> AuthorizationStatus:
|
||||
class ChargePoint(OcppChargePoint):
|
||||
@on(Action.boot_notification)
|
||||
async def on_boot_notification(self, charge_point_vendor, charge_point_model, **kwargs):
|
||||
self.boot_info = {"vendor": charge_point_vendor, "model": charge_point_model, **kwargs}
|
||||
record_event("BootNotification", self.id, **self.boot_info)
|
||||
log.info("BootNotification: vendor=%r model=%r extra=%r",
|
||||
charge_point_vendor, charge_point_model, kwargs)
|
||||
return call_result.BootNotification(
|
||||
@@ -136,6 +165,8 @@ class ChargePoint(OcppChargePoint):
|
||||
@on(Action.status_notification)
|
||||
async def on_status_notification(self, connector_id, error_code, status, **kwargs):
|
||||
CONNECTORS[(self.id, connector_id)] = status
|
||||
record_event("StatusNotification", self.id,
|
||||
connector=connector_id, status=status, error=error_code)
|
||||
log.info("StatusNotification: connector=%s status=%s error=%s",
|
||||
connector_id, status, error_code)
|
||||
return call_result.StatusNotification()
|
||||
@@ -144,6 +175,7 @@ class ChargePoint(OcppChargePoint):
|
||||
async def on_authorize(self, id_tag, **kwargs):
|
||||
# RFID card tap, or app pre-auth. Plug-in autocharge sometimes lands here too.
|
||||
status = decide(id_tag, "Authorize (card/app/autocharge)")
|
||||
record_event("Authorize", self.id, id_tag=id_tag, result=status.value)
|
||||
return call_result.Authorize(id_tag_info={"status": status})
|
||||
|
||||
@on(Action.start_transaction)
|
||||
@@ -160,6 +192,8 @@ class ChargePoint(OcppChargePoint):
|
||||
tx, connector_id, meter_start)
|
||||
else:
|
||||
tx = 0 # 0 tells the charger the transaction is not authorized
|
||||
record_event("StartTransaction", self.id, connector=connector_id,
|
||||
id_tag=id_tag, meter_start=meter_start, result=status.value, tx=tx)
|
||||
return call_result.StartTransaction(
|
||||
transaction_id=tx, id_tag_info={"status": status}
|
||||
)
|
||||
@@ -168,6 +202,8 @@ class ChargePoint(OcppChargePoint):
|
||||
async def on_stop_transaction(self, meter_stop, timestamp, transaction_id, **kwargs):
|
||||
info = ACTIVE_TX.pop(transaction_id, None)
|
||||
used = (meter_stop - info["meter_start"]) if info else "?"
|
||||
record_event("StopTransaction", self.id, tx=transaction_id,
|
||||
meter_stop=meter_stop, delivered_wh=used, **kwargs)
|
||||
log.info("Transaction %s STOPPED (meter_stop=%s, delivered=%s Wh)",
|
||||
transaction_id, meter_stop, used)
|
||||
return call_result.StopTransaction(
|
||||
@@ -176,6 +212,8 @@ class ChargePoint(OcppChargePoint):
|
||||
|
||||
@on(Action.meter_values)
|
||||
async def on_meter_values(self, connector_id, meter_value, **kwargs):
|
||||
record_event("MeterValues", self.id, connector=connector_id,
|
||||
values=meter_value, **kwargs)
|
||||
log.info("MeterValues: connector=%s values=%r", connector_id, meter_value)
|
||||
return call_result.MeterValues()
|
||||
|
||||
@@ -217,34 +255,218 @@ async def remote_stop(transaction_id: int) -> str:
|
||||
return resp.status
|
||||
|
||||
|
||||
async def on_connect(connection):
|
||||
path = connection.request.path
|
||||
cp_id = path.strip("/").split("/")[-1] or "unknown"
|
||||
log.info("Charger connected: id=%r from %s subprotocol=%r",
|
||||
cp_id, connection.remote_address, connection.subprotocol)
|
||||
cp = ChargePoint(cp_id, connection)
|
||||
# ---- discovery: interrogate the charger about what it is and what it supports ----
|
||||
async def interrogate(cp: ChargePoint) -> dict:
|
||||
"""GetConfiguration + trigger a StatusNotification per gun; save to discovery_<id>.json.
|
||||
|
||||
GetConfiguration with no keys asks for *everything* the charger exposes:
|
||||
NumberOfConnectors, SupportedFeatureProfiles, meter settings, local-auth
|
||||
support, ... A rejected/timed-out probe is itself a finding — record it.
|
||||
"""
|
||||
report = {
|
||||
"charge_point": cp.id,
|
||||
"probed_at": now(),
|
||||
"boot_info": getattr(cp, "boot_info", None),
|
||||
}
|
||||
try:
|
||||
resp = await cp.call(call.GetConfiguration())
|
||||
report["configuration"] = resp.configuration_key
|
||||
report["unknown_keys"] = resp.unknown_key
|
||||
except Exception as exc:
|
||||
report["configuration_error"] = repr(exc)
|
||||
try:
|
||||
resp = await cp.call(
|
||||
call.TriggerMessage(requested_message=MessageTrigger.status_notification)
|
||||
)
|
||||
report["trigger_status_notification"] = resp.status
|
||||
await asyncio.sleep(2) # give the triggered StatusNotifications time to arrive
|
||||
except Exception as exc:
|
||||
report["trigger_error"] = repr(exc)
|
||||
report["connectors_seen"] = {
|
||||
str(conn): status for (cp_id, conn), status in CONNECTORS.items() if cp_id == cp.id
|
||||
}
|
||||
path = HERE / f"discovery_{cp.id}.json"
|
||||
path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
log.info(
|
||||
"Discovery report -> %s (%d config keys, guns seen: %s)",
|
||||
path.name, len(report.get("configuration") or []),
|
||||
list(report["connectors_seen"]) or "none yet",
|
||||
)
|
||||
return report
|
||||
|
||||
|
||||
async def _auto_interrogate(cp: ChargePoint):
|
||||
await asyncio.sleep(5) # let BootNotification land first
|
||||
try:
|
||||
await interrogate(cp)
|
||||
except Exception:
|
||||
log.exception("auto-interrogation of %r failed", cp.id)
|
||||
|
||||
|
||||
class _WSAdapter:
|
||||
"""Bridge a Starlette WebSocket to the recv()/send() interface the ocpp lib expects."""
|
||||
|
||||
def __init__(self, ws: WebSocket):
|
||||
self._ws = ws
|
||||
|
||||
async def recv(self) -> str:
|
||||
return await self._ws.receive_text()
|
||||
|
||||
async def send(self, message: str) -> None:
|
||||
await self._ws.send_text(message)
|
||||
|
||||
async def close(self, code: int = 1000, reason: str = "") -> None:
|
||||
await self._ws.close(code=code)
|
||||
|
||||
|
||||
# ---- discovery HTTP API (curl / browser / phone over NetBird) ----
|
||||
api = FastAPI(
|
||||
title="Charger Discovery API",
|
||||
description="Poke the charger over its live OCPP socket. Interactive docs: /docs",
|
||||
)
|
||||
|
||||
TRIGGERABLE = {
|
||||
"status": MessageTrigger.status_notification,
|
||||
"meter": MessageTrigger.meter_values,
|
||||
"heartbeat": MessageTrigger.heartbeat,
|
||||
"boot": MessageTrigger.boot_notification,
|
||||
}
|
||||
|
||||
|
||||
@api.websocket("/{cp_path:path}")
|
||||
async def ocpp_websocket(ws: WebSocket, cp_path: str):
|
||||
"""The OCPP endpoint the JC-6620 dials: ws://<host>:9000/<ChargerID>."""
|
||||
cp_id = cp_path.strip("/").split("/")[-1] or "unknown"
|
||||
offered = [
|
||||
p.strip()
|
||||
for p in ws.headers.get("sec-websocket-protocol", "").split(",")
|
||||
if p.strip()
|
||||
]
|
||||
if not offered:
|
||||
log.warning(
|
||||
"Charger %r connected WITHOUT an ocpp subprotocol header. "
|
||||
"Handling it anyway so we can see its traffic.", cp_id,
|
||||
)
|
||||
await ws.accept(subprotocol="ocpp1.6" if "ocpp1.6" in offered else None)
|
||||
log.info("Charger connected: id=%r from %s subprotocols=%r", cp_id, ws.client, offered)
|
||||
record_event("connected", cp_id, client=str(ws.client), subprotocols=offered)
|
||||
cp = ChargePoint(cp_id, _WSAdapter(ws))
|
||||
CONNECTED[cp_id] = cp
|
||||
asyncio.create_task(_auto_interrogate(cp))
|
||||
try:
|
||||
await cp.start()
|
||||
except websockets.exceptions.ConnectionClosed:
|
||||
except WebSocketDisconnect:
|
||||
log.info("Charger %r disconnected", cp_id)
|
||||
finally:
|
||||
record_event("disconnected", cp_id)
|
||||
CONNECTED.pop(cp_id, None)
|
||||
for key in [k for k in CONNECTORS if k[0] == cp_id]:
|
||||
CONNECTORS.pop(key, None)
|
||||
|
||||
|
||||
def _pick_cp(cp_id: Optional[str]) -> ChargePoint:
|
||||
if cp_id is not None:
|
||||
cp = CONNECTED.get(cp_id)
|
||||
if cp is None:
|
||||
raise HTTPException(404, f"charge point {cp_id!r} is not connected")
|
||||
return cp
|
||||
if len(CONNECTED) == 1:
|
||||
return next(iter(CONNECTED.values()))
|
||||
raise HTTPException(409, f"specify ?cp=<id>; currently connected: {list(CONNECTED)}")
|
||||
|
||||
|
||||
async def _ocpp(coro):
|
||||
"""Run an OCPP call for an HTTP handler, mapping failures to HTTP errors."""
|
||||
try:
|
||||
return await coro
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise HTTPException(502, f"OCPP call failed: {exc!r}")
|
||||
|
||||
|
||||
@api.get("/status")
|
||||
async def api_status():
|
||||
return {
|
||||
"mode": "learn" if CONFIG.get("learn_mode") else "enforce",
|
||||
"connected": {cp_id: getattr(cp, "boot_info", None) for cp_id, cp in CONNECTED.items()},
|
||||
"connectors": {f"{cp_id}/{conn}": s for (cp_id, conn), s in CONNECTORS.items()},
|
||||
"active_transactions": ACTIVE_TX,
|
||||
"recent_auth_events": list(AUTH_EVENTS),
|
||||
}
|
||||
|
||||
|
||||
@api.get("/events")
|
||||
async def api_events(limit: int = 100, event: Optional[str] = None):
|
||||
"""Tail the event journal; filter with ?event=MeterValues etc."""
|
||||
if not EVENTS_PATH.exists():
|
||||
return []
|
||||
lines = EVENTS_PATH.read_text(encoding="utf-8").splitlines()
|
||||
entries = [json.loads(line) for line in lines if line.strip()]
|
||||
if event is not None:
|
||||
entries = [e for e in entries if e.get("event") == event]
|
||||
return entries[-limit:]
|
||||
|
||||
|
||||
@api.get("/tags")
|
||||
async def api_tags():
|
||||
seen = json.loads(SEEN_PATH.read_text(encoding="utf-8")) if SEEN_PATH.exists() else {}
|
||||
return {"authorized": CONFIG["authorized"], "seen": seen}
|
||||
|
||||
|
||||
@api.post("/probe")
|
||||
async def api_probe(cp: Optional[str] = None):
|
||||
return await _ocpp(interrogate(_pick_cp(cp)))
|
||||
|
||||
|
||||
@api.post("/start")
|
||||
async def api_start(id_tag: str = "app-remote", connector: int = 1, cp: Optional[str] = None):
|
||||
status = await _ocpp(remote_start(_pick_cp(cp).id, id_tag, connector))
|
||||
return {"remote_start": status}
|
||||
|
||||
|
||||
@api.post("/stop")
|
||||
@api.post("/stop/{tx}")
|
||||
async def api_stop(tx: Optional[int] = None):
|
||||
if tx is None:
|
||||
if len(ACTIVE_TX) != 1:
|
||||
raise HTTPException(409, f"specify /stop/<tx>; active: {list(ACTIVE_TX)}")
|
||||
tx = next(iter(ACTIVE_TX))
|
||||
status = await _ocpp(remote_stop(tx))
|
||||
return {"remote_stop": status, "transaction": tx}
|
||||
|
||||
|
||||
@api.post("/trigger/{what}")
|
||||
async def api_trigger(what: str, connector: Optional[int] = None, cp: Optional[str] = None):
|
||||
if what not in TRIGGERABLE:
|
||||
raise HTTPException(400, f"unknown trigger {what!r}; options: {list(TRIGGERABLE)}")
|
||||
payload = call.TriggerMessage(requested_message=TRIGGERABLE[what], connector_id=connector)
|
||||
resp = await _ocpp(_pick_cp(cp).call(payload))
|
||||
return {"trigger": what, "status": resp.status}
|
||||
|
||||
|
||||
@api.post("/unlock/{connector}")
|
||||
async def api_unlock(connector: int, cp: Optional[str] = None):
|
||||
resp = await _ocpp(_pick_cp(cp).call(call.UnlockConnector(connector_id=connector)))
|
||||
return {"unlock": connector, "status": resp.status}
|
||||
|
||||
|
||||
@api.post("/setconfig")
|
||||
async def api_setconfig(key: str, value: str, cp: Optional[str] = None):
|
||||
resp = await _ocpp(_pick_cp(cp).call(call.ChangeConfiguration(key=key, value=value)))
|
||||
return {"key": key, "value": value, "status": resp.status}
|
||||
|
||||
|
||||
async def main():
|
||||
def select_subprotocol(connection, subprotocols):
|
||||
return "ocpp1.6"
|
||||
|
||||
server = await websockets.serve(
|
||||
on_connect, "0.0.0.0", 9000,
|
||||
subprotocols=["ocpp1.6"],
|
||||
select_subprotocol=select_subprotocol,
|
||||
)
|
||||
mode = "LEARN (accepting & recording new ids)" if CONFIG["learn_mode"] else "ENFORCING allowlist"
|
||||
log.info("Private CSMS on ws://0.0.0.0:9000/<id> | mode: %s | %d authorized id(s)",
|
||||
mode, len(CONFIG["authorized"]))
|
||||
await server.wait_closed()
|
||||
log.info(
|
||||
"Private CSMS on ws://0.0.0.0:9000/<id> | discovery API http://0.0.0.0:9000/docs"
|
||||
" | mode: %s | %d authorized id(s)",
|
||||
mode, len(CONFIG["authorized"]),
|
||||
)
|
||||
await uvicorn.Server(
|
||||
uvicorn.Config(api, host="0.0.0.0", port=9000, log_config=None)
|
||||
).serve()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,4 +1,17 @@
|
||||
{
|
||||
"learn_mode": true,
|
||||
"authorized": {}
|
||||
"authorized": {
|
||||
"1000000000000393": {
|
||||
"name": "RFID card A (tapped first, 2026-07-09)",
|
||||
"kind": "card"
|
||||
},
|
||||
"app-remote": {
|
||||
"name": "Web/app remote start token",
|
||||
"kind": "app"
|
||||
},
|
||||
"1000000000000395": {
|
||||
"name": "RFID card B (tapped second, 2026-07-09)",
|
||||
"kind": "card"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -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="#f9faf9" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
<title>Art IoT</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+1958
File diff suppressed because it is too large
Load Diff
@@ -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/chakra-petch": "^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"
|
||||
}
|
||||
}
|
||||
@@ -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 |
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "Art IoT",
|
||||
"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" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
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";
|
||||
import Account from "./pages/Account";
|
||||
|
||||
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 />} />
|
||||
<Route path="/account" element={<Account />} />
|
||||
{admin && <Route path="/cards" element={<Cards />} />}
|
||||
{admin && <Route path="/users" element={<Users />} />}
|
||||
<Route path="*" element={<Navigate to="/" replace state={{ from: location }} />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
@@ -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 === "*");
|
||||
@@ -0,0 +1,41 @@
|
||||
/** State-of-charge gauge: a battery whose fill sweeps the owner-specified
|
||||
* gradient — red (empty) → blue (half) → green (full). */
|
||||
|
||||
type RGB = [number, number, number];
|
||||
const RED: RGB = [191, 53, 39];
|
||||
const BLUE: RGB = [33, 96, 196];
|
||||
const GREEN: RGB = [23, 138, 92];
|
||||
|
||||
function mix(a: RGB, b: RGB, t: number): string {
|
||||
const c = a.map((v, i) => Math.round(v + (b[i] - v) * t));
|
||||
return `rgb(${c[0]}, ${c[1]}, ${c[2]})`;
|
||||
}
|
||||
|
||||
export function socColor(soc: number): string {
|
||||
const s = Math.max(0, Math.min(100, soc));
|
||||
return s <= 50 ? mix(RED, BLUE, s / 50) : mix(BLUE, GREEN, (s - 50) / 50);
|
||||
}
|
||||
|
||||
export default function Battery({ soc }: { soc: number | null | undefined }) {
|
||||
const known = soc != null;
|
||||
const pct = known ? Math.max(0, Math.min(100, soc)) : 0;
|
||||
const color = known ? socColor(pct) : "transparent";
|
||||
return (
|
||||
<div
|
||||
className="battery"
|
||||
role="meter"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={known ? Math.round(pct) : undefined}
|
||||
aria-label="Vehicle state of charge"
|
||||
>
|
||||
<span className="battery__shell">
|
||||
<span className="battery__fill" style={{ width: `${pct}%`, background: color }} />
|
||||
</span>
|
||||
<span className="battery__cap" />
|
||||
<span className="battery__pct" style={known ? { color: socColor(pct) } : undefined}>
|
||||
{known ? `${Math.round(pct)}%` : "—"}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/** The signature element: a physical indicator lamp, like the ones on the
|
||||
* charger cabinet itself. Owner-specified state language:
|
||||
* gray = idle · pulsing blue = cable plugged · green = charging · red = fault */
|
||||
export type LampTone = "off" | "green" | "blue" | "bluepulse" | "amber" | "red";
|
||||
|
||||
const TONE_CLASS: Record<LampTone, string> = {
|
||||
off: "lamp",
|
||||
green: "lamp lamp--green",
|
||||
blue: "lamp lamp--blue",
|
||||
bluepulse: "lamp lamp--blue lamp--pulse-blue",
|
||||
amber: "lamp lamp--amber",
|
||||
red: "lamp lamp--red",
|
||||
};
|
||||
|
||||
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 || ocppStatus === "Charging") return "green";
|
||||
switch (ocppStatus) {
|
||||
case "Preparing":
|
||||
return "bluepulse"; // cable in the socket, waiting to start
|
||||
case "SuspendedEV":
|
||||
case "SuspendedEVSE":
|
||||
case "Finishing":
|
||||
return "blue"; // still plugged, not delivering
|
||||
case "Reserved":
|
||||
return "amber";
|
||||
case "Faulted":
|
||||
case "Unavailable":
|
||||
return "red";
|
||||
default:
|
||||
return "off"; // Available (idle), Offline, no status yet
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
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">Art IoT</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">
|
||||
<NavLink to="/account" className="topbar__who" title="Account settings">
|
||||
{me?.name}
|
||||
</NavLink>
|
||||
<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`}
|
||||
— 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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/chakra-petch/400.css";
|
||||
import "@fontsource/chakra-petch/500.css";
|
||||
import "@fontsource/chakra-petch/600.css";
|
||||
import "@fontsource/chakra-petch/700.css";
|
||||
import "@fontsource/chakra-petch/700-italic.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>,
|
||||
);
|
||||
@@ -0,0 +1,167 @@
|
||||
import { FormEvent, useState } from "react";
|
||||
import { api, isAdmin, scopeAllowed } from "../api";
|
||||
import { useStatus } from "../queries";
|
||||
import { useApp } from "../store";
|
||||
|
||||
/** The logged-in user's own permissions, in plain words. Built purely from
|
||||
* data this user may already see (status carries charger gun labels for
|
||||
* everyone, and only the relays they control). */
|
||||
function MyPermissions() {
|
||||
const me = useApp((s) => s.me)!;
|
||||
const { data: status } = useStatus();
|
||||
|
||||
if (isAdmin(me.scopes)) {
|
||||
return (
|
||||
<section className="panel panel--narrow">
|
||||
<header className="panel__head">
|
||||
<h2>Your permissions</h2>
|
||||
</header>
|
||||
<span className="chip chip--card">Administrator</span>
|
||||
<p className="panel__note">
|
||||
Full access: both guns, all relays, cards, users and history of everyone.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const guns: string[] = [];
|
||||
for (const [cp, meta] of Object.entries(status?.chargers ?? {}))
|
||||
for (const [conn, label] of Object.entries(meta.guns ?? {}))
|
||||
if (scopeAllowed(me.scopes, `charger:${cp}:${conn}`))
|
||||
guns.push(`${meta.label ?? cp} — ${label}`);
|
||||
const relays = Object.values(status?.relays ?? {}).map((r) => r.label);
|
||||
|
||||
return (
|
||||
<section className="panel panel--narrow">
|
||||
<header className="panel__head">
|
||||
<h2>Your permissions</h2>
|
||||
</header>
|
||||
{guns.length + relays.length === 0 ? (
|
||||
<p className="panel__note">
|
||||
No device permissions yet — ask an admin to grant you a gun or a relay.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="permlist">
|
||||
{guns.map((g) => (
|
||||
<li key={g}>
|
||||
<span className="chip chip--plugged">Gun</span> {g}
|
||||
</li>
|
||||
))}
|
||||
{relays.map((r) => (
|
||||
<li key={r}>
|
||||
<span className="chip chip--app">Relay</span> {r}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="panel__note">
|
||||
History shows only your own charging sessions.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function AppearanceSection() {
|
||||
const theme = useApp((s) => s.theme);
|
||||
const setTheme = useApp((s) => s.setTheme);
|
||||
return (
|
||||
<section className="panel panel--narrow">
|
||||
<header className="panel__head">
|
||||
<h2>Appearance</h2>
|
||||
</header>
|
||||
<label className="switch">
|
||||
<span className="switch__label">Dark theme</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
checked={theme === "dark"}
|
||||
onChange={(e) => setTheme(e.target.checked ? "dark" : "light")}
|
||||
/>
|
||||
<span className="switch__track" aria-hidden>
|
||||
<span className="switch__thumb" />
|
||||
</span>
|
||||
</label>
|
||||
<p className="panel__note">Saved on this device.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Account() {
|
||||
const me = useApp((s) => s.me)!;
|
||||
const toast = useApp((s) => s.toast);
|
||||
const [current, setCurrent] = useState("");
|
||||
const [next, setNext] = useState("");
|
||||
const [repeat, setRepeat] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function submit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (next !== repeat) {
|
||||
toast("New passwords do not match", "error");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.post("/me/password", { current_password: current, new_password: next });
|
||||
toast("Password changed");
|
||||
setCurrent("");
|
||||
setNext("");
|
||||
setRepeat("");
|
||||
} catch (err) {
|
||||
toast((err as Error).message, "error");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<AppearanceSection />
|
||||
<MyPermissions />
|
||||
<section className="panel panel--narrow">
|
||||
<header className="panel__head">
|
||||
<h2>Account</h2>
|
||||
<span className="panel__meta mono">{me.name}</span>
|
||||
</header>
|
||||
<form onSubmit={submit} className="cardform" style={{ marginTop: 0 }}>
|
||||
<label className="field">
|
||||
<span>Current password</span>
|
||||
<input
|
||||
type="password"
|
||||
value={current}
|
||||
onChange={(e) => setCurrent(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>New password</span>
|
||||
<input
|
||||
type="password"
|
||||
value={next}
|
||||
onChange={(e) => setNext(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
minLength={4}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Repeat new password</span>
|
||||
<input
|
||||
type="password"
|
||||
value={repeat}
|
||||
onChange={(e) => setRepeat(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<div className="cardform__actions">
|
||||
<button className="btn btn--primary" disabled={busy}>
|
||||
{busy ? "Changing…" : "Change password"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
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 & tokens</h2>
|
||||
</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" data-label="Tag">{tag}</td>
|
||||
<td className="strong" data-label="Name">{entry.name}</td>
|
||||
<td data-label="Type">
|
||||
<span className={`chip chip--${entry.kind === "app" ? "app" : "card"}`}>
|
||||
{entry.kind}
|
||||
</span>
|
||||
</td>
|
||||
<td data-label="Belongs to">{entry.user ?? <span className="dim">unassigned</span>}</td>
|
||||
<td className="dim" data-label="Guns">{entry.guns?.join(", ") ?? "all guns"}</td>
|
||||
<td className="num table__actions">
|
||||
<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 />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
import { api, scopeAllowed } from "../api";
|
||||
import Battery from "../components/Battery";
|
||||
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; // OCPP status, or "Offline" / "NoStatus" synthesized here
|
||||
tx: (ActiveTx & { txId: string }) | null;
|
||||
}
|
||||
|
||||
/** Every gun the system knows about is ALWAYS shown: the chargers registry
|
||||
* defines the cards, live connector reports and transactions overlay state. */
|
||||
function gunsFrom(status: Status): Gun[] {
|
||||
const guns = new Map<string, Gun>();
|
||||
|
||||
for (const [cp, meta] of Object.entries(status.chargers)) {
|
||||
const online = cp in status.connected;
|
||||
for (const [conn, label] of Object.entries(meta.guns ?? {})) {
|
||||
guns.set(`${cp}/${conn}`, {
|
||||
cp,
|
||||
connector: Number(conn),
|
||||
label,
|
||||
chargerLabel: meta.label ?? cp,
|
||||
ocppStatus: online ? "NoStatus" : "Offline",
|
||||
tx: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const [key, ocppStatus] of Object.entries(status.connectors)) {
|
||||
const cp = key.slice(0, key.lastIndexOf("/"));
|
||||
const connector = Number(key.slice(key.lastIndexOf("/") + 1));
|
||||
if (connector <= 0) continue; // connector 0 = the whole charge point
|
||||
const existing = guns.get(`${cp}/${connector}`);
|
||||
if (existing) existing.ocppStatus = ocppStatus;
|
||||
else
|
||||
guns.set(`${cp}/${connector}`, {
|
||||
cp,
|
||||
connector,
|
||||
label: `Gun ${connector}`,
|
||||
chargerLabel: status.chargers[cp]?.label ?? cp,
|
||||
ocppStatus,
|
||||
tx: null,
|
||||
});
|
||||
}
|
||||
|
||||
for (const [txId, tx] of Object.entries(status.active_transactions)) {
|
||||
const gun = guns.get(`${tx.cp}/${tx.connector}`);
|
||||
if (gun) gun.tx = { ...tx, txId };
|
||||
}
|
||||
|
||||
return [...guns.values()].sort(
|
||||
(a, b) => a.cp.localeCompare(b.cp) || a.connector - b.connector,
|
||||
);
|
||||
}
|
||||
|
||||
/** Chip text + tone per the owner's state language. */
|
||||
function gunState(gun: Gun): { label: string; cls: string } {
|
||||
if (gun.tx) return { label: "Charging", cls: "charging" };
|
||||
switch (gun.ocppStatus) {
|
||||
case "Charging":
|
||||
return { label: "Charging", cls: "charging" };
|
||||
case "Preparing":
|
||||
return { label: "Plugged in", cls: "plugged" };
|
||||
case "SuspendedEV":
|
||||
case "SuspendedEVSE":
|
||||
return { label: "Paused", cls: "plugged" };
|
||||
case "Finishing":
|
||||
return { label: "Finishing", cls: "plugged" };
|
||||
case "Available":
|
||||
return { label: "Idle", cls: "idle" };
|
||||
case "Offline":
|
||||
return { label: "Offline", cls: "offline" };
|
||||
case "NoStatus":
|
||||
return { label: "No status yet", cls: "offline" };
|
||||
case "Faulted":
|
||||
return { label: "Fault", cls: "faulted" };
|
||||
default:
|
||||
return { label: gun.ocppStatus, cls: "idle" };
|
||||
}
|
||||
}
|
||||
|
||||
function GunBay({ gun, scopes }: { gun: Gun; scopes: string[] }) {
|
||||
const toast = useApp((s) => s.toast);
|
||||
const may = scopeAllowed(scopes, `charger:${gun.cp}:${gun.connector}`);
|
||||
// Start arms ONLY with a cable in the car (Preparing / pulsing blue) —
|
||||
// an idle, unplugged gun keeps the button disabled (owner, 2026-07-12)
|
||||
const ready = !gun.tx && gun.ocppStatus === "Preparing";
|
||||
|
||||
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}`),
|
||||
);
|
||||
|
||||
const state = gunState(gun);
|
||||
return (
|
||||
<article className="bay">
|
||||
<header className="bay__head">
|
||||
<span className="bay__eyebrow">{gun.chargerLabel}</span>
|
||||
<Lamp tone={statusTone(gun.ocppStatus, !!gun.tx)} title={state.label} />
|
||||
</header>
|
||||
<h2 className="bay__title">{gun.label}</h2>
|
||||
<div className="bay__status">
|
||||
<span className={`chip chip--${state.cls}`}>{state.label}</span>
|
||||
{gun.ocppStatus === "Preparing" && !gun.tx && (
|
||||
<span className="bay__hint">cable in the socket — ready to start</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{gun.tx && (
|
||||
<>
|
||||
<div className="bay__charge">
|
||||
<Battery soc={gun.tx.telemetry?.soc} />
|
||||
<div className="bay__kw">
|
||||
<span className="bay__kw-num">
|
||||
{gun.tx.telemetry?.power_w != null
|
||||
? (gun.tx.telemetry.power_w / 1000).toFixed(1)
|
||||
: "—"}
|
||||
</span>
|
||||
<span className="bay__kw-unit">kW</span>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
<div>
|
||||
<dt>Delivered</dt>
|
||||
<dd className="mono">
|
||||
{gun.tx.telemetry?.energy_wh != null
|
||||
? `${((gun.tx.telemetry.energy_wh - gun.tx.meter_start) / 1000).toFixed(2)} kWh`
|
||||
: "—"}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Voltage</dt>
|
||||
<dd className="mono">
|
||||
{gun.tx.telemetry?.voltage_v != null
|
||||
? `${gun.tx.telemetry.voltage_v.toFixed(0)} V`
|
||||
: "—"}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Current</dt>
|
||||
<dd className="mono">
|
||||
{gun.tx.telemetry?.current_a != null
|
||||
? `${gun.tx.telemetry.current_a.toFixed(1)} A`
|
||||
: "—"}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{!gun.tx.telemetry && (
|
||||
<span className="bay__hint">first meter reading arrives within a minute…</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<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>}
|
||||
{may && !gun.tx && !ready && gun.ocppStatus === "Available" && (
|
||||
<span className="bay__hint">plug the cable into the car to enable</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 — controls enable as soon as it connects.</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!guns.length && !offline && (
|
||||
<p className="empty">Connected, waiting for the first gun status report…</p>
|
||||
)}
|
||||
<div className="bays">
|
||||
{guns.map((g) => (
|
||||
<GunBay key={`${g.cp}/${g.connector}`} gun={g} scopes={me.scopes} />
|
||||
))}
|
||||
</div>
|
||||
<Relays status={status} scopes={me.scopes} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { isAdmin } from "../api";
|
||||
import { useSessions, useStatus } from "../queries";
|
||||
import { useApp } from "../store";
|
||||
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 me = useApp((s) => s.me)!;
|
||||
const admin = isAdmin(me.scopes);
|
||||
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">
|
||||
{admin
|
||||
? "No charging sessions yet. The first card tap or in-app start will appear here with who, when, how, and how many kWh."
|
||||
: "No charging sessions yet. Sessions you start — by card or in-app — appear here."}
|
||||
</p>
|
||||
);
|
||||
|
||||
const totalKwh = sessions.reduce((acc, s) => acc + (s.wh ?? 0), 0) / 1000;
|
||||
|
||||
return (
|
||||
<section className="panel">
|
||||
<header className="panel__head">
|
||||
<h2>{admin ? "All charging sessions" : "Your 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" data-label="Who">{s.who || s.id_tag}</td>
|
||||
<td data-label="Via">
|
||||
<MethodChip method={s.method} />
|
||||
</td>
|
||||
<td data-label="Gun">{gunLabel(s, status?.chargers ?? {})}</td>
|
||||
<td className="mono" data-label="Started">{fmtTime(s.started)}</td>
|
||||
<td data-label="Duration">
|
||||
{s.ended ? (
|
||||
fmtDuration(s.started, s.ended)
|
||||
) : (
|
||||
<span className="chip chip--live">charging</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="num mono strong" data-label="kWh">{fmtKwh(s.wh)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -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>Art IoT</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>
|
||||
);
|
||||
}
|
||||
@@ -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 table__actions">
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -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"),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { create } from "zustand";
|
||||
import type { Me } from "./types";
|
||||
|
||||
export type Theme = "light" | "dark";
|
||||
|
||||
const THEME_KEY = "artiot-theme";
|
||||
|
||||
function applyTheme(theme: Theme) {
|
||||
document.documentElement.dataset.theme = theme;
|
||||
document
|
||||
.querySelector('meta[name="theme-color"]')
|
||||
?.setAttribute("content", theme === "dark" ? "#1b211f" : "#f9faf9");
|
||||
}
|
||||
|
||||
// Light unless the user chose dark before; applied at module load, before
|
||||
// the first render, so the login screen is themed too.
|
||||
const initialTheme: Theme = localStorage.getItem(THEME_KEY) === "dark" ? "dark" : "light";
|
||||
applyTheme(initialTheme);
|
||||
|
||||
/** 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;
|
||||
theme: Theme;
|
||||
setTheme: (theme: Theme) => 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 }),
|
||||
theme: initialTheme,
|
||||
setTheme: (theme) => {
|
||||
localStorage.setItem(THEME_KEY, theme);
|
||||
applyTheme(theme);
|
||||
set({ theme });
|
||||
},
|
||||
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) })),
|
||||
}));
|
||||
@@ -0,0 +1,524 @@
|
||||
/* ============================================================
|
||||
Art IoT — instrument-panel design system, mk II
|
||||
Surfaces like enameled switchgear, copper-busbar accent,
|
||||
indicator lamps as the signature element.
|
||||
Type: Chakra Petch (all UI — its chamfered glyphs set the
|
||||
geometry of the whole panel) + IBM Plex Mono (data only:
|
||||
identifiers, timestamps, tabular numbers).
|
||||
Corners: square. The only diagonal is the chamfer cut on
|
||||
bays, the login plate and solid buttons — echoing the face.
|
||||
============================================================ */
|
||||
|
||||
: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: charging */
|
||||
--blue: #2160c4; /* plugged-in blue */
|
||||
--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);
|
||||
--dropshadow: drop-shadow(0 1px 2px rgb(29 37 35 / 0.07)) drop-shadow(0 4px 10px rgb(29 37 35 / 0.06));
|
||||
--font-ui: "Chakra Petch", "Segoe UI", system-ui, sans-serif;
|
||||
--font-mono: "IBM Plex Mono", ui-monospace, Consolas, monospace;
|
||||
/* label: the recurring small-caps utility voice */
|
||||
--label: 600 11px/1.4 var(--font-ui);
|
||||
--label-track: 0.11em;
|
||||
}
|
||||
|
||||
/* Dark is opt-in via the Account switch (persisted in localStorage);
|
||||
light is the default regardless of the OS preference. */
|
||||
:root[data-theme="dark"] {
|
||||
--paper: #131816;
|
||||
--panel: #1b211f;
|
||||
--panel-inset: #161c1a;
|
||||
--ink: #e4e9e7;
|
||||
--ink-dim: #93a09b;
|
||||
--line: #2c3531;
|
||||
--copper: #d07a3e;
|
||||
--copper-deep: #b25c28;
|
||||
--live: #2fae7c;
|
||||
--blue: #4f8ee8;
|
||||
--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);
|
||||
--dropshadow: drop-shadow(0 1px 2px rgb(0 0 0 / 0.45)) drop-shadow(0 4px 10px rgb(0 0 0 / 0.35));
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; margin: 0; }
|
||||
|
||||
html { color-scheme: light; }
|
||||
html[data-theme="dark"] { color-scheme: dark; }
|
||||
|
||||
body {
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
font-family: var(--font-ui);
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
button, input, select { font: inherit; color: inherit; border-radius: 0; }
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--copper);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.mono { font-family: var(--font-mono); font-size: 0.93em; }
|
||||
.strong { font-weight: 600; }
|
||||
.dim { color: var(--ink-dim); }
|
||||
.num { text-align: right; }
|
||||
|
||||
/* ---------- indicator lamp (signature element) ----------
|
||||
Deliberately round in a square world: it is a physical lamp
|
||||
on the cabinet face, not UI chrome. */
|
||||
.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--blue {
|
||||
background: radial-gradient(circle at 35% 30%, #9ec4ff, var(--blue) 70%);
|
||||
box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 8px color-mix(in srgb, var(--blue) 55%, transparent);
|
||||
}
|
||||
.lamp--pulse-blue { animation: lamp-pulse-blue 1.5s ease-in-out infinite; }
|
||||
@keyframes lamp-pulse-blue {
|
||||
0%, 100% {
|
||||
box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 3px color-mix(in srgb, var(--blue) 35%, transparent);
|
||||
filter: brightness(0.85);
|
||||
}
|
||||
50% {
|
||||
box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 15px color-mix(in srgb, var(--blue) 90%, transparent);
|
||||
filter: brightness(1.15);
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.lamp--pulse-blue { animation: none; }
|
||||
* { transition: none !important; }
|
||||
}
|
||||
|
||||
/* ---------- app shell ---------- */
|
||||
.shell { min-height: 100dvh; display: flex; flex-direction: column; }
|
||||
|
||||
.topbar {
|
||||
display: flex; align-items: stretch; gap: 18px;
|
||||
min-height: 54px;
|
||||
padding: 0 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; align-self: center; }
|
||||
.brand__mark { width: 28px; height: 28px; }
|
||||
.brand__mark path { fill: var(--copper); }
|
||||
.brand__name {
|
||||
display: block;
|
||||
font-weight: 700; font-style: italic;
|
||||
text-transform: uppercase; letter-spacing: 0.05em;
|
||||
line-height: 1.15;
|
||||
}
|
||||
.brand__sub {
|
||||
display: block; font: var(--label); font-size: 10px;
|
||||
text-transform: uppercase; letter-spacing: 0.16em; color: var(--ink-dim);
|
||||
}
|
||||
|
||||
/* Desktop nav: underline tabs riding the topbar rule. */
|
||||
.nav { display: flex; gap: 2px; flex: 1; overflow-x: auto; }
|
||||
.nav__link {
|
||||
display: inline-flex; align-items: center; gap: 7px;
|
||||
padding: 0 14px;
|
||||
color: var(--ink-dim);
|
||||
text-decoration: none;
|
||||
font-size: 13px; font-weight: 600;
|
||||
text-transform: uppercase; letter-spacing: 0.07em;
|
||||
white-space: nowrap;
|
||||
box-shadow: inset 0 -2px 0 transparent;
|
||||
}
|
||||
.nav__link:hover { color: var(--ink); background: var(--panel-inset); }
|
||||
.nav__link.active { color: var(--copper-deep); box-shadow: inset 0 -2px 0 var(--copper); }
|
||||
|
||||
.badge {
|
||||
background: var(--amber); color: #fff;
|
||||
font-family: var(--font-mono); font-size: 11px; font-weight: 600;
|
||||
padding: 1px 6px;
|
||||
}
|
||||
|
||||
.topbar__user { display: flex; align-items: center; gap: 10px; align-self: center; margin-left: auto; }
|
||||
.topbar__who {
|
||||
font-family: var(--font-mono); font-size: 13px; color: var(--ink-dim);
|
||||
text-decoration: none; padding: 4px 8px;
|
||||
}
|
||||
.topbar__who:hover { color: var(--ink); background: var(--panel-inset); }
|
||||
.topbar__who.active { color: var(--copper-deep); }
|
||||
|
||||
.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));
|
||||
border-left: 3px solid var(--amber);
|
||||
background: color-mix(in srgb, var(--amber) 9%, var(--panel));
|
||||
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-top: 3px solid var(--copper);
|
||||
clip-path: polygon(0 0, calc(100% - 18px) 0, 100% 18px, 100% 100%, 0 100%);
|
||||
filter: var(--dropshadow);
|
||||
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: 24px; font-weight: 700; font-style: italic;
|
||||
text-transform: uppercase; letter-spacing: 0.05em;
|
||||
}
|
||||
.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);
|
||||
box-shadow: var(--shadow);
|
||||
padding: 18px 20px;
|
||||
}
|
||||
.panel--narrow { max-width: 460px; }
|
||||
.panel--attention { border-color: color-mix(in srgb, var(--amber) 50%, var(--line)); border-left: 3px solid var(--amber); }
|
||||
.panel--offline { display: flex; gap: 14px; align-items: center; border-left: 3px solid var(--red); }
|
||||
.panel--offline p { color: var(--ink-dim); font-size: 14px; }
|
||||
.panel--offline h2 { font-size: 15px; }
|
||||
|
||||
.panel__head {
|
||||
display: flex; align-items: baseline; justify-content: space-between; gap: 12px;
|
||||
margin-bottom: 12px; flex-wrap: wrap;
|
||||
}
|
||||
.panel__head h2 {
|
||||
font-size: 14px; font-weight: 700;
|
||||
text-transform: uppercase; letter-spacing: 0.09em;
|
||||
display: flex; align-items: center; gap: 9px;
|
||||
}
|
||||
.panel__meta { color: var(--ink-dim); font-size: 13px; }
|
||||
.panel__note { color: var(--ink-dim); font-size: 13.5px; margin-top: 8px; }
|
||||
.panel__inset {
|
||||
margin-top: 14px; padding: 16px;
|
||||
background: var(--panel-inset);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
.panel__inset h3 { font-size: 14px; margin-bottom: 10px; }
|
||||
|
||||
.bays {
|
||||
display: grid; gap: 18px;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 290px), 1fr));
|
||||
}
|
||||
|
||||
/* Gun bay: the primary instrument. Chamfered top-right corner —
|
||||
the same cut Chakra Petch makes on its letterforms. */
|
||||
.bay {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-top: 3px solid var(--copper);
|
||||
clip-path: polygon(0 0, calc(100% - 14px) 0, 100% 14px, 100% 100%, 0 100%);
|
||||
filter: var(--dropshadow);
|
||||
padding: 18px 20px;
|
||||
display: flex; flex-direction: column; gap: 10px;
|
||||
}
|
||||
.bay__head { display: flex; justify-content: space-between; align-items: center; }
|
||||
.bay__head .lamp { margin-right: 14px; } /* clear of the chamfer */
|
||||
.bay__eyebrow {
|
||||
font: var(--label);
|
||||
text-transform: uppercase; letter-spacing: var(--label-track); 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; flex-wrap: wrap; }
|
||||
.bay__hint { color: var(--ink-dim); font-size: 13px; }
|
||||
|
||||
.bay__charge {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 14px;
|
||||
padding: 12px 14px;
|
||||
background: var(--panel-inset);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
.bay__kw { display: flex; align-items: baseline; gap: 5px; }
|
||||
.bay__kw-num { font-size: 28px; font-weight: 600; letter-spacing: 0.01em; font-variant-numeric: tabular-nums; }
|
||||
.bay__kw-unit {
|
||||
font: var(--label);
|
||||
text-transform: uppercase; letter-spacing: var(--label-track); color: var(--ink-dim);
|
||||
}
|
||||
|
||||
/* ---------- battery gauge (SoC, red -> blue -> green) ---------- */
|
||||
.battery { display: flex; align-items: center; gap: 2px; }
|
||||
.battery__shell {
|
||||
display: inline-block; width: 52px; height: 22px;
|
||||
border: 2px solid var(--ink-dim);
|
||||
padding: 2px; background: var(--panel);
|
||||
}
|
||||
.battery__fill {
|
||||
display: block; height: 100%;
|
||||
min-width: 2px;
|
||||
transition: width 0.6s ease, background 0.6s ease;
|
||||
}
|
||||
.battery__cap {
|
||||
width: 3px; height: 10px;
|
||||
background: var(--ink-dim);
|
||||
}
|
||||
.battery__pct { font-size: 16px; font-weight: 600; margin-left: 8px; font-variant-numeric: tabular-nums; }
|
||||
|
||||
.bay__telemetry {
|
||||
display: grid; grid-template-columns: repeat(auto-fit, minmax(86px, 1fr));
|
||||
gap: 10px 18px;
|
||||
padding: 12px 14px;
|
||||
background: var(--panel-inset);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
.bay__telemetry dt {
|
||||
font: var(--label); font-size: 10px;
|
||||
text-transform: uppercase; letter-spacing: var(--label-track); color: var(--ink-dim);
|
||||
}
|
||||
.bay__telemetry dd { font-weight: 600; font-size: 14px; white-space: nowrap; }
|
||||
|
||||
.bay__actions { display: flex; align-items: center; gap: 12px; margin-top: 2px; flex-wrap: wrap; }
|
||||
|
||||
/* ---------- chips ---------- */
|
||||
.chip {
|
||||
display: inline-block;
|
||||
font-size: 11.5px; font-weight: 600;
|
||||
text-transform: uppercase; letter-spacing: 0.08em;
|
||||
padding: 3px 9px;
|
||||
background: var(--panel-inset); color: var(--ink-dim);
|
||||
border: 1px solid var(--line);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.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--plugged { background: color-mix(in srgb, var(--blue) 13%, transparent); color: var(--blue); border-color: color-mix(in srgb, var(--blue) 40%, transparent); }
|
||||
.chip--offline { opacity: 0.7; }
|
||||
.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;
|
||||
padding: 10px 18px;
|
||||
font-size: 13px; font-weight: 600;
|
||||
text-transform: uppercase; letter-spacing: 0.06em;
|
||||
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; }
|
||||
/* Solid (load-bearing) buttons carry the chamfer cut. */
|
||||
.btn--primary, .btn--danger {
|
||||
clip-path: polygon(0 0, 100% 0, 100% calc(100% - 9px), calc(100% - 9px) 100%, 0 100%);
|
||||
}
|
||||
.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); border-color: var(--ink-dim); }
|
||||
.btn--sm { padding: 6px 12px; font-size: 12px; }
|
||||
.btn--block { width: 100%; }
|
||||
.btn--dangertext { color: var(--red); }
|
||||
|
||||
/* ---------- forms ---------- */
|
||||
.field { display: flex; flex-direction: column; gap: 5px; }
|
||||
.field > span, .field__label {
|
||||
font: var(--label);
|
||||
text-transform: uppercase; letter-spacing: var(--label-track); color: var(--ink-dim);
|
||||
}
|
||||
.field input, .field select {
|
||||
background: var(--paper);
|
||||
border: 1px solid var(--line);
|
||||
padding: 10px 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(min(100%, 200px), 1fr)); margin-bottom: 12px; }
|
||||
|
||||
/* Slide switch, squared like everything else — a slider on the panel face. */
|
||||
.switch { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 4px 0; cursor: pointer; }
|
||||
.switch__label { font-weight: 500; }
|
||||
.switch input { position: absolute; opacity: 0; width: 0; height: 0; }
|
||||
.switch__track {
|
||||
width: 42px; height: 22px; flex: none;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel-inset);
|
||||
padding: 2px;
|
||||
display: inline-flex;
|
||||
transition: background 0.15s, border-color 0.15s;
|
||||
}
|
||||
.switch__thumb {
|
||||
width: 16px; height: 16px;
|
||||
background: var(--ink-dim);
|
||||
transition: transform 0.15s, background 0.15s;
|
||||
}
|
||||
.switch input:checked + .switch__track {
|
||||
background: color-mix(in srgb, var(--copper) 15%, transparent);
|
||||
border-color: var(--copper);
|
||||
}
|
||||
.switch input:checked + .switch__track .switch__thumb {
|
||||
transform: translateX(20px);
|
||||
background: var(--copper);
|
||||
}
|
||||
.switch input:focus-visible + .switch__track { outline: 2px solid var(--copper); outline-offset: 2px; }
|
||||
|
||||
.check { display: flex; align-items: center; gap: 9px; padding: 4px 0; cursor: pointer; }
|
||||
.check input { accent-color: var(--copper); width: 16px; height: 16px; flex: none; }
|
||||
.check--strong { font-weight: 600; }
|
||||
|
||||
.cardform { display: flex; flex-direction: column; gap: 12px; margin-top: 12px; }
|
||||
.cardform__actions { display: flex; gap: 10px; flex-wrap: wrap; }
|
||||
|
||||
.gunpicker, .matrix { display: flex; flex-direction: column; gap: 6px; }
|
||||
|
||||
.permlist { list-style: none; padding: 0; display: flex; flex-direction: column; gap: 8px; }
|
||||
.permlist li { display: flex; align-items: center; gap: 10px; font-weight: 500; }
|
||||
.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: var(--label); font-size: 10.5px;
|
||||
text-transform: uppercase; letter-spacing: var(--label-track); 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; }
|
||||
.table .btn + .btn { margin-left: 8px; }
|
||||
|
||||
.relay-list, .pending-list { list-style: none; padding: 0; display: flex; flex-direction: column; }
|
||||
.relay {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 12px 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-left: 3px solid var(--copper);
|
||||
padding: 11px 16px;
|
||||
font-size: 14px; box-shadow: var(--shadow);
|
||||
}
|
||||
.toast--error { background: var(--red); border-left-color: color-mix(in srgb, var(--red) 55%, black); color: #fff; }
|
||||
|
||||
/* ---------- responsive: the phone is the primary panel ---------- */
|
||||
@media (max-width: 640px) {
|
||||
.topbar { min-height: 50px; }
|
||||
.brand__mark { width: 24px; height: 24px; }
|
||||
|
||||
/* Nav becomes a fixed bottom tab bar — thumb reach beats a crammed topbar. */
|
||||
.nav {
|
||||
position: fixed; left: 0; right: 0; bottom: 0; z-index: 20;
|
||||
background: var(--panel);
|
||||
border-top: 1px solid var(--line);
|
||||
padding: 0 max(4px, env(safe-area-inset-left)) env(safe-area-inset-bottom) max(4px, env(safe-area-inset-right));
|
||||
overflow-x: visible;
|
||||
}
|
||||
.nav__link {
|
||||
flex: 1; justify-content: center;
|
||||
padding: 14px 4px;
|
||||
font-size: 12px;
|
||||
box-shadow: inset 0 2px 0 transparent; /* accent flips to the top edge */
|
||||
}
|
||||
.nav__link.active { box-shadow: inset 0 2px 0 var(--copper); background: var(--panel-inset); }
|
||||
|
||||
.content { padding-top: 14px; padding-bottom: calc(76px + env(safe-area-inset-bottom)); }
|
||||
.toasts { bottom: calc(64px + env(safe-area-inset-bottom)); }
|
||||
|
||||
/* Bigger touch targets */
|
||||
.btn { padding: 12px 18px; }
|
||||
.btn--sm { padding: 9px 14px; }
|
||||
|
||||
/* Tables collapse into labeled stacked rows — no sideways scrolling. */
|
||||
.table thead { display: none; }
|
||||
.table, .table tbody { display: block; }
|
||||
.table tr { display: block; border-bottom: 1px solid var(--line); padding: 10px 0; }
|
||||
.table tr:last-child { border-bottom: none; }
|
||||
.table td {
|
||||
display: flex; justify-content: space-between; align-items: center; gap: 12px;
|
||||
border: none; padding: 3px 0;
|
||||
}
|
||||
.table td.num { text-align: left; }
|
||||
.table td[data-label]::before {
|
||||
content: attr(data-label);
|
||||
font: var(--label); font-size: 10.5px;
|
||||
text-transform: uppercase; letter-spacing: var(--label-track);
|
||||
color: var(--ink-dim);
|
||||
flex: none;
|
||||
}
|
||||
.table td.table__actions { justify-content: flex-end; padding-top: 8px; }
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
export interface Me {
|
||||
name: string;
|
||||
scopes: string[];
|
||||
id_tag: string | null;
|
||||
}
|
||||
|
||||
export interface Telemetry {
|
||||
energy_wh?: number;
|
||||
power_w?: number;
|
||||
soc?: number;
|
||||
voltage_v?: number;
|
||||
current_a?: number;
|
||||
time?: string;
|
||||
}
|
||||
|
||||
export interface ActiveTx {
|
||||
cp: string;
|
||||
connector: number;
|
||||
id_tag: string;
|
||||
who: string;
|
||||
method: string;
|
||||
meter_start: number;
|
||||
started: string;
|
||||
telemetry?: Telemetry;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"root":["./src/app.tsx","./src/api.ts","./src/main.tsx","./src/queries.ts","./src/store.ts","./src/types.ts","./src/components/battery.tsx","./src/components/lamp.tsx","./src/components/layout.tsx","./src/pages/account.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"}
|
||||
@@ -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",
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
[2,"2901b39c-8ec0-4b2e-9402-ecf19aeda2f9","MeterValues",{"connectorId":1,"transactionId":2,"meterValue":[{"timestamp":"2026-07-12T07:22:13.558Z","sampledValue":[{"value":"0.0","context":"Transaction.Begin","format":"Raw","measurand":"Current.Import","location":"Outlet","unit":"A"},{"value":"405731","context":"Transaction.Begin","format":"Raw","measurand":"Energy.Active.Import.Register","location":"Outlet","unit":"Wh"},{"value":"0","context":"Transaction.Begin","format":"Raw","measurand":"Power.Active.Import","location":"Outlet","unit":"W"},{"value":"0","context":"Transaction.Begin","format":"Raw","measurand":"SoC","location":"Outlet","unit":"Percent"},{"value":"0.0","context":"Transaction.Begin","format":"Raw","measurand":"Voltage","location":"Outlet","unit":"V"}]}]}]
|
||||
@@ -1,24 +1,48 @@
|
||||
---
|
||||
type: concept
|
||||
updated: 2026-07-09
|
||||
updated: 2026-07-11
|
||||
tags: [auth, requirements]
|
||||
---
|
||||
|
||||
# Authorization Methods
|
||||
|
||||
The three planned ways to authorize a charging session. Architecturally they all collapse to one gate: **`decide(id_tag)` in `station.py`** ([[csms-toolkit]]) returns Accepted/Rejected against the allowlist in `station_config.json`. Per [[2026-07-09-findings-and-requirements]]:
|
||||
The three planned ways to authorize a charging session. Architecturally they all collapse to one gate: **`decide(id_tag, connector)` in the [[backend]]** (`backend/csms.py`; formerly `station.py` in [[csms-toolkit]]) returns Accepted/Rejected against the allowlist in `backend.db`. Per [[2026-07-09-findings-and-requirements]]. On top of these charger-side methods sits the **per-user API permission system** (last section).
|
||||
|
||||
## 1. RFID cards — ✅ mechanism built, enrollment pending
|
||||
## 1. RFID cards — ✅ verified live (2026-07-09)
|
||||
|
||||
Use the cards already owned. Flow: enable learn mode → tap each card once → harvest its idTag from `seen_tags.json` → add to `authorized` with a name (`kind: "card"`) → 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.
|
||||
|
||||
## 2. By vehicle / chassis — ⚠️ needs a physical test
|
||||
> [!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.
|
||||
|
||||
True VIN-based **ISO 15118 Plug & Charge is unlikely** on a basic AC unit. The realistic option is **Autocharge**: some chargers automatically send a per-vehicle idTag when a car plugs in, no card tap needed.
|
||||
> [!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.
|
||||
|
||||
**The test:** plug the car in *without* tapping a card. If a stable idTag shows up in `seen_tags.json`, whitelist it as `kind: "car"` and "by vehicle" works. If nothing appears, this method is not achievable on the [[anfu-charger|Anfu hardware]] — drop it.
|
||||
Since 2026-07-11 a card can be **linked to a user and restricted per gun**:
|
||||
|
||||
## 3. Mobile / web app — 📋 to build
|
||||
- `"user": "julian"` on the allowlist entry ties the card to a user account — sessions started with it attribute to that person in the history, and the owner sees their card's sessions even without gun-wide permissions (ownership is looked up live, so linking is retroactive for history visibility).
|
||||
- `"guns": ["eu092025:2"]` restricts the card to specific guns, **charger-qualified** (fnmatch patterns, so `"eu092025:*"` = all guns of one charger) — multi-charger-safe by construction. The check fires at `StartTransaction` (the only message that carries the connector); the preceding `Authorize` (tap) still says Accepted — harmless on this charger, because `AuthorizeRemoteTxRequests=false` makes `StartTransaction` the decisive call anyway (see the probe facts below). ✅ verified with a fake charge point: gun-2-only card → `Invalid`/tx 0 on gun 1, Accepted on gun 2.
|
||||
|
||||
Both are editable from the panel's Admin tab (owner dropdown + guns field).
|
||||
|
||||
## 2. By vehicle / chassis — ❌ CLOSED: not supported (2026-07-09)
|
||||
|
||||
Exhaustively tested on the real hardware; the charger never forwards any vehicle identifier as an OCPP idTag. Three escalating tests, all negative (full record in `discovering/events.jsonl`):
|
||||
|
||||
1. **Plain plug-in, no card** (both cars, both guns, ~15:03Z and ~15:08Z): connector → `Preparing`, then silence. No Autocharge out of the box.
|
||||
2. **`MacEnabled=true` live** (ChangeConfiguration Accepted, no reboot; EU/CCS car replugged 15:22Z): no idTag in 5+ min.
|
||||
3. **`MacEnabled=true` after a full power-cycle** (setting confirmed persisted post-reboot via re-probe; EU car replugged 15:33:51Z): no idTag in ~3.5 min. This was the definitive variant, since this charger family applies some settings only on boot ([[troubleshooting]] #4).
|
||||
|
||||
`MacEnabled` reverted to `false` afterwards. Whatever that key does, it is not Autocharge-style idTag forwarding — despite the charger demonstrably holding a DC handshake with the car (it reports the car's SoC). The EVCCID/VIN exists inside the charger but firmware `1.24.0620.1` never surfaces it over OCPP.
|
||||
|
||||
> [!note] Confirmed: the charger *has* the VIN (owner observation, 2026-07-09)
|
||||
> The **touchscreen displays the chassis number (VIN) of Chinese cars** — direct proof the GB/T 27930 BRM handshake delivers the VIN to the charger. The identity dead-ends at the UI; it's purely an OCPP-mapping gap in the firmware, not a hardware limit. Two long-shot future leads: (1) a firmware update; (2) the writable, empty `DataTransferVendorId` config key — setting it might make the charger emit vendor-specific `DataTransfer` frames (which `station.py` already logs) that could include the VIN.
|
||||
|
||||
**Consequence:** vehicle-based auth is off the table. Households authorize via **RFID cards ✅** and the **app remote-start ✅** — both verified. (If a future firmware update changes this, retest with the same three steps.)
|
||||
|
||||
## 3. Mobile / web app — ✅ verified end-to-end (panel → live charger, 2026-07-12)
|
||||
|
||||
The exact calls the app will make were proven on the real charger with a car plugged in: `RemoteStartTransaction(connector=1, idTag="app-remote")` → Accepted → StartTransaction → Charging; `RemoteStopTransaction(tx)` → Accepted → StopTransaction (`reason: Remote`). Both guns ran **simultaneous transactions** (card on gun 2, remote on gun 1). The shared `app-remote` idTag used for that test is **retired** (2026-07-12): starts now run under per-user idTags, and the [[frontend|panel]] executed a real remote start on the live charger. The remaining allowlist entry is safe to delete; `app-remote` only functions in zero-user bootstrap mode. The original UI wishlist, all since delivered by the panel:
|
||||
|
||||
A mobile-friendly web control panel (no app store):
|
||||
|
||||
@@ -26,3 +50,33 @@ A mobile-friendly web control panel (no app store):
|
||||
- Live charger status
|
||||
- Clickable allowlist management
|
||||
- Bound to `0.0.0.0`, reached only over [[netbird|NetBird]]; optional PIN/token for defense-in-depth (❓ open decision, see [[overview]])
|
||||
- Must be **per-gun**: the charger has two connectors ([[2026-07-09-discovery-eu092025]])
|
||||
|
||||
## Who may control what — API users & scopes (built 2026-07-11)
|
||||
|
||||
The [[backend]] now has real multi-user authorization on top of the three methods above, because not every household member may control everything. Requirement (owner, 2026-07-11): some users control gun 1 only, some gun 2, some only certain [[wifi-relays|relays]].
|
||||
|
||||
- **Users** live in the `settings` table of `backend.db`: username + PBKDF2 password hash + scope list + a personal `id_tag` (`app-<name>`) used for their remote starts, so charging sessions are **attributable per person**. The app idTag is NOT an allowlist entry (2026-07-12): `decide()` validates it against the user record directly and enforces the user's gun scopes; the Cards page shows only physical cards.
|
||||
- **Login**: `POST /api/login` (username/password) → 30-day HMAC-signed session, delivered as an HttpOnly cookie (for the PWA) and as a bearer token (for curl). Stateless — survives backend restarts; deleting a user kills their sessions.
|
||||
- **Scopes** (fnmatch wildcards work):
|
||||
|
||||
| Scope | Grants |
|
||||
|---|---|
|
||||
| `charger:eu092025:1` | start/stop/unlock gun 1 |
|
||||
| `charger:eu092025:2` | same for gun 2 |
|
||||
| `relay:<name>` / `relay:*` | switch those relays (others are invisible to the user) |
|
||||
| `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`.
|
||||
- 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.
|
||||
|
||||
## 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
|
||||
|
||||
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.
|
||||
|
||||
@@ -6,7 +6,9 @@ tags: [hardware]
|
||||
|
||||
# Anfu Home Charger (charging pile)
|
||||
|
||||
The physical home EV charger this whole project revolves around. It is not a single device but a small network of three, behind its own Four-Faith router (see [[network-topology]]). Per [[2026-07-09-findings-and-requirements]]:
|
||||
The physical home EV charger this whole project revolves around. Identity per the live probe ([[2026-07-09-discovery-eu092025]]): **SimpleCharge "MultiSocketCharger"**, serial `24310588`, firmware `1.24.0620.1`, OCPP ID **`eu092025`** — with **two guns** (connectors 1 and 2).
|
||||
|
||||
It is not a single device but a small network of three, behind its own Four-Faith router (see [[network-topology]]). Per [[2026-07-09-findings-and-requirements]]:
|
||||
|
||||
- **[[jc-6620|JC-6620]]** (`192.168.2.228`) — OCPP communication controller; the OCPP client that dials the CSMS
|
||||
- **EV charging controller** (`192.168.2.118`, DHCP) — the main control board that actually manages charging; the JC-6620 talks to it on port 2403
|
||||
@@ -25,8 +27,15 @@ The physical home EV charger this whole project revolves around. It is not a sin
|
||||
> [!warning] Power-cycle required
|
||||
> URL or network changes only take effect after power-cycling the pile.
|
||||
|
||||
## Capabilities in question
|
||||
## Capabilities (per the live probe, [[2026-07-09-discovery-eu092025]], and the live charging test)
|
||||
|
||||
> [!warning] Superseded: "basic AC unit" (assumed in [[2026-07-09-findings-and-requirements]])
|
||||
> The first live charging session (2026-07-09) showed gun 2 delivering **30.6 kW at 309.6 V / 98.8 A with SoC reporting** — that's **DC fast charging**, not AC. This is a DC-capable multi-standard charger.
|
||||
|
||||
- ✅ OCPP 1.6J over WebSocket — verified working
|
||||
- ⚠️ Autocharge (per-vehicle idTag on plug-in) — needs a physical test; see [[authorization]]
|
||||
- ❌ True ISO 15118 Plug & Charge — unlikely on a basic AC unit
|
||||
- ✅ **DC fast charger, 60 kW** (owner-confirmed) with **two guns** — `NumberOfConnectors=2`: **gun 1 = EU standard (CCS), gun 2 = Chinese standard (GB/T)**; 30.6 kW observed on gun 2 while both guns charged simultaneously
|
||||
- ⚠️ Telemetry quirk: while charging, gun 1's periodic samples read 0 W / 0 V (though SoC updated and energy was delivered — 349 Wh per Transaction.End); gun 2's samples looked sane. Watch whether gun 1 metering is lazy/lagged.
|
||||
- ✅ Feature profiles: Core, **RemoteTrigger** (verified), **SmartCharging** (Power-based profiles, max 3 periods), Reservation, LocalAuthListManagement (max **6** entries), FirmwareManagement
|
||||
- ✅ Meter data every 60 s while charging: Energy, Power, **SoC**, Voltage, Current
|
||||
- ❌ Autocharge / vehicle ID over OCPP — **tested and closed 2026-07-09**: no idTag ever forwarded, even with `MacEnabled=true` after a power-cycle ([[authorization]]); the charger clearly holds the DC handshake (reports SoC) but firmware `1.24.0620.1` keeps the vehicle identity to itself
|
||||
- ❌ True ISO 15118 Plug & Charge — nothing in the config suggests it
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
type: entity
|
||||
updated: 2026-07-12
|
||||
tags: [software, csms, backend, relays, auth]
|
||||
---
|
||||
|
||||
# Backend (`../backend/`)
|
||||
|
||||
The production successor to [[csms-toolkit|station.py]] (built 2026-07-11): one FastAPI/uvicorn process on **port 9000** that is both the private CSMS for the [[anfu-charger]] and the controller for the [[wifi-relays|Tuya WiFi relays]] — phases 1–2 of the [[architecture-plan]].
|
||||
|
||||
```
|
||||
backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
|
||||
├── main.py app assembly + entrypoint (uvicorn :9000), serves the panel
|
||||
├── csms.py OCPP 1.6J ChargePoint handlers, decide() gate, remote start/stop
|
||||
├── relays.py tinytuya local control of the SmartLife relays
|
||||
├── routes.py REST under /api/* (login + per-scope permission checks)
|
||||
├── users.py passwords (PBKDF2), sessions (HMAC), scope matcher, user CLI
|
||||
├── store.py SQLite session store: who charged, when, how many kWh + meter samples
|
||||
├── config.py app-state sections (users/allowlist/relays/chargers), db-backed
|
||||
├── journal.py events.jsonl (raw ground truth)
|
||||
└── backend.db THE one store (SQLite, gitignored): sessions + samples +
|
||||
settings (users, allowlist, relays, chargers, session secret)
|
||||
```
|
||||
|
||||
## Surfaces (all on :9000 — the touchscreen URL never changes)
|
||||
|
||||
- `ws://<host>:9000/<ChargerID>` — OCPP WebSocket (catch-all path, the JC-6620 dials in)
|
||||
- `GET /` — **the [[frontend|React panel]]** served from `../frontend/dist/` with SPA fallback (deep links land on index.html; `/api/*` + `/docs` excluded; 503 with instructions if not built)
|
||||
- `POST /api/login|logout`, `GET /api/me`, `POST /api/me/password` (self-service change, current password required) — username/password → 30-day session (cookie + bearer)
|
||||
- `GET /api/sessions?limit&cp&connector` — **charging history: who / when / kWh** (visibility: PRIVATE — own sessions only, i.e. own app starts + own linked cards; admin sees all; gun scopes grant control, not visibility); `GET /api/sessions/{tx}/samples` — per-minute energy/power/SoC for charts
|
||||
- `GET /api/status` — connected chargers, gun states, active transactions, auth events + pending-card count (admin), relays (filtered to what the caller may control)
|
||||
- `GET /api/events?limit&event=` — tail the journal (admin)
|
||||
- `POST /api/charger/start|stop[/{tx}]|unlock/{n}` — gun-scoped; `trigger/{...}|setconfig|probe` — admin
|
||||
- `GET/PUT/DELETE /api/allowlist[/{idTag}]` — enrolled cards/tokens (admin)
|
||||
- `GET /api/cards/pending` + `POST /api/cards/pending/{id}/approve|reject`, `GET/DELETE /api/cards/denied[/{id}]` — the **unknown-card review workflow** (admin); pending count rides `/api/status` as the notification signal
|
||||
- `GET /api/permissions` — the grantable-permission catalog (chargers/guns/relays) that drives the panel's checkbox matrix (admin)
|
||||
- `GET/PUT/DELETE /api/users[/{name}]` — user CRUD (admin), enables a PWA admin page later
|
||||
- `GET /api/relays[?live=true]`, `GET /api/relays/{name}`, `POST /api/relays/{name}/on|off|toggle` — relay-scoped
|
||||
- `/docs` — interactive OpenAPI docs
|
||||
|
||||
## Design facts
|
||||
|
||||
- Carried over from the proven discovery code: the `decide()` gate ([[authorization]]) — now with card→user linking (`"user"`) and charger-qualified gun restriction (`"guns": ["eu092025:2"]`, fnmatch) — the `_WSAdapter` WebSocket bridge, and the JSONL event journal. `DataTransfer` frames are journaled too (the VIN long-shot lead in [[authorization]]).
|
||||
- **Multi-charger by design**: a second charger only needs the same URL with a unique ChargerID; scopes, sessions, card restrictions, and the panel are all keyed by charger id. Gun display names come from the `"chargers"` config section (not hardcoded).
|
||||
- **Multi-user auth** (2026-07-11, replaced the interim `api_token`): username/password users with permission scopes — `charger:<cp>:<gun>`, `relay:<name>`, `admin` — full model in [[authorization]]. Stdlib crypto only (PBKDF2 + HMAC sessions). Zero users = open API (startup warns); bootstrap via `python -m backend.users add <name> --scopes admin`.
|
||||
- Remote starts run under the calling user's own idTag (`app-<name>`) → per-person session attribution. Since 2026-07-12 these tags are **validated directly against the user record** (never enrolled in the allowlist — the old synthetic "app token of <name>" entries are auto-dropped on startup), and the charger-side gate enforces the user's `charger:<cp>:<gun>` scopes too.
|
||||
- **Consumption tracking** (`store.py`, 2026-07-11): every `StartTransaction` opens a row in `backend.db` with a resolved "who" (allowlist name or username); `StopTransaction` closes it and computes Wh from the meter diff; `MeterValues` rows land in a `samples` table (energy/power/SoC, kW→W normalized). Transaction ids continue from `MAX(tx)` across restarts, and stop-by-tx falls back to the store so sessions running through a backend restart stay stoppable.
|
||||
- **Live telemetry** (2026-07-12): the latest meter sample per active transaction (SoC, W, V, A, energy) rides `/api/status` as `active_transactions[tx].telemetry`; `Transaction.Begin` snapshots are skipped (taken before the car's BMS is read). The `samples` table stores energy/power/SoC/voltage/current + OCPP context per minute.
|
||||
- Ctrl+C gotcha, fixed 2026-07-12: uvicorn's graceful shutdown waited forever for the charger's never-closing WebSocket — `timeout_graceful_shutdown=3` caps it; one Ctrl+C now exits in ~3 s and the charger redials.
|
||||
- SPA cache headers: `index.html` is `no-cache` (phones must revalidate — stale builds plagued early testing), hashed `assets/*` cache forever. Remember: **`:9000` serves the last `npm run build`** — source edits are invisible until a build runs (`npm run dev` for live editing).
|
||||
- Relay calls are blocking tinytuya I/O, run via `asyncio.to_thread` so the OCPP socket never stalls.
|
||||
- Venv at repo root (`../venv/`, Python 3.13); deps pinned in `backend/requirements.txt` (fastapi, uvicorn, websockets, ocpp, tinytuya) — the auth system added none.
|
||||
- Sessions record the **auth method** (`card` vs `app`) for the audit trail; unknown cards NEVER charge — they queue in `pending_cards` for admin approve/reject (learn mode is gone).
|
||||
- ✅ Smoke-tested (65 checks as of 2026-07-12, isolated temp db via the `BACKEND_DB` env override): REST surface, allowlist CRUD incl. gun-restricted cards, login/sessions/scopes, user/relay/charger CRUD, the full consumption pipeline (start → meter sample → stop → kWh → visibility filtering), static panel serving, and a fake charge point over the real WS route. Lives in the repo (`backend/smoke_test.py`) since 2026-07-12 — it's the CI gate in [[deployment]].
|
||||
- **Container-ready** (2026-07-12, [[deployment]]): `BACKEND_EVENTS` env override relocates `events.jsonl` (mirrors `BACKEND_DB`), and unauthenticated `GET /api/health` serves Docker/Traefik/Komodo probes.
|
||||
- ✅ **Live charger connected** (2026-07-11 evening): `eu092025` dials the backend (events.jsonl). ⚠️ Panel not yet exercised from a real phone; relays unconfigured until the [[wifi-relays|key extraction]] is done.
|
||||
|
||||
## Web panel
|
||||
|
||||
See [[frontend]] — React/Vite app, built to `frontend/dist/` and served by this process.
|
||||
|
||||
## Deliberately deferred
|
||||
|
||||
SSE live push (the panel polls), per-session charts from the `samples` table (data is already collected), auto-interrogation on connect (manual `POST /api/charger/probe`).
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
type: entity
|
||||
updated: 2026-07-09
|
||||
updated: 2026-07-11
|
||||
tags: [software, csms]
|
||||
---
|
||||
|
||||
@@ -8,6 +8,8 @@ tags: [software, csms]
|
||||
|
||||
The Python scripts that play the CSMS (backend) side of the [[ocpp|OCPP]] link. Currently discovery/tester-grade; `station.py` is the seed of the real controller. Per [[2026-07-09-findings-and-requirements]]:
|
||||
|
||||
> [!warning] Superseded for production (2026-07-11): `station.py` was ported into the [[backend]] package (`../backend/`), which adds allowlist CRUD, optional API token auth, and [[wifi-relays|Tuya relay]] control. `discovering/` stays as the discovery/diagnostic toolkit (`csms.py`, `rawlisten.py`, fake charge point) — don't run `station.py` and the backend at the same time; both bind port 9000.
|
||||
|
||||
| File | Purpose |
|
||||
|---|---|
|
||||
| `csms.py` | Minimal OCPP 1.6J server — accepts everything, logs raw frames. Discovery/tester. |
|
||||
@@ -16,10 +18,19 @@ The Python scripts that play the CSMS (backend) side of the [[ocpp|OCPP]] link.
|
||||
| `station_config.json` | `{ "learn_mode": bool, "authorized": { "<idTag>": {name, kind} } }` |
|
||||
| `seen_tags.json` | Auto-recorded log of every idTag observed (discovery / Autocharge testing). |
|
||||
|
||||
- **Runtime:** Python venv with `websockets` 16.0 + `ocpp`; listens on `ws://0.0.0.0:9000/<chargePointId>`.
|
||||
- **Runtime:** Python venv with `fastapi` + `uvicorn` + `ocpp` (2026-07-09: `station.py` moved from raw `websockets` to a single FastAPI/uvicorn process — the phase-1 shape from [[architecture-plan]]).
|
||||
- **Single port 9000:** the OCPP WebSocket (`ws://0.0.0.0:9000/<chargePointId>`, any path) *and* the discovery HTTP API share it, so the hardcoded touchscreen URL never changes.
|
||||
- **The one gate:** every [[authorization]] method funnels through `decide(id_tag)` in `station.py` — Accepted/Rejected against the allowlist.
|
||||
- **Host requirements:** inbound TCP 9000 open (Windows firewall silently drops otherwise — see [[troubleshooting]]) and a stable IP, since the [[anfu-charger|charger touchscreen]] URL is hardcoded.
|
||||
|
||||
## Discovery API (in `station.py`, docs at `http://<host>:9000/docs`)
|
||||
|
||||
- Auto-interrogation on every charger connect: `GetConfiguration` (all keys) + `TriggerMessage(StatusNotification)` → saved to `discovery_<id>.json` (first real capture: [[2026-07-09-discovery-eu092025]])
|
||||
- **Event journal:** every OCPP event (connect/disconnect, boot, status, authorize, start/stop transaction, meter values) is appended as one JSON line to `events.jsonl` — permanent, restart-proof, greppable; tail it via `GET /events?limit=N&event=<kind>`
|
||||
- `GET /status` (chargers, guns, transactions, auth events) · `GET /tags` (seen + authorized)
|
||||
- `POST /probe` · `/start` · `/stop[/{tx}]` · `/trigger/{status|meter|heartbeat|boot}` · `/unlock/{connector}` · `/setconfig?key=&value=`
|
||||
- With one charger connected, `?cp=` may be omitted. ✅ Verified end-to-end against both a fake charge point and the real charger.
|
||||
|
||||
## Still to build
|
||||
|
||||
The web control panel (remote start/stop, live status, allowlist management) served behind [[netbird|NetBird]] — see [[overview]] for the plan and open host decision.
|
||||
The web control panel (remote start/stop, live status, allowlist management) served behind [[netbird|NetBird]] — now on the [[backend]], see [[overview]] for the plan and open host decision.
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
type: entity
|
||||
updated: 2026-07-12
|
||||
tags: [deployment, ci-cd, docker, komodo, traefik]
|
||||
---
|
||||
|
||||
# Deployment — Docker / Gitea CI / Komodo / Traefik
|
||||
|
||||
How the [[backend]] (+ built [[frontend]]) ships to production. Added 2026-07-12; ⚠️ pipeline authored but the first run through the Gitea runner is still pending (no Docker on the dev machine — the runner is the first place the image actually builds).
|
||||
|
||||
## Shape
|
||||
|
||||
One image, one container, one stack:
|
||||
|
||||
- **`Dockerfile`** (repo root) — two stages: `node:24-alpine` runs `npm ci && npm run build` in `frontend/`, then `python:3.13-slim` installs `backend/requirements.txt`, copies `backend/` + the built `dist/` to where `backend/main.py` expects it (`/app/frontend/dist`). Runs as UID 1000 under tini, `CMD python -m backend.main`.
|
||||
- **State on a volume**: `BACKEND_DB=/data/backend.db` and `BACKEND_EVENTS=/data/events.jsonl` env overrides (the latter added 2026-07-12 to `journal.py`, mirroring the existing `store.py` override) put all mutable state on the `artiot-data` volume — the container is disposable.
|
||||
- **`compose.yaml`** — the Komodo-managed stack. Env-tunable: `ARTIOT_TAG` (default `main`; set a commit SHA to pin/rollback), `ARTIOT_HOST`, `TRAEFIK_NETWORK` (default `traefik`), `ARTIOT_ENTRYPOINT` (`websecure`), `ARTIOT_CERTRESOLVER` (`letsencrypt`).
|
||||
- **`GET /api/health`** — unauthenticated liveness probe (added 2026-07-12) used by the Docker healthcheck; also handy for Traefik/Komodo.
|
||||
|
||||
## Two front doors, same port
|
||||
|
||||
| Door | Path | Why |
|
||||
|---|---|---|
|
||||
| Charger | `ws://<docker-host>:9000/<ChargerID>` — **published port, no proxy** | The URL is hardcoded in the charger touchscreen (change = power-cycle, [[troubleshooting]] #4) and the [[jc-6620|JC-6620]] speaks plain `ws://` — no TLS, no SNI, nothing for Traefik to route on. Docker host needs a DHCP reservation at the IP the charger dials. |
|
||||
| Humans | `https://$ARTIOT_HOST` via Traefik labels | Panel with TLS; same container port 9000. |
|
||||
|
||||
## CI (`.gitea/workflows/build.yml`)
|
||||
|
||||
Mirrors the polymarket-bot repo's pattern. On push to `main` (paths-filtered): plain `docker build` → **smoke test gate** (`backend/smoke_test.py`, 65 checks — REST auth/scopes, per-gun cards, pending-card workflow, OCPP WS round-trips via a fake charge point, session store, SPA serving; in-process against a temp db, promoted into the repo 2026-07-12) → push `git.infra.msai.al/art/charging_station:{main,<sha>}` → HMAC-signed Komodo stack redeploy webhook. A failed smoke test means the image is never pushed.
|
||||
|
||||
Repo secrets required: `REGISTRY_USERNAME`, `REGISTRY_PASSWORD`, `KOMODO_STACK_WEBHOOK_URL`, `KOMODO_WEBHOOK_SECRET`.
|
||||
|
||||
## Migration & constraints
|
||||
|
||||
- **Moving the existing install**: copy the current `backend/backend.db` into the volume (`docker compose cp backend/backend.db artiot:/data/backend.db`, restart) — users, cards, sessions, and the session-signing secret all ride along, so nobody re-logs-in. Fresh install instead: `docker compose exec artiot python -m backend.users add <name> --scopes admin`.
|
||||
- **Charger reachability**: today the charger dials `10.0.10.203:9000` — either the Docker host takes over that address or the touchscreen URL changes (power-cycle). ❓ ties into the always-on-host decision in [[overview]].
|
||||
- **Relay reachability**: [[wifi-relays|tinytuya]] is plain TCP to the relay IPs — the Docker host's network must reach that subnet (bridge networking is fine; device discovery by broadcast is not needed once IPs are registered).
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
type: entity
|
||||
updated: 2026-07-12
|
||||
tags: [software, frontend, react]
|
||||
---
|
||||
|
||||
# Frontend (`../frontend/`)
|
||||
|
||||
The React control panel — branded **"Art IoT"** by the owner (2026-07-12) — (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. ~95 kB gzipped JS.
|
||||
- ✅ **Verified on the owner's phone against the live charger** (2026-07-12): login, gun cards, and a real in-app remote start.
|
||||
|
||||
## Pages
|
||||
|
||||
| Route | Who | What |
|
||||
|---|---|---|
|
||||
| `/` (Control) | all | one "bay" card per gun — **every registry-declared gun always renders**, even offline; status lamp, Start/Stop gated by scope **and** cable-plugged readiness; a charging bay shows the **SoC battery gauge (red→blue→green fill)**, a big kW readout, delivered kWh, voltage, current, plus who/via/duration; relay toggles with on-demand live read |
|
||||
| `/account` | all | **your permissions in plain words** (admin badge, or the guns/relays you may control) + self-service password change (current password required) |
|
||||
| `/history` | all | admins: the full audit table (**who charged, via Card or In-app, which gun, when, duration, kWh**); everyone else: **only their own sessions** |
|
||||
| `/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, in the owner-specified language (2026-07-12): **gray = idle, pulsing blue = cable in the socket, green = charging**, red = fault/offline banner, amber = pending cards. Reduced motion respected; keyboard focus visible.
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
type: entity
|
||||
updated: 2026-07-11
|
||||
tags: [hardware, relays, tuya]
|
||||
---
|
||||
|
||||
# WiFi Relays (SmartLife / Tuya)
|
||||
|
||||
Several WiFi relays scattered around the property, currently driven by the **SmartLife app** (owner report, 2026-07-11). Scope expansion: the [[backend]] should control them too, so one self-hosted system runs both the [[anfu-charger|charger]] and the relays.
|
||||
|
||||
## What they are
|
||||
|
||||
SmartLife = Tuya's consumer app, so these are **Tuya WiFi devices**. The "discovered by Bluetooth at first" behavior the owner observed is Tuya's standard BLE-assisted *pairing* (the phone passes WiFi credentials over BLE once); after provisioning the relays live on WiFi and speak **Tuya's local protocol on TCP 6668**, which the `tinytuya` library drives directly — **no Tuya cloud in the loop** for day-to-day control. SmartLife keeps working in parallel; local and app control don't conflict.
|
||||
|
||||
## Control path (implemented in `backend/relays.py`, ⚠️ awaiting keys)
|
||||
|
||||
Local control needs each device's **id + local key**, extracted once via Tuya's own API:
|
||||
|
||||
1. Create a (free) account at `iot.tuya.com` → Cloud → create a project (data center matching the SmartLife account region).
|
||||
2. Link the SmartLife app account to the project (Devices → Link App Account → scan QR in SmartLife).
|
||||
3. From the repo root: `venv\Scripts\python -m tinytuya wizard` — enter the project's API id/secret; it dumps every paired device's `id`, `key`, `ip`, and protocol `version`.
|
||||
4. Register each relay via `PUT /api/relays/<name>` (admin; interactive form at `/docs`) with its `id`, `key`, `ip`, `version`. The Tuya cloud account is never needed again unless a device is re-paired (**re-pairing regenerates the local key**).
|
||||
|
||||
Recommended: DHCP reservations for the relays and pinned `"ip"` entries in the config — `"ip": "auto"` works via UDP broadcast discovery but is slower and only finds relays on the same L2 segment as the backend host (❓ verify which subnet the relays are on vs. the future always-on host, see [[network-topology]]).
|
||||
|
||||
## API (see [[backend]])
|
||||
|
||||
`GET /api/relays?live=true` (poll all), `GET /api/relays/{name}`, `POST /api/relays/{name}/on|off|toggle`. ⚠️ Untested against the physical relays until the keys are in the config.
|
||||
+11
-5
@@ -1,6 +1,6 @@
|
||||
---
|
||||
type: meta
|
||||
updated: 2026-07-09
|
||||
updated: 2026-07-12
|
||||
tags: [index]
|
||||
---
|
||||
|
||||
@@ -16,20 +16,26 @@ 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
|
||||
- [[jc-6620]] — the OCPP communication controller / client; its IPs and shipped-gateway gotcha
|
||||
- [[csms-toolkit]] — the Python CSMS scripts in `../discovering/` and what each does
|
||||
- [[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]])
|
||||
- [[wifi-relays]] — the Tuya/SmartLife WiFi relays; local tinytuya control path + key-extraction steps
|
||||
- [[deployment]] — Docker image, Gitea CI pipeline, Komodo stack, Traefik routing; how the backend ships
|
||||
- [[netbird]] — the private overlay network; security boundary for the future web panel
|
||||
|
||||
## Concepts
|
||||
|
||||
- [[network-topology]] — charger LAN behind the Four-Faith router, NAT direction, what's verified
|
||||
- [[authorization]] — the three auth methods (RFID ✅ / Autocharge ⚠️ / web app 📋) and the `decide()` gate
|
||||
- [[authorization]] — charger auth methods (RFID ✅ / by-vehicle ❌ / app ✅), per-gun cards, and the API user/scope permission system
|
||||
- [[troubleshooting]] — ordered "charger won't connect" checklist of hard-won gotchas
|
||||
- [[ocpp]] — OCPP 1.6J basics and how the roles/messages map to this project
|
||||
|
||||
## Notes
|
||||
|
||||
*(none yet — filed answers to questions go here)*
|
||||
- [[architecture-plan]] — stack decision (FastAPI + PWA now, Flutter optional later) and 6-phase build plan
|
||||
- [[discovery-runbook]] — step-by-step physical test session: Autocharge first, then RFID taps, then remote start
|
||||
|
||||
## Sources
|
||||
|
||||
- [[2026-07-09-findings-and-requirements]] — founding findings/requirements doc (ingested 2026-07-09, 1 raw file)
|
||||
- [[2026-07-09-findings-and-requirements]] — founding findings/requirements doc (ingested 2026-07-09)
|
||||
- [[2026-07-09-discovery-eu092025]] — live GetConfiguration capability dump from the real charger: 2 guns, feature profiles, meter data (ingested 2026-07-09)
|
||||
|
||||
+92
@@ -15,3 +15,95 @@ Instantiated the LLM-wiki pattern for the charging-station project: schema (`CLA
|
||||
## [2026-07-09] ingest | Findings & Requirements (founding source)
|
||||
|
||||
Ingested `raw/FINDINGS_AND_REQUIREMENTS.md` → [[2026-07-09-findings-and-requirements]]. Seeded [[overview]] plus entities ([[anfu-charger]], [[jc-6620]], [[csms-toolkit]], [[netbird]]) and concepts ([[network-topology]], [[authorization]], [[troubleshooting]], [[ocpp]]). Open decisions tracked in [[overview]].
|
||||
|
||||
## [2026-07-09] query | Stack decision → architecture plan filed
|
||||
|
||||
Discussed backend (Fastify vs FastAPI), web frontend, and Flutter. Decided: FastAPI single-process CSMS+API+PWA; Flutter deferred to optional phase 2. Filed as [[architecture-plan]]; index updated.
|
||||
|
||||
## [2026-07-09] ingest | Live capability probe of the real charger (eu092025)
|
||||
|
||||
Built discovery layer into station.py (single FastAPI process on :9000 — OCPP WS + HTTP API with /status /tags /probe /start /stop /trigger /unlock /setconfig; auto-GetConfiguration on connect). The real charger connected during testing: SimpleCharge MultiSocketCharger, fw 1.24.0620.1, TWO guns, RemoteTrigger verified. Ingested raw/discovery_eu092025.json → [[2026-07-09-discovery-eu092025]]; updated [[anfu-charger]], [[authorization]], [[csms-toolkit]], [[overview]].
|
||||
|
||||
## [2026-07-09] meta | Discovery runbook filed
|
||||
|
||||
Filed [[discovery-runbook]]: physical test session plan (Autocharge plug-in test first, then RFID card taps, optional remote start). Awaiting hardware results.
|
||||
|
||||
## [2026-07-09] meta | Event journal added to station.py
|
||||
|
||||
All OCPP events now persist to events.jsonl (one JSON line each) with a GET /events tail endpoint — so the upcoming Autocharge/RFID/charging test session is fully recorded for later ingest. Verified with fake charger + live eu092025 reconnect. Updated [[csms-toolkit]].
|
||||
|
||||
## [2026-07-09] ingest | First live plug-in test: no Autocharge by default
|
||||
|
||||
Car plugged into gun 2 (no card): StatusNotification Available->Preparing at 15:02:59Z, then silence — no Authorize/StartTransaction/idTag in ~2 min. Preliminary: no Autocharge out of the box; MacEnabled=true retry pending. Updated [[authorization]].
|
||||
|
||||
## [2026-07-09] ingest | Full live test session: RFID + remote start/stop verified, no Autocharge, charger is DC
|
||||
|
||||
Live session with both cars: card ...393 -> Authorize -> charging on gun 2 (GB/T DC, 30.6 kW observed, 1807 Wh delivered); RemoteStart/RemoteStop proven on gun 1 (EU, 349 Wh); two cars plugged without cards produced no idTag (Autocharge negative, MacEnabled retry remains). Superseded "basic AC unit" assumption. Card + app-remote enrolled in allowlist. Updated [[authorization]], [[anfu-charger]], [[overview]]. Raw record: discovering/events.jsonl.
|
||||
|
||||
## [2026-07-09] ingest | Card B captured; gun 2 re-stop; possible auto-restart after remote stop
|
||||
|
||||
Card B (...395) tapped and enrolled. Gun 2 had started a NEW session (same card id ...393, ~65 s after the previous remote stop, cable still plugged) — stopped it remotely (tx 3, 2264 Wh). Open question ❓: re-tap or auth-cache auto-restart? Noted in [[authorization]].
|
||||
|
||||
## [2026-07-09] meta | Charger confirmed 60 kW DC; MacEnabled flipped to true
|
||||
|
||||
Owner confirmed: 60 kW DC fast charger (gun 1 EU/CCS, gun 2 GB/T). No vehicle id observed via OCPP yet, but DC handshake means the charger receives EVCCID (CCS) / possibly VIN (GB/T). Set MacEnabled=true (ChangeConfiguration Accepted, live). Replug test pending. Updated [[anfu-charger]], [[authorization]].
|
||||
|
||||
## [2026-07-09] ingest | "By vehicle" auth definitively closed; charger is 60 kW DC
|
||||
|
||||
Owner confirmed 60 kW DC. Final Autocharge variant: power-cycled pile with MacEnabled=true (setting persisted, verified by post-reboot probe), EU car replugged 15:33:51Z -> no idTag in ~3.5 min. Closed method 2 as NOT SUPPORTED; MacEnabled reverted to false. Updated [[authorization]], [[overview]], [[anfu-charger]], [[discovery-runbook]]. Remaining next steps: learn_mode off, PWA panel, remote-stop-restart question.
|
||||
|
||||
## [2026-07-09] ingest | Touchscreen shows VIN of Chinese (GB/T) cars
|
||||
|
||||
Owner observation: the pile's own UI displays the chassis/VIN for GB/T cars -> confirms the BRM handshake delivers the VIN to the charger; firmware just never maps it to an OCPP idTag. Noted in [[authorization]] with the DataTransferVendorId long-shot lead.
|
||||
|
||||
## [2026-07-11] ingest | Scope expansion: backend also controls the Tuya/SmartLife WiFi relays
|
||||
|
||||
Owner: the backend should also drive the WiFi relays currently on the SmartLife app (BLE-assisted pairing = standard Tuya onboarding; they're Tuya WiFi devices). Decision: local control via tinytuya (TCP 6668), no Tuya cloud in the day-to-day loop; one-time id/local-key extraction via `tinytuya wizard` pending. Created [[wifi-relays]]; updated [[architecture-plan]], [[overview]].
|
||||
|
||||
## [2026-07-11] meta | Production backend built (../backend/) — architecture-plan phases 1-2
|
||||
|
||||
Ported station.py into the `backend/` package: one FastAPI process on :9000 = OCPP CSMS + /api/* (charger control, allowlist CRUD, runtime learn-mode flip, optional api_token auth) + /api/relays/* (tinytuya via asyncio.to_thread). Allowlist migrated to backend/config.json (gitignored — holds Tuya local keys; config.example.json documents shape). Smoke-tested: 13 checks incl. fake CP BootNotification/Authorize over the real WS route. Not yet cut over on the live charger. Created [[backend]]; updated [[csms-toolkit]] (superseded-for-production callout), [[architecture-plan]], [[overview]], [[index]].
|
||||
|
||||
## [2026-07-11] meta | Multi-user auth system: username/password + per-resource scopes
|
||||
|
||||
Owner requirement: per-user permissions (gun 1 vs gun 2 of eu092025, per-relay or all relays). Owner chose username+password over plain tokens; per-gun RFID restriction included. Built into [[backend]]: users.py (PBKDF2 passwords, stateless HMAC sessions 30d, cookie+bearer, fnmatch scopes charger:<cp>:<gun> / relay:<name> / admin), login/me/users CRUD endpoints, scope checks on every route, relay visibility filtering, remote starts attributed via per-user idTag, decide() enforces optional "connectors" on allowlist entries at StartTransaction. Zero users = open API (bootstrap via `python -m backend.users add`). Smoke test grown 13 -> 28 checks, all passing. Resolved the "web app auth" open decision. Updated [[authorization]] (new scopes section + per-gun cards), [[backend]], [[overview]].
|
||||
|
||||
## [2026-07-11] meta | Consumption tracking (SQLite) + the PWA control panel
|
||||
|
||||
Owner requirement: button-push start when a gun is ready (and permitted) + "who charged when and how many kWh". Built store.py (sessions.db: sessions with resolved who/started/ended/Wh + per-minute samples energy/power/SoC; tx ids survive restarts; stop falls back to store after restart), /api/sessions with visibility rules (own + in-scope guns; admin all), and the phase-3 web panel in backend/static/ (vanilla JS PWA at /: login, gun cards with scope- and readiness-gated Start/Stop, relay toggles, history tab, admin tab with allowlist/users/mode). Fixed a sqlite connection leak (with-connect commits but never closes). Smoke test 28 -> 37 checks, all passing. Updated [[backend]], [[architecture-plan]] (phases 1-3 all done), [[overview]], [[index]].
|
||||
|
||||
## [2026-07-11] meta | Cards linked to users; multi-charger gaps closed
|
||||
|
||||
Owner requirements: cards must belong to a person (not float around as "RFID card A (tapped first...)"), and adding a second charger must be clean. Allowlist entries now take "user" (sessions attribute to the person; owner sees their card's history) and charger-qualified "guns": ["eu092025:2"] (fnmatch; replaces the charger-blind "connectors" field). Gun display names moved from hardcoded panel JS to a "chargers" config section served via /api/status. Adding a charger = point it at the same URL with a unique ChargerID + grant charger:<id>:<gun> scopes. Panel admin tab: owner dropdown + guns field. Smoke test 37 -> 42 checks. Updated [[authorization]], [[backend]].
|
||||
|
||||
## [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]].
|
||||
|
||||
## [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.
|
||||
|
||||
## [2026-07-12] meta | Panel live on the owner's phone; gun state language; password self-service
|
||||
|
||||
Owner confirmed the React panel loads on the phone after backend restart. Changes on request: (1) both guns ALWAYS render on Control — gun cards come from the chargers registry, live reports only overlay state (offline/no-status shown gray); (2) new lamp/chip language: gray=idle, pulsing blue=cable plugged, green=charging; (3) POST /api/me/password + /account page — any user changes their own password (current password required; admin reset via PUT /api/users stays). Smoke: 58 checks. Updated [[frontend]], [[backend]].
|
||||
|
||||
## [2026-07-12] meta | Private history; permissions on Account; Start only when plugged; "Art IoT" rename
|
||||
|
||||
Owner (testing on the phone, second user created): (1) transactions are now PRIVATE — non-admins see only their own sessions (app starts + linked cards); gun scopes grant control, not visibility; admins see all. (2) Account page shows the user's own permissions in plain words (admin badge, or gun/relay list built from data they already see). (3) Start button arms ONLY when the cable is plugged (Preparing) — an idle unplugged gun shows "plug the cable into the car to enable". Owner also renamed the app to "Art IoT" (login, topbar, manifest, title) — kept. Smoke: 59 checks. Updated [[backend]], [[frontend]].
|
||||
|
||||
## [2026-07-12] meta | Live telemetry on the gun cards: SoC battery gauge + kW/V/A/delivered
|
||||
|
||||
Owner wants meter values visible per gun in Control. Backend: latest Sample.Periodic per active tx kept in memory (ACTIVE_TX telemetry) and shipped with /api/status (Transaction.Begin snapshots skipped — taken before the car's BMS is read). Also this morning's finding filed: begin/end snapshots are legitimately 0 A/0 V, and a 42 s session never gets a periodic sample. Frontend: battery gauge with red->blue->green SoC gradient + big kW readout + Delivered/Voltage/Current rows on charging bays; earlier commit added voltage_v/current_a/context columns to samples. Smoke: 60 checks. Updated [[frontend]], [[backend]] implicitly via log.
|
||||
|
||||
## [2026-07-12] meta | User app idTags no longer pollute the allowlist
|
||||
|
||||
Owner: "why do we need this app token of X? We just need the user." Agreed — decide() now validates a user's app idTag directly against the user record (and enforces their charger:<cp>:<gun> scopes at the charger-side gate too); charger_start no longer auto-enrolls; enrolling a user's tag via the allowlist API returns 400; existing "app token of <name>" entries are auto-dropped at startup. Open-mode bootstrap: "app-remote" authorizes with zero users configured. Session method audit: user tags -> "app". Smoke: 63 checks. Updated [[backend]], [[authorization]].
|
||||
|
||||
## [2026-07-12] lint | Session wrap-up: milestones + gaps from today filed
|
||||
|
||||
Owner asked whether the wiki needs updating — it did. Filed: panel verified end-to-end on the phone incl. a real in-app start on the live charger (tx 1-2, 141 Wh, who=julian/method=app; the two pre-refactor session rows' who labels were repaired in the db); six household users created; "app-remote" retired (delete from Cards when convenient); Ctrl+C shutdown fix (timeout_graceful_shutdown=3 vs the never-closing charger socket); SPA cache headers + the ":9000 serves the last build" rule; telemetry columns (V/A/context) + live telemetry on /api/status; battery gauge in Control. Refreshed [[overview]] (milestones + trimmed next steps: Tuya keys, remote-stop question, deploy as service), [[backend]], [[frontend]], [[authorization]].
|
||||
|
||||
## [2026-07-12] meta | CI/CD pipeline: Docker + Gitea Actions + Komodo + Traefik
|
||||
|
||||
Owner asked for a deployment pipeline matching his infra (Gitea workflows, Komodo-controlled compose stack behind Traefik). Added: multi-stage `Dockerfile` (node builds the panel, python:3.13-slim serves it), `compose.yaml` (port 9000 published raw for the charger's hardcoded ws:// dial-in, Traefik labels for the panel, env-tunable for Komodo), `.gitea/workflows/build.yml` (build -> 65-check smoke gate -> push to git.infra.msai.al -> HMAC Komodo redeploy, mirroring the polymarket-bot repo). Backend: `BACKEND_EVENTS` override, `GET /api/health`, smoke test promoted into `backend/smoke_test.py`. New page [[deployment]]; updated [[backend]], [[overview]], [[index]]. ⚠️ First runner build pending (no local Docker).
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
type: note
|
||||
updated: 2026-07-11
|
||||
tags: [architecture, decision, plan]
|
||||
---
|
||||
|
||||
# Architecture & Build Plan
|
||||
|
||||
Filed 2026-07-09 from a stack discussion (Flutter? Fastify vs FastAPI? web frontend?). Extends the requirements in [[2026-07-09-findings-and-requirements]] and the roadmap in [[overview]].
|
||||
|
||||
> [!note] Scope expansion (2026-07-11): the backend also controls the household [[wifi-relays|Tuya/SmartLife WiFi relays]] — locally via tinytuya, same process, under `/api/relays/*`. This strengthens the FastAPI/one-process decision: charger + relays + panel behind one NetBird-reachable port.
|
||||
|
||||
## Stack decision
|
||||
|
||||
**Backend: FastAPI (Python) — decided.**
|
||||
|
||||
The deciding constraint: the backend *is* the CSMS. `RemoteStartTransaction`/`RemoteStopTransaction` can only be sent down the live OCPP WebSocket the [[jc-6620|JC-6620]] holds open, so the API server and the OCPP server must share process state. The proven code ([[csms-toolkit]]) is already Python on the `ocpp` library; Fastify would mean rewriting OCPP in Node (immature libraries) or a two-process IPC design. FastAPI hosts everything in one uvicorn process on one port:
|
||||
|
||||
```
|
||||
FastAPI app (uvicorn, :9000, on the always-on host)
|
||||
├── /<chargePointId> OCPP 1.6J WebSocket (catch-all) ← JC-6620 dials in here
|
||||
├── /api/* REST: status, charger start/stop, allowlist CRUD, sessions
|
||||
├── /api/relays/* Tuya relay control (tinytuya, local protocol)
|
||||
├── /api/events journal tail (SSE live push later, for the panel)
|
||||
└── / static PWA (the web panel)
|
||||
```
|
||||
|
||||
(The `ocpp` ChargePoint class only needs send/recv; a FastAPI WebSocket route wraps it. Keep port 9000 so the charger touchscreen URL doesn't change — [[troubleshooting]] #4: changing it needs a power-cycle.)
|
||||
|
||||
**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]].
|
||||
|
||||
> [!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.**
|
||||
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.
|
||||
|
||||
**Storage: SQLite** (single file) for sessions/meter values/seen tags; the allowlist can migrate from `station_config.json` into it once the panel manages it. JSON files were fine for discovery; history queries want a real table. → ✅ implemented 2026-07-11 as `backend/store.py` (`sessions` + `samples` tables); allowlist/users stayed in config.json — right size for a household, revisit only if it grows.
|
||||
|
||||
## Build phases
|
||||
|
||||
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]].
|
||||
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.
|
||||
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.
|
||||
|
||||
Phases 1–3 are pure software and can proceed before the host decision; only phase 4 needs it.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
type: note
|
||||
updated: 2026-07-09
|
||||
tags: [runbook, discovery, hardware-test]
|
||||
---
|
||||
|
||||
# Discovery Test Runbook — Autocharge + RFID Session
|
||||
|
||||
> [!note] Executed 2026-07-09 — all tests done, results in [[authorization]] and [[overview]]
|
||||
> Test A (Autocharge): ❌ negative through all variants incl. `MacEnabled=true` + power-cycle. Test B (RFID): ✅ cards A+B captured & enrolled. Test C (remote start/stop): ✅ both verified. Kept as the template for any future retest (e.g. after a firmware update).
|
||||
|
||||
The physical test session to settle the open [[authorization]] questions. Prereq: `station.py` running (`venv\Scripts\python station.py` in `../discovering/`), learn mode ON, charger `eu092025` connected. Watch at `http://10.0.10.203:9000/status`, `/tags`, or `/docs`.
|
||||
|
||||
## Order matters
|
||||
|
||||
Do the Autocharge test **before** ever tapping a card in this session — the first plug-in is the clean observation.
|
||||
|
||||
## Test A — Autocharge (plug in, no card)
|
||||
|
||||
Connect a gun to a car. Do not tap anything.
|
||||
|
||||
| Observation | Conclusion | Next step |
|
||||
|---|---|---|
|
||||
| New idTag in console / `/tags` | ✅ Autocharge works | Let it charge ~2 min (captures first MeterValues/SoC), stop, whitelist the id as `kind:"car"` |
|
||||
| Connector "Preparing", no idTag | No Autocharge by default | Retry after `POST /setconfig?key=MacEnabled&value=true` (lead from [[2026-07-09-discovery-eu092025]]) |
|
||||
| Nothing | "By vehicle" not supported | Close the open decision in [[overview]] as ❌ |
|
||||
|
||||
## Test B — RFID cards
|
||||
|
||||
Tap each owned card once. Each should log `[LEARN] NEW idTag=...` and appear in `/tags`. **Write down the physical tap order** so the ids can be named in the allowlist.
|
||||
|
||||
## Test C (optional) — remote start
|
||||
|
||||
With a car plugged in: `curl -X POST "http://10.0.10.203:9000/start?connector=1"` — this is exactly what the future web panel will do. Expect `{"remote_start":"Accepted"}` then a `StartTransaction` (note: `AuthorizeRemoteTxRequests=false`, so no separate Authorize).
|
||||
|
||||
## Afterwards
|
||||
|
||||
Feed results back into the wiki (ingest `seen_tags.json` observations), name cards in `station_config.json` → `authorized`, and once all household ids are enrolled: set `learn_mode: false` and restart — the charger is then enforcing.
|
||||
+25
-11
@@ -1,34 +1,48 @@
|
||||
---
|
||||
type: meta
|
||||
updated: 2026-07-09
|
||||
updated: 2026-07-12
|
||||
tags: [synthesis]
|
||||
---
|
||||
|
||||
# Overview — Anfu Home Charger OCPP Project
|
||||
|
||||
**Goal:** a private, self-hosted [[ocpp|OCPP 1.6J]] backend (CSMS) for a home EV charger. No billing, no public charging. Three ways to authorize a charge: existing RFID cards, by vehicle (if the hardware allows — ⚠️ untested), and a mobile-friendly web app reached over [[netbird|NetBird]].
|
||||
**Goal:** a private, self-hosted [[ocpp|OCPP 1.6J]] backend (CSMS) for a home EV charger. No billing, no public charging. Authorization via existing RFID cards ✅ and a mobile-friendly web app reached over [[netbird|NetBird]] (by-vehicle ❌ closed — firmware never forwards a vehicle id). **Scope expanded 2026-07-11:** the same backend also controls the household [[wifi-relays|Tuya/SmartLife WiFi relays]], locally via tinytuya.
|
||||
|
||||
## Current state (2026-07-09)
|
||||
## Current state (2026-07-11)
|
||||
|
||||
**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: discovery-grade.** The [[csms-toolkit]] (`../discovering/`) can accept connections, log frames, and enforce an allowlist with learn mode. It is a tester/foundation, not yet the always-on production service.
|
||||
**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.
|
||||
|
||||
**Authorization: designed, partially built.** All three methods funnel through one gate — `decide(id_tag)` in `station.py`. See [[authorization]] for the plan per method.
|
||||
**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]]).
|
||||
|
||||
**Authorization: 2 of 3 methods ✅ verified live (2026-07-09 test session, both cars plugged, both guns charging simultaneously):**
|
||||
- **RFID** ✅ — card `…393` tapped → Authorize → real charging session on gun 2 (DC, ~26 kW avg, 1.8 kWh delivered). Card enrolled as "RFID card A".
|
||||
- **Remote (app path)** ✅ — RemoteStart and RemoteStop both Accepted and executed on gun 1; `app-remote` token enrolled.
|
||||
- **By vehicle** ❌ **closed** — three escalating tests (plain plug-in, `MacEnabled=true` live, `MacEnabled=true` after power-cycle) all negative; this firmware never forwards a vehicle ID over OCPP ([[authorization]]).
|
||||
|
||||
Hardware surprise: this is a **DC-capable multi-standard charger** (gun 1 EU, gun 2 Chinese GB/T @ 30 kW), not the assumed basic AC unit — see [[anfu-charger]].
|
||||
|
||||
## Milestones reached (2026-07-12)
|
||||
|
||||
- ✅ Live cutover: `eu092025` connects to `python -m backend.main` (2026-07-11 evening)
|
||||
- ✅ **The panel works end-to-end on the owner's phone**: login, and a real in-app remote start on gun 1 of the live charger (2026-07-12 morning, tx 1–2, 141 Wh, attributed who=julian / method=app)
|
||||
- ✅ Six household users created (admin + scoped members)
|
||||
|
||||
## What's next
|
||||
|
||||
1. **RFID enrollment** — tap each card in learn mode, harvest idTags from `seen_tags.json`, add to the allowlist, then flip `learn_mode=false`. (Mechanism already implemented.)
|
||||
2. **Autocharge test** — ⚠️ plug the car in *without* tapping a card; if a stable idTag appears, "by vehicle" works. If not, it's off the table for this hardware. See [[authorization]].
|
||||
3. **Web control panel** — Start/Stop via OCPP `RemoteStartTransaction`/`RemoteStopTransaction`, live status, allowlist management. Served behind NetBird.
|
||||
1. **Extract the Tuya local keys** (`tinytuya wizard` — steps in [[wifi-relays]]) and register them via `PUT /api/relays/<name>` → relays become controllable.
|
||||
2. **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]]). Test: remote-stop, touch nothing for 5 min.
|
||||
3. **Deploy via the new CI/CD pipeline** ([[deployment]], built 2026-07-12): Gitea Actions builds + smoke-tests the Docker image, Komodo runs the compose stack behind Traefik. ⚠️ First runner build pending; set the 4 repo secrets, then decide the Docker host (❓ below) and give it the IP the charger dials.
|
||||
4. Housekeeping: delete the retired `app-remote` allowlist entry from the Cards page; tap the remaining household cards so they pend and can be linked to their owners.
|
||||
|
||||
## Open decisions ❓
|
||||
|
||||
| Decision | Options | Status |
|
||||
|---|---|---|
|
||||
| Always-on host for CSMS + app | LAN PC · the `10.0.10.203` machine · dedicated box (e.g. Pi on charger LAN, joined to NetBird) | open |
|
||||
| Web app auth | NetBird isolation only · also PIN/token | open |
|
||||
| Autocharge | run the plug-in test or skip "by chassis" | open — needs physical test |
|
||||
| Always-on host for CSMS + app | LAN PC · the `10.0.10.203` machine · dedicated box (e.g. Pi on charger LAN, joined to NetBird) | open — must be a **Docker host** now ([[deployment]], 2026-07-12): reachable at the exact IP:9000 the charger dials, on a subnet that reaches the [[wifi-relays|relays]], joined to the Traefik network |
|
||||
| Web app auth | — | ✅ **resolved 2026-07-11**: username+password login with per-resource scopes (gun 1 / gun 2 / per-relay / admin) — see [[authorization]]. Bootstrap: create the first admin user via `python -m backend.users add` |
|
||||
| Autocharge / by vehicle | — | ❌ **closed 2026-07-09**: not supported by this firmware ([[authorization]]) |
|
||||
| Host IP stability | static IP · DHCP reservation | open (required either way — touchscreen URL is hardcoded) |
|
||||
|
||||
## Sources
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
{
|
||||
"charge_point": "eu092025",
|
||||
"probed_at": "2026-07-09T13:49:56.843881+00:00",
|
||||
"boot_info": {
|
||||
"vendor": "SimpleCharge",
|
||||
"model": "MultiSocketCharger",
|
||||
"charge_point_serial_number": "24310588",
|
||||
"firmware_version": "1.24.0620.1",
|
||||
"iccid": "",
|
||||
"imsi": ""
|
||||
},
|
||||
"configuration": [
|
||||
{
|
||||
"key": "AllowOfflineTxForUnknownId",
|
||||
"readonly": false,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "AuthorizationCacheEnabled",
|
||||
"readonly": false,
|
||||
"value": "true"
|
||||
},
|
||||
{
|
||||
"key": "AuthorizeRemoteTxRequests",
|
||||
"readonly": false,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "ClockAlignedDataInterval",
|
||||
"readonly": false,
|
||||
"value": "0"
|
||||
},
|
||||
{
|
||||
"key": "ConnectorPhaseRotationMaxLength",
|
||||
"readonly": true,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "ConnectionTimeOut",
|
||||
"readonly": false,
|
||||
"value": "60"
|
||||
},
|
||||
{
|
||||
"key": "GetConfigurationMaxKeys",
|
||||
"readonly": true,
|
||||
"value": "30"
|
||||
},
|
||||
{
|
||||
"key": "HeartbeatInterval",
|
||||
"readonly": false,
|
||||
"value": "7200"
|
||||
},
|
||||
{
|
||||
"key": "LocalAuthorizeOffline",
|
||||
"readonly": false,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "LocalPreAuthorize",
|
||||
"readonly": false,
|
||||
"value": "0"
|
||||
},
|
||||
{
|
||||
"key": "MaxEnergyOnInvalidId",
|
||||
"readonly": false,
|
||||
"value": "0"
|
||||
},
|
||||
{
|
||||
"key": "MeterValueSampleInterval",
|
||||
"readonly": false,
|
||||
"value": "60"
|
||||
},
|
||||
{
|
||||
"key": "NumberOfConnectors",
|
||||
"readonly": true,
|
||||
"value": "2"
|
||||
},
|
||||
{
|
||||
"key": "ResetRetries",
|
||||
"readonly": false,
|
||||
"value": "0"
|
||||
},
|
||||
{
|
||||
"key": "StopTransactionOnEVSideDisconnect",
|
||||
"readonly": false,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "StopTransactionOnInvalidId",
|
||||
"readonly": false,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "TransactionMessageAttempts",
|
||||
"readonly": false,
|
||||
"value": "50"
|
||||
},
|
||||
{
|
||||
"key": "TransactionMessageRetryInterval",
|
||||
"readonly": false,
|
||||
"value": "60"
|
||||
},
|
||||
{
|
||||
"key": "WebSocketPingInterval",
|
||||
"readonly": false,
|
||||
"value": "60"
|
||||
},
|
||||
{
|
||||
"key": "LocalAuthListEnabled",
|
||||
"readonly": false,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "LocalAuthListMaxLength",
|
||||
"readonly": true,
|
||||
"value": "6"
|
||||
},
|
||||
{
|
||||
"key": "SendLocalListMaxLength",
|
||||
"readonly": true,
|
||||
"value": "6"
|
||||
},
|
||||
{
|
||||
"key": "ChargeProfileMaxStackLevel",
|
||||
"readonly": true,
|
||||
"value": "3"
|
||||
},
|
||||
{
|
||||
"key": "UnlockConnectorOnEVSideDisconnect",
|
||||
"readonly": false,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "SendJCMeterValuesType",
|
||||
"readonly": true,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "ChargingScheduleAllowedChargingRateUnit",
|
||||
"readonly": true,
|
||||
"value": "Power"
|
||||
},
|
||||
{
|
||||
"key": "ChargingScheduleMaxPeriods",
|
||||
"readonly": true,
|
||||
"value": "3"
|
||||
},
|
||||
{
|
||||
"key": "MaxChargingProfilesInstalled",
|
||||
"readonly": true,
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"key": "LocalListVersion",
|
||||
"readonly": true,
|
||||
"value": "-1"
|
||||
},
|
||||
{
|
||||
"key": "MeterValuesAlignedData",
|
||||
"readonly": false,
|
||||
"value": "Energy.Active.Import.Register,Power.Active.Import,SoC,Voltage,Current.Import"
|
||||
},
|
||||
{
|
||||
"key": "MeterValuesSampledData",
|
||||
"readonly": false,
|
||||
"value": "Energy.Active.Import.Register,Power.Active.Import,SoC,Voltage,Current.Import"
|
||||
},
|
||||
{
|
||||
"key": "StopTxnAlignedData",
|
||||
"readonly": false,
|
||||
"value": "SoC"
|
||||
},
|
||||
{
|
||||
"key": "StopTxnSampledData",
|
||||
"readonly": false,
|
||||
"value": "Energy.Active.Import.Register"
|
||||
},
|
||||
{
|
||||
"key": "ConnectorPhaseRotation",
|
||||
"readonly": false,
|
||||
"value": "RST"
|
||||
},
|
||||
{
|
||||
"key": "SupportedFeatureProfiles",
|
||||
"readonly": true,
|
||||
"value": "Core,FirmwareManagement,LocalAuthListManagement,Reservation,SmartCharging,RemoteTrigger"
|
||||
},
|
||||
{
|
||||
"key": "Url",
|
||||
"readonly": false,
|
||||
"value": "http://10.0.10.203:9000"
|
||||
},
|
||||
{
|
||||
"key": "Vendor",
|
||||
"readonly": true,
|
||||
"value": "JC"
|
||||
},
|
||||
{
|
||||
"key": "Model",
|
||||
"readonly": true,
|
||||
"value": "MultiSocketCharger"
|
||||
},
|
||||
{
|
||||
"key": "TimeZone",
|
||||
"readonly": false,
|
||||
"value": "0"
|
||||
},
|
||||
{
|
||||
"key": "ProtocolName",
|
||||
"readonly": true,
|
||||
"value": "ocpp1.6"
|
||||
},
|
||||
{
|
||||
"key": "QRCodeTextOfConnector-1",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "QRCodeTextOfConnector-2",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "QRCodeTextOfConnector-3",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "AuthorizationKey",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "AuthorizationUser",
|
||||
"readonly": true,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "CpoName",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "OutputLimitRate",
|
||||
"readonly": false,
|
||||
"value": "100"
|
||||
},
|
||||
{
|
||||
"key": "PeakPrice",
|
||||
"readonly": false,
|
||||
"value": "1.0000"
|
||||
},
|
||||
{
|
||||
"key": "OffPeakPrice",
|
||||
"readonly": false,
|
||||
"value": "0.5000"
|
||||
},
|
||||
{
|
||||
"key": "IdleFeePerMinute",
|
||||
"readonly": false,
|
||||
"value": "0.0100"
|
||||
},
|
||||
{
|
||||
"key": "IdleTime",
|
||||
"readonly": false,
|
||||
"value": "5"
|
||||
},
|
||||
{
|
||||
"key": "MacEnabled",
|
||||
"readonly": false,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "FreeChargeMode",
|
||||
"readonly": false,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "KeepConnectOTAServer",
|
||||
"readonly": false,
|
||||
"value": "true"
|
||||
},
|
||||
{
|
||||
"key": "DataTransferVendorId",
|
||||
"readonly": false,
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"key": "MeterValuesAlignedDataMaxLength",
|
||||
"readonly": true,
|
||||
"value": "5"
|
||||
},
|
||||
{
|
||||
"key": "MeterValuesSampledDataMaxLength",
|
||||
"readonly": true,
|
||||
"value": "5"
|
||||
},
|
||||
{
|
||||
"key": "StopTxnAlignedDataMaxLength",
|
||||
"readonly": true,
|
||||
"value": "5"
|
||||
},
|
||||
{
|
||||
"key": "StopTxnSampledDataMaxLength",
|
||||
"readonly": true,
|
||||
"value": "5"
|
||||
},
|
||||
{
|
||||
"key": "SupportedFeatureProfilesMaxLength",
|
||||
"readonly": true,
|
||||
"value": "6"
|
||||
},
|
||||
{
|
||||
"key": "ReserveConnectorZeroSupported",
|
||||
"readonly": true,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "ConnectorSwitch3to1PhaseSupported",
|
||||
"readonly": true,
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"key": "ChargePointID",
|
||||
"readonly": false,
|
||||
"value": "eu092025"
|
||||
}
|
||||
],
|
||||
"unknown_keys": null,
|
||||
"trigger_status_notification": "Accepted",
|
||||
"connectors_seen": {
|
||||
"0": "Available",
|
||||
"1": "Available",
|
||||
"2": "Available"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
type: source
|
||||
updated: 2026-07-09
|
||||
ingested: 2026-07-09
|
||||
raw: raw/discovery_eu092025.json
|
||||
tags: [discovery, capabilities, ocpp]
|
||||
---
|
||||
|
||||
# Discovery Probe — Live Capability Dump from "eu092025"
|
||||
|
||||
**Raw source:** [discovery_eu092025.json](../raw/discovery_eu092025.json) — the answer the real charger gave to `GetConfiguration` (all keys) + `TriggerMessage`, captured live on 2026-07-09 by the new auto-interrogation in [[csms-toolkit]]. This replaces guesswork with the charger's own capability sheet.
|
||||
|
||||
## TL;DR
|
||||
|
||||
The pile identifies as **SimpleCharge "MultiSocketCharger"**, serial `24310588`, firmware `1.24.0620.1`, OCPP charge-point ID **`eu092025`**, and it has **two guns** (`NumberOfConnectors=2`; connectors 1 and 2, plus 0 = the whole unit — all reported "Available"). It supports far more than we assumed: **RemoteTrigger ✅ (verified), SmartCharging, Reservation, LocalAuthListManagement, FirmwareManagement**.
|
||||
|
||||
## Key configuration facts
|
||||
|
||||
| Key | Value | Meaning for us |
|
||||
|---|---|---|
|
||||
| `NumberOfConnectors` | **2** | Two guns — the app/UI must be per-connector, not per-charger |
|
||||
| `SupportedFeatureProfiles` | Core, FirmwareManagement, LocalAuthListManagement, Reservation, SmartCharging, RemoteTrigger | RemoteTrigger already verified working ✅ |
|
||||
| `AuthorizeRemoteTxRequests` | `false` | Remote starts skip a separate Authorize — our `decide()` gate still fires at StartTransaction ([[authorization]]) |
|
||||
| `LocalAuthListMaxLength` | **6** | On-charger offline allowlist holds only 6 idTags — enough for a household |
|
||||
| `LocalAuthListEnabled` / `LocalAuthorizeOffline` | `false` / `false` | Offline auth currently off; charger is fully CSMS-dependent when offline |
|
||||
| `MeterValueSampleInterval` | 60 s | Live data every minute during charging |
|
||||
| `MeterValuesSampledData` | Energy, **Power**, **SoC**, Voltage, Current | Rich live telemetry — even state-of-charge — for the web panel |
|
||||
| `HeartbeatInterval` / `WebSocketPingInterval` | 7200 s / 60 s | Liveness comes from WS pings, not heartbeats |
|
||||
| `ConnectionTimeOut` | 60 s | A remote start waits 60 s for a plug-in before expiring |
|
||||
| `MacEnabled` | `false` | ❓ Suggestive lead for [[authorization|"by vehicle"]] — possibly MAC-based vehicle recognition; worth flipping during the Autocharge test |
|
||||
| `FreeChargeMode` | `false` | Exists — a "just charge, no auth" escape hatch if we ever want it |
|
||||
| `Url` | `http://10.0.10.203:9000` | Confirms this PC is the configured CSMS host |
|
||||
| Pricing keys (`PeakPrice`, `IdleFeePerMinute`, …) | set | Vendor billing leftovers; irrelevant for private use |
|
||||
|
||||
Also present: `QRCodeTextOfConnector-1..3` (writable, empty), `ChargingScheduleAllowedChargingRateUnit=Power` with max 3 schedule periods and 1 installed profile (SmartCharging is real but small), `ReserveConnectorZeroSupported=false`.
|
||||
|
||||
## Boot identity (via TriggerMessage(BootNotification))
|
||||
|
||||
`vendor=SimpleCharge, model=MultiSocketCharger, serial=24310588, firmware=1.24.0620.1` — note `GetConfiguration` reports `Vendor=JC` (the [[jc-6620|JC-6620]] module vendor) while BootNotification says SimpleCharge (the charger brand).
|
||||
|
||||
## Wiki changes from this ingest
|
||||
|
||||
Updated [[anfu-charger]] (identity + capabilities), [[authorization]] (remote-auth behavior, LocalAuthList, MacEnabled lead), [[csms-toolkit]] (discovery API), [[overview]].
|
||||
Reference in New Issue
Block a user