Compare commits

...

14 Commits

Author SHA1 Message Date
julian 272a6ad97d feat(frontend): user-switchable light/dark theme
Build Art IoT image / build-and-publish (push) Successful in 21s
- dark tokens move from prefers-color-scheme to :root[data-theme="dark"];
  light is the default for everyone regardless of OS preference
- choice persisted in localStorage (artiot-theme), applied to <html> at
  module load so the login screen themes before first paint
- Account page gains an Appearance section with a squared slide switch;
  meta theme-color follows the active theme
2026-07-18 10:00:12 +02:00
julian 96ea568e53 style(frontend): Chakra Petch instrument-panel restyle + real mobile layout
Build Art IoT image / build-and-publish (push) Successful in 43s
- Chakra Petch replaces Archivo for all UI type (Plex Mono demoted to data:
  ids, timestamps, tabular numbers); brand set in 700 italic caps
- every corner squared; signature chamfer cut (echoing the typeface) on gun
  bays, login plate and solid buttons; lamps stay round (physical lamps)
- phones: nav becomes a fixed bottom tab bar with safe-area padding, tables
  collapse into labeled stacked rows (data-label), bigger touch targets
- desktop nav as underline tabs; inline styles in Account moved to classes
2026-07-18 09:05:12 +02:00
julian 9eaacf5eeb fix(deploy): update Traefik cert resolver from 'acme' to 'le' in compose.yaml
Build Art IoT image / build-and-publish (push) Successful in 14s
2026-07-17 19:52:31 +02:00
julian d7264a758a fix(deploy): correct formatting of Traefik cert resolver in compose.yaml
Build Art IoT image / build-and-publish (push) Successful in 14s
2026-07-17 19:50:58 +02:00
julian dbc4a477cb fix(deploy): update Traefik cert resolver to use 'acme' for TLS configuration
Build Art IoT image / build-and-publish (push) Successful in 14s
2026-07-17 19:49:07 +02:00
julian 086b799158 docs(wiki): deployment entity page — Docker/Gitea CI/Komodo/Traefik; CLAUDE.md deploy pointers
Build Art IoT image / build-and-publish (push) Successful in 16s
2026-07-12 10:32:57 +02:00
julian 268bed5d92 feat(deploy): Docker image + Komodo compose stack + Gitea CI pipeline
- Dockerfile: node:24-alpine builds frontend/dist, python:3.13-slim runs
  backend.main as uid 1000 under tini; state on /data via env overrides
- compose.yaml: raw 9000:9000 for the charger's hardcoded ws:// dial-in,
  Traefik labels for the panel, everything Komodo-tunable (ARTIOT_TAG/HOST,
  TRAEFIK_NETWORK, entrypoint, certresolver), curl healthcheck
- .gitea/workflows/build.yml: build -> 65-check smoke gate in the image ->
  push :main + :sha to git.infra.msai.al/art/charging_station -> HMAC-signed
  Komodo stack redeploy (polymarket-bot pattern; same secret names)
2026-07-12 10:32:47 +02:00
julian 5f33eedbb1 feat(backend): container readiness — BACKEND_EVENTS override, GET /api/health, smoke test in-repo
- journal.py: events.jsonl path overridable via BACKEND_EVENTS (mirrors
  BACKEND_DB) so containers journal onto the data volume
- routes.py: unauthenticated GET /api/health for Docker/Traefik/Komodo probes
- backend/smoke_test.py: the 65-check suite promoted from the scratchpad;
  temp-dir DB + journal, runs anywhere via python -m backend.smoke_test
2026-07-12 10:32:37 +02:00
julian 12db2e719d docs(wiki): session wrap-up — panel verified live, milestones, ops gotchas, next steps trimmed 2026-07-12 10:13:36 +02:00
julian d285a32829 chore(frontend): drop the 'what may authorize' subtitle for good; rebuild 2026-07-12 10:01:25 +02:00
julian 11e467a576 fix(backend): cache headers for the SPA — no-cache index.html, immutable hashed assets
Phones kept showing stale builds because index.html was served without
cache headers; assets/* are content-hashed and safe to cache forever.
2026-07-12 09:54:51 +02:00
julian a9b8436f2c refactor(backend): user app idTags validated against the user record, not the allowlist
'app token of <name>' synthetic allowlist entries are gone: decide()
recognizes a user's personal idTag directly, enforces the user's own
charger:<cp>:<gun> scopes at the charger-side gate, and attributes the
session (who=user, method=app). charger_start no longer auto-enrolls;
PUT /api/allowlist/<user-tag> returns 400; stale entries auto-drop at
startup. Zero-user open mode still authorizes 'app-remote' for
bootstrap. Smoke: 63 checks.
2026-07-12 09:50:27 +02:00
julian 25fa1f9fc5 feat: live telemetry on gun cards — SoC battery gauge, kW, V, A, delivered kWh
- backend keeps the latest meter sample per active transaction in memory
  and ships it as active_transactions[tx].telemetry on /api/status
  (Transaction.Begin snapshots skipped: taken before the BMS is read)
- Battery component: fill + color sweep red (empty) -> blue (half) ->
  green (full) per the owner's spec; aria meter semantics
- charging bays show the gauge, a prominent kW readout, and delivered
  kWh / voltage / current rows; hint while awaiting the first sample
- smoke: 60 checks (telemetry rides /api/status)
2026-07-12 09:39:05 +02:00
julian 8d8affe6ff feat(backend): capture voltage, current and sample context in meter samples
The charger sends Voltage/Current.Import in every MeterValues frame but
we only stored energy/power/SoC. samples now also record voltage_v,
current_a and the OCPP context (Sample.Periodic vs Transaction.Begin/End
snapshots, which are legitimately all-zero). Existing dbs migrate via
ALTER TABLE on open.
2026-07-12 09:32:32 +02:00
34 changed files with 1135 additions and 178 deletions
+20
View File
@@ -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__/
+95
View File
@@ -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"
+2
View File
@@ -6,3 +6,5 @@ Four parts:
- **`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 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
View File
@@ -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"]
+6
View File
@@ -54,6 +54,12 @@ def _load() -> dict:
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
+51 -7
View File
@@ -26,7 +26,7 @@ from ocpp.v16.enums import (
RegistrationStatus,
)
from . import store
from . import store, users
from .config import CONFIG, HERE, save
from .journal import now, record_event
@@ -68,11 +68,16 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
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"]):
@@ -83,6 +88,20 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
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
@@ -98,6 +117,14 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
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."""
@@ -151,9 +178,15 @@ class ChargePoint(OcppChargePoint):
_tx_counter["n"] += 1
tx = _tx_counter["n"]
who = resolve_who(id_tag)
# audit: HOW was this session authorized? kind of the allowlist
# entry -> "card" (physical tap) or "app" (in-app button press)
method = CONFIG["authorized"].get(id_tag, {}).get("kind", "unknown")
# 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,
@@ -192,10 +225,11 @@ class ChargePoint(OcppChargePoint):
tx = kwargs.get("transaction_id")
if tx is not None:
for entry in meter_value or []:
reading = {}
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):
@@ -207,10 +241,20 @@ class ChargePoint(OcppChargePoint):
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()),
reading.get("energy_wh"), reading.get("power_w"),
reading.get("soc"))
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()
+4 -1
View File
@@ -5,12 +5,15 @@ 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
EVENTS_PATH = HERE / "events.jsonl"
# 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")
+6 -2
View File
@@ -52,8 +52,12 @@ async def spa(full_path: str):
)
candidate = (DIST / full_path).resolve() if full_path else None
if candidate and candidate.is_file() and candidate.is_relative_to(DIST.resolve()):
return FileResponse(candidate)
return FileResponse(DIST / "index.html")
# 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>).
+12 -4
View File
@@ -71,6 +71,13 @@ def _visible_relays(user: dict) -> dict:
}
# ---- 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
@@ -159,11 +166,9 @@ 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
# 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']}"
if id_tag not in CONFIG["authorized"]:
CONFIG["authorized"][id_tag] = {"name": f"app token of {user['name']}", "kind": "app"}
save()
status = await _ocpp(csms.remote_start(target.id, id_tag, connector))
return {"remote_start": status, "id_tag": id_tag}
@@ -272,6 +277,9 @@ async def allowlist_put(id_tag: str, entry: AllowlistEntry,
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)
+305
View File
@@ -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})")
+16 -6
View File
@@ -51,7 +51,10 @@ CREATE TABLE IF NOT EXISTS samples (
time TEXT NOT NULL,
energy_wh REAL,
power_w REAL,
soc 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);
@@ -64,10 +67,14 @@ def _db():
con = sqlite3.connect(DB_PATH)
con.row_factory = sqlite3.Row
con.executescript(_SCHEMA)
# migration for dbs created before the audit column existed
# 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)
@@ -114,12 +121,15 @@ def end_session(tx: int, ended: str, meter_stop: float,
)
def add_sample(tx: int, time: str, energy_wh: Optional[float],
power_w: Optional[float], soc: Optional[float]) -> None:
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) VALUES (?, ?, ?, ?, ?)",
(tx, time, energy_wh, power_w, soc),
"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),
)
+62
View File
@@ -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}
+1 -1
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#171d1b" />
<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>
+5 -5
View File
@@ -8,7 +8,7 @@
"name": "charging-station-panel",
"version": "1.0.0",
"dependencies": {
"@fontsource/archivo": "^5.1.0",
"@fontsource/chakra-petch": "^5.1.0",
"@fontsource/ibm-plex-mono": "^5.1.0",
"@tanstack/react-query": "^5.62.0",
"react": "^19.0.0",
@@ -748,10 +748,10 @@
"node": ">=18"
}
},
"node_modules/@fontsource/archivo": {
"version": "5.2.8",
"resolved": "https://registry.npmjs.org/@fontsource/archivo/-/archivo-5.2.8.tgz",
"integrity": "sha512-Fc4yuMt85MmcYooUVpYHAJRJTymPv2+J9HsMP2f5mxR/0pIWgE2V5XfgNTavPpklX2rJFprdT36iE6Rr8ds9MA==",
"node_modules/@fontsource/chakra-petch": {
"version": "5.2.7",
"resolved": "https://registry.npmjs.org/@fontsource/chakra-petch/-/chakra-petch-5.2.7.tgz",
"integrity": "sha512-GLbun5WZJNAEc8FtWxwcgo+4Kurqdwejvf671l+YfIjyQgPvTjyxXYP7Ffg2HAY89NGnp3oOvKQjRzfm/fBECw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
+1 -1
View File
@@ -9,7 +9,7 @@
"preview": "vite preview"
},
"dependencies": {
"@fontsource/archivo": "^5.1.0",
"@fontsource/chakra-petch": "^5.1.0",
"@fontsource/ibm-plex-mono": "^5.1.0",
"@tanstack/react-query": "^5.62.0",
"react": "^19.0.0",
+41
View File
@@ -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>
);
}
+5 -4
View File
@@ -3,10 +3,11 @@ import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App";
import "@fontsource/archivo/400.css";
import "@fontsource/archivo/500.css";
import "@fontsource/archivo/600.css";
import "@fontsource/archivo/700.css";
import "@fontsource/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";
+32 -6
View File
@@ -12,12 +12,12 @@ function MyPermissions() {
if (isAdmin(me.scopes)) {
return (
<section className="panel" style={{ maxWidth: 440 }}>
<section className="panel panel--narrow">
<header className="panel__head">
<h2>Your permissions</h2>
</header>
<span className="chip chip--card">Administrator</span>
<p className="dim" style={{ marginTop: 8, fontSize: 14 }}>
<p className="panel__note">
Full access: both guns, all relays, cards, users and history of everyone.
</p>
</section>
@@ -32,12 +32,12 @@ function MyPermissions() {
const relays = Object.values(status?.relays ?? {}).map((r) => r.label);
return (
<section className="panel" style={{ maxWidth: 440 }}>
<section className="panel panel--narrow">
<header className="panel__head">
<h2>Your permissions</h2>
</header>
{guns.length + relays.length === 0 ? (
<p className="dim" style={{ fontSize: 14 }}>
<p className="panel__note">
No device permissions yet — ask an admin to grant you a gun or a relay.
</p>
) : (
@@ -54,13 +54,38 @@ function MyPermissions() {
))}
</ul>
)}
<p className="dim" style={{ marginTop: 8, fontSize: 13 }}>
<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);
@@ -91,8 +116,9 @@ export default function Account() {
return (
<>
<AppearanceSection />
<MyPermissions />
<section className="panel" style={{ maxWidth: 440 }}>
<section className="panel panel--narrow">
<header className="panel__head">
<h2>Account</h2>
<span className="panel__meta mono">{me.name}</span>
+6 -7
View File
@@ -218,7 +218,6 @@ function AuthorizedSection() {
<section className="panel">
<header className="panel__head">
<h2>Enrolled cards &amp; tokens</h2>
<span className="panel__meta">what may authorize a charge, and who it belongs to</span>
</header>
{!entries.length && <p className="empty">Nothing enrolled yet.</p>}
<div className="table-wrap">
@@ -226,16 +225,16 @@ function AuthorizedSection() {
<tbody>
{entries.map(([tag, entry]) => (
<tr key={tag}>
<td className="mono">{tag}</td>
<td className="strong">{entry.name}</td>
<td>
<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>{entry.user ?? <span className="dim">unassigned</span>}</td>
<td className="dim">{entry.guns?.join(", ") ?? "all guns"}</td>
<td className="num">
<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>
+54 -13
View File
@@ -1,4 +1,5 @@
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";
@@ -127,20 +128,60 @@ function GunBay({ gun, scopes }: { gun: Gun; scopes: string[] }) {
</div>
{gun.tx && (
<dl className="bay__telemetry">
<div>
<dt>By</dt>
<dd>{gun.tx.who || gun.tx.id_tag}</dd>
<>
<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>
<div>
<dt>Via</dt>
<dd>{gun.tx.method === "app" ? "In-app" : gun.tx.method === "card" ? "Card" : gun.tx.method}</dd>
</div>
<div>
<dt>Running</dt>
<dd>{fmtSince(gun.tx.started)}</dd>
</div>
</dl>
<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">
+7 -7
View File
@@ -36,7 +36,7 @@ export default function History() {
<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 of yours yet. Sessions you start — by card or in-app — appear here."}
: "No charging sessions yet. Sessions you start — by card or in-app — appear here."}
</p>
);
@@ -66,20 +66,20 @@ export default function History() {
<tbody>
{sessions.map((s) => (
<tr key={s.tx}>
<td className="strong">{s.who || s.id_tag}</td>
<td>
<td className="strong" data-label="Who">{s.who || s.id_tag}</td>
<td data-label="Via">
<MethodChip method={s.method} />
</td>
<td>{gunLabel(s, status?.chargers ?? {})}</td>
<td className="mono">{fmtTime(s.started)}</td>
<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">{fmtKwh(s.wh)}</td>
<td className="num mono strong" data-label="kWh">{fmtKwh(s.wh)}</td>
</tr>
))}
</tbody>
+1 -1
View File
@@ -243,7 +243,7 @@ export default function Users() {
<tr key={u.name}>
<td className="strong">{u.name}</td>
<td className="dim">{describeScopes(u.scopes, catalog)}</td>
<td className="num">
<td className="num table__actions">
<button className="btn btn--ghost btn--sm" onClick={() => setEditing(u)}>
Edit
</button>
+24
View File
@@ -1,11 +1,29 @@
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;
@@ -17,6 +35,12 @@ 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;
+227 -93
View File
@@ -1,8 +1,12 @@
/* ============================================================
Art IoT — instrument-panel design system
Art IoT — instrument-panel design system, mk II
Surfaces like enameled switchgear, copper-busbar accent,
indicator lamps as the signature element.
Type: Archivo (UI) + IBM Plex Mono (telemetry & identifiers).
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 {
@@ -20,57 +24,63 @@
--red: #bf3527;
--lamp-off: #c4ccc8;
--shadow: 0 1px 2px rgb(29 37 35 / 0.06), 0 4px 16px rgb(29 37 35 / 0.05);
--radius: 10px;
--font-ui: "Archivo", "Segoe UI", system-ui, sans-serif;
--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;
}
@media (prefers-color-scheme: dark) {
:root {
--paper: #131816;
--panel: #1b211f;
--panel-inset: #161c1a;
--ink: #e4e9e7;
--ink-dim: #93a09b;
--line: #2c3531;
--copper: #d07a3e;
--copper-deep: #b25c28;
--live: #2fae7c;
--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);
}
/* 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 dark; }
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: 15.5px;
font-size: 15px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
button, input, select { font: inherit; color: inherit; }
button, input, select { font: inherit; color: inherit; border-radius: 0; }
:focus-visible {
outline: 2px solid var(--copper);
outline-offset: 2px;
border-radius: 4px;
}
.mono { font-family: var(--font-mono); font-size: 0.92em; }
.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) ---------- */
/* ---------- 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;
@@ -116,45 +126,53 @@ button, input, select { font: inherit; color: inherit; }
.shell { min-height: 100dvh; display: flex; flex-direction: column; }
.topbar {
display: flex; align-items: center; gap: 20px;
padding: 10px clamp(14px, 4vw, 32px);
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; }
.brand__mark { width: 30px; height: 30px; }
.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; letter-spacing: 0.01em; line-height: 1.15; }
.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-family: var(--font-mono); font-size: 10.5px;
text-transform: uppercase; letter-spacing: 0.14em; color: var(--ink-dim);
display: block; font: var(--label); font-size: 10px;
text-transform: uppercase; letter-spacing: 0.16em; color: var(--ink-dim);
}
.nav { display: flex; gap: 4px; flex: 1; overflow-x: auto; }
/* 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: 7px 13px;
border-radius: 8px;
padding: 0 14px;
color: var(--ink-dim);
text-decoration: none;
font-weight: 500;
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); background: color-mix(in srgb, var(--copper) 12%, transparent); font-weight: 600; }
.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;
border-radius: 999px; padding: 1px 7px;
padding: 1px 6px;
}
.topbar__user { display: flex; align-items: center; gap: 10px; }
.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; border-radius: 6px;
text-decoration: none; padding: 4px 8px;
}
.topbar__who:hover { color: var(--ink); background: var(--panel-inset); }
.topbar__who.active { color: var(--copper-deep); }
@@ -164,8 +182,8 @@ button, input, select { font: inherit; color: inherit; }
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));
border-radius: var(--radius);
color: var(--ink);
text-decoration: none;
font-weight: 500;
@@ -196,92 +214,136 @@ button, input, select { font: inherit; color: inherit; }
width: min(380px, 100%);
background: var(--panel);
border: 1px solid var(--line);
border-radius: 14px;
box-shadow: var(--shadow);
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: 22px; font-weight: 700; letter-spacing: -0.01em; }
.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);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 18px 20px;
}
.panel--attention { border-color: color-mix(in srgb, var(--amber) 50%, var(--line)); }
.panel--offline { display: flex; gap: 14px; align-items: center; }
.panel--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: 16px; font-weight: 700; display: flex; align-items: center; gap: 9px; }
.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);
border-radius: 8px;
}
.panel__inset h3 { font-size: 14px; margin-bottom: 10px; }
.bays {
display: grid; gap: 18px;
grid-template-columns: repeat(auto-fit, minmax(290px, 1fr));
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-radius: var(--radius);
box-shadow: var(--shadow);
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;
border-top: 3px solid var(--copper);
}
.bay__head { display: flex; justify-content: space-between; align-items: center; }
.bay__head .lamp { margin-right: 14px; } /* clear of the chamfer */
.bay__eyebrow {
font-family: var(--font-mono); font-size: 11px;
text-transform: uppercase; letter-spacing: 0.14em; color: var(--ink-dim);
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; }
.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__telemetry {
display: flex; gap: 22px;
padding: 10px 12px;
.bay__charge {
display: flex; align-items: center; justify-content: space-between; gap: 14px;
padding: 12px 14px;
background: var(--panel-inset);
border-radius: 8px;
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-family: var(--font-mono); font-size: 10.5px;
text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-dim);
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; }
.bay__telemetry dd { font-weight: 600; font-size: 14px; white-space: nowrap; }
.bay__actions { display: flex; align-items: center; gap: 12px; margin-top: 2px; }
.bay__actions { display: flex; align-items: center; gap: 12px; margin-top: 2px; flex-wrap: wrap; }
/* ---------- chips ---------- */
.chip {
display: inline-block;
font-family: var(--font-mono); font-size: 11.5px; font-weight: 600;
text-transform: uppercase; letter-spacing: 0.07em;
padding: 3px 9px; border-radius: 999px;
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--idle { /* the quiet gray default */ }
.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); }
@@ -290,49 +352,79 @@ button, input, select { font: inherit; color: inherit; }
/* ---------- buttons ---------- */
.btn {
border: 1px solid transparent;
border-radius: 8px;
padding: 9px 18px;
font-weight: 600;
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); }
.btn--sm { padding: 5px 12px; font-size: 13.5px; }
.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-family: var(--font-mono); font-size: 11px;
text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-dim);
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);
border-radius: 8px;
padding: 9px 12px;
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(200px, 1fr)); margin-bottom: 12px; }
.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; }
.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; }
.cardform__actions { display: flex; gap: 10px; flex-wrap: wrap; }
.gunpicker, .matrix { display: flex; flex-direction: column; gap: 6px; }
@@ -345,18 +437,19 @@ button, input, select { font: inherit; color: inherit; }
.table { width: 100%; border-collapse: collapse; font-size: 14px; }
.table th {
text-align: left; padding: 8px 10px;
font-family: var(--font-mono); font-size: 10.5px;
text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-dim);
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: 10px 2px; border-bottom: 1px solid var(--line);
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; }
@@ -376,15 +469,56 @@ button, input, select { font: inherit; color: inherit; }
}
.toast {
background: var(--ink); color: var(--paper);
border-radius: 9px; padding: 11px 16px;
border-left: 3px solid var(--copper);
padding: 11px 16px;
font-size: 14px; box-shadow: var(--shadow);
}
.toast--error { background: var(--red); color: #fff; }
.toast--error { background: var(--red); border-left-color: color-mix(in srgb, var(--red) 55%, black); color: #fff; }
/* ---------- responsive ---------- */
/* ---------- responsive: the phone is the primary panel ---------- */
@media (max-width: 640px) {
.topbar { flex-wrap: wrap; row-gap: 6px; }
.nav { order: 3; width: 100%; }
.bay__telemetry { flex-wrap: wrap; gap: 12px 20px; }
.content { padding-top: 14px; }
.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; }
}
+10
View File
@@ -4,6 +4,15 @@ export interface Me {
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;
@@ -12,6 +21,7 @@ export interface ActiveTx {
method: string;
meter_start: number;
started: string;
telemetry?: Telemetry;
}
export interface ChargerMeta {
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/app.tsx","./src/api.ts","./src/main.tsx","./src/queries.ts","./src/store.ts","./src/types.ts","./src/components/lamp.tsx","./src/components/layout.tsx","./src/pages/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"}
{"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"}
+1
View File
@@ -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"}]}]}]
+3 -3
View File
@@ -40,9 +40,9 @@ Exhaustively tested on the real hardware; the charger never forwards any vehicle
**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 — ✅ control path verified live (2026-07-09)
## 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 `app-remote` idTag is enrolled in the allowlist as `kind:"app"`. What remains is only the UI:
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):
@@ -56,7 +56,7 @@ A mobile-friendly web control panel (no app store):
The [[backend]] now has real multi-user authorization on top of the three methods above, because not every household member may control everything. Requirement (owner, 2026-07-11): some users control gun 1 only, some gun 2, some only certain [[wifi-relays|relays]].
- **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**.
- **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):
+7 -3
View File
@@ -1,6 +1,6 @@
---
type: entity
updated: 2026-07-11
updated: 2026-07-12
tags: [software, csms, backend, relays, auth]
---
@@ -43,12 +43,16 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
- 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>`, auto-enrolled) → per-person session attribution.
- 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 2026-07-11 (54 checks, isolated temp db via the `BACKEND_DB` env override): REST surface, allowlist CRUD incl. gun-restricted cards, login/sessions/scopes, user/relay/charger CRUD, the full consumption pipeline (start → meter sample → stop → kWh → visibility filtering), static panel serving, and a fake charge point over the real WS route.
- ✅ 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
+37
View File
@@ -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).
+5 -4
View File
@@ -1,24 +1,25 @@
---
type: entity
updated: 2026-07-11
updated: 2026-07-12
tags: [software, frontend, react]
---
# Frontend (`../frontend/`)
The React control panel (built 2026-07-11, replacing the single-file vanilla-JS panel at the owner's request). Stack per the owner's spec: **Vite + TypeScript + React 19, React Router 7 (routing), zustand (auth/UI state), TanStack Query 5 (server state, polling)**.
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. ~94 kB gzipped JS.
- 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** gun readiness; live session shows who/via/duration; relay toggles with on-demand live read |
| `/` (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 |
+2 -1
View File
@@ -1,6 +1,6 @@
---
type: meta
updated: 2026-07-11
updated: 2026-07-12
tags: [index]
---
@@ -20,6 +20,7 @@ Catalog of every wiki page. Updated on every ingest. (Schema/conventions live in
- [[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
+16
View File
@@ -91,3 +91,19 @@ Owner confirmed the React panel loads on the phone after backend restart. Change
## [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).
+12 -8
View File
@@ -1,6 +1,6 @@
---
type: meta
updated: 2026-07-11
updated: 2026-07-12
tags: [synthesis]
---
@@ -23,20 +23,24 @@ tags: [synthesis]
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. ~~Cut the live charger over to the backend~~ — ✅ done 2026-07-11 evening: `eu092025` connects to `python -m backend.main` (verified in events.jsonl). Remaining: a card tap + a panel button-push on the live charger.
2. **Create the real users** — `python -m backend.users add <name> --scopes ...` for each household member (the API stays open until the first user exists).
3. **Extract the Tuya local keys** (`tinytuya wizard` — steps in [[wifi-relays]]) and register them via `PUT /api/relays/<name>` → relays become controllable.
4. **Restart the backend once** to pick up the React panel + pending-card workflow (state changes never need restarts; code updates do).
5. **Test the panel from a phone** — `http://<host>:9000/`; verify login, a real button-push start on a ready gun, the pending-card banner (tap an unenrolled card), and add-to-home-screen over [[netbird|NetBird]].
6. **Resolve the ❓ remote-stop restart question** — did the gun-2 session auto-restart from auth cache after RemoteStop, or was the card re-tapped? Affects the app's Stop button UX ([[authorization]]).
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 — now also needs subnet reachability to the [[wifi-relays|relays]] for local Tuya control |
| 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) |