Compare commits
6 Commits
9562fdaf6b
...
12db2e719d
| Author | SHA1 | Date | |
|---|---|---|---|
| 12db2e719d | |||
| d285a32829 | |||
| 11e467a576 | |||
| a9b8436f2c | |||
| 25fa1f9fc5 | |||
| 8d8affe6ff |
@@ -54,6 +54,12 @@ def _load() -> dict:
|
||||
for key, default in DEFAULTS.items():
|
||||
cfg.setdefault(key, default if not isinstance(default, dict) else dict(default))
|
||||
cfg.pop("learn_mode", None) # superseded by the pending-cards workflow
|
||||
# users' app idTags used to be auto-enrolled as "app token of <name>"
|
||||
# allowlist entries; they now authorize via the user record directly
|
||||
user_tags = {u.get("id_tag") for u in cfg["users"].values()}
|
||||
for tag in [t for t in cfg["authorized"] if t in user_tags]:
|
||||
del cfg["authorized"][tag]
|
||||
log.info("dropped redundant allowlist entry %r (a user's app token)", tag)
|
||||
if not cfg.get("session_secret"):
|
||||
cfg["session_secret"] = secrets.token_hex(32)
|
||||
return cfg
|
||||
|
||||
+51
-7
@@ -26,7 +26,7 @@ from ocpp.v16.enums import (
|
||||
RegistrationStatus,
|
||||
)
|
||||
|
||||
from . import store
|
||||
from . import store, users
|
||||
from .config import CONFIG, HERE, save
|
||||
from .journal import now, record_event
|
||||
|
||||
@@ -68,11 +68,16 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
|
||||
which matches this charger, since AuthorizeRemoteTxRequests=false means
|
||||
StartTransaction is the decisive call anyway.
|
||||
|
||||
A user's app idTag (users.<name>.id_tag, used for their in-app starts) is
|
||||
validated directly against the user record — it is NOT an allowlist entry,
|
||||
and it must satisfy the user's own charger:<cp>:<gun> scopes.
|
||||
|
||||
Unknown idTags are always refused: silently if the admin already rejected
|
||||
the card, otherwise they land in pending_cards for the admin to decide.
|
||||
"""
|
||||
entry = CONFIG["authorized"].get(id_tag)
|
||||
known = entry is not None
|
||||
app_user = user_for_tag(id_tag)
|
||||
gun = f"{cp}:{connector}" if cp and connector is not None else None
|
||||
if known and gun and entry.get("guns") \
|
||||
and not any(fnmatch(gun, pat) for pat in entry["guns"]):
|
||||
@@ -83,6 +88,20 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
|
||||
name = entry.get("name", "?")
|
||||
log.info("[OK] AUTHORIZED idTag=%r (%s) via %s", id_tag, name, context)
|
||||
status = AuthorizationStatus.accepted
|
||||
elif app_user is not None:
|
||||
known = True
|
||||
scopes = CONFIG["users"][app_user].get("scopes", [])
|
||||
if gun and not users.allowed(scopes, f"charger:{cp}:{connector}"):
|
||||
log.warning("[NO] REJECTED app idTag of %r on %s (no permission)",
|
||||
app_user, gun)
|
||||
status = AuthorizationStatus.invalid
|
||||
else:
|
||||
log.info("[OK] AUTHORIZED app start by user %r via %s", app_user, context)
|
||||
status = AuthorizationStatus.accepted
|
||||
elif id_tag == "app-remote" and not CONFIG["users"]:
|
||||
# bootstrap: with zero users the API is open and starts run as "app-remote"
|
||||
log.info("[OK] AUTHORIZED app-remote (open mode, no users yet)")
|
||||
status = AuthorizationStatus.accepted
|
||||
elif id_tag in CONFIG["denied_cards"]:
|
||||
log.warning("[NO] DENIED idTag=%r (admin-rejected card) via %s", id_tag, context)
|
||||
status = AuthorizationStatus.invalid
|
||||
@@ -98,6 +117,14 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
|
||||
return status
|
||||
|
||||
|
||||
def user_for_tag(id_tag: str) -> Optional[str]:
|
||||
"""Username whose personal app idTag this is, if any."""
|
||||
for username, user in CONFIG["users"].items():
|
||||
if user.get("id_tag") == id_tag:
|
||||
return username
|
||||
return None
|
||||
|
||||
|
||||
def resolve_who(id_tag: str) -> str:
|
||||
"""Human label for a session: the card's owning user, the allowlist entry
|
||||
name, the username behind an app idTag, or the raw tag — in that order."""
|
||||
@@ -151,9 +178,15 @@ class ChargePoint(OcppChargePoint):
|
||||
_tx_counter["n"] += 1
|
||||
tx = _tx_counter["n"]
|
||||
who = resolve_who(id_tag)
|
||||
# audit: HOW was this session authorized? kind of the allowlist
|
||||
# entry -> "card" (physical tap) or "app" (in-app button press)
|
||||
method = CONFIG["authorized"].get(id_tag, {}).get("kind", "unknown")
|
||||
# audit: HOW was this session authorized? allowlist kind ->
|
||||
# "card" (physical tap); a user's app idTag -> "app" (in-app button)
|
||||
entry = CONFIG["authorized"].get(id_tag)
|
||||
if entry is not None:
|
||||
method = entry.get("kind", "unknown")
|
||||
elif user_for_tag(id_tag) or id_tag == "app-remote":
|
||||
method = "app"
|
||||
else:
|
||||
method = "unknown"
|
||||
ACTIVE_TX[tx] = {
|
||||
"cp": self.id, "connector": connector_id, "id_tag": id_tag,
|
||||
"who": who, "method": method,
|
||||
@@ -192,10 +225,11 @@ class ChargePoint(OcppChargePoint):
|
||||
tx = kwargs.get("transaction_id")
|
||||
if tx is not None:
|
||||
for entry in meter_value or []:
|
||||
reading = {}
|
||||
reading, context = {}, None
|
||||
for sv in entry.get("sampled_value") or []:
|
||||
# measurand defaults to the energy register when omitted
|
||||
measurand = sv.get("measurand", "Energy.Active.Import.Register")
|
||||
context = sv.get("context", context) # Sample.Periodic / Transaction.Begin / .End
|
||||
try:
|
||||
value = float(sv.get("value"))
|
||||
except (TypeError, ValueError):
|
||||
@@ -207,10 +241,20 @@ class ChargePoint(OcppChargePoint):
|
||||
reading["power_w"] = value * 1000 if sv.get("unit") == "kW" else value
|
||||
elif measurand == "SoC":
|
||||
reading["soc"] = value
|
||||
elif measurand == "Voltage":
|
||||
reading["voltage_v"] = value * 1000 if sv.get("unit") == "kV" else value
|
||||
elif measurand == "Current.Import":
|
||||
reading["current_a"] = value
|
||||
if reading:
|
||||
store.add_sample(tx, entry.get("timestamp", now()),
|
||||
reading.get("energy_wh"), reading.get("power_w"),
|
||||
reading.get("soc"))
|
||||
context=context, **reading)
|
||||
# live telemetry for the panel: latest sample rides
|
||||
# /api/status. Transaction.Begin is skipped — it's taken
|
||||
# before the car's BMS is read (SoC 0, all zeros).
|
||||
if context != "Transaction.Begin" and tx in ACTIVE_TX:
|
||||
ACTIVE_TX[tx].setdefault("telemetry", {}).update(
|
||||
{**reading, "time": entry.get("timestamp")}
|
||||
)
|
||||
log.info("MeterValues: connector=%s values=%r", connector_id, meter_value)
|
||||
return call_result.MeterValues()
|
||||
|
||||
|
||||
+6
-2
@@ -52,8 +52,12 @@ async def spa(full_path: str):
|
||||
)
|
||||
candidate = (DIST / full_path).resolve() if full_path else None
|
||||
if candidate and candidate.is_file() and candidate.is_relative_to(DIST.resolve()):
|
||||
return FileResponse(candidate)
|
||||
return FileResponse(DIST / "index.html")
|
||||
# hashed assets are immutable; cache them hard
|
||||
headers = {"Cache-Control": "public, max-age=31536000, immutable"} \
|
||||
if full_path.startswith("assets/") else {"Cache-Control": "no-cache"}
|
||||
return FileResponse(candidate, headers=headers)
|
||||
# index.html must always revalidate, or phones keep showing stale builds
|
||||
return FileResponse(DIST / "index.html", headers={"Cache-Control": "no-cache"})
|
||||
|
||||
|
||||
# Catch-all WS route so the charger may dial any path (it uses /<ChargerID>).
|
||||
|
||||
+5
-4
@@ -159,11 +159,9 @@ async def charger_start(connector: int = 1, cp: Optional[str] = None,
|
||||
user: dict = Depends(current_user)):
|
||||
target = _cp(cp)
|
||||
need(user, f"charger:{target.id}:{connector}")
|
||||
# remote starts run under the caller's own idTag so sessions are attributable
|
||||
# remote starts run under the caller's own idTag so sessions are
|
||||
# attributable; decide() validates it directly against the user record
|
||||
id_tag = user.get("id_tag") or f"app-{user['name']}"
|
||||
if id_tag not in CONFIG["authorized"]:
|
||||
CONFIG["authorized"][id_tag] = {"name": f"app token of {user['name']}", "kind": "app"}
|
||||
save()
|
||||
status = await _ocpp(csms.remote_start(target.id, id_tag, connector))
|
||||
return {"remote_start": status, "id_tag": id_tag}
|
||||
|
||||
@@ -272,6 +270,9 @@ async def allowlist_put(id_tag: str, entry: AllowlistEntry,
|
||||
need(user, "admin")
|
||||
if entry.user is not None and entry.user not in CONFIG["users"]:
|
||||
raise HTTPException(400, f"cannot link card to unknown user {entry.user!r}")
|
||||
if csms.user_for_tag(id_tag) is not None:
|
||||
raise HTTPException(400, f"{id_tag!r} is a user's app token — it authorizes "
|
||||
"through the user's own permissions, not the allowlist")
|
||||
CONFIG["authorized"][id_tag] = entry.model_dump(exclude_none=True)
|
||||
save()
|
||||
log.info("allowlist: added/updated %r (%s)", id_tag, entry.name)
|
||||
|
||||
+16
-6
@@ -51,7 +51,10 @@ CREATE TABLE IF NOT EXISTS samples (
|
||||
time TEXT NOT NULL,
|
||||
energy_wh REAL,
|
||||
power_w REAL,
|
||||
soc REAL
|
||||
soc REAL,
|
||||
voltage_v REAL,
|
||||
current_a REAL,
|
||||
context TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_samples_tx ON samples (tx);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions (started);
|
||||
@@ -64,10 +67,14 @@ def _db():
|
||||
con = sqlite3.connect(DB_PATH)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.executescript(_SCHEMA)
|
||||
# migration for dbs created before the audit column existed
|
||||
# migrations for dbs created before later columns existed
|
||||
cols = [row[1] for row in con.execute("PRAGMA table_info(sessions)")]
|
||||
if "method" not in cols:
|
||||
con.execute("ALTER TABLE sessions ADD COLUMN method TEXT")
|
||||
sample_cols = [row[1] for row in con.execute("PRAGMA table_info(samples)")]
|
||||
for col, ddl in (("voltage_v", "REAL"), ("current_a", "REAL"), ("context", "TEXT")):
|
||||
if col not in sample_cols:
|
||||
con.execute(f"ALTER TABLE samples ADD COLUMN {col} {ddl}")
|
||||
return closing(con)
|
||||
|
||||
|
||||
@@ -114,12 +121,15 @@ def end_session(tx: int, ended: str, meter_stop: float,
|
||||
)
|
||||
|
||||
|
||||
def add_sample(tx: int, time: str, energy_wh: Optional[float],
|
||||
power_w: Optional[float], soc: Optional[float]) -> None:
|
||||
def add_sample(tx: int, time: str, energy_wh: Optional[float] = None,
|
||||
power_w: Optional[float] = None, soc: Optional[float] = None,
|
||||
voltage_v: Optional[float] = None, current_a: Optional[float] = None,
|
||||
context: Optional[str] = None) -> None:
|
||||
with _db() as con, con:
|
||||
con.execute(
|
||||
"INSERT INTO samples (tx, time, energy_wh, power_w, soc) VALUES (?, ?, ?, ?, ?)",
|
||||
(tx, time, energy_wh, power_w, soc),
|
||||
"INSERT INTO samples (tx, time, energy_wh, power_w, soc, voltage_v, current_a, context)"
|
||||
" VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(tx, time, energy_wh, power_w, soc, voltage_v, current_a, context),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/** State-of-charge gauge: a battery whose fill sweeps the owner-specified
|
||||
* gradient — red (empty) → blue (half) → green (full). */
|
||||
|
||||
type RGB = [number, number, number];
|
||||
const RED: RGB = [191, 53, 39];
|
||||
const BLUE: RGB = [33, 96, 196];
|
||||
const GREEN: RGB = [23, 138, 92];
|
||||
|
||||
function mix(a: RGB, b: RGB, t: number): string {
|
||||
const c = a.map((v, i) => Math.round(v + (b[i] - v) * t));
|
||||
return `rgb(${c[0]}, ${c[1]}, ${c[2]})`;
|
||||
}
|
||||
|
||||
export function socColor(soc: number): string {
|
||||
const s = Math.max(0, Math.min(100, soc));
|
||||
return s <= 50 ? mix(RED, BLUE, s / 50) : mix(BLUE, GREEN, (s - 50) / 50);
|
||||
}
|
||||
|
||||
export default function Battery({ soc }: { soc: number | null | undefined }) {
|
||||
const known = soc != null;
|
||||
const pct = known ? Math.max(0, Math.min(100, soc)) : 0;
|
||||
const color = known ? socColor(pct) : "transparent";
|
||||
return (
|
||||
<div
|
||||
className="battery"
|
||||
role="meter"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={known ? Math.round(pct) : undefined}
|
||||
aria-label="Vehicle state of charge"
|
||||
>
|
||||
<span className="battery__shell">
|
||||
<span className="battery__fill" style={{ width: `${pct}%`, background: color }} />
|
||||
</span>
|
||||
<span className="battery__cap" />
|
||||
<span className="battery__pct mono" style={known ? { color: socColor(pct) } : undefined}>
|
||||
{known ? `${Math.round(pct)}%` : "—"}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -218,7 +218,6 @@ function AuthorizedSection() {
|
||||
<section className="panel">
|
||||
<header className="panel__head">
|
||||
<h2>Enrolled cards & tokens</h2>
|
||||
<span className="panel__meta">what may authorize a charge, and who it belongs to</span>
|
||||
</header>
|
||||
{!entries.length && <p className="empty">Nothing enrolled yet.</p>}
|
||||
<div className="table-wrap">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { api, scopeAllowed } from "../api";
|
||||
import Battery from "../components/Battery";
|
||||
import { Lamp, statusTone } from "../components/Lamp";
|
||||
import { useAction, useLiveRelays, useStatus } from "../queries";
|
||||
import { useApp } from "../store";
|
||||
@@ -127,20 +128,60 @@ function GunBay({ gun, scopes }: { gun: Gun; scopes: string[] }) {
|
||||
</div>
|
||||
|
||||
{gun.tx && (
|
||||
<dl className="bay__telemetry">
|
||||
<div>
|
||||
<dt>By</dt>
|
||||
<dd>{gun.tx.who || gun.tx.id_tag}</dd>
|
||||
<>
|
||||
<div className="bay__charge">
|
||||
<Battery soc={gun.tx.telemetry?.soc} />
|
||||
<div className="bay__kw">
|
||||
<span className="bay__kw-num mono">
|
||||
{gun.tx.telemetry?.power_w != null
|
||||
? (gun.tx.telemetry.power_w / 1000).toFixed(1)
|
||||
: "—"}
|
||||
</span>
|
||||
<span className="bay__kw-unit">kW</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Via</dt>
|
||||
<dd>{gun.tx.method === "app" ? "In-app" : gun.tx.method === "card" ? "Card" : gun.tx.method}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Running</dt>
|
||||
<dd>{fmtSince(gun.tx.started)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<dl className="bay__telemetry">
|
||||
<div>
|
||||
<dt>By</dt>
|
||||
<dd>{gun.tx.who || gun.tx.id_tag}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Via</dt>
|
||||
<dd>{gun.tx.method === "app" ? "In-app" : gun.tx.method === "card" ? "Card" : gun.tx.method}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Running</dt>
|
||||
<dd>{fmtSince(gun.tx.started)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Delivered</dt>
|
||||
<dd className="mono">
|
||||
{gun.tx.telemetry?.energy_wh != null
|
||||
? `${((gun.tx.telemetry.energy_wh - gun.tx.meter_start) / 1000).toFixed(2)} kWh`
|
||||
: "—"}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Voltage</dt>
|
||||
<dd className="mono">
|
||||
{gun.tx.telemetry?.voltage_v != null
|
||||
? `${gun.tx.telemetry.voltage_v.toFixed(0)} V`
|
||||
: "—"}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Current</dt>
|
||||
<dd className="mono">
|
||||
{gun.tx.telemetry?.current_a != null
|
||||
? `${gun.tx.telemetry.current_a.toFixed(1)} A`
|
||||
: "—"}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{!gun.tx.telemetry && (
|
||||
<span className="bay__hint">first meter reading arrives within a minute…</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<footer className="bay__actions">
|
||||
|
||||
@@ -36,7 +36,7 @@ export default function History() {
|
||||
<p className="empty">
|
||||
{admin
|
||||
? "No charging sessions yet. The first card tap or in-app start will appear here with who, when, how, and how many kWh."
|
||||
: "No charging sessions of yours yet. Sessions you start — by card or in-app — appear here."}
|
||||
: "No charging sessions yet. Sessions you start — by card or in-app — appear here."}
|
||||
</p>
|
||||
);
|
||||
|
||||
|
||||
+32
-2
@@ -256,8 +256,39 @@ button, input, select { font: inherit; color: inherit; }
|
||||
.bay__status { display: flex; align-items: center; gap: 10px; min-height: 26px; }
|
||||
.bay__hint { color: var(--ink-dim); font-size: 13px; }
|
||||
|
||||
.bay__charge {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 14px;
|
||||
padding: 12px 14px;
|
||||
background: var(--panel-inset);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.bay__kw { display: flex; align-items: baseline; gap: 5px; }
|
||||
.bay__kw-num { font-size: 26px; font-weight: 600; letter-spacing: -0.02em; }
|
||||
.bay__kw-unit {
|
||||
font-family: var(--font-mono); font-size: 11px;
|
||||
text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-dim);
|
||||
}
|
||||
|
||||
/* ---------- battery gauge (SoC, red -> blue -> green) ---------- */
|
||||
.battery { display: flex; align-items: center; gap: 2px; }
|
||||
.battery__shell {
|
||||
display: inline-block; width: 52px; height: 22px;
|
||||
border: 2px solid var(--ink-dim); border-radius: 6px;
|
||||
padding: 2px; background: var(--panel);
|
||||
}
|
||||
.battery__fill {
|
||||
display: block; height: 100%; border-radius: 3px;
|
||||
min-width: 2px;
|
||||
transition: width 0.6s ease, background 0.6s ease;
|
||||
}
|
||||
.battery__cap {
|
||||
width: 3px; height: 10px; border-radius: 0 2px 2px 0;
|
||||
background: var(--ink-dim);
|
||||
}
|
||||
.battery__pct { font-size: 15px; font-weight: 600; margin-left: 8px; }
|
||||
|
||||
.bay__telemetry {
|
||||
display: flex; gap: 22px;
|
||||
display: flex; flex-wrap: wrap; gap: 10px 22px;
|
||||
padding: 10px 12px;
|
||||
background: var(--panel-inset);
|
||||
border-radius: 8px;
|
||||
@@ -281,7 +312,6 @@ button, input, select { font: inherit; color: inherit; }
|
||||
}
|
||||
.chip--live, .chip--charging { background: color-mix(in srgb, var(--live) 14%, transparent); color: var(--live); border-color: color-mix(in srgb, var(--live) 40%, transparent); }
|
||||
.chip--plugged { background: color-mix(in srgb, var(--blue) 13%, transparent); color: var(--blue); border-color: color-mix(in srgb, var(--blue) 40%, transparent); }
|
||||
.chip--idle { /* the quiet gray default */ }
|
||||
.chip--offline { opacity: 0.7; }
|
||||
.chip--faulted, .chip--unavailable { background: color-mix(in srgb, var(--red) 12%, transparent); color: var(--red); border-color: color-mix(in srgb, var(--red) 40%, transparent); }
|
||||
.chip--card { background: color-mix(in srgb, var(--copper) 13%, transparent); color: var(--copper-deep); border-color: color-mix(in srgb, var(--copper) 40%, transparent); }
|
||||
|
||||
@@ -4,6 +4,15 @@ export interface Me {
|
||||
id_tag: string | null;
|
||||
}
|
||||
|
||||
export interface Telemetry {
|
||||
energy_wh?: number;
|
||||
power_w?: number;
|
||||
soc?: number;
|
||||
voltage_v?: number;
|
||||
current_a?: number;
|
||||
time?: string;
|
||||
}
|
||||
|
||||
export interface ActiveTx {
|
||||
cp: string;
|
||||
connector: number;
|
||||
@@ -12,6 +21,7 @@ export interface ActiveTx {
|
||||
method: string;
|
||||
meter_start: number;
|
||||
started: string;
|
||||
telemetry?: Telemetry;
|
||||
}
|
||||
|
||||
export interface ChargerMeta {
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"root":["./src/app.tsx","./src/api.ts","./src/main.tsx","./src/queries.ts","./src/store.ts","./src/types.ts","./src/components/lamp.tsx","./src/components/layout.tsx","./src/pages/account.tsx","./src/pages/cards.tsx","./src/pages/dashboard.tsx","./src/pages/history.tsx","./src/pages/login.tsx","./src/pages/users.tsx"],"version":"5.9.3"}
|
||||
{"root":["./src/app.tsx","./src/api.ts","./src/main.tsx","./src/queries.ts","./src/store.ts","./src/types.ts","./src/components/battery.tsx","./src/components/lamp.tsx","./src/components/layout.tsx","./src/pages/account.tsx","./src/pages/cards.tsx","./src/pages/dashboard.tsx","./src/pages/history.tsx","./src/pages/login.tsx","./src/pages/users.tsx"],"version":"5.9.3"}
|
||||
@@ -0,0 +1 @@
|
||||
[2,"2901b39c-8ec0-4b2e-9402-ecf19aeda2f9","MeterValues",{"connectorId":1,"transactionId":2,"meterValue":[{"timestamp":"2026-07-12T07:22:13.558Z","sampledValue":[{"value":"0.0","context":"Transaction.Begin","format":"Raw","measurand":"Current.Import","location":"Outlet","unit":"A"},{"value":"405731","context":"Transaction.Begin","format":"Raw","measurand":"Energy.Active.Import.Register","location":"Outlet","unit":"Wh"},{"value":"0","context":"Transaction.Begin","format":"Raw","measurand":"Power.Active.Import","location":"Outlet","unit":"W"},{"value":"0","context":"Transaction.Begin","format":"Raw","measurand":"SoC","location":"Outlet","unit":"Percent"},{"value":"0.0","context":"Transaction.Begin","format":"Raw","measurand":"Voltage","location":"Outlet","unit":"V"}]}]}]
|
||||
@@ -40,9 +40,9 @@ Exhaustively tested on the real hardware; the charger never forwards any vehicle
|
||||
|
||||
**Consequence:** vehicle-based auth is off the table. Households authorize via **RFID cards ✅** and the **app remote-start ✅** — both verified. (If a future firmware update changes this, retest with the same three steps.)
|
||||
|
||||
## 3. Mobile / web app — ✅ control path verified live (2026-07-09)
|
||||
## 3. Mobile / web app — ✅ verified end-to-end (panel → live charger, 2026-07-12)
|
||||
|
||||
The exact calls the app will make were proven on the real charger with a car plugged in: `RemoteStartTransaction(connector=1, idTag="app-remote")` → Accepted → StartTransaction → Charging; `RemoteStopTransaction(tx)` → Accepted → StopTransaction (`reason: Remote`). Both guns ran **simultaneous transactions** (card on gun 2, remote on gun 1). The `app-remote` idTag is enrolled in the allowlist as `kind:"app"`. What remains is only the UI:
|
||||
The exact calls the app will make were proven on the real charger with a car plugged in: `RemoteStartTransaction(connector=1, idTag="app-remote")` → Accepted → StartTransaction → Charging; `RemoteStopTransaction(tx)` → Accepted → StopTransaction (`reason: Remote`). Both guns ran **simultaneous transactions** (card on gun 2, remote on gun 1). The shared `app-remote` idTag used for that test is **retired** (2026-07-12): starts now run under per-user idTags, and the [[frontend|panel]] executed a real remote start on the live charger. The remaining allowlist entry is safe to delete; `app-remote` only functions in zero-user bootstrap mode. The original UI wishlist, all since delivered by the panel:
|
||||
|
||||
A mobile-friendly web control panel (no app store):
|
||||
|
||||
@@ -56,7 +56,7 @@ A mobile-friendly web control panel (no app store):
|
||||
|
||||
The [[backend]] now has real multi-user authorization on top of the three methods above, because not every household member may control everything. Requirement (owner, 2026-07-11): some users control gun 1 only, some gun 2, some only certain [[wifi-relays|relays]].
|
||||
|
||||
- **Users** live in the `settings` table of `backend.db`: username + PBKDF2 password hash + scope list + a personal `id_tag` (`app-<name>`) used for their remote starts, so charging sessions are **attributable per person**.
|
||||
- **Users** live in the `settings` table of `backend.db`: username + PBKDF2 password hash + scope list + a personal `id_tag` (`app-<name>`) used for their remote starts, so charging sessions are **attributable per person**. The app idTag is NOT an allowlist entry (2026-07-12): `decide()` validates it against the user record directly and enforces the user's gun scopes; the Cards page shows only physical cards.
|
||||
- **Login**: `POST /api/login` (username/password) → 30-day HMAC-signed session, delivered as an HttpOnly cookie (for the PWA) and as a bearer token (for curl). Stateless — survives backend restarts; deleting a user kills their sessions.
|
||||
- **Scopes** (fnmatch wildcards work):
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
type: entity
|
||||
updated: 2026-07-11
|
||||
updated: 2026-07-12
|
||||
tags: [software, csms, backend, relays, auth]
|
||||
---
|
||||
|
||||
@@ -43,8 +43,11 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
|
||||
- Carried over from the proven discovery code: the `decide()` gate ([[authorization]]) — now with card→user linking (`"user"`) and charger-qualified gun restriction (`"guns": ["eu092025:2"]`, fnmatch) — the `_WSAdapter` WebSocket bridge, and the JSONL event journal. `DataTransfer` frames are journaled too (the VIN long-shot lead in [[authorization]]).
|
||||
- **Multi-charger by design**: a second charger only needs the same URL with a unique ChargerID; scopes, sessions, card restrictions, and the panel are all keyed by charger id. Gun display names come from the `"chargers"` config section (not hardcoded).
|
||||
- **Multi-user auth** (2026-07-11, replaced the interim `api_token`): username/password users with permission scopes — `charger:<cp>:<gun>`, `relay:<name>`, `admin` — full model in [[authorization]]. Stdlib crypto only (PBKDF2 + HMAC sessions). Zero users = open API (startup warns); bootstrap via `python -m backend.users add <name> --scopes admin`.
|
||||
- Remote starts run under the calling user's own idTag (`app-<name>`, auto-enrolled) → per-person session attribution.
|
||||
- Remote starts run under the calling user's own idTag (`app-<name>`) → per-person session attribution. Since 2026-07-12 these tags are **validated directly against the user record** (never enrolled in the allowlist — the old synthetic "app token of <name>" entries are auto-dropped on startup), and the charger-side gate enforces the user's `charger:<cp>:<gun>` scopes too.
|
||||
- **Consumption tracking** (`store.py`, 2026-07-11): every `StartTransaction` opens a row in `backend.db` with a resolved "who" (allowlist name or username); `StopTransaction` closes it and computes Wh from the meter diff; `MeterValues` rows land in a `samples` table (energy/power/SoC, kW→W normalized). Transaction ids continue from `MAX(tx)` across restarts, and stop-by-tx falls back to the store so sessions running through a backend restart stay stoppable.
|
||||
- **Live telemetry** (2026-07-12): the latest meter sample per active transaction (SoC, W, V, A, energy) rides `/api/status` as `active_transactions[tx].telemetry`; `Transaction.Begin` snapshots are skipped (taken before the car's BMS is read). The `samples` table stores energy/power/SoC/voltage/current + OCPP context per minute.
|
||||
- Ctrl+C gotcha, fixed 2026-07-12: uvicorn's graceful shutdown waited forever for the charger's never-closing WebSocket — `timeout_graceful_shutdown=3` caps it; one Ctrl+C now exits in ~3 s and the charger redials.
|
||||
- SPA cache headers: `index.html` is `no-cache` (phones must revalidate — stale builds plagued early testing), hashed `assets/*` cache forever. Remember: **`:9000` serves the last `npm run build`** — source edits are invisible until a build runs (`npm run dev` for live editing).
|
||||
- Relay calls are blocking tinytuya I/O, run via `asyncio.to_thread` so the OCPP socket never stalls.
|
||||
- Venv at repo root (`../venv/`, Python 3.13); deps pinned in `backend/requirements.txt` (fastapi, uvicorn, websockets, ocpp, tinytuya) — the auth system added none.
|
||||
- Sessions record the **auth method** (`card` vs `app`) for the audit trail; unknown cards NEVER charge — they queue in `pending_cards` for admin approve/reject (learn mode is gone).
|
||||
|
||||
@@ -1,24 +1,25 @@
|
||||
---
|
||||
type: entity
|
||||
updated: 2026-07-11
|
||||
updated: 2026-07-12
|
||||
tags: [software, frontend, react]
|
||||
---
|
||||
|
||||
# Frontend (`../frontend/`)
|
||||
|
||||
The React control panel (built 2026-07-11, replacing the single-file vanilla-JS panel at the owner's request). Stack per the owner's spec: **Vite + TypeScript + React 19, React Router 7 (routing), zustand (auth/UI state), TanStack Query 5 (server state, polling)**.
|
||||
The React control panel — branded **"Art IoT"** by the owner (2026-07-12) — (built 2026-07-11, replacing the single-file vanilla-JS panel at the owner's request). Stack per the owner's spec: **Vite + TypeScript + React 19, React Router 7 (routing), zustand (auth/UI state), TanStack Query 5 (server state, polling)**.
|
||||
|
||||
## Dev / prod workflow
|
||||
|
||||
- **Dev**: `npm run dev` in `frontend/` → Vite on `:5173`, **proxies `/api` to the backend on `:9000`** (`vite.config.ts`), so the session cookie flows normally.
|
||||
- **Prod**: `npm run build` → `frontend/dist/`; the [[backend]] serves it statically with an SPA fallback (exact files win, everything else gets `index.html`, `/api/*` and `/docs` excluded). No separate web server.
|
||||
- Fully self-contained: fonts (Archivo + IBM Plex Mono via Fontsource) are bundled into `dist/` — nothing loads from a CDN, so it works over [[netbird|NetBird]] without internet. ~94 kB gzipped JS.
|
||||
- Fully self-contained: fonts (Archivo + IBM Plex Mono via Fontsource) are bundled into `dist/` — nothing loads from a CDN, so it works over [[netbird|NetBird]] without internet. ~95 kB gzipped JS.
|
||||
- ✅ **Verified on the owner's phone against the live charger** (2026-07-12): login, gun cards, and a real in-app remote start.
|
||||
|
||||
## Pages
|
||||
|
||||
| Route | Who | What |
|
||||
|---|---|---|
|
||||
| `/` (Control) | all | one "bay" card per gun — **every registry-declared gun always renders**, even offline; status lamp, Start/Stop gated by scope **and** gun readiness; live session shows who/via/duration; relay toggles with on-demand live read |
|
||||
| `/` (Control) | all | one "bay" card per gun — **every registry-declared gun always renders**, even offline; status lamp, Start/Stop gated by scope **and** cable-plugged readiness; a charging bay shows the **SoC battery gauge (red→blue→green fill)**, a big kW readout, delivered kWh, voltage, current, plus who/via/duration; relay toggles with on-demand live read |
|
||||
| `/account` | all | **your permissions in plain words** (admin badge, or the guns/relays you may control) + self-service password change (current password required) |
|
||||
| `/history` | all | admins: the full audit table (**who charged, via Card or In-app, which gun, when, duration, kWh**); everyone else: **only their own sessions** |
|
||||
| `/cards` | admin | **pending cards awaiting review** (approve → name + owner + gun restrictions in one step; reject → silenced), enrolled cards with owner/guns editing, rejected list with un-reject |
|
||||
|
||||
+12
@@ -91,3 +91,15 @@ Owner confirmed the React panel loads on the phone after backend restart. Change
|
||||
## [2026-07-12] meta | Private history; permissions on Account; Start only when plugged; "Art IoT" rename
|
||||
|
||||
Owner (testing on the phone, second user created): (1) transactions are now PRIVATE — non-admins see only their own sessions (app starts + linked cards); gun scopes grant control, not visibility; admins see all. (2) Account page shows the user's own permissions in plain words (admin badge, or gun/relay list built from data they already see). (3) Start button arms ONLY when the cable is plugged (Preparing) — an idle unplugged gun shows "plug the cable into the car to enable". Owner also renamed the app to "Art IoT" (login, topbar, manifest, title) — kept. Smoke: 59 checks. Updated [[backend]], [[frontend]].
|
||||
|
||||
## [2026-07-12] meta | Live telemetry on the gun cards: SoC battery gauge + kW/V/A/delivered
|
||||
|
||||
Owner wants meter values visible per gun in Control. Backend: latest Sample.Periodic per active tx kept in memory (ACTIVE_TX telemetry) and shipped with /api/status (Transaction.Begin snapshots skipped — taken before the car's BMS is read). Also this morning's finding filed: begin/end snapshots are legitimately 0 A/0 V, and a 42 s session never gets a periodic sample. Frontend: battery gauge with red->blue->green SoC gradient + big kW readout + Delivered/Voltage/Current rows on charging bays; earlier commit added voltage_v/current_a/context columns to samples. Smoke: 60 checks. Updated [[frontend]], [[backend]] implicitly via log.
|
||||
|
||||
## [2026-07-12] meta | User app idTags no longer pollute the allowlist
|
||||
|
||||
Owner: "why do we need this app token of X? We just need the user." Agreed — decide() now validates a user's app idTag directly against the user record (and enforces their charger:<cp>:<gun> scopes at the charger-side gate too); charger_start no longer auto-enrolls; enrolling a user's tag via the allowlist API returns 400; existing "app token of <name>" entries are auto-dropped at startup. Open-mode bootstrap: "app-remote" authorizes with zero users configured. Session method audit: user tags -> "app". Smoke: 63 checks. Updated [[backend]], [[authorization]].
|
||||
|
||||
## [2026-07-12] lint | Session wrap-up: milestones + gaps from today filed
|
||||
|
||||
Owner asked whether the wiki needs updating — it did. Filed: panel verified end-to-end on the phone incl. a real in-app start on the live charger (tx 1-2, 141 Wh, who=julian/method=app; the two pre-refactor session rows' who labels were repaired in the db); six household users created; "app-remote" retired (delete from Cards when convenient); Ctrl+C shutdown fix (timeout_graceful_shutdown=3 vs the never-closing charger socket); SPA cache headers + the ":9000 serves the last build" rule; telemetry columns (V/A/context) + live telemetry on /api/status; battery gauge in Control. Refreshed [[overview]] (milestones + trimmed next steps: Tuya keys, remote-stop question, deploy as service), [[backend]], [[frontend]], [[authorization]].
|
||||
|
||||
+11
-7
@@ -1,6 +1,6 @@
|
||||
---
|
||||
type: meta
|
||||
updated: 2026-07-11
|
||||
updated: 2026-07-12
|
||||
tags: [synthesis]
|
||||
---
|
||||
|
||||
@@ -23,14 +23,18 @@ tags: [synthesis]
|
||||
|
||||
Hardware surprise: this is a **DC-capable multi-standard charger** (gun 1 EU, gun 2 Chinese GB/T @ 30 kW), not the assumed basic AC unit — see [[anfu-charger]].
|
||||
|
||||
## Milestones reached (2026-07-12)
|
||||
|
||||
- ✅ Live cutover: `eu092025` connects to `python -m backend.main` (2026-07-11 evening)
|
||||
- ✅ **The panel works end-to-end on the owner's phone**: login, and a real in-app remote start on gun 1 of the live charger (2026-07-12 morning, tx 1–2, 141 Wh, attributed who=julian / method=app)
|
||||
- ✅ Six household users created (admin + scoped members)
|
||||
|
||||
## What's next
|
||||
|
||||
1. ~~Cut the live charger over to the backend~~ — ✅ done 2026-07-11 evening: `eu092025` connects to `python -m backend.main` (verified in events.jsonl). Remaining: a card tap + a panel button-push on the live charger.
|
||||
2. **Create the real users** — `python -m backend.users add <name> --scopes ...` for each household member (the API stays open until the first user exists).
|
||||
3. **Extract the Tuya local keys** (`tinytuya wizard` — steps in [[wifi-relays]]) and register them via `PUT /api/relays/<name>` → relays become controllable.
|
||||
4. **Restart the backend once** to pick up the React panel + pending-card workflow (state changes never need restarts; code updates do).
|
||||
5. **Test the panel from a phone** — `http://<host>:9000/`; verify login, a real button-push start on a ready gun, the pending-card banner (tap an unenrolled card), and add-to-home-screen over [[netbird|NetBird]].
|
||||
6. **Resolve the ❓ remote-stop restart question** — did the gun-2 session auto-restart from auth cache after RemoteStop, or was the card re-tapped? Affects the app's Stop button UX ([[authorization]]).
|
||||
1. **Extract the Tuya local keys** (`tinytuya wizard` — steps in [[wifi-relays]]) and register them via `PUT /api/relays/<name>` → relays become controllable.
|
||||
2. **Resolve the ❓ remote-stop restart question** — did the gun-2 session auto-restart from auth cache after RemoteStop, or was the card re-tapped? Affects the app's Stop button UX ([[authorization]]). Test: remote-stop, touch nothing for 5 min.
|
||||
3. **Deploy as an always-on service** ([[architecture-plan]] phase 4) — decide the host (❓ below), run under NSSM/systemd, DHCP reservation.
|
||||
4. Housekeeping: delete the retired `app-remote` allowlist entry from the Cards page; tap the remaining household cards so they pend and can be linked to their owners.
|
||||
|
||||
## Open decisions ❓
|
||||
|
||||
|
||||
Reference in New Issue
Block a user