Compare commits

...

3 Commits

Author SHA1 Message Date
julian 3326c8d16c docs(wiki): discovery results, architecture, auth model, backend + relay pages
Ingests the 2026-07-09 live session (source page + raw GetConfiguration
dump): charger identified as SimpleCharge MultiSocketCharger, 60 kW DC
dual-standard (gun 1 EU/CCS, gun 2 GB/T); RFID and remote start/stop
verified; by-vehicle auth closed as not supported (three escalating tests
incl. MacEnabled=true after power-cycle); touchscreen-shows-VIN observation
with the DataTransferVendorId long-shot lead.

Adds/updates: architecture plan (FastAPI + PWA, phases 1-3 done), backend
entity, wifi-relays entity (Tuya local-control path + key extraction steps),
authorization concept (API user/scope model, per-gun cards), overview,
runbook, index, log.
2026-07-11 18:58:20 +02:00
julian d7b17d9cb2 feat(backend): production backend — CSMS, multi-user auth, relays, session store, web panel
One FastAPI process on port 9000 (the charger's hardcoded URL), replacing
discovering/station.py for production:

- csms.py: OCPP 1.6J handlers ported from the proven discovery code; the
  decide() gate now supports per-gun RFID restriction ("connectors": [2])
  enforced at StartTransaction
- users.py: username/password auth (PBKDF2), stateless HMAC sessions
  (cookie + bearer, 30 days), fnmatch permission scopes
  (charger:<cp>:<gun>, relay:<name>, admin) and a user CLI
- relays.py: local tinytuya control of the SmartLife/Tuya WiFi relays
  (no cloud; needs one-time id/local-key extraction via tinytuya wizard)
- store.py: SQLite consumption tracking — who charged, when, how many kWh,
  per-minute energy/power/SoC samples; tx ids survive restarts
- routes.py: /api/* with per-scope checks, allowlist/user CRUD, runtime
  learn-mode flip, session history with visibility rules
- static/: self-contained vanilla-JS PWA — login, per-gun start/stop gated
  by scope + gun readiness, relay toggles, history, admin tab

config.json (password hashes, session secret, Tuya keys) and sessions.db
are gitignored; config.example.json documents the shape. Covered by a
37-check smoke test incl. a fake charge point over the real WS route.
2026-07-11 18:58:09 +02:00
julian 5c88e8fa3c feat(discovering): single-process CSMS on :9000 with discovery API + live session captures
station.py is now one FastAPI/uvicorn process owning port 9000: the OCPP 1.6J
WebSocket (catch-all path) plus an HTTP control API (status, events, tags,
probe, remote start/stop, trigger, unlock, setconfig). Adds the events.jsonl
journal and auto-interrogation on connect.

Includes the captures from the 2026-07-09 live test session: full
GetConfiguration dump of eu092025, real charging transactions on both guns
(RFID + remote start/stop), and the negative Autocharge/MacEnabled results.
Cards A/B + app-remote enrolled in station_config.json.
2026-07-11 18:57:55 +02:00
35 changed files with 3227 additions and 51 deletions
+10
View File
@@ -0,0 +1,10 @@
# Runtime state + secrets (Tuya local keys live in config.json)
config.json
events.jsonl
seen_tags.json
sessions.db
discovery_*.json
snapshot.json
tinytuya.json
devices.json
tuya-raw.json
View File
+40
View File
@@ -0,0 +1,40 @@
{
"learn_mode": true,
"session_secret": "<auto-generated on first run — signs login sessions>",
"users": {
"admin-user": {
"password": "<pbkdf2 hash — create users with: python -m backend.users add <name>>",
"scopes": ["admin"],
"id_tag": "app-admin-user"
},
"gun1-only-user": {
"password": "<pbkdf2 hash>",
"scopes": ["charger:eu092025:1", "relay:garden-lights"],
"id_tag": "app-gun1-only-user"
},
"relays-only-user": {
"password": "<pbkdf2 hash>",
"scopes": ["relay:*"],
"id_tag": "app-relays-only-user"
}
},
"authorized": {
"1000000000000000": { "name": "Example RFID card, works on both guns", "kind": "card" },
"1000000000000001": {
"name": "Example RFID card restricted to gun 2",
"kind": "card",
"connectors": [2]
},
"app-remote": { "name": "Web/app remote start token", "kind": "app" }
},
"relays": {
"example-relay": {
"id": "<tuya device id from tinytuya wizard>",
"key": "<tuya local key from tinytuya wizard>",
"ip": "auto",
"version": 3.3,
"switch": 1,
"label": "Garden lights"
}
}
}
+47
View File
@@ -0,0 +1,47 @@
"""Backend configuration — one JSON file, config.json, next to this module.
Holds the charger allowlist (learn_mode + authorized idTags, same shape the
discovery phase used), the user accounts with their permission scopes, and the
Tuya relay registry. config.json is gitignored because it contains secrets
(password hashes, the session-signing secret, Tuya local keys);
config.example.json documents the shape.
"""
import json
import secrets
from pathlib import Path
HERE = Path(__file__).resolve().parent
CONFIG_PATH = HERE / "config.json"
DEFAULTS = {
"learn_mode": True,
"users": {}, # name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag": ...}
"authorized": {}, # idTag -> {"name", "kind": "card|app|car", optional "connectors": [1]}
"relays": {}, # name -> {"id", "key", "ip", "version", "switch", "label"}
}
def load() -> dict:
if CONFIG_PATH.exists():
cfg = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
else:
cfg = {}
for key, default in DEFAULTS.items():
cfg.setdefault(key, default if not isinstance(default, dict) else dict(default))
return cfg
CONFIG = load()
if not CONFIG.get("session_secret"):
CONFIG["session_secret"] = secrets.token_hex(32)
CONFIG_PATH.write_text(
json.dumps(CONFIG, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)
def save() -> None:
CONFIG_PATH.write_text(
json.dumps(CONFIG, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)
+313
View File
@@ -0,0 +1,313 @@
"""OCPP 1.6J charge-point side of the backend (the CSMS).
Ported from the proven discovery code (../discovering/station.py) with the
same core design: the API server IS the CSMS, because RemoteStart/Stop can
only travel down the live WebSocket the charger holds open. Every auth method
(RFID tap, app remote start) flows through the single decide() gate.
"""
import asyncio
import json
import logging
from collections import deque
from typing import Optional
from fastapi import WebSocket, WebSocketDisconnect
from ocpp.routing import on
from ocpp.v16 import ChargePoint as OcppChargePoint
from ocpp.v16 import call, call_result
from ocpp.v16.enums import (
Action,
AuthorizationStatus,
DataTransferStatus,
MessageTrigger,
RegistrationStatus,
)
from . import store
from .config import CONFIG, HERE
from .journal import now, record_event, record_seen
log = logging.getLogger("csms")
# ---- shared runtime state (the REST routes read/drive these) ----
CONNECTED: dict = {} # cp_id -> ChargePoint instance
CONNECTORS: dict = {} # (cp_id, connector_id) -> latest status string
ACTIVE_TX: dict = {} # transaction_id -> {cp, connector, id_tag, meter_start, started}
AUTH_EVENTS = deque(maxlen=50) # recent authorization attempts (for the panel UI)
_tx_counter = {"n": store.max_tx()} # tx ids continue across restarts
TRIGGERABLE = {
"status": MessageTrigger.status_notification,
"meter": MessageTrigger.meter_values,
"heartbeat": MessageTrigger.heartbeat,
"boot": MessageTrigger.boot_notification,
}
def decide(id_tag: str, context: str, connector: Optional[int] = None) -> AuthorizationStatus:
"""The one gate every auth method flows through: is this idTag allowed?
An allowlist entry may carry "connectors": [1] to restrict a card to
specific guns. Only StartTransaction knows the connector, so the per-gun
check fires there; a plain Authorize (card tap) still accepts a known card
— which matches this charger, since AuthorizeRemoteTxRequests=false means
StartTransaction is the decisive call anyway.
"""
entry = CONFIG["authorized"].get(id_tag)
known = entry is not None
if known and connector is not None and entry.get("connectors") \
and connector not in entry["connectors"]:
log.warning("[NO] REJECTED idTag=%r (%s) not allowed on connector %s (allowed: %s)",
id_tag, entry.get("name", "?"), connector, entry["connectors"])
status = AuthorizationStatus.invalid
elif known:
name = entry.get("name", "?")
log.info("[OK] AUTHORIZED idTag=%r (%s) via %s", id_tag, name, context)
status = AuthorizationStatus.accepted
elif CONFIG.get("learn_mode"):
log.warning("[LEARN] NEW idTag=%r via %s -> accepting & recording.", id_tag, context)
record_seen(id_tag, context)
status = AuthorizationStatus.accepted
else:
log.warning("[NO] REJECTED unknown idTag=%r via %s", id_tag, context)
record_seen(id_tag, context)
status = AuthorizationStatus.invalid
AUTH_EVENTS.append(
{"time": now(), "id_tag": id_tag, "context": context,
"connector": connector, "result": status.value, "known": known}
)
return status
def resolve_who(id_tag: str) -> str:
"""Human label for a session: allowlist entry name, username, or the raw tag."""
entry = CONFIG["authorized"].get(id_tag)
if entry and entry.get("name"):
return entry["name"]
for username, user in CONFIG["users"].items():
if user.get("id_tag") == id_tag:
return username
return id_tag
class ChargePoint(OcppChargePoint):
@on(Action.boot_notification)
async def on_boot_notification(self, charge_point_vendor, charge_point_model, **kwargs):
self.boot_info = {"vendor": charge_point_vendor, "model": charge_point_model, **kwargs}
record_event("BootNotification", self.id, **self.boot_info)
log.info("BootNotification: vendor=%r model=%r extra=%r",
charge_point_vendor, charge_point_model, kwargs)
return call_result.BootNotification(
current_time=now(), interval=30, status=RegistrationStatus.accepted
)
@on(Action.heartbeat)
async def on_heartbeat(self):
return call_result.Heartbeat(current_time=now())
@on(Action.status_notification)
async def on_status_notification(self, connector_id, error_code, status, **kwargs):
CONNECTORS[(self.id, connector_id)] = status
record_event("StatusNotification", self.id,
connector=connector_id, status=status, error=error_code)
log.info("StatusNotification: connector=%s status=%s error=%s",
connector_id, status, error_code)
return call_result.StatusNotification()
@on(Action.authorize)
async def on_authorize(self, id_tag, **kwargs):
status = decide(id_tag, "Authorize (card/app)")
record_event("Authorize", self.id, id_tag=id_tag, result=status.value)
return call_result.Authorize(id_tag_info={"status": status})
@on(Action.start_transaction)
async def on_start_transaction(self, connector_id, id_tag, meter_start, timestamp, **kwargs):
status = decide(id_tag, f"StartTransaction (connector {connector_id})",
connector=connector_id)
if status == AuthorizationStatus.accepted:
_tx_counter["n"] += 1
tx = _tx_counter["n"]
who = resolve_who(id_tag)
ACTIVE_TX[tx] = {
"cp": self.id, "connector": connector_id, "id_tag": id_tag,
"who": who, "meter_start": meter_start, "started": now(),
}
store.start_session(tx, self.id, connector_id, id_tag, who,
timestamp, meter_start)
log.info("Transaction %s STARTED on connector %s by %s (meter_start=%s)",
tx, connector_id, who, meter_start)
else:
tx = 0 # 0 tells the charger the transaction is not authorized
record_event("StartTransaction", self.id, connector=connector_id,
id_tag=id_tag, meter_start=meter_start, result=status.value, tx=tx)
return call_result.StartTransaction(
transaction_id=tx, id_tag_info={"status": status}
)
@on(Action.stop_transaction)
async def on_stop_transaction(self, meter_stop, timestamp, transaction_id, **kwargs):
info = ACTIVE_TX.pop(transaction_id, None)
used = (meter_stop - info["meter_start"]) if info else "?"
store.end_session(transaction_id, timestamp, meter_stop,
reason=kwargs.get("reason"))
record_event("StopTransaction", self.id, tx=transaction_id,
meter_stop=meter_stop, delivered_wh=used, **kwargs)
log.info("Transaction %s STOPPED (meter_stop=%s, delivered=%s Wh)",
transaction_id, meter_stop, used)
return call_result.StopTransaction(
id_tag_info={"status": AuthorizationStatus.accepted}
)
@on(Action.meter_values)
async def on_meter_values(self, connector_id, meter_value, **kwargs):
record_event("MeterValues", self.id, connector=connector_id,
values=meter_value, **kwargs)
tx = kwargs.get("transaction_id")
if tx is not None:
for entry in meter_value or []:
reading = {}
for sv in entry.get("sampled_value") or []:
# measurand defaults to the energy register when omitted
measurand = sv.get("measurand", "Energy.Active.Import.Register")
try:
value = float(sv.get("value"))
except (TypeError, ValueError):
continue
if measurand == "Energy.Active.Import.Register":
# some firmwares report kWh; normalize to Wh
reading["energy_wh"] = value * 1000 if sv.get("unit") == "kWh" else value
elif measurand == "Power.Active.Import":
reading["power_w"] = value * 1000 if sv.get("unit") == "kW" else value
elif measurand == "SoC":
reading["soc"] = value
if reading:
store.add_sample(tx, entry.get("timestamp", now()),
reading.get("energy_wh"), reading.get("power_w"),
reading.get("soc"))
log.info("MeterValues: connector=%s values=%r", connector_id, meter_value)
return call_result.MeterValues()
@on(Action.data_transfer)
async def on_data_transfer(self, vendor_id, **kwargs):
# Journaled because a vendor DataTransfer frame is the long-shot lead
# for the charger ever surfacing the vehicle VIN (wiki: authorization).
record_event("DataTransfer", self.id, vendor_id=vendor_id, **kwargs)
log.info("DataTransfer: vendor_id=%r extra=%r", vendor_id, kwargs)
return call_result.DataTransfer(status=DataTransferStatus.accepted)
@on(Action.firmware_status_notification)
async def on_firmware_status(self, status, **kwargs):
log.info("FirmwareStatusNotification: %s", status)
return call_result.FirmwareStatusNotification()
@on(Action.diagnostics_status_notification)
async def on_diagnostics_status(self, status, **kwargs):
log.info("DiagnosticsStatusNotification: %s", status)
return call_result.DiagnosticsStatusNotification()
# ---- outbound OCPP commands (called by the REST routes) ----
async def remote_start(cp_id: str, id_tag: str, connector_id: int = 1) -> str:
cp = CONNECTED.get(cp_id)
if cp is None:
raise RuntimeError(f"charge point {cp_id!r} is not connected")
resp = await cp.call(call.RemoteStartTransaction(id_tag=id_tag, connector_id=connector_id))
log.info("RemoteStartTransaction(%s, connector=%s) -> %s", id_tag, connector_id, resp.status)
return resp.status
async def remote_stop(transaction_id: int) -> str:
# fall back to the store so sessions still running after a backend restart
# (charger keeps them alive) remain stoppable
info = ACTIVE_TX.get(transaction_id) or store.open_session(transaction_id)
if info is None:
raise RuntimeError(f"no active transaction {transaction_id}")
cp = CONNECTED.get(info["cp"])
if cp is None:
raise RuntimeError("charge point is not connected")
resp = await cp.call(call.RemoteStopTransaction(transaction_id=transaction_id))
log.info("RemoteStopTransaction(%s) -> %s", transaction_id, resp.status)
return resp.status
async def interrogate(cp: ChargePoint) -> dict:
"""GetConfiguration + trigger a StatusNotification; save to discovery_<id>.json."""
report = {
"charge_point": cp.id,
"probed_at": now(),
"boot_info": getattr(cp, "boot_info", None),
}
try:
resp = await cp.call(call.GetConfiguration())
report["configuration"] = resp.configuration_key
report["unknown_keys"] = resp.unknown_key
except Exception as exc:
report["configuration_error"] = repr(exc)
try:
resp = await cp.call(
call.TriggerMessage(requested_message=MessageTrigger.status_notification)
)
report["trigger_status_notification"] = resp.status
await asyncio.sleep(2) # give the triggered StatusNotifications time to arrive
except Exception as exc:
report["trigger_error"] = repr(exc)
report["connectors_seen"] = {
str(conn): status for (cp_id, conn), status in CONNECTORS.items() if cp_id == cp.id
}
path = HERE / f"discovery_{cp.id}.json"
path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
return report
class _WSAdapter:
"""Bridge a Starlette WebSocket to the recv()/send() interface the ocpp lib expects."""
def __init__(self, ws: WebSocket):
self._ws = ws
async def recv(self) -> str:
return await self._ws.receive_text()
async def send(self, message: str) -> None:
await self._ws.send_text(message)
async def close(self, code: int = 1000, reason: str = "") -> None:
await self._ws.close(code=code)
async def ocpp_socket(ws: WebSocket, cp_path: str) -> None:
"""The OCPP endpoint the JC-6620 dials: ws://<host>:9000/<ChargerID>."""
cp_id = cp_path.strip("/").split("/")[-1] or "unknown"
offered = [
p.strip()
for p in ws.headers.get("sec-websocket-protocol", "").split(",")
if p.strip()
]
await ws.accept(subprotocol="ocpp1.6" if "ocpp1.6" in offered else None)
log.info("Charger connected: id=%r from %s subprotocols=%r", cp_id, ws.client, offered)
record_event("connected", cp_id, client=str(ws.client), subprotocols=offered)
cp = ChargePoint(cp_id, _WSAdapter(ws))
CONNECTED[cp_id] = cp
try:
await cp.start()
except WebSocketDisconnect:
log.info("Charger %r disconnected", cp_id)
finally:
record_event("disconnected", cp_id)
CONNECTED.pop(cp_id, None)
for key in [k for k in CONNECTORS if k[0] == cp_id]:
CONNECTORS.pop(key, None)
def pick_cp(cp_id: Optional[str]) -> ChargePoint:
"""Resolve which charger a REST call targets; auto-select when only one is connected."""
if cp_id is not None:
cp = CONNECTED.get(cp_id)
if cp is None:
raise KeyError(f"charge point {cp_id!r} is not connected")
return cp
if len(CONNECTED) == 1:
return next(iter(CONNECTED.values()))
raise KeyError(f"specify ?cp=<id>; currently connected: {list(CONNECTED)}")
+61
View File
@@ -0,0 +1,61 @@
"""Durable journals: events.jsonl (everything the charger tells us) and
seen_tags.json (unknown idTags captured in learn mode).
JSONL now, SQLite later — the append-only line format survives crashes and is
trivially greppable/ingestable, which is all the current phase needs.
"""
import json
import logging
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
HERE = Path(__file__).resolve().parent
EVENTS_PATH = HERE / "events.jsonl"
SEEN_PATH = HERE / "seen_tags.json"
log = logging.getLogger("journal")
def now() -> str:
return datetime.now(timezone.utc).isoformat()
def record_event(event: str, cp_id: str, **data) -> None:
entry = {"time": now(), "event": event, "cp": cp_id, **data}
try:
with EVENTS_PATH.open("a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n")
except Exception:
log.exception("failed to journal event %r", event)
def read_events(limit: int = 100, event: Optional[str] = None) -> list:
if not EVENTS_PATH.exists():
return []
lines = EVENTS_PATH.read_text(encoding="utf-8").splitlines()
entries = [json.loads(line) for line in lines if line.strip()]
if event is not None:
entries = [e for e in entries if e.get("event") == event]
return entries[-limit:]
def record_seen(id_tag: str, context: str) -> None:
try:
seen = json.loads(SEEN_PATH.read_text(encoding="utf-8")) if SEEN_PATH.exists() else {}
except Exception:
seen = {}
entry = seen.get(id_tag, {"count": 0, "first_seen": now(), "contexts": []})
entry["count"] += 1
entry["last_seen"] = now()
if context not in entry["contexts"]:
entry["contexts"].append(context)
seen[id_tag] = entry
SEEN_PATH.write_text(json.dumps(seen, indent=2), encoding="utf-8")
def read_seen() -> dict:
if not SEEN_PATH.exists():
return {}
return json.loads(SEEN_PATH.read_text(encoding="utf-8"))
+79
View File
@@ -0,0 +1,79 @@
"""Home energy backend — private CSMS for the Anfu charger + local control of
the Tuya/SmartLife WiFi relays. One uvicorn process, one port:
ws://<host>:9000/<ChargerID> OCPP 1.6J (the JC-6620 dials in here)
http://<host>:9000/api/* REST for the web panel / curl
http://<host>:9000/docs interactive API docs
Port 9000 is load-bearing: it's hardcoded in the charger's touchscreen URL and
changing it there requires a power-cycle (wiki: troubleshooting #4).
Run: venv\\Scripts\\python -m backend.main (from the repo root)
"""
import asyncio
import logging
from pathlib import Path
import uvicorn
from fastapi import FastAPI, WebSocket
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from . import csms, routes
from .config import CONFIG
STATIC = Path(__file__).resolve().parent / "static"
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s | %(message)s",
)
log = logging.getLogger("backend")
app = FastAPI(
title="Home Energy Backend",
description="Private OCPP CSMS + WiFi relay control. The charger dials "
"ws://<host>:9000/<id>; everything else lives under /api/*.",
)
app.include_router(routes.router)
app.mount("/static", StaticFiles(directory=STATIC), name="static")
@app.get("/")
async def index_page():
return FileResponse(STATIC / "index.html")
# the service worker must be served from / so its scope covers the whole app
@app.get("/sw.js")
async def service_worker():
return FileResponse(STATIC / "sw.js", media_type="application/javascript")
# Catch-all WS route so the charger may dial any path (it uses /<ChargerID>).
# WebSocket and HTTP routes match independently, so this never shadows /api/*.
@app.websocket("/{cp_path:path}")
async def ocpp_websocket(ws: WebSocket, cp_path: str):
await csms.ocpp_socket(ws, cp_path)
async def main():
mode = "LEARN (accepting & recording new ids)" if CONFIG["learn_mode"] else "ENFORCING allowlist"
log.info(
"CSMS ws://0.0.0.0:9000/<id> | API http://0.0.0.0:9000/docs | mode: %s | "
"%d authorized id(s) | %d user(s) | %d relay(s) configured",
mode, len(CONFIG["authorized"]), len(CONFIG["users"]), len(CONFIG["relays"]),
)
if not CONFIG["users"]:
log.warning(
"NO USERS CONFIGURED — the API is OPEN (anonymous admin). "
"Create one: venv\\Scripts\\python -m backend.users add <name> --scopes admin"
)
await uvicorn.Server(
uvicorn.Config(app, host="0.0.0.0", port=9000, log_config=None)
).serve()
if __name__ == "__main__":
asyncio.run(main())
+103
View File
@@ -0,0 +1,103 @@
"""Local control of the Tuya/SmartLife WiFi relays — no Tuya cloud in the loop.
The relays pair via the SmartLife app (BLE-assisted onboarding) but once on
WiFi they speak Tuya's local protocol on TCP 6668, which tinytuya drives
directly. Each relay needs its device id + LOCAL KEY in config.json under
"relays" — extracted once with `tinytuya wizard` (see the wiki: wifi-relays).
tinytuya is synchronous/blocking, so every call runs in a worker thread via
asyncio.to_thread to keep the OCPP socket responsive.
"""
import asyncio
import logging
try:
import tinytuya
except ImportError: # backend still runs (charger-only) without it
tinytuya = None
from .config import CONFIG
log = logging.getLogger("relays")
class RelayError(RuntimeError):
pass
def configured() -> dict:
"""The relay registry without secrets — safe to return over the API."""
return {
name: {"label": cfg.get("label", name), "ip": cfg.get("ip", "auto")}
for name, cfg in CONFIG["relays"].items()
}
def _device(name: str):
if tinytuya is None:
raise RelayError("tinytuya is not installed (pip install tinytuya)")
cfg = CONFIG["relays"].get(name)
if cfg is None:
raise RelayError(f"unknown relay {name!r}; configured: {list(CONFIG['relays'])}")
ip = cfg.get("ip", "auto")
# "Auto" makes tinytuya find the device via its UDP broadcast (slower);
# pin the IP in config.json (with a DHCP reservation) once known.
dev = tinytuya.OutletDevice(
cfg["id"], ip if ip and ip != "auto" else "Auto", cfg["key"]
)
dev.set_version(float(cfg.get("version", 3.3)))
dev.set_socketTimeout(5)
return dev, str(cfg.get("switch", 1))
def _check(name: str, result) -> dict:
if not isinstance(result, dict) or "dps" not in result:
raise RelayError(f"relay {name!r} did not answer: {result!r}")
return result["dps"]
def _status_sync(name: str) -> dict:
dev, sw = _device(name)
dps = _check(name, dev.status())
return {"relay": name, "on": bool(dps.get(sw)), "dps": dps}
def _switch_sync(name: str, on: bool) -> dict:
dev, sw = _device(name)
result = dev.set_status(on, int(sw))
# some firmwares reply with the new dps, some with an empty ack — verify
if not (isinstance(result, dict) and "dps" in result):
result = dev.status()
dps = _check(name, result)
actual = bool(dps.get(sw, on))
if actual != on:
raise RelayError(f"relay {name!r} did not switch (wanted {on}, reads {actual})")
return {"relay": name, "on": actual}
async def status(name: str) -> dict:
return await asyncio.to_thread(_status_sync, name)
async def switch(name: str, on: bool) -> dict:
return await asyncio.to_thread(_switch_sync, name, on)
async def toggle(name: str) -> dict:
current = await status(name)
return await switch(name, not current["on"])
async def status_all() -> dict:
"""Poll every configured relay concurrently; errors become per-relay strings."""
names = list(CONFIG["relays"])
results = await asyncio.gather(*(status(n) for n in names), return_exceptions=True)
out = {}
for name, res in zip(names, results):
if isinstance(res, BaseException):
out[name] = {"relay": name, "error": str(res)}
else:
out[name] = res
out[name]["label"] = CONFIG["relays"][name].get("label", name)
return out
+5
View File
@@ -0,0 +1,5 @@
fastapi==0.139.0
uvicorn==0.51.0
websockets==16.0
ocpp==2.1.0
tinytuya==1.20.0
+339
View File
@@ -0,0 +1,339 @@
"""REST API — everything under /api/*, for the web panel (and curl).
Authorization model (see backend/users.py):
* POST /api/login {username, password} -> HMAC session token, set as an
HttpOnly cookie AND returned in the body (usable as a Bearer token).
* Every endpoint resolves the caller to a user and checks a permission
scope: charger:<cp>:<gun>, relay:<name>, or admin (implies everything).
* With ZERO users configured the API is open (anonymous admin) so nothing
breaks before the first `python -m backend.users add` — main.py warns.
"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel
from . import csms, relays, store, users
from .config import CONFIG, save
from .journal import read_events, read_seen
from ocpp.v16 import call
log = logging.getLogger("api")
SESSION_COOKIE = "session"
def current_user(request: Request) -> dict:
"""Resolve the session cookie or Bearer token to a user dict."""
if not CONFIG["users"]:
return {"name": "anonymous", "scopes": ["admin"], "id_tag": "app-remote"}
token = request.cookies.get(SESSION_COOKIE) or (
request.headers.get("authorization") or ""
).removeprefix("Bearer ").strip()
username = users.verify_session(token) if token else None
if username is None:
raise HTTPException(401, "not logged in (or session expired)")
return {"name": username, **CONFIG["users"][username]}
def need(user: dict, scope: str) -> None:
if not users.allowed(user["scopes"], scope):
raise HTTPException(403, f"user {user['name']!r} lacks permission {scope!r}")
router = APIRouter(prefix="/api")
def _cp(cp_id: Optional[str]) -> csms.ChargePoint:
try:
return csms.pick_cp(cp_id)
except KeyError as exc:
raise HTTPException(409, str(exc.args[0]))
async def _ocpp(coro):
"""Run an OCPP call for an HTTP handler, mapping failures to HTTP errors."""
try:
return await coro
except HTTPException:
raise
except Exception as exc:
raise HTTPException(502, f"OCPP call failed: {exc!r}")
def _visible_relays(user: dict) -> dict:
return {
name: info
for name, info in relays.configured().items()
if users.allowed(user["scopes"], f"relay:{name}")
}
# ---- login / identity ----
class LoginBody(BaseModel):
username: str
password: str
@router.post("/login")
async def login(body: LoginBody, response: Response):
entry = CONFIG["users"].get(body.username)
if not CONFIG["users"]:
raise HTTPException(409, "no users configured — the API is open; log in is pointless "
"until `python -m backend.users add` creates one")
if entry is None or not users.verify_password(body.password, entry.get("password", "")):
log.warning("failed login for %r", body.username)
raise HTTPException(401, "wrong username or password")
token = users.mint_session(body.username)
response.set_cookie(
SESSION_COOKIE, token, max_age=users.SESSION_TTL,
httponly=True, samesite="lax", # no `secure`: plain http inside NetBird
)
log.info("login: %r", body.username)
return {"token": token, "user": users.public_view(body.username, entry)}
@router.post("/logout")
async def logout(response: Response):
# sessions are stateless — logout just clears the cookie on this client
response.delete_cookie(SESSION_COOKIE)
return {"logged_out": True}
@router.get("/me")
async def me(user: dict = Depends(current_user)):
return users.public_view(user["name"], user)
# ---- status & journals ----
@router.get("/status")
async def api_status(user: dict = Depends(current_user)):
return {
"mode": "learn" if CONFIG.get("learn_mode") else "enforce",
"connected": {
cp_id: getattr(cp, "boot_info", None) for cp_id, cp in csms.CONNECTED.items()
},
"connectors": {f"{cp_id}/{conn}": s for (cp_id, conn), s in csms.CONNECTORS.items()},
"active_transactions": csms.ACTIVE_TX,
"recent_auth_events": list(csms.AUTH_EVENTS),
"relays": _visible_relays(user),
}
@router.get("/events")
async def api_events(limit: int = 100, event: Optional[str] = None,
user: dict = Depends(current_user)):
need(user, "admin")
return read_events(limit=limit, event=event)
# ---- charger control (scope: charger:<cp>:<gun>) ----
@router.post("/charger/start")
async def charger_start(connector: int = 1, cp: Optional[str] = None,
user: dict = Depends(current_user)):
target = _cp(cp)
need(user, f"charger:{target.id}:{connector}")
# remote starts run under the caller's own idTag so sessions are attributable
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}
@router.post("/charger/stop")
@router.post("/charger/stop/{tx}")
async def charger_stop(tx: Optional[int] = None, user: dict = Depends(current_user)):
if tx is None:
if len(csms.ACTIVE_TX) != 1:
raise HTTPException(409, f"specify /stop/<tx>; active: {list(csms.ACTIVE_TX)}")
tx = next(iter(csms.ACTIVE_TX))
info = csms.ACTIVE_TX.get(tx) or store.open_session(tx)
if info is None:
raise HTTPException(409, f"no active transaction {tx}")
need(user, f"charger:{info['cp']}:{info['connector']}")
status = await _ocpp(csms.remote_stop(tx))
return {"remote_stop": status, "transaction": tx}
@router.post("/charger/unlock/{connector}")
async def charger_unlock(connector: int, cp: Optional[str] = None,
user: dict = Depends(current_user)):
target = _cp(cp)
need(user, f"charger:{target.id}:{connector}")
resp = await _ocpp(target.call(call.UnlockConnector(connector_id=connector)))
return {"unlock": connector, "status": resp.status}
@router.post("/charger/trigger/{what}")
async def charger_trigger(what: str, connector: Optional[int] = None,
cp: Optional[str] = None, user: dict = Depends(current_user)):
need(user, "admin")
if what not in csms.TRIGGERABLE:
raise HTTPException(400, f"unknown trigger {what!r}; options: {list(csms.TRIGGERABLE)}")
payload = call.TriggerMessage(
requested_message=csms.TRIGGERABLE[what], connector_id=connector
)
resp = await _ocpp(_cp(cp).call(payload))
return {"trigger": what, "status": resp.status}
@router.post("/charger/setconfig")
async def charger_setconfig(key: str, value: str, cp: Optional[str] = None,
user: dict = Depends(current_user)):
need(user, "admin")
resp = await _ocpp(_cp(cp).call(call.ChangeConfiguration(key=key, value=value)))
return {"key": key, "value": value, "status": resp.status}
@router.post("/charger/probe")
async def charger_probe(cp: Optional[str] = None, user: dict = Depends(current_user)):
need(user, "admin")
return await _ocpp(csms.interrogate(_cp(cp)))
# ---- session history: who charged when and how many kWh ----
def _may_see_session(user: dict, s: dict) -> bool:
"""Own sessions, sessions on guns you control, or everything for admin."""
return (
s["id_tag"] == user.get("id_tag")
or users.allowed(user["scopes"], f"charger:{s['cp']}:{s['connector']}")
)
@router.get("/sessions")
async def sessions_list(limit: int = 50, cp: Optional[str] = None,
connector: Optional[int] = None,
user: dict = Depends(current_user)):
rows = store.query_sessions(limit=limit, cp=cp, connector=connector)
return [s for s in rows if _may_see_session(user, s)]
@router.get("/sessions/{tx}/samples")
async def session_samples(tx: int, user: dict = Depends(current_user)):
session = store.get_session(tx)
if session is None:
raise HTTPException(404, f"no session {tx}")
if not _may_see_session(user, session):
raise HTTPException(403, f"user {user['name']!r} may not view session {tx}")
return {"session": session, "samples": store.samples_for(tx)}
# ---- allowlist management (admin) ----
class AllowlistEntry(BaseModel):
name: str
kind: str = "card" # card | app | car
connectors: Optional[list[int]] = None # e.g. [2] = this card only works on gun 2
@router.get("/allowlist")
async def allowlist_get(user: dict = Depends(current_user)):
need(user, "admin")
return {
"learn_mode": CONFIG["learn_mode"],
"authorized": CONFIG["authorized"],
"seen": read_seen(),
}
@router.put("/allowlist/{id_tag}")
async def allowlist_put(id_tag: str, entry: AllowlistEntry,
user: dict = Depends(current_user)):
need(user, "admin")
CONFIG["authorized"][id_tag] = entry.model_dump(exclude_none=True)
save()
log.info("allowlist: added/updated %r (%s)", id_tag, entry.name)
return {"authorized": CONFIG["authorized"]}
@router.delete("/allowlist/{id_tag}")
async def allowlist_delete(id_tag: str, user: dict = Depends(current_user)):
need(user, "admin")
if CONFIG["authorized"].pop(id_tag, None) is None:
raise HTTPException(404, f"idTag {id_tag!r} is not in the allowlist")
save()
log.info("allowlist: removed %r", id_tag)
return {"authorized": CONFIG["authorized"]}
@router.post("/mode")
async def set_mode(learn: bool, user: dict = Depends(current_user)):
"""Flip learn mode at runtime — no restart needed; decide() reads CONFIG live."""
need(user, "admin")
CONFIG["learn_mode"] = learn
save()
log.warning("mode changed: %s", "LEARN" if learn else "ENFORCE")
return {"mode": "learn" if learn else "enforce"}
# ---- user management (admin) ----
class UserBody(BaseModel):
password: Optional[str] = None
scopes: Optional[list[str]] = None
@router.get("/users")
async def users_list(user: dict = Depends(current_user)):
need(user, "admin")
return [users.public_view(name, u) for name, u in CONFIG["users"].items()]
@router.put("/users/{name}")
async def users_put(name: str, body: UserBody, user: dict = Depends(current_user)):
need(user, "admin")
try:
updated = users.set_user(name, password=body.password, scopes=body.scopes)
except ValueError as exc:
raise HTTPException(400, str(exc))
log.info("users: %r set by %r (scopes=%s)", name, user["name"], updated["scopes"])
return users.public_view(name, updated)
@router.delete("/users/{name}")
async def users_delete(name: str, user: dict = Depends(current_user)):
need(user, "admin")
if name == user["name"]:
raise HTTPException(400, "refusing to delete the account you are logged in as")
try:
users.remove_user(name)
except KeyError:
raise HTTPException(404, f"no user {name!r}")
log.info("users: %r removed by %r", name, user["name"])
return {"removed": name}
# ---- relays (scope: relay:<name>) ----
@router.get("/relays")
async def relays_list(live: bool = False, user: dict = Depends(current_user)):
"""Relays the caller may control; ?live=true polls each for its actual state."""
visible = _visible_relays(user)
if not live:
return visible
polled = await relays.status_all()
return {name: polled[name] for name in visible if name in polled}
@router.get("/relays/{name}")
async def relay_status(name: str, user: dict = Depends(current_user)):
need(user, f"relay:{name}")
try:
return await relays.status(name)
except relays.RelayError as exc:
raise HTTPException(502, str(exc))
@router.post("/relays/{name}/{verb}")
async def relay_switch(name: str, verb: str, user: dict = Depends(current_user)):
need(user, f"relay:{name}")
actions = {"on": True, "off": False}
try:
if verb == "toggle":
return await relays.toggle(name)
if verb in actions:
return await relays.switch(name, actions[verb])
except relays.RelayError as exc:
raise HTTPException(502, str(exc))
raise HTTPException(400, f"unknown verb {verb!r}; use on, off or toggle")
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<rect width="100" height="100" rx="22" fill="#0f172a"/>
<path d="M55 12 L28 56 L46 56 L41 88 L72 42 L52 42 Z" fill="#facc15"/>
</svg>

After

Width:  |  Height:  |  Size: 201 B

+486
View File
@@ -0,0 +1,486 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#0f172a">
<title>Home Energy</title>
<link rel="manifest" href="/static/manifest.json">
<link rel="icon" href="/static/icon.svg">
<style>
:root {
--bg: #f1f5f9; --card: #ffffff; --text: #0f172a; --muted: #64748b;
--line: #e2e8f0; --accent: #2563eb; --ok: #16a34a; --warn: #d97706;
--bad: #dc2626; --chip: #e2e8f0;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0f172a; --card: #1e293b; --text: #e2e8f0; --muted: #94a3b8;
--line: #334155; --chip: #334155;
}
}
* { box-sizing: border-box; margin: 0; }
body {
background: var(--bg); color: var(--text);
font: 16px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
padding-bottom: 76px;
}
header {
display: flex; align-items: center; gap: 8px;
padding: 14px 16px 10px;
}
header h1 { font-size: 20px; flex: 1; }
header .who { color: var(--muted); font-size: 14px; }
main { max-width: 640px; margin: 0 auto; padding: 0 12px; }
.card {
background: var(--card); border: 1px solid var(--line);
border-radius: 14px; padding: 14px 16px; margin-bottom: 12px;
}
.card h2 { font-size: 15px; color: var(--muted); margin-bottom: 10px; font-weight: 600; }
.row { display: flex; align-items: center; gap: 10px; }
.row .grow { flex: 1; min-width: 0; }
.title { font-weight: 600; }
.sub { color: var(--muted); font-size: 13px; }
.chip {
display: inline-block; padding: 2px 10px; border-radius: 999px;
background: var(--chip); font-size: 13px; font-weight: 600;
}
.chip.ok { background: color-mix(in srgb, var(--ok) 18%, transparent); color: var(--ok); }
.chip.warn { background: color-mix(in srgb, var(--warn) 18%, transparent); color: var(--warn); }
.chip.bad { background: color-mix(in srgb, var(--bad) 18%, transparent); color: var(--bad); }
.chip.accent { background: color-mix(in srgb, var(--accent) 15%, transparent); color: var(--accent); }
button {
font: inherit; font-weight: 600; border: 0; border-radius: 10px;
padding: 10px 16px; cursor: pointer; background: var(--accent); color: #fff;
}
button.secondary { background: var(--chip); color: var(--text); }
button.danger { background: var(--bad); }
button.small { padding: 6px 10px; font-size: 13px; border-radius: 8px; }
button:disabled { opacity: .45; cursor: default; }
input, select {
font: inherit; color: var(--text); background: var(--bg);
border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; width: 100%;
}
form .row { margin-bottom: 8px; }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
th, td { text-align: left; padding: 7px 6px; border-bottom: 1px solid var(--line); }
th { color: var(--muted); font-weight: 600; font-size: 12px; text-transform: uppercase; }
td.num, th.num { text-align: right; }
.scroll { overflow-x: auto; }
nav {
position: fixed; bottom: 0; left: 0; right: 0;
display: flex; background: var(--card); border-top: 1px solid var(--line);
padding-bottom: env(safe-area-inset-bottom);
}
nav button {
flex: 1; background: none; color: var(--muted); border-radius: 0;
padding: 12px 0 10px; font-size: 13px;
}
nav button.active { color: var(--accent); }
#toast {
position: fixed; left: 50%; bottom: 86px; transform: translateX(-50%);
background: var(--text); color: var(--bg); padding: 10px 18px;
border-radius: 10px; font-size: 14px; opacity: 0; transition: opacity .25s;
pointer-events: none; max-width: 90vw;
}
#toast.show { opacity: 1; }
#login { max-width: 360px; margin: 12vh auto 0; padding: 0 16px; }
#login .card { padding: 22px; }
#login h1 { font-size: 22px; margin-bottom: 16px; text-align: center; }
#login button { width: 100%; margin-top: 6px; }
.hidden { display: none !important; }
.offline { text-align: center; color: var(--muted); padding: 18px 0; }
</style>
</head>
<body>
<div id="login" class="hidden">
<div class="card">
<h1>&#9889; Home Energy</h1>
<form onsubmit="return doLogin(event)">
<div class="row"><input id="l-user" placeholder="Username" autocomplete="username" required></div>
<div class="row"><input id="l-pass" type="password" placeholder="Password" autocomplete="current-password" required></div>
<button>Log in</button>
</form>
</div>
</div>
<div id="app" class="hidden">
<header>
<h1>&#9889; Home Energy</h1>
<span class="who" id="whoami"></span>
<button class="secondary small" id="logout-btn" onclick="doLogout()">Log out</button>
</header>
<main>
<section id="tab-control">
<div id="guns"></div>
<div class="card" id="relays-card">
<h2>Relays</h2>
<div id="relays"></div>
<div class="row" style="margin-top:8px">
<button class="secondary small" onclick="refreshRelaysLive()">Refresh live states</button>
</div>
</div>
</section>
<section id="tab-history" class="hidden">
<div class="card">
<h2>Charging sessions</h2>
<div class="scroll"><table>
<thead><tr><th>Who</th><th>Gun</th><th>Started</th><th class="num">kWh</th><th></th></tr></thead>
<tbody id="sessions"></tbody>
</table></div>
</div>
</section>
<section id="tab-admin" class="hidden">
<div class="card">
<h2>Mode</h2>
<div class="row">
<div class="grow"><span class="title" id="mode-label"></span>
<div class="sub">Learn mode accepts and records unknown cards; enforce rejects them.</div></div>
<button class="small" id="mode-btn" onclick="toggleMode()"></button>
</div>
</div>
<div class="card">
<h2>Allowlist</h2>
<div class="scroll"><table>
<thead><tr><th>idTag</th><th>Name</th><th>Guns</th><th></th></tr></thead>
<tbody id="allowlist"></tbody>
</table></div>
<div id="seen-tags"></div>
<form onsubmit="return addAllowlist(event)" style="margin-top:10px">
<div class="row"><input id="a-tag" placeholder="idTag" required></div>
<div class="row">
<input id="a-name" placeholder="Name (e.g. RFID card C)" required>
<select id="a-kind" style="width:110px"><option>card</option><option>app</option><option>car</option></select>
</div>
<div class="row">
<input id="a-conn" placeholder="Guns, e.g. 1,2 — empty = all">
<button class="small">Add</button>
</div>
</form>
</div>
<div class="card">
<h2>Users</h2>
<div class="scroll"><table>
<thead><tr><th>User</th><th>Scopes</th><th></th></tr></thead>
<tbody id="users"></tbody>
</table></div>
<form onsubmit="return addUser(event)" style="margin-top:10px">
<div class="row"><input id="u-name" placeholder="Username" required></div>
<div class="row"><input id="u-pass" type="password" placeholder="Password (empty = keep current)"></div>
<div class="row">
<input id="u-scopes" placeholder='Scopes, e.g. admin or charger:eu092025:1 relay:*'>
<button class="small">Save</button>
</div>
</form>
</div>
</section>
</main>
<nav>
<button data-tab="control" class="active" onclick="showTab('control')">&#9889; Control</button>
<button data-tab="history" onclick="showTab('history')">&#128202; History</button>
<button data-tab="admin" class="hidden" onclick="showTab('admin')">&#9881; Admin</button>
</nav>
</div>
<div id="toast"></div>
<script>
"use strict";
let me = null, status = null, pollTimer = null;
// ---- tiny helpers ----
const $ = (id) => document.getElementById(id);
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
function toast(msg) {
const t = $("toast");
t.textContent = msg;
t.classList.add("show");
clearTimeout(t._h);
t._h = setTimeout(() => t.classList.remove("show"), 3000);
}
async function api(path, opts = {}) {
const r = await fetch("/api" + path, {
headers: { "Content-Type": "application/json" }, ...opts,
});
if (r.status === 401 && path !== "/login") { showLogin(); throw new Error("not logged in"); }
if (!r.ok) {
let detail = r.statusText;
try { detail = (await r.json()).detail || detail; } catch {}
throw new Error(detail);
}
return r.json();
}
// fnmatch-style scope check, mirroring backend/users.py
function scopeOk(needed) {
if (!me) return false;
return me.scopes.some(g => {
if (g === "*" || g === "admin") return true;
const re = new RegExp("^" + g.split("*").map(p => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$");
return re.test(needed);
});
}
const isAdmin = () => me && me.scopes.some(g => g === "admin" || g === "*");
// ---- login flow ----
function showLogin() {
clearInterval(pollTimer);
$("app").classList.add("hidden");
$("login").classList.remove("hidden");
}
async function doLogin(ev) {
ev.preventDefault();
try {
await api("/login", { method: "POST", body: JSON.stringify({
username: $("l-user").value.trim(), password: $("l-pass").value }) });
$("l-pass").value = "";
await boot();
} catch (e) { toast(e.message); }
return false;
}
async function doLogout() {
await api("/logout", { method: "POST" }).catch(() => {});
me = null;
showLogin();
}
async function boot() {
try { me = await api("/me"); } catch { return; } // api() already showed login
$("login").classList.add("hidden");
$("app").classList.remove("hidden");
$("whoami").textContent = me.name === "anonymous" ? "open mode" : me.name;
$("logout-btn").classList.toggle("hidden", me.name === "anonymous");
document.querySelector('nav [data-tab="admin"]').classList.toggle("hidden", !isAdmin());
await refreshStatus();
clearInterval(pollTimer);
pollTimer = setInterval(() => {
if (!document.hidden && !$("tab-control").classList.contains("hidden")) refreshStatus();
}, 5000);
}
// ---- tabs ----
function showTab(name) {
for (const t of ["control", "history", "admin"]) {
$("tab-" + t).classList.toggle("hidden", t !== name);
document.querySelector(`nav [data-tab="${t}"]`).classList.toggle("active", t === name);
}
if (name === "history") loadSessions();
if (name === "admin") loadAdmin();
if (name === "control") refreshStatus();
}
// ---- control tab ----
const STATUS_CHIP = {
Available: "", Preparing: "accent", Charging: "ok", SuspendedEV: "warn",
SuspendedEVSE: "warn", Finishing: "", Faulted: "bad", Unavailable: "bad", Reserved: "warn",
};
async function refreshStatus() {
try { status = await api("/status"); } catch { return; }
renderGuns();
renderRelays(null);
}
function renderGuns() {
const box = $("guns");
const cps = Object.keys(status.connected);
if (!cps.length) {
box.innerHTML = `<div class="card"><div class="offline">Charger offline — waiting for it to dial in&hellip;</div></div>`;
return;
}
// active transaction per (cp, connector)
const txByGun = {};
for (const [tx, info] of Object.entries(status.active_transactions))
txByGun[`${info.cp}/${info.connector}`] = { tx, ...info };
let html = "";
for (const cp of cps) {
const conns = Object.entries(status.connectors)
.map(([key, st]) => ({ key, st, conn: +key.split("/")[1], cpId: key.split("/")[0] }))
.filter(c => c.cpId === cp && c.conn > 0)
.sort((a, b) => a.conn - b.conn);
if (!conns.length)
html += `<div class="card"><div class="sub">${esc(cp)} connected — no gun status yet</div></div>`;
for (const { conn, st } of conns) {
const gunName = conn === 1 ? "Gun 1 · EU (CCS)" : conn === 2 ? "Gun 2 · GB/T" : `Gun ${conn}`;
const active = txByGun[`${cp}/${conn}`];
const may = scopeOk(`charger:${cp}:${conn}`);
const canStart = may && !active && (st === "Preparing" || st === "Available");
let action = "";
if (active && may)
action = `<button class="danger" onclick="stopTx(${active.tx})">Stop</button>`;
else if (!active)
action = `<button ${canStart ? "" : "disabled"} onclick="startGun('${esc(cp)}',${conn})">Start</button>`;
let sub = st === "Preparing" && !active ? "Cable plugged — ready to start" : "";
if (active) sub = `${esc(active.who || active.id_tag)} · since ${fmtTime(active.started)}`;
if (!may) sub = "No permission for this gun";
html += `<div class="card"><div class="row">
<div class="grow"><div class="title">${gunName}</div><div class="sub">${sub || "&nbsp;"}</div></div>
<span class="chip ${STATUS_CHIP[st] || ""}">${esc(st)}</span>${action}
</div></div>`;
}
}
box.innerHTML = html;
}
async function startGun(cp, conn) {
try {
const r = await api(`/charger/start?connector=${conn}&cp=${encodeURIComponent(cp)}`, { method: "POST" });
toast(`Start: ${r.remote_start}`);
setTimeout(refreshStatus, 1500);
} catch (e) { toast(e.message); }
}
async function stopTx(tx) {
try {
const r = await api(`/charger/stop/${tx}`, { method: "POST" });
toast(`Stop: ${r.remote_stop}`);
setTimeout(refreshStatus, 1500);
} catch (e) { toast(e.message); }
}
// ---- relays ----
let relayLive = {}; // name -> true/false/undefined, from the last live poll/switch
function renderRelays(_) {
const names = Object.keys(status.relays || {});
$("relays-card").classList.toggle("hidden", !names.length);
$("relays").innerHTML = names.map(name => {
const label = status.relays[name].label || name;
const on = relayLive[name];
const chip = on === undefined ? `<span class="chip">?</span>`
: `<span class="chip ${on ? "ok" : ""}">${on ? "ON" : "OFF"}</span>`;
return `<div class="row" style="padding:6px 0">
<div class="grow title">${esc(label)}</div>${chip}
<button class="small" onclick="toggleRelay('${esc(name)}')">Toggle</button>
</div>`;
}).join("");
}
async function toggleRelay(name) {
try {
const r = await api(`/relays/${encodeURIComponent(name)}/toggle`, { method: "POST" });
relayLive[name] = r.on;
renderRelays();
toast(`${name}: ${r.on ? "ON" : "OFF"}`);
} catch (e) { toast(e.message); }
}
async function refreshRelaysLive() {
try {
const live = await api("/relays?live=true");
for (const [name, st] of Object.entries(live))
relayLive[name] = "on" in st ? st.on : undefined;
renderRelays();
} catch (e) { toast(e.message); }
}
// ---- history tab ----
const fmtTime = (iso) => iso ? new Date(iso).toLocaleString([], { dateStyle: "short", timeStyle: "short" }) : "";
const fmtKwh = (wh) => wh == null ? "…" : (wh / 1000).toFixed(2);
function fmtDuration(a, b) {
if (!a || !b) return "";
const mins = Math.max(0, Math.round((new Date(b) - new Date(a)) / 60000));
return mins >= 60 ? `${Math.floor(mins / 60)}h${String(mins % 60).padStart(2, "0")}` : `${mins}m`;
}
async function loadSessions() {
try {
const rows = await api("/sessions?limit=100");
$("sessions").innerHTML = rows.map(s => `<tr>
<td>${esc(s.who || s.id_tag)}</td>
<td>${s.connector}</td>
<td>${fmtTime(s.started)}</td>
<td class="num"><b>${fmtKwh(s.wh)}</b></td>
<td class="sub">${s.ended ? fmtDuration(s.started, s.ended) : '<span class="chip ok">live</span>'}</td>
</tr>`).join("") || `<tr><td colspan="5" class="sub">No sessions yet</td></tr>`;
} catch (e) { toast(e.message); }
}
// ---- admin tab ----
async function loadAdmin() {
try {
const al = await api("/allowlist");
$("mode-label").textContent = al.learn_mode ? "Learn mode" : "Enforcing allowlist";
$("mode-btn").textContent = al.learn_mode ? "Enforce" : "Back to learn";
$("mode-btn").dataset.learn = al.learn_mode;
$("allowlist").innerHTML = Object.entries(al.authorized).map(([tag, e]) => `<tr>
<td class="sub">${esc(tag)}</td><td>${esc(e.name)}</td>
<td>${e.connectors ? e.connectors.join(",") : "all"}</td>
<td><button class="danger small" onclick="delAllowlist('${esc(tag)}')">&#10005;</button></td>
</tr>`).join("");
const seen = Object.entries(al.seen || {}).filter(([tag]) => !(tag in al.authorized));
$("seen-tags").innerHTML = seen.length
? `<div class="sub" style="margin-top:8px">Seen but not enrolled:</div>` + seen.map(([tag, s]) =>
`<div class="row" style="padding:4px 0"><div class="grow sub">${esc(tag)} (&times;${s.count})</div>
<button class="small secondary" onclick="$('a-tag').value='${esc(tag)}';$('a-name').focus()">Enroll</button></div>`).join("")
: "";
const users = await api("/users");
$("users").innerHTML = users.map(u => `<tr>
<td>${esc(u.name)}</td><td class="sub">${esc(u.scopes.join(" "))}</td>
<td><button class="danger small" onclick="delUser('${esc(u.name)}')">&#10005;</button></td>
</tr>`).join("") || `<tr><td colspan="3" class="sub">No users — API is open</td></tr>`;
} catch (e) { toast(e.message); }
}
async function toggleMode() {
const toLearn = $("mode-btn").dataset.learn !== "true";
if (!toLearn && !confirm("Enforce the allowlist? Unknown cards will be rejected.")) return;
try { await api(`/mode?learn=${toLearn}`, { method: "POST" }); loadAdmin(); }
catch (e) { toast(e.message); }
}
async function addAllowlist(ev) {
ev.preventDefault();
const body = { name: $("a-name").value.trim(), kind: $("a-kind").value };
const conns = $("a-conn").value.trim();
if (conns) body.connectors = conns.split(",").map(s => +s.trim()).filter(Boolean);
try {
await api(`/allowlist/${encodeURIComponent($("a-tag").value.trim())}`,
{ method: "PUT", body: JSON.stringify(body) });
$("a-tag").value = $("a-name").value = $("a-conn").value = "";
loadAdmin();
} catch (e) { toast(e.message); }
return false;
}
async function delAllowlist(tag) {
if (!confirm(`Remove ${tag} from the allowlist?`)) return;
try { await api(`/allowlist/${encodeURIComponent(tag)}`, { method: "DELETE" }); loadAdmin(); }
catch (e) { toast(e.message); }
}
async function addUser(ev) {
ev.preventDefault();
const body = {};
if ($("u-pass").value) body.password = $("u-pass").value;
if ($("u-scopes").value.trim()) body.scopes = $("u-scopes").value.trim().split(/\s+/);
try {
await api(`/users/${encodeURIComponent($("u-name").value.trim())}`,
{ method: "PUT", body: JSON.stringify(body) });
$("u-name").value = $("u-pass").value = $("u-scopes").value = "";
loadAdmin();
} catch (e) { toast(e.message); }
return false;
}
async function delUser(name) {
if (!confirm(`Delete user ${name}?`)) return;
try { await api(`/users/${encodeURIComponent(name)}`, { method: "DELETE" }); loadAdmin(); }
catch (e) { toast(e.message); }
}
// ---- go ----
if ("serviceWorker" in navigator) navigator.serviceWorker.register("/sw.js").catch(() => {});
boot();
</script>
</body>
</html>
+12
View File
@@ -0,0 +1,12 @@
{
"name": "Home Energy",
"short_name": "Energy",
"description": "Home EV charger and relay control",
"start_url": "/",
"display": "standalone",
"background_color": "#0f172a",
"theme_color": "#0f172a",
"icons": [
{ "src": "/static/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }
]
}
+6
View File
@@ -0,0 +1,6 @@
// Minimal service worker: required for "add to home screen" installability.
// No caching — the panel is only reachable over NetBird/LAN anyway, and a
// stale cached UI causes more confusion than a brief offline error.
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim()));
self.addEventListener("fetch", () => {});
+132
View File
@@ -0,0 +1,132 @@
"""Charging-session store — who charged, when, and how many kWh.
SQLite (stdlib) in sessions.db next to this module. Two tables:
sessions — one row per transaction: cp, connector, idTag, resolved "who",
start/end timestamps (charger-reported), meter readings, Wh, reason
samples — per-minute MeterValues while charging (energy/power/SoC) for
later charts
The events.jsonl journal (journal.py) stays the raw ground truth; this is the
queryable view. Transaction ids come from MAX(tx)+1 here, so they survive
backend restarts (the in-memory counter used to reset to 0).
sqlite3 connections are cheap at household scale — one per call, no pooling.
"""
import sqlite3
from contextlib import closing
from pathlib import Path
from typing import Optional
HERE = Path(__file__).resolve().parent
DB_PATH = HERE / "sessions.db"
_SCHEMA = """
CREATE TABLE IF NOT EXISTS sessions (
tx INTEGER PRIMARY KEY,
cp TEXT NOT NULL,
connector INTEGER NOT NULL,
id_tag TEXT NOT NULL,
who TEXT,
started TEXT NOT NULL,
ended TEXT,
meter_start REAL NOT NULL,
meter_stop REAL,
wh REAL,
reason TEXT
);
CREATE TABLE IF NOT EXISTS samples (
tx INTEGER NOT NULL,
time TEXT NOT NULL,
energy_wh REAL,
power_w REAL,
soc REAL
);
CREATE INDEX IF NOT EXISTS idx_samples_tx ON samples (tx);
CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions (started);
"""
def _db():
"""Context manager: commits on success AND closes (a bare `with sqlite3
.connect(...)` only commits — the handle would leak)."""
con = sqlite3.connect(DB_PATH)
con.row_factory = sqlite3.Row
con.executescript(_SCHEMA)
return closing(con)
def max_tx() -> int:
with _db() as con, con:
row = con.execute("SELECT MAX(tx) AS m FROM sessions").fetchone()
return row["m"] or 0
def start_session(tx: int, cp: str, connector: int, id_tag: str, who: str,
started: str, meter_start: float) -> None:
with _db() as con, con:
con.execute(
"INSERT OR REPLACE INTO sessions (tx, cp, connector, id_tag, who, started, meter_start)"
" VALUES (?, ?, ?, ?, ?, ?, ?)",
(tx, cp, connector, id_tag, who, started, meter_start),
)
def end_session(tx: int, ended: str, meter_stop: float,
reason: Optional[str] = None) -> None:
with _db() as con, con:
con.execute(
"UPDATE sessions SET ended = ?, meter_stop = ?, reason = ?,"
" wh = ? - meter_start WHERE tx = ?",
(ended, meter_stop, reason, meter_stop, tx),
)
def add_sample(tx: int, time: str, energy_wh: Optional[float],
power_w: Optional[float], soc: Optional[float]) -> 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),
)
def get_session(tx: int) -> Optional[dict]:
with _db() as con, con:
row = con.execute("SELECT * FROM sessions WHERE tx = ?", (tx,)).fetchone()
return dict(row) if row else None
def open_session(tx: int) -> Optional[dict]:
"""An unfinished session (e.g. still running after a backend restart)."""
with _db() as con, con:
row = con.execute(
"SELECT * FROM sessions WHERE tx = ? AND ended IS NULL", (tx,)
).fetchone()
return dict(row) if row else None
def query_sessions(limit: int = 50, cp: Optional[str] = None,
connector: Optional[int] = None) -> list:
sql, args = "SELECT * FROM sessions", []
where = []
if cp is not None:
where.append("cp = ?")
args.append(cp)
if connector is not None:
where.append("connector = ?")
args.append(connector)
if where:
sql += " WHERE " + " AND ".join(where)
sql += " ORDER BY tx DESC LIMIT ?"
args.append(limit)
with _db() as con, con:
return [dict(row) for row in con.execute(sql, args)]
def samples_for(tx: int) -> list:
with _db() as con, con:
return [
dict(row) for row in
con.execute("SELECT * FROM samples WHERE tx = ? ORDER BY time", (tx,))
]
+157
View File
@@ -0,0 +1,157 @@
"""User accounts, password hashing, sessions, and the scope matcher.
Everything is stdlib crypto: PBKDF2-HMAC-SHA256 for passwords, HMAC-signed
stateless tokens for sessions (they survive backend restarts; "logout" is the
client dropping its cookie). Users live in config.json -> "users":
"julian": {
"password": "pbkdf2$600000$<salt hex>$<hash hex>",
"scopes": ["admin"], # or charger:<cp>:<gun>, relay:<name>
"id_tag": "app-julian" # idTag used for their remote starts
}
Scopes are matched with fnmatch, so "relay:*" or "charger:eu092025:*" work.
"admin" implies every scope and is required for management endpoints.
CLI (from the repo root):
venv\\Scripts\\python -m backend.users add <name> --scopes admin
venv\\Scripts\\python -m backend.users list
venv\\Scripts\\python -m backend.users remove <name>
"""
import base64
import hashlib
import hmac
import secrets
import time
from fnmatch import fnmatch
from .config import CONFIG, save
PBKDF2_ITERATIONS = 600_000
SESSION_TTL = 30 * 24 * 3600 # 30 days
# ---- passwords ----
def hash_password(password: str) -> str:
salt = secrets.token_hex(16)
digest = hashlib.pbkdf2_hmac(
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
)
return f"pbkdf2${PBKDF2_ITERATIONS}${salt}${digest.hex()}"
def verify_password(password: str, stored: str) -> bool:
try:
scheme, iterations, salt, expected = stored.split("$")
if scheme != "pbkdf2":
return False
digest = hashlib.pbkdf2_hmac(
"sha256", password.encode(), bytes.fromhex(salt), int(iterations)
)
return hmac.compare_digest(digest.hex(), expected)
except (ValueError, AttributeError):
return False
# ---- sessions (stateless HMAC tokens) ----
def _secret() -> bytes:
return CONFIG["session_secret"].encode()
def _sign(payload: str) -> str:
return hmac.new(_secret(), payload.encode(), hashlib.sha256).hexdigest()
def mint_session(username: str) -> str:
payload = f"{username}|{int(time.time()) + SESSION_TTL}"
token = f"{payload}|{_sign(payload)}"
return base64.urlsafe_b64encode(token.encode()).decode()
def verify_session(token: str) -> str | None:
"""Return the username for a valid, unexpired token; None otherwise."""
try:
username, expires, signature = (
base64.urlsafe_b64decode(token.encode()).decode().split("|")
)
except Exception:
return None
if not hmac.compare_digest(_sign(f"{username}|{expires}"), signature):
return None
if int(expires) < time.time():
return None
if username not in CONFIG["users"]:
return None # deleted users lose their sessions
return username
# ---- scopes ----
def allowed(scopes: list, needed: str) -> bool:
return any(
grant in ("*", "admin") or fnmatch(needed, grant) for grant in scopes
)
# ---- user management (used by the CLI and the admin API) ----
def set_user(name: str, password: str | None = None, scopes: list | None = None) -> dict:
user = CONFIG["users"].get(name, {"scopes": [], "id_tag": f"app-{name}"})
if password is not None:
user["password"] = hash_password(password)
if scopes is not None:
user["scopes"] = scopes
user.setdefault("id_tag", f"app-{name}")
if "password" not in user:
raise ValueError(f"new user {name!r} needs a password")
CONFIG["users"][name] = user
save()
return user
def remove_user(name: str) -> None:
if CONFIG["users"].pop(name, None) is None:
raise KeyError(name)
save()
def public_view(name: str, user: dict) -> dict:
"""A user entry without the password hash — safe for /api/me and /api/users."""
return {"name": name, "scopes": user["scopes"], "id_tag": user.get("id_tag")}
def _cli() -> None:
import argparse
import getpass
parser = argparse.ArgumentParser(prog="backend.users", description=__doc__)
sub = parser.add_subparsers(dest="cmd", required=True)
p_add = sub.add_parser("add", help="add a user or update an existing one")
p_add.add_argument("name")
p_add.add_argument("--scopes", nargs="+", default=None,
help='e.g. admin, "charger:eu092025:1", "relay:*"')
sub.add_parser("list", help="list users and their scopes")
p_rm = sub.add_parser("remove", help="delete a user")
p_rm.add_argument("name")
args = parser.parse_args()
if args.cmd == "list":
for name, user in CONFIG["users"].items():
print(f"{name:20} scopes={user['scopes']} id_tag={user.get('id_tag')}")
if not CONFIG["users"]:
print("no users configured — the API is OPEN (anonymous admin)")
elif args.cmd == "add":
existing = args.name in CONFIG["users"]
password = getpass.getpass(f"{'New ' if not existing else ''}password for {args.name!r}: ")
if not existing or password:
confirm = getpass.getpass("Repeat password: ")
if password != confirm:
raise SystemExit("passwords do not match")
user = set_user(args.name, password=password or None, scopes=args.scopes)
print(f"{'updated' if existing else 'created'} {args.name!r}: scopes={user['scopes']}")
elif args.cmd == "remove":
remove_user(args.name)
print(f"removed {args.name!r}")
if __name__ == "__main__":
_cli()
+31
View File
@@ -0,0 +1,31 @@
{
"charge_point": "TESTCP",
"probed_at": "2026-07-09T14:50:00.315598+00:00",
"boot_info": {
"vendor": "FakeVendor",
"model": "FakeModel-7kW",
"firmware_version": "0.0.1"
},
"configuration": [
{
"key": "NumberOfConnectors",
"readonly": true,
"value": "1"
},
{
"key": "SupportedFeatureProfiles",
"readonly": true,
"value": "Core,RemoteTrigger,LocalAuthListManagement"
},
{
"key": "MeterValueSampleInterval",
"readonly": false,
"value": "60"
}
],
"unknown_keys": [],
"trigger_status_notification": "Accepted",
"connectors_seen": {
"1": "Available"
}
}
+336
View File
@@ -0,0 +1,336 @@
{
"charge_point": "eu092025",
"probed_at": "2026-07-09T15:33:50.788871+00:00",
"boot_info": {
"vendor": "SimpleCharge",
"model": "MultiSocketCharger",
"charge_point_serial_number": "24310588",
"firmware_version": "1.24.0620.1",
"iccid": "",
"imsi": ""
},
"configuration": [
{
"key": "AllowOfflineTxForUnknownId",
"readonly": false,
"value": "false"
},
{
"key": "AuthorizationCacheEnabled",
"readonly": false,
"value": "true"
},
{
"key": "AuthorizeRemoteTxRequests",
"readonly": false,
"value": "false"
},
{
"key": "ClockAlignedDataInterval",
"readonly": false,
"value": "0"
},
{
"key": "ConnectorPhaseRotationMaxLength",
"readonly": true,
"value": "1"
},
{
"key": "ConnectionTimeOut",
"readonly": false,
"value": "60"
},
{
"key": "GetConfigurationMaxKeys",
"readonly": true,
"value": "30"
},
{
"key": "HeartbeatInterval",
"readonly": false,
"value": "7200"
},
{
"key": "LocalAuthorizeOffline",
"readonly": false,
"value": "false"
},
{
"key": "LocalPreAuthorize",
"readonly": false,
"value": "0"
},
{
"key": "MaxEnergyOnInvalidId",
"readonly": false,
"value": "0"
},
{
"key": "MeterValueSampleInterval",
"readonly": false,
"value": "60"
},
{
"key": "NumberOfConnectors",
"readonly": true,
"value": "2"
},
{
"key": "ResetRetries",
"readonly": false,
"value": "0"
},
{
"key": "StopTransactionOnEVSideDisconnect",
"readonly": false,
"value": "1"
},
{
"key": "StopTransactionOnInvalidId",
"readonly": false,
"value": "1"
},
{
"key": "TransactionMessageAttempts",
"readonly": false,
"value": "50"
},
{
"key": "TransactionMessageRetryInterval",
"readonly": false,
"value": "60"
},
{
"key": "WebSocketPingInterval",
"readonly": false,
"value": "60"
},
{
"key": "LocalAuthListEnabled",
"readonly": false,
"value": "false"
},
{
"key": "LocalAuthListMaxLength",
"readonly": true,
"value": "6"
},
{
"key": "SendLocalListMaxLength",
"readonly": true,
"value": "6"
},
{
"key": "ChargeProfileMaxStackLevel",
"readonly": true,
"value": "3"
},
{
"key": "UnlockConnectorOnEVSideDisconnect",
"readonly": false,
"value": "1"
},
{
"key": "SendJCMeterValuesType",
"readonly": true,
"value": "1"
},
{
"key": "ChargingScheduleAllowedChargingRateUnit",
"readonly": true,
"value": "Power"
},
{
"key": "ChargingScheduleMaxPeriods",
"readonly": true,
"value": "3"
},
{
"key": "MaxChargingProfilesInstalled",
"readonly": true,
"value": "1"
},
{
"key": "LocalListVersion",
"readonly": true,
"value": "-1"
},
{
"key": "MeterValuesAlignedData",
"readonly": false,
"value": "Energy.Active.Import.Register,Power.Active.Import,SoC,Voltage,Current.Import"
},
{
"key": "MeterValuesSampledData",
"readonly": false,
"value": "Energy.Active.Import.Register,Power.Active.Import,SoC,Voltage,Current.Import"
},
{
"key": "StopTxnAlignedData",
"readonly": false,
"value": "SoC"
},
{
"key": "StopTxnSampledData",
"readonly": false,
"value": "Energy.Active.Import.Register"
},
{
"key": "ConnectorPhaseRotation",
"readonly": false,
"value": "RST"
},
{
"key": "SupportedFeatureProfiles",
"readonly": true,
"value": "Core,FirmwareManagement,LocalAuthListManagement,Reservation,SmartCharging,RemoteTrigger"
},
{
"key": "Url",
"readonly": false,
"value": "http://10.0.10.203:9000"
},
{
"key": "Vendor",
"readonly": true,
"value": "JC"
},
{
"key": "Model",
"readonly": true,
"value": "MultiSocketCharger"
},
{
"key": "TimeZone",
"readonly": false,
"value": "0"
},
{
"key": "ProtocolName",
"readonly": true,
"value": "ocpp1.6"
},
{
"key": "QRCodeTextOfConnector-1",
"readonly": false,
"value": ""
},
{
"key": "QRCodeTextOfConnector-2",
"readonly": false,
"value": ""
},
{
"key": "QRCodeTextOfConnector-3",
"readonly": false,
"value": ""
},
{
"key": "AuthorizationKey",
"readonly": false,
"value": ""
},
{
"key": "AuthorizationUser",
"readonly": true,
"value": ""
},
{
"key": "CpoName",
"readonly": false,
"value": ""
},
{
"key": "OutputLimitRate",
"readonly": false,
"value": "100"
},
{
"key": "PeakPrice",
"readonly": false,
"value": "1.0000"
},
{
"key": "OffPeakPrice",
"readonly": false,
"value": "0.5000"
},
{
"key": "IdleFeePerMinute",
"readonly": false,
"value": "0.0100"
},
{
"key": "IdleTime",
"readonly": false,
"value": "5"
},
{
"key": "MacEnabled",
"readonly": false,
"value": "true"
},
{
"key": "FreeChargeMode",
"readonly": false,
"value": "false"
},
{
"key": "KeepConnectOTAServer",
"readonly": false,
"value": "true"
},
{
"key": "DataTransferVendorId",
"readonly": false,
"value": ""
},
{
"key": "MeterValuesAlignedDataMaxLength",
"readonly": true,
"value": "5"
},
{
"key": "MeterValuesSampledDataMaxLength",
"readonly": true,
"value": "5"
},
{
"key": "StopTxnAlignedDataMaxLength",
"readonly": true,
"value": "5"
},
{
"key": "StopTxnSampledDataMaxLength",
"readonly": true,
"value": "5"
},
{
"key": "SupportedFeatureProfilesMaxLength",
"readonly": true,
"value": "6"
},
{
"key": "ReserveConnectorZeroSupported",
"readonly": true,
"value": "false"
},
{
"key": "ConnectorSwitch3to1PhaseSupported",
"readonly": true,
"value": "false"
},
{
"key": "ChargePointID",
"readonly": false,
"value": "eu092025"
}
],
"unknown_keys": null,
"trigger_status_notification": "Accepted",
"connectors_seen": {
"0": "Available",
"1": "Preparing",
"2": "Available"
}
}
+61
View File
@@ -0,0 +1,61 @@
{"time": "2026-07-09T14:49:55.301899+00:00", "event": "connected", "cp": "TESTCP", "client": "Address(host='127.0.0.1', port=52661)", "subprotocols": ["ocpp1.6"]}
{"time": "2026-07-09T14:49:55.311317+00:00", "event": "BootNotification", "cp": "TESTCP", "vendor": "FakeVendor", "model": "FakeModel-7kW", "firmware_version": "0.0.1"}
{"time": "2026-07-09T14:49:55.318486+00:00", "event": "Authorize", "cp": "TESTCP", "id_tag": "CARD-TEST-123", "result": "Accepted"}
{"time": "2026-07-09T14:50:00.334616+00:00", "event": "StatusNotification", "cp": "TESTCP", "connector": 1, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T14:50:03.389613+00:00", "event": "connected", "cp": "eu092025", "client": "Address(host='10.0.10.152', port=44810)", "subprotocols": ["ocpp1.6"]}
{"time": "2026-07-09T14:50:08.719261+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 0, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T14:50:08.926940+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T14:50:09.132883+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T14:50:15.331029+00:00", "event": "disconnected", "cp": "TESTCP"}
{"time": "2026-07-09T14:54:16.567013+00:00", "event": "connected", "cp": "eu092025", "client": "Address(host='10.0.10.152', port=43000)", "subprotocols": ["ocpp1.6"]}
{"time": "2026-07-09T14:54:21.741178+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 0, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T14:54:21.903108+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T14:54:22.109657+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T15:02:59.819374+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Preparing", "error": "NoError"}
{"time": "2026-07-09T15:07:19.906156+00:00", "event": "Authorize", "cp": "eu092025", "id_tag": "1000000000000393", "result": "Accepted"}
{"time": "2026-07-09T15:07:20.139915+00:00", "event": "StartTransaction", "cp": "eu092025", "connector": 2, "id_tag": "1000000000000393", "meter_start": 3513857, "result": "Accepted", "tx": 1}
{"time": "2026-07-09T15:07:20.323299+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Charging", "error": "NoError"}
{"time": "2026-07-09T15:07:20.906172+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:07:19.445Z", "sampled_value": [{"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3513857", "context": "Transaction.Begin", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
{"time": "2026-07-09T15:07:43.370964+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Preparing", "error": "NoError"}
{"time": "2026-07-09T15:08:21.093068+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:08:20.617277826Z", "sampled_value": [{"value": "98.8", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3514087", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "30580", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "61", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "309.6", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
{"time": "2026-07-09T15:08:58.365193+00:00", "event": "StartTransaction", "cp": "eu092025", "connector": 1, "id_tag": "app-remote", "meter_start": 405382, "result": "Accepted", "tx": 2}
{"time": "2026-07-09T15:08:58.668936+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Charging", "error": "NoError"}
{"time": "2026-07-09T15:08:59.044085+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 1, "values": [{"timestamp": "2026-07-09T15:08:57.720Z", "sampled_value": [{"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "405382", "context": "Transaction.Begin", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 2}
{"time": "2026-07-09T15:09:21.178130+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:09:20.728656493Z", "sampled_value": [{"value": "98.6", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3514622", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "30660", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "62", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "311.0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
{"time": "2026-07-09T15:09:59.338172+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 1, "values": [{"timestamp": "2026-07-09T15:09:58.900267471Z", "sampled_value": [{"value": "0.0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "405382", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "64", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 2}
{"time": "2026-07-09T15:10:09.353518+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Finishing", "error": "NoError"}
{"time": "2026-07-09T15:10:10.392443+00:00", "event": "StopTransaction", "cp": "eu092025", "tx": 2, "meter_stop": 405731, "delivered_wh": 349, "id_tag": "app-remote", "reason": "Remote", "transaction_data": [{"timestamp": "2026-07-09T15:10:08.231Z", "sampled_value": [{"value": "405731", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}]}]}
{"time": "2026-07-09T15:10:10.655340+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 1, "values": [{"timestamp": "2026-07-09T15:10:08.231Z", "sampled_value": [{"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "405731", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.End", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "64", "context": "Transaction.End", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 2}
{"time": "2026-07-09T15:10:21.181272+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:10:20.751714927Z", "sampled_value": [{"value": "98.4", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3515115", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "30680", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "63", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "311.8", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
{"time": "2026-07-09T15:11:21.161004+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:11:20.752496181Z", "sampled_value": [{"value": "98.3", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3515617", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "30640", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "65", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "311.8", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
{"time": "2026-07-09T15:11:26.454939+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Finishing", "error": "NoError"}
{"time": "2026-07-09T15:11:27.967000+00:00", "event": "StopTransaction", "cp": "eu092025", "tx": 1, "meter_stop": 3515664, "delivered_wh": 1807, "id_tag": "1000000000000393", "reason": "Remote", "transaction_data": [{"timestamp": "2026-07-09T15:11:26.858Z", "sampled_value": [{"value": "3515664", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}]}]}
{"time": "2026-07-09T15:11:28.173805+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:11:26.858Z", "sampled_value": [{"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3515664", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.End", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "65", "context": "Transaction.End", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 1}
{"time": "2026-07-09T15:12:06.504623+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T15:12:11.528746+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Preparing", "error": "NoError"}
{"time": "2026-07-09T15:12:31.966934+00:00", "event": "Authorize", "cp": "eu092025", "id_tag": "1000000000000393", "result": "Accepted"}
{"time": "2026-07-09T15:12:32.272632+00:00", "event": "StartTransaction", "cp": "eu092025", "connector": 2, "id_tag": "1000000000000393", "meter_start": 3515664, "result": "Accepted", "tx": 3}
{"time": "2026-07-09T15:12:32.450600+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Charging", "error": "NoError"}
{"time": "2026-07-09T15:12:33.053501+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:12:31.679Z", "sampled_value": [{"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3515664", "context": "Transaction.Begin", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "0", "context": "Transaction.Begin", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.Begin", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 3}
{"time": "2026-07-09T15:13:33.234090+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:13:32.875985191Z", "sampled_value": [{"value": "129.3", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3516035", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "40690", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "65", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "314.7", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 3}
{"time": "2026-07-09T15:13:56.469910+00:00", "event": "Authorize", "cp": "eu092025", "id_tag": "1000000000000395", "result": "Accepted"}
{"time": "2026-07-09T15:14:33.303145+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:14:32.970773241Z", "sampled_value": [{"value": "121.2", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3516671", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "38050", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "67", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "314.0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 3}
{"time": "2026-07-09T15:14:38.019887+00:00", "event": "Authorize", "cp": "eu092025", "id_tag": "1000000000000395", "result": "Accepted"}
{"time": "2026-07-09T15:15:33.369007+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:15:33.061647792Z", "sampled_value": [{"value": "121.2", "context": "Sample.Periodic", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3517340", "context": "Sample.Periodic", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "38050", "context": "Sample.Periodic", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "68", "context": "Sample.Periodic", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "314.0", "context": "Sample.Periodic", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 3}
{"time": "2026-07-09T15:16:31.502080+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Finishing", "error": "NoError"}
{"time": "2026-07-09T15:16:32.612265+00:00", "event": "StopTransaction", "cp": "eu092025", "tx": 3, "meter_stop": 3517928, "delivered_wh": 2264, "id_tag": "1000000000000393", "reason": "Remote", "transaction_data": [{"timestamp": "2026-07-09T15:16:31.628Z", "sampled_value": [{"value": "3517928", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}]}]}
{"time": "2026-07-09T15:16:32.739682+00:00", "event": "MeterValues", "cp": "eu092025", "connector": 2, "values": [{"timestamp": "2026-07-09T15:16:31.628Z", "sampled_value": [{"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Current.Import", "location": "Outlet", "unit": "A"}, {"value": "3517928", "context": "Transaction.End", "format": "Raw", "measurand": "Energy.Active.Import.Register", "location": "Outlet", "unit": "Wh"}, {"value": "0", "context": "Transaction.End", "format": "Raw", "measurand": "Power.Active.Import", "location": "Outlet", "unit": "W"}, {"value": "69", "context": "Transaction.End", "format": "Raw", "measurand": "SoC", "location": "Outlet", "unit": "Percent"}, {"value": "0.0", "context": "Transaction.End", "format": "Raw", "measurand": "Voltage", "location": "Outlet", "unit": "V"}]}], "transaction_id": 3}
{"time": "2026-07-09T15:16:37.120878+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T15:22:11.084171+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T15:22:14.593031+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Preparing", "error": "NoError"}
{"time": "2026-07-09T15:32:56.678733+00:00", "event": "disconnected", "cp": "eu092025"}
{"time": "2026-07-09T15:33:45.785808+00:00", "event": "connected", "cp": "eu092025", "client": "Address(host='10.0.10.152', port=33650)", "subprotocols": ["ocpp1.6"]}
{"time": "2026-07-09T15:33:46.288738+00:00", "event": "BootNotification", "cp": "eu092025", "vendor": "SimpleCharge", "model": "MultiSocketCharger", "charge_point_serial_number": "24310588", "firmware_version": "1.24.0620.1", "iccid": "", "imsi": ""}
{"time": "2026-07-09T15:33:47.696131+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 0, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T15:33:49.711246+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T15:33:49.921913+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T15:33:51.124034+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Preparing", "error": "NoError"}
{"time": "2026-07-09T15:33:51.234093+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 0, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T15:33:51.443211+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 2, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T16:56:22.781138+00:00", "event": "StatusNotification", "cp": "eu092025", "connector": 1, "status": "Available", "error": "NoError"}
{"time": "2026-07-09T17:45:22.815009+00:00", "event": "disconnected", "cp": "eu092025"}
+2
View File
@@ -1,4 +1,6 @@
attrs==26.1.0
fastapi==0.139.0
uvicorn==0.51.0
jsonschema==4.26.0
jsonschema-specifications==2025.9.1
ocpp==2.1.0
+35
View File
@@ -0,0 +1,35 @@
{
"CARD-TEST-123": {
"count": 2,
"first_seen": "2026-07-09T13:48:25.276914+00:00",
"contexts": [
"Authorize (card/app/autocharge)"
],
"last_seen": "2026-07-09T14:49:55.317640+00:00"
},
"1000000000000393": {
"count": 4,
"first_seen": "2026-07-09T15:07:19.905448+00:00",
"contexts": [
"Authorize (card/app/autocharge)",
"StartTransaction (connector 2)"
],
"last_seen": "2026-07-09T15:12:32.270138+00:00"
},
"app-remote": {
"count": 1,
"first_seen": "2026-07-09T15:08:58.363084+00:00",
"contexts": [
"StartTransaction (connector 1)"
],
"last_seen": "2026-07-09T15:08:58.363112+00:00"
},
"1000000000000395": {
"count": 2,
"first_seen": "2026-07-09T15:13:56.468848+00:00",
"contexts": [
"Authorize (card/app/autocharge)"
],
"last_seen": "2026-07-09T15:14:38.018675+00:00"
}
}
+241 -19
View File
@@ -19,6 +19,18 @@ Workflow:
3. Move the ones you want into "authorized" in station_config.json, name them.
4. Set "learn_mode": false and restart -> only your ids are accepted.
Discovery API (same port 9000 the charger dials — http://<host>:9000, docs at /docs):
GET /status connected chargers, guns, transactions, auth events
GET /events?limit=100&event=X tail the permanent event journal (events.jsonl)
GET /tags seen + authorized idTags
POST /probe GetConfiguration + trigger StatusNotification,
saved to discovery_<id>.json (also auto-runs on connect)
POST /start?id_tag=X&connector=1 RemoteStartTransaction
POST /stop/{tx} or POST /stop RemoteStopTransaction (no tx = the only active one)
POST /trigger/{status|meter|heartbeat|boot}?connector=N
POST /unlock/{connector} UnlockConnector
POST /setconfig?key=K&value=V ChangeConfiguration (e.g. MeterValueSampleInterval)
Run: venv/Scripts/python station.py
"""
@@ -28,8 +40,10 @@ import logging
from collections import deque
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
import websockets
import uvicorn
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
from ocpp.routing import on
from ocpp.v16 import ChargePoint as OcppChargePoint
@@ -38,12 +52,14 @@ from ocpp.v16.enums import (
Action,
AuthorizationStatus,
DataTransferStatus,
MessageTrigger,
RegistrationStatus,
)
HERE = Path(__file__).resolve().parent
CONFIG_PATH = HERE / "station_config.json"
SEEN_PATH = HERE / "seen_tags.json"
EVENTS_PATH = HERE / "events.jsonl"
logging.basicConfig(
level=logging.INFO,
@@ -79,6 +95,17 @@ def load_config() -> dict:
CONFIG = load_config()
def record_event(event: str, cp_id: str, **data) -> None:
"""Append one JSON line to events.jsonl — the permanent journal of everything
the charger tells us (and what we told it). Survives restarts; grep/ingest later."""
entry = {"time": now(), "event": event, "cp": cp_id, **data}
try:
with EVENTS_PATH.open("a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n")
except Exception:
log.exception("failed to journal event %r", event)
def record_seen(id_tag: str, context: str) -> None:
"""Append/refresh an entry in seen_tags.json so you can harvest ids later."""
try:
@@ -123,6 +150,8 @@ def decide(id_tag: str, context: str) -> AuthorizationStatus:
class ChargePoint(OcppChargePoint):
@on(Action.boot_notification)
async def on_boot_notification(self, charge_point_vendor, charge_point_model, **kwargs):
self.boot_info = {"vendor": charge_point_vendor, "model": charge_point_model, **kwargs}
record_event("BootNotification", self.id, **self.boot_info)
log.info("BootNotification: vendor=%r model=%r extra=%r",
charge_point_vendor, charge_point_model, kwargs)
return call_result.BootNotification(
@@ -136,6 +165,8 @@ class ChargePoint(OcppChargePoint):
@on(Action.status_notification)
async def on_status_notification(self, connector_id, error_code, status, **kwargs):
CONNECTORS[(self.id, connector_id)] = status
record_event("StatusNotification", self.id,
connector=connector_id, status=status, error=error_code)
log.info("StatusNotification: connector=%s status=%s error=%s",
connector_id, status, error_code)
return call_result.StatusNotification()
@@ -144,6 +175,7 @@ class ChargePoint(OcppChargePoint):
async def on_authorize(self, id_tag, **kwargs):
# RFID card tap, or app pre-auth. Plug-in autocharge sometimes lands here too.
status = decide(id_tag, "Authorize (card/app/autocharge)")
record_event("Authorize", self.id, id_tag=id_tag, result=status.value)
return call_result.Authorize(id_tag_info={"status": status})
@on(Action.start_transaction)
@@ -160,6 +192,8 @@ class ChargePoint(OcppChargePoint):
tx, connector_id, meter_start)
else:
tx = 0 # 0 tells the charger the transaction is not authorized
record_event("StartTransaction", self.id, connector=connector_id,
id_tag=id_tag, meter_start=meter_start, result=status.value, tx=tx)
return call_result.StartTransaction(
transaction_id=tx, id_tag_info={"status": status}
)
@@ -168,6 +202,8 @@ class ChargePoint(OcppChargePoint):
async def on_stop_transaction(self, meter_stop, timestamp, transaction_id, **kwargs):
info = ACTIVE_TX.pop(transaction_id, None)
used = (meter_stop - info["meter_start"]) if info else "?"
record_event("StopTransaction", self.id, tx=transaction_id,
meter_stop=meter_stop, delivered_wh=used, **kwargs)
log.info("Transaction %s STOPPED (meter_stop=%s, delivered=%s Wh)",
transaction_id, meter_stop, used)
return call_result.StopTransaction(
@@ -176,6 +212,8 @@ class ChargePoint(OcppChargePoint):
@on(Action.meter_values)
async def on_meter_values(self, connector_id, meter_value, **kwargs):
record_event("MeterValues", self.id, connector=connector_id,
values=meter_value, **kwargs)
log.info("MeterValues: connector=%s values=%r", connector_id, meter_value)
return call_result.MeterValues()
@@ -217,34 +255,218 @@ async def remote_stop(transaction_id: int) -> str:
return resp.status
async def on_connect(connection):
path = connection.request.path
cp_id = path.strip("/").split("/")[-1] or "unknown"
log.info("Charger connected: id=%r from %s subprotocol=%r",
cp_id, connection.remote_address, connection.subprotocol)
cp = ChargePoint(cp_id, connection)
# ---- discovery: interrogate the charger about what it is and what it supports ----
async def interrogate(cp: ChargePoint) -> dict:
"""GetConfiguration + trigger a StatusNotification per gun; save to discovery_<id>.json.
GetConfiguration with no keys asks for *everything* the charger exposes:
NumberOfConnectors, SupportedFeatureProfiles, meter settings, local-auth
support, ... A rejected/timed-out probe is itself a finding — record it.
"""
report = {
"charge_point": cp.id,
"probed_at": now(),
"boot_info": getattr(cp, "boot_info", None),
}
try:
resp = await cp.call(call.GetConfiguration())
report["configuration"] = resp.configuration_key
report["unknown_keys"] = resp.unknown_key
except Exception as exc:
report["configuration_error"] = repr(exc)
try:
resp = await cp.call(
call.TriggerMessage(requested_message=MessageTrigger.status_notification)
)
report["trigger_status_notification"] = resp.status
await asyncio.sleep(2) # give the triggered StatusNotifications time to arrive
except Exception as exc:
report["trigger_error"] = repr(exc)
report["connectors_seen"] = {
str(conn): status for (cp_id, conn), status in CONNECTORS.items() if cp_id == cp.id
}
path = HERE / f"discovery_{cp.id}.json"
path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
log.info(
"Discovery report -> %s (%d config keys, guns seen: %s)",
path.name, len(report.get("configuration") or []),
list(report["connectors_seen"]) or "none yet",
)
return report
async def _auto_interrogate(cp: ChargePoint):
await asyncio.sleep(5) # let BootNotification land first
try:
await interrogate(cp)
except Exception:
log.exception("auto-interrogation of %r failed", cp.id)
class _WSAdapter:
"""Bridge a Starlette WebSocket to the recv()/send() interface the ocpp lib expects."""
def __init__(self, ws: WebSocket):
self._ws = ws
async def recv(self) -> str:
return await self._ws.receive_text()
async def send(self, message: str) -> None:
await self._ws.send_text(message)
async def close(self, code: int = 1000, reason: str = "") -> None:
await self._ws.close(code=code)
# ---- discovery HTTP API (curl / browser / phone over NetBird) ----
api = FastAPI(
title="Charger Discovery API",
description="Poke the charger over its live OCPP socket. Interactive docs: /docs",
)
TRIGGERABLE = {
"status": MessageTrigger.status_notification,
"meter": MessageTrigger.meter_values,
"heartbeat": MessageTrigger.heartbeat,
"boot": MessageTrigger.boot_notification,
}
@api.websocket("/{cp_path:path}")
async def ocpp_websocket(ws: WebSocket, cp_path: str):
"""The OCPP endpoint the JC-6620 dials: ws://<host>:9000/<ChargerID>."""
cp_id = cp_path.strip("/").split("/")[-1] or "unknown"
offered = [
p.strip()
for p in ws.headers.get("sec-websocket-protocol", "").split(",")
if p.strip()
]
if not offered:
log.warning(
"Charger %r connected WITHOUT an ocpp subprotocol header. "
"Handling it anyway so we can see its traffic.", cp_id,
)
await ws.accept(subprotocol="ocpp1.6" if "ocpp1.6" in offered else None)
log.info("Charger connected: id=%r from %s subprotocols=%r", cp_id, ws.client, offered)
record_event("connected", cp_id, client=str(ws.client), subprotocols=offered)
cp = ChargePoint(cp_id, _WSAdapter(ws))
CONNECTED[cp_id] = cp
asyncio.create_task(_auto_interrogate(cp))
try:
await cp.start()
except websockets.exceptions.ConnectionClosed:
except WebSocketDisconnect:
log.info("Charger %r disconnected", cp_id)
finally:
record_event("disconnected", cp_id)
CONNECTED.pop(cp_id, None)
for key in [k for k in CONNECTORS if k[0] == cp_id]:
CONNECTORS.pop(key, None)
def _pick_cp(cp_id: Optional[str]) -> ChargePoint:
if cp_id is not None:
cp = CONNECTED.get(cp_id)
if cp is None:
raise HTTPException(404, f"charge point {cp_id!r} is not connected")
return cp
if len(CONNECTED) == 1:
return next(iter(CONNECTED.values()))
raise HTTPException(409, f"specify ?cp=<id>; currently connected: {list(CONNECTED)}")
async def _ocpp(coro):
"""Run an OCPP call for an HTTP handler, mapping failures to HTTP errors."""
try:
return await coro
except HTTPException:
raise
except Exception as exc:
raise HTTPException(502, f"OCPP call failed: {exc!r}")
@api.get("/status")
async def api_status():
return {
"mode": "learn" if CONFIG.get("learn_mode") else "enforce",
"connected": {cp_id: getattr(cp, "boot_info", None) for cp_id, cp in CONNECTED.items()},
"connectors": {f"{cp_id}/{conn}": s for (cp_id, conn), s in CONNECTORS.items()},
"active_transactions": ACTIVE_TX,
"recent_auth_events": list(AUTH_EVENTS),
}
@api.get("/events")
async def api_events(limit: int = 100, event: Optional[str] = None):
"""Tail the event journal; filter with ?event=MeterValues etc."""
if not EVENTS_PATH.exists():
return []
lines = EVENTS_PATH.read_text(encoding="utf-8").splitlines()
entries = [json.loads(line) for line in lines if line.strip()]
if event is not None:
entries = [e for e in entries if e.get("event") == event]
return entries[-limit:]
@api.get("/tags")
async def api_tags():
seen = json.loads(SEEN_PATH.read_text(encoding="utf-8")) if SEEN_PATH.exists() else {}
return {"authorized": CONFIG["authorized"], "seen": seen}
@api.post("/probe")
async def api_probe(cp: Optional[str] = None):
return await _ocpp(interrogate(_pick_cp(cp)))
@api.post("/start")
async def api_start(id_tag: str = "app-remote", connector: int = 1, cp: Optional[str] = None):
status = await _ocpp(remote_start(_pick_cp(cp).id, id_tag, connector))
return {"remote_start": status}
@api.post("/stop")
@api.post("/stop/{tx}")
async def api_stop(tx: Optional[int] = None):
if tx is None:
if len(ACTIVE_TX) != 1:
raise HTTPException(409, f"specify /stop/<tx>; active: {list(ACTIVE_TX)}")
tx = next(iter(ACTIVE_TX))
status = await _ocpp(remote_stop(tx))
return {"remote_stop": status, "transaction": tx}
@api.post("/trigger/{what}")
async def api_trigger(what: str, connector: Optional[int] = None, cp: Optional[str] = None):
if what not in TRIGGERABLE:
raise HTTPException(400, f"unknown trigger {what!r}; options: {list(TRIGGERABLE)}")
payload = call.TriggerMessage(requested_message=TRIGGERABLE[what], connector_id=connector)
resp = await _ocpp(_pick_cp(cp).call(payload))
return {"trigger": what, "status": resp.status}
@api.post("/unlock/{connector}")
async def api_unlock(connector: int, cp: Optional[str] = None):
resp = await _ocpp(_pick_cp(cp).call(call.UnlockConnector(connector_id=connector)))
return {"unlock": connector, "status": resp.status}
@api.post("/setconfig")
async def api_setconfig(key: str, value: str, cp: Optional[str] = None):
resp = await _ocpp(_pick_cp(cp).call(call.ChangeConfiguration(key=key, value=value)))
return {"key": key, "value": value, "status": resp.status}
async def main():
def select_subprotocol(connection, subprotocols):
return "ocpp1.6"
server = await websockets.serve(
on_connect, "0.0.0.0", 9000,
subprotocols=["ocpp1.6"],
select_subprotocol=select_subprotocol,
)
mode = "LEARN (accepting & recording new ids)" if CONFIG["learn_mode"] else "ENFORCING allowlist"
log.info("Private CSMS on ws://0.0.0.0:9000/<id> | mode: %s | %d authorized id(s)",
mode, len(CONFIG["authorized"]))
await server.wait_closed()
log.info(
"Private CSMS on ws://0.0.0.0:9000/<id> | discovery API http://0.0.0.0:9000/docs"
" | mode: %s | %d authorized id(s)",
mode, len(CONFIG["authorized"]),
)
await uvicorn.Server(
uvicorn.Config(api, host="0.0.0.0", port=9000, log_config=None)
).serve()
if __name__ == "__main__":
+14 -1
View File
@@ -1,4 +1,17 @@
{
"learn_mode": true,
"authorized": {}
"authorized": {
"1000000000000393": {
"name": "RFID card A (tapped first, 2026-07-09)",
"kind": "card"
},
"app-remote": {
"name": "Web/app remote start token",
"kind": "app"
},
"1000000000000395": {
"name": "RFID card B (tapped second, 2026-07-09)",
"kind": "card"
}
}
}
+51 -8
View File
@@ -1,24 +1,42 @@
---
type: concept
updated: 2026-07-09
updated: 2026-07-11
tags: [auth, requirements]
---
# Authorization Methods
The three planned ways to authorize a charging session. Architecturally they all collapse to one gate: **`decide(id_tag)` in `station.py`** ([[csms-toolkit]]) returns Accepted/Rejected against the allowlist in `station_config.json`. Per [[2026-07-09-findings-and-requirements]]:
The three planned ways to authorize a charging session. Architecturally they all collapse to one gate: **`decide(id_tag, connector)` in the [[backend]]** (`backend/csms.py`; formerly `station.py` in [[csms-toolkit]]) returns Accepted/Rejected against the allowlist in `backend/config.json`. Per [[2026-07-09-findings-and-requirements]]. On top of these charger-side methods sits the **per-user API permission system** (last section).
## 1. RFID cards — ✅ mechanism built, enrollment pending
## 1. RFID cards — ✅ verified live (2026-07-09)
Use the cards already owned. Flow: enable learn mode → tap each card once → harvest its idTag from `seen_tags.json` → add to `authorized` with a name (`kind: "card"`) → set `learn_mode=false` to enforce.
First card tapped on the real charger: idTag `1000000000000393` → Authorize → StartTransaction on gun 2 → **actual charging session started** (tx 1, meter_start 3,513.857 kWh). Enrolled as "RFID card A". Second card captured the same session: `1000000000000395` → "RFID card B". The ids are sequential — the cards ship as a numbered batch. Remaining: tap any further cards, then set `learn_mode=false` to enforce.
## 2. By vehicle / chassis — ⚠️ needs a physical test
> [!warning] Session restarted after remote stop (❓ verify mechanism)
> ~65 s after a RemoteStop on gun 2 (cable left plugged), a **new** transaction began with the same card id. Either the owner re-tapped, or the charger auto-restarts from its authorization cache (`AuthorizationCacheEnabled=true`). Matters for app UX: "stop" may not stick while the cable stays in. Test: remote-stop and touch nothing for 5 min.
True VIN-based **ISO 15118 Plug & Charge is unlikely** on a basic AC unit. The realistic option is **Autocharge**: some chargers automatically send a per-vehicle idTag when a car plugs in, no card tap needed.
Flow for each new card: tap once in learn mode → harvest its idTag from `seen_tags.json` / `GET /api/allowlist` → add to `authorized` with a name (`kind: "card"`).
**The test:** plug the car in *without* tapping a card. If a stable idTag shows up in `seen_tags.json`, whitelist it as `kind: "car"` and "by vehicle" works. If nothing appears, this method is not achievable on the [[anfu-charger|Anfu hardware]] — drop it.
Since 2026-07-11 a card can be **restricted per gun**: an optional `"connectors": [2]` on its allowlist entry makes `decide()` reject it on any other connector. The check fires at `StartTransaction` (the only message that carries the connector); the preceding `Authorize` (tap) still says Accepted — harmless on this charger, because `AuthorizeRemoteTxRequests=false` makes `StartTransaction` the decisive call anyway (see the probe facts below). ✅ verified with a fake charge point: gun-2-only card → `Invalid`/tx 0 on gun 1, Accepted on gun 2.
## 3. Mobile / web app — 📋 to build
## 2. By vehicle / chassis — ❌ CLOSED: not supported (2026-07-09)
Exhaustively tested on the real hardware; the charger never forwards any vehicle identifier as an OCPP idTag. Three escalating tests, all negative (full record in `discovering/events.jsonl`):
1. **Plain plug-in, no card** (both cars, both guns, ~15:03Z and ~15:08Z): connector → `Preparing`, then silence. No Autocharge out of the box.
2. **`MacEnabled=true` live** (ChangeConfiguration Accepted, no reboot; EU/CCS car replugged 15:22Z): no idTag in 5+ min.
3. **`MacEnabled=true` after a full power-cycle** (setting confirmed persisted post-reboot via re-probe; EU car replugged 15:33:51Z): no idTag in ~3.5 min. This was the definitive variant, since this charger family applies some settings only on boot ([[troubleshooting]] #4).
`MacEnabled` reverted to `false` afterwards. Whatever that key does, it is not Autocharge-style idTag forwarding — despite the charger demonstrably holding a DC handshake with the car (it reports the car's SoC). The EVCCID/VIN exists inside the charger but firmware `1.24.0620.1` never surfaces it over OCPP.
> [!note] Confirmed: the charger *has* the VIN (owner observation, 2026-07-09)
> The **touchscreen displays the chassis number (VIN) of Chinese cars** — direct proof the GB/T 27930 BRM handshake delivers the VIN to the charger. The identity dead-ends at the UI; it's purely an OCPP-mapping gap in the firmware, not a hardware limit. Two long-shot future leads: (1) a firmware update; (2) the writable, empty `DataTransferVendorId` config key — setting it might make the charger emit vendor-specific `DataTransfer` frames (which `station.py` already logs) that could include the VIN.
**Consequence:** vehicle-based auth is off the table. Households authorize via **RFID cards ✅** and the **app remote-start ✅** — both verified. (If a future firmware update changes this, retest with the same three steps.)
## 3. Mobile / web app — ✅ control path verified live (2026-07-09)
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:
A mobile-friendly web control panel (no app store):
@@ -26,3 +44,28 @@ A mobile-friendly web control panel (no app store):
- Live charger status
- Clickable allowlist management
- Bound to `0.0.0.0`, reached only over [[netbird|NetBird]]; optional PIN/token for defense-in-depth (❓ open decision, see [[overview]])
- Must be **per-gun**: the charger has two connectors ([[2026-07-09-discovery-eu092025]])
## Who may control what — API users & scopes (built 2026-07-11)
The [[backend]] now has real multi-user authorization on top of the three methods above, because not every household member may control everything. Requirement (owner, 2026-07-11): some users control gun 1 only, some gun 2, some only certain [[wifi-relays|relays]].
- **Users** live in `backend/config.json` → `"users"`: username + PBKDF2 password hash + scope list + a personal `id_tag` (`app-<name>`) used for their remote starts, so charging sessions are **attributable per person**.
- **Login**: `POST /api/login` (username/password) → 30-day HMAC-signed session, delivered as an HttpOnly cookie (for the PWA) and as a bearer token (for curl). Stateless — survives backend restarts; deleting a user kills their sessions.
- **Scopes** (fnmatch wildcards work):
| Scope | Grants |
|---|---|
| `charger:eu092025:1` | start/stop/unlock gun 1 |
| `charger:eu092025:2` | same for gun 2 |
| `relay:<name>` / `relay:*` | switch those relays (others are invisible to the user) |
| `admin` | everything, incl. allowlist/user CRUD, learn-mode flip, setconfig, events |
- **Bootstrap**: zero users = open API (startup warns loudly). First user: `venv\Scripts\python -m backend.users add <name> --scopes admin`.
- ✅ Verified by the 28-check smoke test (login, wrong password, cookie + bearer, per-scope 403s, relay visibility filtering, user CRUD, session invalidation on delete). ⚠️ Not yet exercised from a real browser/PWA (doesn't exist yet).
This resolves the ❓ "web app auth" open decision in [[overview]]: username+password with per-resource scopes, chosen over plain tokens by the owner.
## Facts from the live probe that shape this design
Per [[2026-07-09-discovery-eu092025]]: `AuthorizeRemoteTxRequests=false`, so remote starts don't trigger a separate Authorize — the `decide()` gate fires when the charger sends `StartTransaction`. The on-charger offline allowlist (`LocalAuthList`) holds max **6 idTags** and is currently disabled; enough for a household if we ever want tap-to-charge to survive CSMS downtime.
+13 -4
View File
@@ -6,7 +6,9 @@ tags: [hardware]
# Anfu Home Charger (charging pile)
The physical home EV charger this whole project revolves around. It is not a single device but a small network of three, behind its own Four-Faith router (see [[network-topology]]). Per [[2026-07-09-findings-and-requirements]]:
The physical home EV charger this whole project revolves around. Identity per the live probe ([[2026-07-09-discovery-eu092025]]): **SimpleCharge "MultiSocketCharger"**, serial `24310588`, firmware `1.24.0620.1`, OCPP ID **`eu092025`** — with **two guns** (connectors 1 and 2).
It is not a single device but a small network of three, behind its own Four-Faith router (see [[network-topology]]). Per [[2026-07-09-findings-and-requirements]]:
- **[[jc-6620|JC-6620]]** (`192.168.2.228`) — OCPP communication controller; the OCPP client that dials the CSMS
- **EV charging controller** (`192.168.2.118`, DHCP) — the main control board that actually manages charging; the JC-6620 talks to it on port 2403
@@ -25,8 +27,15 @@ The physical home EV charger this whole project revolves around. It is not a sin
> [!warning] Power-cycle required
> URL or network changes only take effect after power-cycling the pile.
## Capabilities in question
## Capabilities (per the live probe, [[2026-07-09-discovery-eu092025]], and the live charging test)
> [!warning] Superseded: "basic AC unit" (assumed in [[2026-07-09-findings-and-requirements]])
> The first live charging session (2026-07-09) showed gun 2 delivering **30.6 kW at 309.6 V / 98.8 A with SoC reporting** — that's **DC fast charging**, not AC. This is a DC-capable multi-standard charger.
- ✅ OCPP 1.6J over WebSocket — verified working
- ⚠️ Autocharge (per-vehicle idTag on plug-in) — needs a physical test; see [[authorization]]
- ❌ True ISO 15118 Plug & Charge — unlikely on a basic AC unit
- ✅ **DC fast charger, 60 kW** (owner-confirmed) with **two guns** — `NumberOfConnectors=2`: **gun 1 = EU standard (CCS), gun 2 = Chinese standard (GB/T)**; 30.6 kW observed on gun 2 while both guns charged simultaneously
- ⚠️ Telemetry quirk: while charging, gun 1's periodic samples read 0 W / 0 V (though SoC updated and energy was delivered — 349 Wh per Transaction.End); gun 2's samples looked sane. Watch whether gun 1 metering is lazy/lagged.
- ✅ Feature profiles: Core, **RemoteTrigger** (verified), **SmartCharging** (Power-based profiles, max 3 periods), Reservation, LocalAuthListManagement (max **6** entries), FirmwareManagement
- ✅ Meter data every 60 s while charging: Energy, Power, **SoC**, Voltage, Current
- ❌ Autocharge / vehicle ID over OCPP — **tested and closed 2026-07-09**: no idTag ever forwarded, even with `MacEnabled=true` after a power-cycle ([[authorization]]); the charger clearly holds the DC handshake (reports SoC) but firmware `1.24.0620.1` keeps the vehicle identity to itself
- ❌ True ISO 15118 Plug & Charge — nothing in the config suggests it
+57
View File
@@ -0,0 +1,57 @@
---
type: entity
updated: 2026-07-11
tags: [software, csms, backend, relays, auth]
---
# Backend (`../backend/`)
The production successor to [[csms-toolkit|station.py]] (built 2026-07-11): one FastAPI/uvicorn process on **port 9000** that is both the private CSMS for the [[anfu-charger]] and the controller for the [[wifi-relays|Tuya WiFi relays]] — phases 1–2 of the [[architecture-plan]].
```
backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
├── main.py app assembly + entrypoint (uvicorn :9000), serves the panel
├── csms.py OCPP 1.6J ChargePoint handlers, decide() gate, remote start/stop
├── relays.py tinytuya local control of the SmartLife relays
├── routes.py REST under /api/* (login + per-scope permission checks)
├── users.py passwords (PBKDF2), sessions (HMAC), scope matcher, user CLI
├── store.py SQLite session store: who charged, when, how many kWh + meter samples
├── config.py config.json load/save
├── journal.py events.jsonl + seen_tags.json (raw ground truth)
├── static/ the web panel PWA (index.html, manifest, service worker, icon)
├── config.json users + allowlist + relay registry — GITIGNORED (password
│ hashes, session secret, Tuya local keys); see config.example.json
└── sessions.db SQLite (gitignored, auto-created)
```
## Surfaces (all on :9000 — the touchscreen URL never changes)
- `ws://<host>:9000/<ChargerID>` — OCPP WebSocket (catch-all path, the JC-6620 dials in)
- `GET /` — **the web panel** (mobile-first PWA, vanilla JS, self-contained; login → tabs Control / History / Admin, buttons filtered by the user's scopes; polls `/api/status` every 5 s)
- `POST /api/login|logout`, `GET /api/me` — username/password → 30-day session (cookie + bearer)
- `GET /api/sessions?limit&cp&connector` — **charging history: who / when / kWh** (visibility: own sessions + guns within scope; admin sees all); `GET /api/sessions/{tx}/samples` — per-minute energy/power/SoC for charts
- `GET /api/status` — mode, connected chargers, gun states, active transactions, auth events, relays (filtered to what the caller may control)
- `GET /api/events?limit&event=` — tail the journal (admin)
- `POST /api/charger/start|stop[/{tx}]|unlock/{n}` — gun-scoped; `trigger/{...}|setconfig|probe` — admin
- `GET/PUT/DELETE /api/allowlist[/{idTag}]` + `POST /api/mode?learn=` — admin; **learn mode flips at runtime, no restart**
- `GET/PUT/DELETE /api/users[/{name}]` — user CRUD (admin), enables a PWA admin page later
- `GET /api/relays[?live=true]`, `GET /api/relays/{name}`, `POST /api/relays/{name}/on|off|toggle` — relay-scoped
- `/docs` — interactive OpenAPI docs
## Design facts
- Carried over from the proven discovery code: the `decide()` gate ([[authorization]]) — now with optional per-gun card restriction (`"connectors": [2]`) — the `_WSAdapter` WebSocket bridge, learn mode, the JSONL event journal. `DataTransfer` frames are journaled too (the VIN long-shot lead in [[authorization]]).
- **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.
- **Consumption tracking** (`store.py`, 2026-07-11): every `StartTransaction` opens a row in `sessions.db` with a resolved "who" (allowlist name or username); `StopTransaction` closes it and computes Wh from the meter diff; `MeterValues` rows land in a `samples` table (energy/power/SoC, kW→W normalized). Transaction ids continue from `MAX(tx)` across restarts, and stop-by-tx falls back to the store so sessions running through a backend restart stay stoppable.
- 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.
- ✅ Smoke-tested 2026-07-11 (37 checks): REST surface, allowlist CRUD incl. gun-restricted cards, login/sessions/scopes, user CRUD, the full consumption pipeline (start → meter sample → stop → kWh → visibility filtering), static panel serving, and a fake charge point over the real WS route. ⚠️ Not yet run against the live charger or a real phone browser; relays unconfigured until the [[wifi-relays|key extraction]] is done.
## Web panel notes
Vanilla JS on purpose (no framework, no CDN — the panel must work with NetBird-only reachability). Start button enables only when the gun reports `Preparing`/`Available` **and** the user holds that gun's scope. Gun cards show who is charging and since when; History tab lists who/when/kWh; Admin tab (admin scope only) manages allowlist (incl. per-gun cards + "seen but not enrolled" quick-enroll), users, and the learn/enforce toggle. Trivial service worker = installable ("add to home screen") without cache-staleness risk.
## Deliberately deferred
SSE live push (the panel polls), per-session charts from the `samples` table (data is already collected), auto-interrogation on connect (manual `POST /api/charger/probe`).
+14 -3
View File
@@ -1,6 +1,6 @@
---
type: entity
updated: 2026-07-09
updated: 2026-07-11
tags: [software, csms]
---
@@ -8,6 +8,8 @@ tags: [software, csms]
The Python scripts that play the CSMS (backend) side of the [[ocpp|OCPP]] link. Currently discovery/tester-grade; `station.py` is the seed of the real controller. Per [[2026-07-09-findings-and-requirements]]:
> [!warning] Superseded for production (2026-07-11): `station.py` was ported into the [[backend]] package (`../backend/`), which adds allowlist CRUD, optional API token auth, and [[wifi-relays|Tuya relay]] control. `discovering/` stays as the discovery/diagnostic toolkit (`csms.py`, `rawlisten.py`, fake charge point) — don't run `station.py` and the backend at the same time; both bind port 9000.
| File | Purpose |
|---|---|
| `csms.py` | Minimal OCPP 1.6J server — accepts everything, logs raw frames. Discovery/tester. |
@@ -16,10 +18,19 @@ The Python scripts that play the CSMS (backend) side of the [[ocpp|OCPP]] link.
| `station_config.json` | `{ "learn_mode": bool, "authorized": { "<idTag>": {name, kind} } }` |
| `seen_tags.json` | Auto-recorded log of every idTag observed (discovery / Autocharge testing). |
- **Runtime:** Python venv with `websockets` 16.0 + `ocpp`; listens on `ws://0.0.0.0:9000/<chargePointId>`.
- **Runtime:** Python venv with `fastapi` + `uvicorn` + `ocpp` (2026-07-09: `station.py` moved from raw `websockets` to a single FastAPI/uvicorn process — the phase-1 shape from [[architecture-plan]]).
- **Single port 9000:** the OCPP WebSocket (`ws://0.0.0.0:9000/<chargePointId>`, any path) *and* the discovery HTTP API share it, so the hardcoded touchscreen URL never changes.
- **The one gate:** every [[authorization]] method funnels through `decide(id_tag)` in `station.py` — Accepted/Rejected against the allowlist.
- **Host requirements:** inbound TCP 9000 open (Windows firewall silently drops otherwise — see [[troubleshooting]]) and a stable IP, since the [[anfu-charger|charger touchscreen]] URL is hardcoded.
## Discovery API (in `station.py`, docs at `http://<host>:9000/docs`)
- Auto-interrogation on every charger connect: `GetConfiguration` (all keys) + `TriggerMessage(StatusNotification)` → saved to `discovery_<id>.json` (first real capture: [[2026-07-09-discovery-eu092025]])
- **Event journal:** every OCPP event (connect/disconnect, boot, status, authorize, start/stop transaction, meter values) is appended as one JSON line to `events.jsonl` — permanent, restart-proof, greppable; tail it via `GET /events?limit=N&event=<kind>`
- `GET /status` (chargers, guns, transactions, auth events) · `GET /tags` (seen + authorized)
- `POST /probe` · `/start` · `/stop[/{tx}]` · `/trigger/{status|meter|heartbeat|boot}` · `/unlock/{connector}` · `/setconfig?key=&value=`
- With one charger connected, `?cp=` may be omitted. ✅ Verified end-to-end against both a fake charge point and the real charger.
## Still to build
The web control panel (remote start/stop, live status, allowlist management) served behind [[netbird|NetBird]] — see [[overview]] for the plan and open host decision.
The web control panel (remote start/stop, live status, allowlist management) served behind [[netbird|NetBird]] — now on the [[backend]], see [[overview]] for the plan and open host decision.
+28
View File
@@ -0,0 +1,28 @@
---
type: entity
updated: 2026-07-11
tags: [hardware, relays, tuya]
---
# WiFi Relays (SmartLife / Tuya)
Several WiFi relays scattered around the property, currently driven by the **SmartLife app** (owner report, 2026-07-11). Scope expansion: the [[backend]] should control them too, so one self-hosted system runs both the [[anfu-charger|charger]] and the relays.
## What they are
SmartLife = Tuya's consumer app, so these are **Tuya WiFi devices**. The "discovered by Bluetooth at first" behavior the owner observed is Tuya's standard BLE-assisted *pairing* (the phone passes WiFi credentials over BLE once); after provisioning the relays live on WiFi and speak **Tuya's local protocol on TCP 6668**, which the `tinytuya` library drives directly — **no Tuya cloud in the loop** for day-to-day control. SmartLife keeps working in parallel; local and app control don't conflict.
## Control path (implemented in `backend/relays.py`, ⚠️ awaiting keys)
Local control needs each device's **id + local key**, extracted once via Tuya's own API:
1. Create a (free) account at `iot.tuya.com` → Cloud → create a project (data center matching the SmartLife account region).
2. Link the SmartLife app account to the project (Devices → Link App Account → scan QR in SmartLife).
3. From the repo root: `venv\Scripts\python -m tinytuya wizard` — enter the project's API id/secret; it dumps every paired device's `id`, `key`, `ip`, and protocol `version`.
4. Copy each relay into `backend/config.json` → `"relays"` (shape in `config.example.json`). The Tuya cloud account is never needed again unless a device is re-paired (**re-pairing regenerates the local key**).
Recommended: DHCP reservations for the relays and pinned `"ip"` entries in the config — `"ip": "auto"` works via UDP broadcast discovery but is slower and only finds relays on the same L2 segment as the backend host (❓ verify which subnet the relays are on vs. the future always-on host, see [[network-topology]]).
## API (see [[backend]])
`GET /api/relays?live=true` (poll all), `GET /api/relays/{name}`, `POST /api/relays/{name}/on|off|toggle`. ⚠️ Untested against the physical relays until the keys are in the config.
+9 -5
View File
@@ -1,6 +1,6 @@
---
type: meta
updated: 2026-07-09
updated: 2026-07-11
tags: [index]
---
@@ -16,20 +16,24 @@ Catalog of every wiki page. Updated on every ingest. (Schema/conventions live in
- [[anfu-charger]] — the charging pile: its three internal devices + working touchscreen config
- [[jc-6620]] — the OCPP communication controller / client; its IPs and shipped-gateway gotcha
- [[csms-toolkit]] — the Python CSMS scripts in `../discovering/` and what each does
- [[backend]] — the production backend in `../backend/`: CSMS + REST API + relay control + user auth + consumption store + web panel, all on :9000
- [[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
- [[netbird]] — the private overlay network; security boundary for the future web panel
## Concepts
- [[network-topology]] — charger LAN behind the Four-Faith router, NAT direction, what's verified
- [[authorization]] — the three auth methods (RFID ✅ / Autocharge ⚠️ / web app 📋) and the `decide()` gate
- [[authorization]] — charger auth methods (RFID ✅ / by-vehicle ❌ / app ✅), per-gun cards, and the API user/scope permission system
- [[troubleshooting]] — ordered "charger won't connect" checklist of hard-won gotchas
- [[ocpp]] — OCPP 1.6J basics and how the roles/messages map to this project
## Notes
*(none yet — filed answers to questions go here)*
- [[architecture-plan]] — stack decision (FastAPI + PWA now, Flutter optional later) and 6-phase build plan
- [[discovery-runbook]] — step-by-step physical test session: Autocharge first, then RFID taps, then remote start
## Sources
- [[2026-07-09-findings-and-requirements]] — founding findings/requirements doc (ingested 2026-07-09, 1 raw file)
- [[2026-07-09-findings-and-requirements]] — founding findings/requirements doc (ingested 2026-07-09)
- [[2026-07-09-discovery-eu092025]] — live GetConfiguration capability dump from the real charger: 2 guns, feature profiles, meter data (ingested 2026-07-09)
+56
View File
@@ -15,3 +15,59 @@ Instantiated the LLM-wiki pattern for the charging-station project: schema (`CLA
## [2026-07-09] ingest | Findings & Requirements (founding source)
Ingested `raw/FINDINGS_AND_REQUIREMENTS.md` → [[2026-07-09-findings-and-requirements]]. Seeded [[overview]] plus entities ([[anfu-charger]], [[jc-6620]], [[csms-toolkit]], [[netbird]]) and concepts ([[network-topology]], [[authorization]], [[troubleshooting]], [[ocpp]]). Open decisions tracked in [[overview]].
## [2026-07-09] query | Stack decision → architecture plan filed
Discussed backend (Fastify vs FastAPI), web frontend, and Flutter. Decided: FastAPI single-process CSMS+API+PWA; Flutter deferred to optional phase 2. Filed as [[architecture-plan]]; index updated.
## [2026-07-09] ingest | Live capability probe of the real charger (eu092025)
Built discovery layer into station.py (single FastAPI process on :9000 — OCPP WS + HTTP API with /status /tags /probe /start /stop /trigger /unlock /setconfig; auto-GetConfiguration on connect). The real charger connected during testing: SimpleCharge MultiSocketCharger, fw 1.24.0620.1, TWO guns, RemoteTrigger verified. Ingested raw/discovery_eu092025.json → [[2026-07-09-discovery-eu092025]]; updated [[anfu-charger]], [[authorization]], [[csms-toolkit]], [[overview]].
## [2026-07-09] meta | Discovery runbook filed
Filed [[discovery-runbook]]: physical test session plan (Autocharge plug-in test first, then RFID card taps, optional remote start). Awaiting hardware results.
## [2026-07-09] meta | Event journal added to station.py
All OCPP events now persist to events.jsonl (one JSON line each) with a GET /events tail endpoint — so the upcoming Autocharge/RFID/charging test session is fully recorded for later ingest. Verified with fake charger + live eu092025 reconnect. Updated [[csms-toolkit]].
## [2026-07-09] ingest | First live plug-in test: no Autocharge by default
Car plugged into gun 2 (no card): StatusNotification Available->Preparing at 15:02:59Z, then silence — no Authorize/StartTransaction/idTag in ~2 min. Preliminary: no Autocharge out of the box; MacEnabled=true retry pending. Updated [[authorization]].
## [2026-07-09] ingest | Full live test session: RFID + remote start/stop verified, no Autocharge, charger is DC
Live session with both cars: card ...393 -> Authorize -> charging on gun 2 (GB/T DC, 30.6 kW observed, 1807 Wh delivered); RemoteStart/RemoteStop proven on gun 1 (EU, 349 Wh); two cars plugged without cards produced no idTag (Autocharge negative, MacEnabled retry remains). Superseded "basic AC unit" assumption. Card + app-remote enrolled in allowlist. Updated [[authorization]], [[anfu-charger]], [[overview]]. Raw record: discovering/events.jsonl.
## [2026-07-09] ingest | Card B captured; gun 2 re-stop; possible auto-restart after remote stop
Card B (...395) tapped and enrolled. Gun 2 had started a NEW session (same card id ...393, ~65 s after the previous remote stop, cable still plugged) — stopped it remotely (tx 3, 2264 Wh). Open question ❓: re-tap or auth-cache auto-restart? Noted in [[authorization]].
## [2026-07-09] meta | Charger confirmed 60 kW DC; MacEnabled flipped to true
Owner confirmed: 60 kW DC fast charger (gun 1 EU/CCS, gun 2 GB/T). No vehicle id observed via OCPP yet, but DC handshake means the charger receives EVCCID (CCS) / possibly VIN (GB/T). Set MacEnabled=true (ChangeConfiguration Accepted, live). Replug test pending. Updated [[anfu-charger]], [[authorization]].
## [2026-07-09] ingest | "By vehicle" auth definitively closed; charger is 60 kW DC
Owner confirmed 60 kW DC. Final Autocharge variant: power-cycled pile with MacEnabled=true (setting persisted, verified by post-reboot probe), EU car replugged 15:33:51Z -> no idTag in ~3.5 min. Closed method 2 as NOT SUPPORTED; MacEnabled reverted to false. Updated [[authorization]], [[overview]], [[anfu-charger]], [[discovery-runbook]]. Remaining next steps: learn_mode off, PWA panel, remote-stop-restart question.
## [2026-07-09] ingest | Touchscreen shows VIN of Chinese (GB/T) cars
Owner observation: the pile's own UI displays the chassis/VIN for GB/T cars -> confirms the BRM handshake delivers the VIN to the charger; firmware just never maps it to an OCPP idTag. Noted in [[authorization]] with the DataTransferVendorId long-shot lead.
## [2026-07-11] ingest | Scope expansion: backend also controls the Tuya/SmartLife WiFi relays
Owner: the backend should also drive the WiFi relays currently on the SmartLife app (BLE-assisted pairing = standard Tuya onboarding; they're Tuya WiFi devices). Decision: local control via tinytuya (TCP 6668), no Tuya cloud in the day-to-day loop; one-time id/local-key extraction via `tinytuya wizard` pending. Created [[wifi-relays]]; updated [[architecture-plan]], [[overview]].
## [2026-07-11] meta | Production backend built (../backend/) — architecture-plan phases 1-2
Ported station.py into the `backend/` package: one FastAPI process on :9000 = OCPP CSMS + /api/* (charger control, allowlist CRUD, runtime learn-mode flip, optional api_token auth) + /api/relays/* (tinytuya via asyncio.to_thread). Allowlist migrated to backend/config.json (gitignored — holds Tuya local keys; config.example.json documents shape). Smoke-tested: 13 checks incl. fake CP BootNotification/Authorize over the real WS route. Not yet cut over on the live charger. Created [[backend]]; updated [[csms-toolkit]] (superseded-for-production callout), [[architecture-plan]], [[overview]], [[index]].
## [2026-07-11] meta | Multi-user auth system: username/password + per-resource scopes
Owner requirement: per-user permissions (gun 1 vs gun 2 of eu092025, per-relay or all relays). Owner chose username+password over plain tokens; per-gun RFID restriction included. Built into [[backend]]: users.py (PBKDF2 passwords, stateless HMAC sessions 30d, cookie+bearer, fnmatch scopes charger:<cp>:<gun> / relay:<name> / admin), login/me/users CRUD endpoints, scope checks on every route, relay visibility filtering, remote starts attributed via per-user idTag, decide() enforces optional "connectors" on allowlist entries at StartTransaction. Zero users = open API (bootstrap via `python -m backend.users add`). Smoke test grown 13 -> 28 checks, all passing. Resolved the "web app auth" open decision. Updated [[authorization]] (new scopes section + per-gun cards), [[backend]], [[overview]].
## [2026-07-11] meta | Consumption tracking (SQLite) + the PWA control panel
Owner requirement: button-push start when a gun is ready (and permitted) + "who charged when and how many kWh". Built store.py (sessions.db: sessions with resolved who/started/ended/Wh + per-minute samples energy/power/SoC; tx ids survive restarts; stop falls back to store after restart), /api/sessions with visibility rules (own + in-scope guns; admin all), and the phase-3 web panel in backend/static/ (vanilla JS PWA at /: login, gun cards with scope- and readiness-gated Start/Stop, relay toggles, history tab, admin tab with allowlist/users/mode). Fixed a sqlite connection leak (with-connect commits but never closes). Smoke test 28 -> 37 checks, all passing. Updated [[backend]], [[architecture-plan]] (phases 1-3 all done), [[overview]], [[index]].
+47
View File
@@ -0,0 +1,47 @@
---
type: note
updated: 2026-07-11
tags: [architecture, decision, plan]
---
# Architecture & Build Plan
Filed 2026-07-09 from a stack discussion (Flutter? Fastify vs FastAPI? web frontend?). Extends the requirements in [[2026-07-09-findings-and-requirements]] and the roadmap in [[overview]].
> [!note] Scope expansion (2026-07-11): the backend also controls the household [[wifi-relays|Tuya/SmartLife WiFi relays]] — locally via tinytuya, same process, under `/api/relays/*`. This strengthens the FastAPI/one-process decision: charger + relays + panel behind one NetBird-reachable port.
## Stack decision
**Backend: FastAPI (Python) — decided.**
The deciding constraint: the backend *is* the CSMS. `RemoteStartTransaction`/`RemoteStopTransaction` can only be sent down the live OCPP WebSocket the [[jc-6620|JC-6620]] holds open, so the API server and the OCPP server must share process state. The proven code ([[csms-toolkit]]) is already Python on the `ocpp` library; Fastify would mean rewriting OCPP in Node (immature libraries) or a two-process IPC design. FastAPI hosts everything in one uvicorn process on one port:
```
FastAPI app (uvicorn, :9000, on the always-on host)
├── /<chargePointId> OCPP 1.6J WebSocket (catch-all) ← JC-6620 dials in here
├── /api/* REST: status, charger start/stop, allowlist CRUD, sessions
├── /api/relays/* Tuya relay control (tinytuya, local protocol)
├── /api/events journal tail (SSE live push later, for the panel)
└── / static PWA (the web panel)
```
(The `ocpp` ChargePoint class only needs send/recv; a FastAPI WebSocket route wraps it. Keep port 9000 so the charger touchscreen URL doesn't change — [[troubleshooting]] #4: changing it needs a power-cycle.)
**Web frontend: mobile-first PWA, no build pipeline — decided.**
Plain HTML/JS (Alpine.js or htmx + SSE), served by FastAPI. Features: status card, start/stop, allowlist management, session history. PWA manifest → "add to home screen". Reached only over [[netbird|NetBird]].
**Flutter mobile app: phase 2, optional.**
The PWA covers ~95% of the value. Flutter earns its keep only for push notifications ("charging complete") or as a learning project. It would consume the same REST API (FastAPI's OpenAPI spec → typed Dart client codegen), so nothing built now is wasted. Phone needs the NetBird client either way.
**Storage: SQLite** (single file) for sessions/meter values/seen tags; the allowlist can migrate from `station_config.json` into it once the panel manages it. JSON files were fine for discovery; history queries want a real table. → ✅ implemented 2026-07-11 as `backend/store.py` (`sessions` + `samples` tables); allowlist/users stayed in config.json — right size for a household, revisit only if it grows.
## Build phases
1. **Productionize the CSMS** — ✅ done 2026-07-11 as the [[backend]] package (`../backend/`); SQLite session store added same day (JSONL journal stays as raw ground truth).
2. **REST API** — ✅ done 2026-07-11: status, remote start/stop, allowlist CRUD, runtime learn-mode flip, **relay on/off/toggle**, multi-user login with permission scopes, **session history (who/when/kWh)**. ⚠️ Relay half awaits the [[wifi-relays|local-key extraction]].
3. **Web panel (PWA)** — ✅ built 2026-07-11 (`backend/static/`, vanilla JS instead of Alpine — zero dependencies): login, per-gun status + start/stop gated by scopes and gun readiness, relay toggles, consumption history, admin tab. ⚠️ Untested on a real phone.
4. **Deploy** — pick the always-on host (❓ open, [[overview]]), run as a service (systemd or NSSM on Windows), static IP / DHCP reservation, firewall rule for :9000, joined to NetBird.
5. **Hardware tasks** — RFID enrollment via learn mode; the Autocharge plug-in test ([[authorization]]) to settle "by vehicle".
6. **(Optional) Flutter app** — consumes the same API; adds push notifications.
Phases 1–3 are pure software and can proceed before the host decision; only phase 4 needs it.
+38
View File
@@ -0,0 +1,38 @@
---
type: note
updated: 2026-07-09
tags: [runbook, discovery, hardware-test]
---
# Discovery Test Runbook — Autocharge + RFID Session
> [!note] Executed 2026-07-09 — all tests done, results in [[authorization]] and [[overview]]
> Test A (Autocharge): ❌ negative through all variants incl. `MacEnabled=true` + power-cycle. Test B (RFID): ✅ cards A+B captured & enrolled. Test C (remote start/stop): ✅ both verified. Kept as the template for any future retest (e.g. after a firmware update).
The physical test session to settle the open [[authorization]] questions. Prereq: `station.py` running (`venv\Scripts\python station.py` in `../discovering/`), learn mode ON, charger `eu092025` connected. Watch at `http://10.0.10.203:9000/status`, `/tags`, or `/docs`.
## Order matters
Do the Autocharge test **before** ever tapping a card in this session — the first plug-in is the clean observation.
## Test A — Autocharge (plug in, no card)
Connect a gun to a car. Do not tap anything.
| Observation | Conclusion | Next step |
|---|---|---|
| New idTag in console / `/tags` | ✅ Autocharge works | Let it charge ~2 min (captures first MeterValues/SoC), stop, whitelist the id as `kind:"car"` |
| Connector "Preparing", no idTag | No Autocharge by default | Retry after `POST /setconfig?key=MacEnabled&value=true` (lead from [[2026-07-09-discovery-eu092025]]) |
| Nothing | "By vehicle" not supported | Close the open decision in [[overview]] as ❌ |
## Test B — RFID cards
Tap each owned card once. Each should log `[LEARN] NEW idTag=...` and appear in `/tags`. **Write down the physical tap order** so the ids can be named in the allowlist.
## Test C (optional) — remote start
With a car plugged in: `curl -X POST "http://10.0.10.203:9000/start?connector=1"` — this is exactly what the future web panel will do. Expect `{"remote_start":"Accepted"}` then a `StartTransaction` (note: `AuthorizeRemoteTxRequests=false`, so no separate Authorize).
## Afterwards
Feed results back into the wiki (ingest `seen_tags.json` observations), name cards in `station_config.json` → `authorized`, and once all household ids are enrolled: set `learn_mode: false` and restart — the charger is then enforcing.
+21 -11
View File
@@ -1,34 +1,44 @@
---
type: meta
updated: 2026-07-09
updated: 2026-07-11
tags: [synthesis]
---
# Overview — Anfu Home Charger OCPP Project
**Goal:** a private, self-hosted [[ocpp|OCPP 1.6J]] backend (CSMS) for a home EV charger. No billing, no public charging. Three ways to authorize a charge: existing RFID cards, by vehicle (if the hardware allows — ⚠️ untested), and a mobile-friendly web app reached over [[netbird|NetBird]].
**Goal:** a private, self-hosted [[ocpp|OCPP 1.6J]] backend (CSMS) for a home EV charger. No billing, no public charging. Authorization via existing RFID cards ✅ and a mobile-friendly web app reached over [[netbird|NetBird]] (by-vehicle ❌ closed — firmware never forwards a vehicle id). **Scope expanded 2026-07-11:** the same backend also controls the household [[wifi-relays|Tuya/SmartLife WiFi relays]], locally via tinytuya.
## Current state (2026-07-09)
## Current state (2026-07-11)
**Connectivity: ✅ solved.** The [[jc-6620|JC-6620]] controller inside the [[anfu-charger|charging pile]] reliably dials out to the CSMS — verified both on the charger's own LAN (`192.168.2.114:9000`) and across the NAT boundary on the WAN subnet (`10.0.10.203:9000`). Getting here required the fixes catalogued in [[troubleshooting]]; the network layout is in [[network-topology]].
**Software: discovery-grade.** The [[csms-toolkit]] (`../discovering/`) can accept connections, log frames, and enforce an allowlist with learn mode. It is a tester/foundation, not yet the always-on production service.
**Software: production [[backend]] built (2026-07-11), including the web panel.** `station.py` was ported into the `../backend/` package: one FastAPI process on port 9000 = CSMS WebSocket + `/api/*` (charger control, allowlist CRUD, runtime learn-mode flip) + [[wifi-relays|Tuya relay]] on/off/toggle + **multi-user auth** (username/password, per-resource scopes: gun 1 / gun 2 / per-relay / admin, per-gun-restrictable RFID cards — [[authorization]]) + **consumption tracking** (SQLite: who charged, when, how many kWh, per-minute meter samples) + the **PWA control panel** at `/` (login, scope-filtered start/stop buttons, relay toggles, history, admin). Smoke-tested (37 checks incl. a fake charge point over the real WS route); ⚠️ not yet run against the live charger or a real phone. The [[csms-toolkit]] (`../discovering/`) remains as diagnostic tooling.
**Authorization: designed, partially built.** All three methods funnel through one gate — `decide(id_tag)` in `station.py`. See [[authorization]] for the plan per method.
**Capabilities: ✅ known.** The live probe ([[2026-07-09-discovery-eu092025]]) identified the pile as SimpleCharge "MultiSocketCharger" (fw 1.24.0620.1, OCPP ID `eu092025`) with **two guns**, RemoteTrigger (verified), SmartCharging, Reservation, a 6-entry local auth list, and per-minute meter data including SoC. Only Autocharge remains unknown (physical test pending; `MacEnabled` is a lead — [[authorization]]).
**Authorization: 2 of 3 methods ✅ verified live (2026-07-09 test session, both cars plugged, both guns charging simultaneously):**
- **RFID** ✅ — card `…393` tapped → Authorize → real charging session on gun 2 (DC, ~26 kW avg, 1.8 kWh delivered). Card enrolled as "RFID card A".
- **Remote (app path)** ✅ — RemoteStart and RemoteStop both Accepted and executed on gun 1; `app-remote` token enrolled.
- **By vehicle** ❌ **closed** — three escalating tests (plain plug-in, `MacEnabled=true` live, `MacEnabled=true` after power-cycle) all negative; this firmware never forwards a vehicle ID over OCPP ([[authorization]]).
Hardware surprise: this is a **DC-capable multi-standard charger** (gun 1 EU, gun 2 Chinese GB/T @ 30 kW), not the assumed basic AC unit — see [[anfu-charger]].
## What's next
1. **RFID enrollment** — tap each card in learn mode, harvest idTags from `seen_tags.json`, add to the allowlist, then flip `learn_mode=false`. (Mechanism already implemented.)
2. **Autocharge test** — ⚠️ plug the car in *without* tapping a card; if a stable idTag appears, "by vehicle" works. If not, it's off the table for this hardware. See [[authorization]].
3. **Web control panel** — Start/Stop via OCPP `RemoteStartTransaction`/`RemoteStopTransaction`, live status, allowlist management. Served behind NetBird.
1. **Cut the live charger over to the [[backend]]** — stop `station.py`, run `python -m backend.main` from the repo root, verify the JC-6620 reconnects and a card tap still authorizes (allowlist already migrated to `backend/config.json`).
2. **Create the real users** — `python -m backend.users add <name> --scopes ...` for each household member (the API stays open until the first user exists).
3. **Extract the Tuya local keys** (`tinytuya wizard` — steps in [[wifi-relays]]) and fill `backend/config.json` → relays become controllable.
4. **Flip learn mode off** — both cards + the app token are enrolled; switchable from the panel's Admin tab or `POST /api/mode?learn=false`, no restart. (Only wait if more cards need tapping.)
5. **Test the panel from a phone** — it's built and serving at `http://<host>:9000/`; verify login, a real button-push start on a ready gun, and add-to-home-screen over [[netbird|NetBird]].
6. **Resolve the ❓ remote-stop restart question** — did the gun-2 session auto-restart from auth cache after RemoteStop, or was the card re-tapped? Affects the app's Stop button UX ([[authorization]]).
## Open decisions ❓
| Decision | Options | Status |
|---|---|---|
| Always-on host for CSMS + app | LAN PC · the `10.0.10.203` machine · dedicated box (e.g. Pi on charger LAN, joined to NetBird) | open |
| Web app auth | NetBird isolation only · also PIN/token | open |
| Autocharge | run the plug-in test or skip "by chassis" | open — needs physical test |
| Always-on host for CSMS + app | LAN PC · the `10.0.10.203` machine · dedicated box (e.g. Pi on charger LAN, joined to NetBird) | open — now also needs subnet reachability to the [[wifi-relays|relays]] for local Tuya control |
| Web app auth | — | ✅ **resolved 2026-07-11**: username+password login with per-resource scopes (gun 1 / gun 2 / per-relay / admin) — see [[authorization]]. Bootstrap: create the first admin user via `python -m backend.users add` |
| Autocharge / by vehicle | — | ❌ **closed 2026-07-09**: not supported by this firmware ([[authorization]]) |
| Host IP stability | static IP · DHCP reservation | open (required either way — touchscreen URL is hardcoded) |
## Sources
+336
View File
@@ -0,0 +1,336 @@
{
"charge_point": "eu092025",
"probed_at": "2026-07-09T13:49:56.843881+00:00",
"boot_info": {
"vendor": "SimpleCharge",
"model": "MultiSocketCharger",
"charge_point_serial_number": "24310588",
"firmware_version": "1.24.0620.1",
"iccid": "",
"imsi": ""
},
"configuration": [
{
"key": "AllowOfflineTxForUnknownId",
"readonly": false,
"value": "false"
},
{
"key": "AuthorizationCacheEnabled",
"readonly": false,
"value": "true"
},
{
"key": "AuthorizeRemoteTxRequests",
"readonly": false,
"value": "false"
},
{
"key": "ClockAlignedDataInterval",
"readonly": false,
"value": "0"
},
{
"key": "ConnectorPhaseRotationMaxLength",
"readonly": true,
"value": "1"
},
{
"key": "ConnectionTimeOut",
"readonly": false,
"value": "60"
},
{
"key": "GetConfigurationMaxKeys",
"readonly": true,
"value": "30"
},
{
"key": "HeartbeatInterval",
"readonly": false,
"value": "7200"
},
{
"key": "LocalAuthorizeOffline",
"readonly": false,
"value": "false"
},
{
"key": "LocalPreAuthorize",
"readonly": false,
"value": "0"
},
{
"key": "MaxEnergyOnInvalidId",
"readonly": false,
"value": "0"
},
{
"key": "MeterValueSampleInterval",
"readonly": false,
"value": "60"
},
{
"key": "NumberOfConnectors",
"readonly": true,
"value": "2"
},
{
"key": "ResetRetries",
"readonly": false,
"value": "0"
},
{
"key": "StopTransactionOnEVSideDisconnect",
"readonly": false,
"value": "1"
},
{
"key": "StopTransactionOnInvalidId",
"readonly": false,
"value": "1"
},
{
"key": "TransactionMessageAttempts",
"readonly": false,
"value": "50"
},
{
"key": "TransactionMessageRetryInterval",
"readonly": false,
"value": "60"
},
{
"key": "WebSocketPingInterval",
"readonly": false,
"value": "60"
},
{
"key": "LocalAuthListEnabled",
"readonly": false,
"value": "false"
},
{
"key": "LocalAuthListMaxLength",
"readonly": true,
"value": "6"
},
{
"key": "SendLocalListMaxLength",
"readonly": true,
"value": "6"
},
{
"key": "ChargeProfileMaxStackLevel",
"readonly": true,
"value": "3"
},
{
"key": "UnlockConnectorOnEVSideDisconnect",
"readonly": false,
"value": "1"
},
{
"key": "SendJCMeterValuesType",
"readonly": true,
"value": "1"
},
{
"key": "ChargingScheduleAllowedChargingRateUnit",
"readonly": true,
"value": "Power"
},
{
"key": "ChargingScheduleMaxPeriods",
"readonly": true,
"value": "3"
},
{
"key": "MaxChargingProfilesInstalled",
"readonly": true,
"value": "1"
},
{
"key": "LocalListVersion",
"readonly": true,
"value": "-1"
},
{
"key": "MeterValuesAlignedData",
"readonly": false,
"value": "Energy.Active.Import.Register,Power.Active.Import,SoC,Voltage,Current.Import"
},
{
"key": "MeterValuesSampledData",
"readonly": false,
"value": "Energy.Active.Import.Register,Power.Active.Import,SoC,Voltage,Current.Import"
},
{
"key": "StopTxnAlignedData",
"readonly": false,
"value": "SoC"
},
{
"key": "StopTxnSampledData",
"readonly": false,
"value": "Energy.Active.Import.Register"
},
{
"key": "ConnectorPhaseRotation",
"readonly": false,
"value": "RST"
},
{
"key": "SupportedFeatureProfiles",
"readonly": true,
"value": "Core,FirmwareManagement,LocalAuthListManagement,Reservation,SmartCharging,RemoteTrigger"
},
{
"key": "Url",
"readonly": false,
"value": "http://10.0.10.203:9000"
},
{
"key": "Vendor",
"readonly": true,
"value": "JC"
},
{
"key": "Model",
"readonly": true,
"value": "MultiSocketCharger"
},
{
"key": "TimeZone",
"readonly": false,
"value": "0"
},
{
"key": "ProtocolName",
"readonly": true,
"value": "ocpp1.6"
},
{
"key": "QRCodeTextOfConnector-1",
"readonly": false,
"value": ""
},
{
"key": "QRCodeTextOfConnector-2",
"readonly": false,
"value": ""
},
{
"key": "QRCodeTextOfConnector-3",
"readonly": false,
"value": ""
},
{
"key": "AuthorizationKey",
"readonly": false,
"value": ""
},
{
"key": "AuthorizationUser",
"readonly": true,
"value": ""
},
{
"key": "CpoName",
"readonly": false,
"value": ""
},
{
"key": "OutputLimitRate",
"readonly": false,
"value": "100"
},
{
"key": "PeakPrice",
"readonly": false,
"value": "1.0000"
},
{
"key": "OffPeakPrice",
"readonly": false,
"value": "0.5000"
},
{
"key": "IdleFeePerMinute",
"readonly": false,
"value": "0.0100"
},
{
"key": "IdleTime",
"readonly": false,
"value": "5"
},
{
"key": "MacEnabled",
"readonly": false,
"value": "false"
},
{
"key": "FreeChargeMode",
"readonly": false,
"value": "false"
},
{
"key": "KeepConnectOTAServer",
"readonly": false,
"value": "true"
},
{
"key": "DataTransferVendorId",
"readonly": false,
"value": ""
},
{
"key": "MeterValuesAlignedDataMaxLength",
"readonly": true,
"value": "5"
},
{
"key": "MeterValuesSampledDataMaxLength",
"readonly": true,
"value": "5"
},
{
"key": "StopTxnAlignedDataMaxLength",
"readonly": true,
"value": "5"
},
{
"key": "StopTxnSampledDataMaxLength",
"readonly": true,
"value": "5"
},
{
"key": "SupportedFeatureProfilesMaxLength",
"readonly": true,
"value": "6"
},
{
"key": "ReserveConnectorZeroSupported",
"readonly": true,
"value": "false"
},
{
"key": "ConnectorSwitch3to1PhaseSupported",
"readonly": true,
"value": "false"
},
{
"key": "ChargePointID",
"readonly": false,
"value": "eu092025"
}
],
"unknown_keys": null,
"trigger_status_notification": "Accepted",
"connectors_seen": {
"0": "Available",
"1": "Available",
"2": "Available"
}
}
@@ -0,0 +1,43 @@
---
type: source
updated: 2026-07-09
ingested: 2026-07-09
raw: raw/discovery_eu092025.json
tags: [discovery, capabilities, ocpp]
---
# Discovery Probe — Live Capability Dump from "eu092025"
**Raw source:** [discovery_eu092025.json](../raw/discovery_eu092025.json) — the answer the real charger gave to `GetConfiguration` (all keys) + `TriggerMessage`, captured live on 2026-07-09 by the new auto-interrogation in [[csms-toolkit]]. This replaces guesswork with the charger's own capability sheet.
## TL;DR
The pile identifies as **SimpleCharge "MultiSocketCharger"**, serial `24310588`, firmware `1.24.0620.1`, OCPP charge-point ID **`eu092025`**, and it has **two guns** (`NumberOfConnectors=2`; connectors 1 and 2, plus 0 = the whole unit — all reported "Available"). It supports far more than we assumed: **RemoteTrigger ✅ (verified), SmartCharging, Reservation, LocalAuthListManagement, FirmwareManagement**.
## Key configuration facts
| Key | Value | Meaning for us |
|---|---|---|
| `NumberOfConnectors` | **2** | Two guns — the app/UI must be per-connector, not per-charger |
| `SupportedFeatureProfiles` | Core, FirmwareManagement, LocalAuthListManagement, Reservation, SmartCharging, RemoteTrigger | RemoteTrigger already verified working ✅ |
| `AuthorizeRemoteTxRequests` | `false` | Remote starts skip a separate Authorize — our `decide()` gate still fires at StartTransaction ([[authorization]]) |
| `LocalAuthListMaxLength` | **6** | On-charger offline allowlist holds only 6 idTags — enough for a household |
| `LocalAuthListEnabled` / `LocalAuthorizeOffline` | `false` / `false` | Offline auth currently off; charger is fully CSMS-dependent when offline |
| `MeterValueSampleInterval` | 60 s | Live data every minute during charging |
| `MeterValuesSampledData` | Energy, **Power**, **SoC**, Voltage, Current | Rich live telemetry — even state-of-charge — for the web panel |
| `HeartbeatInterval` / `WebSocketPingInterval` | 7200 s / 60 s | Liveness comes from WS pings, not heartbeats |
| `ConnectionTimeOut` | 60 s | A remote start waits 60 s for a plug-in before expiring |
| `MacEnabled` | `false` | ❓ Suggestive lead for [[authorization|"by vehicle"]] — possibly MAC-based vehicle recognition; worth flipping during the Autocharge test |
| `FreeChargeMode` | `false` | Exists — a "just charge, no auth" escape hatch if we ever want it |
| `Url` | `http://10.0.10.203:9000` | Confirms this PC is the configured CSMS host |
| Pricing keys (`PeakPrice`, `IdleFeePerMinute`, …) | set | Vendor billing leftovers; irrelevant for private use |
Also present: `QRCodeTextOfConnector-1..3` (writable, empty), `ChargingScheduleAllowedChargingRateUnit=Power` with max 3 schedule periods and 1 installed profile (SmartCharging is real but small), `ReserveConnectorZeroSupported=false`.
## Boot identity (via TriggerMessage(BootNotification))
`vendor=SimpleCharge, model=MultiSocketCharger, serial=24310588, firmware=1.24.0620.1` — note `GetConfiguration` reports `Vendor=JC` (the [[jc-6620|JC-6620]] module vendor) while BootNotification says SimpleCharge (the charger brand).
## Wiki changes from this ingest
Updated [[anfu-charger]] (identity + capabilities), [[authorization]] (remote-auth behavior, LocalAuthList, MacEnabled lead), [[csms-toolkit]] (discovery API), [[overview]].