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.
This commit is contained in:
2026-07-11 18:58:09 +02:00
parent 5c88e8fa3c
commit d7b17d9cb2
16 changed files with 1794 additions and 0 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()