Compare commits

..

3 Commits

Author SHA1 Message Date
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
13 changed files with 600 additions and 5 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`. - **`frontend/`** — the React control panel (Vite + TypeScript + React Router + zustand + TanStack Query). Dev: `npm run dev` (proxies `/api` to :9000). Prod: `npm run build` → `frontend/dist/`, served statically by the backend. Documented at `wiki/entities/frontend.md`.
- **`wiki/`** — an LLM-maintained knowledge base about the Anfu home charger OCPP integration. **Read `wiki/CLAUDE.md` before touching anything in it** — it defines the schema, conventions, and ingest/query/lint workflows. `wiki/raw/` is immutable source material; never edit it. - **`wiki/`** — an LLM-maintained knowledge base about the Anfu home charger OCPP integration. **Read `wiki/CLAUDE.md` before touching anything in it** — it defines the schema, conventions, and ingest/query/lint workflows. `wiki/raw/` is immutable source material; never edit it.
- **`discovering/`** — throwaway-ish Python scripts used during discovery (`csms.py`, `rawlisten.py`, `station.py`). Superseded by `backend/` for production; kept as diagnostics. Documented at `wiki/entities/csms-toolkit.md`. - **`discovering/`** — throwaway-ish Python scripts used during discovery (`csms.py`, `rawlisten.py`, `station.py`). Superseded by `backend/` for production; kept as diagnostics. Documented at `wiki/entities/csms-toolkit.md`.
Deployment: `Dockerfile` (node builds the panel, python serves it) + `compose.yaml` (Komodo stack, Traefik labels, raw :9000 for the charger) + `.gitea/workflows/build.yml` (build → smoke gate → push to `git.infra.msai.al` → Komodo redeploy). Documented at `wiki/entities/deployment.md`. Smoke test: `venv\Scripts\python -m backend.smoke_test` (65 checks, isolated temp DB — safe to run anytime).
+58
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"]
+4 -1
View File
@@ -5,12 +5,15 @@ raw ground truth behind the queryable store (store.py).
import json import json
import logging import logging
import os
from datetime import datetime, timezone from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from typing import Optional from typing import Optional
HERE = Path(__file__).resolve().parent HERE = Path(__file__).resolve().parent
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") log = logging.getLogger("journal")
+7
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 ---- # ---- login / identity ----
class LoginBody(BaseModel): class LoginBody(BaseModel):
username: str username: str
+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})")
+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=${ARTIOT_CERTRESOLVER:-letsencrypt}
- traefik.http.services.artiot.loadbalancer.server.port=9000
volumes:
artiot-data:
name: artiot-data
networks:
traefik-net:
external: true
name: ${TRAEFIK_NETWORK:-traefik}
+2 -1
View File
@@ -51,7 +51,8 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
- Relay calls are blocking tinytuya I/O, run via `asyncio.to_thread` so the OCPP socket never stalls. - Relay calls are blocking tinytuya I/O, run via `asyncio.to_thread` so the OCPP socket never stalls.
- Venv at repo root (`../venv/`, Python 3.13); deps pinned in `backend/requirements.txt` (fastapi, uvicorn, websockets, ocpp, tinytuya) — the auth system added none. - Venv at repo root (`../venv/`, Python 3.13); deps pinned in `backend/requirements.txt` (fastapi, uvicorn, websockets, ocpp, tinytuya) — the auth system added none.
- 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). - 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. - ✅ **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 ## 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).
+2 -1
View File
@@ -1,6 +1,6 @@
--- ---
type: meta type: meta
updated: 2026-07-11 updated: 2026-07-12
tags: [index] 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 - [[frontend]] — the React control panel in `../frontend/`: Vite/TS, React Router, zustand, TanStack Query; served by the backend
- [[csms-toolkit]] — the Python CSMS scripts in `../discovering/`; discovery/diagnostic tooling (production role superseded by [[backend]]) - [[csms-toolkit]] — the Python CSMS scripts in `../discovering/`; discovery/diagnostic tooling (production role superseded by [[backend]])
- [[wifi-relays]] — the Tuya/SmartLife WiFi relays; local tinytuya control path + key-extraction steps - [[wifi-relays]] — the Tuya/SmartLife WiFi relays; local tinytuya control path + key-extraction steps
- [[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 - [[netbird]] — the private overlay network; security boundary for the future web panel
## Concepts ## Concepts
+4
View File
@@ -103,3 +103,7 @@ Owner: "why do we need this app token of X? We just need the user." Agreed — d
## [2026-07-12] lint | Session wrap-up: milestones + gaps from today filed ## [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]]. 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).
+2 -2
View File
@@ -33,14 +33,14 @@ Hardware surprise: this is a **DC-capable multi-standard charger** (gun 1 EU, gu
1. **Extract the Tuya local keys** (`tinytuya wizard` — steps in [[wifi-relays]]) and register them via `PUT /api/relays/<name>` → relays become controllable. 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. 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 as an always-on service** ([[architecture-plan]] phase 4) — decide the host (❓ below), run under NSSM/systemd, DHCP reservation. 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. 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 ❓ ## Open decisions ❓
| Decision | Options | Status | | 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` | | 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]]) | | 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) | | Host IP stability | static IP · DHCP reservation | open (required either way — touchscreen URL is hardcoded) |