feat: React control panel; pending-card review workflow; auth-method audit
Frontend rewrite (frontend/, replacing backend/static/): - Vite + TypeScript + React 19, React Router 7, zustand, TanStack Query 5 - dev: vite proxy /api -> :9000; prod: npm run build -> dist/, served by the backend with SPA fallback - pages: Control (gun bays w/ scope+readiness-gated start/stop, relays), History (who/via/gun/when/duration/kWh audit), Cards (pending review, enrolled, rejected), Users (permission checkbox matrix) - self-contained: fonts bundled, no CDN; light/dark; reduced-motion safe Backend: - learn mode removed: unknown cards are always refused and queued in pending_cards; admin approves (name + owner + gun restrictions in one step) or rejects (denied_cards, silent, un-rejectable); pending count rides /api/status as the notification signal - sessions record the auth method (card tap vs in-app button) for audit - GET /api/permissions: grantable-permission catalog driving the UI matrix - SPA static serving with path-traversal guard; 503 hint when not built Smoke test: 54 checks incl. approve/reject round-trips over a fake charge point and method audit assertions.
This commit is contained in:
+10
-2
@@ -7,13 +7,19 @@ semantics. A legacy config.json (pre-2026-07-11 layout) is imported into the
|
||||
database once on startup and renamed to config.json.migrated.
|
||||
|
||||
Sections:
|
||||
learn_mode accept-and-record unknown idTags vs enforce the allowlist
|
||||
users name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag"}
|
||||
authorized idTag -> {"name", "kind": "card|app|car",
|
||||
optional "user": owner, "guns": ["eu092025:2"]}
|
||||
pending_cards unknown idTags tapped on a charger, awaiting the admin's
|
||||
approve (-> authorized, linked to a user) or reject decision;
|
||||
idTag -> {"first_seen", "last_seen", "count", "cp", "connector"}
|
||||
denied_cards rejected idTags; silently refused, never re-pend
|
||||
relays name -> {"id", "key", "ip", "version", "switch", "label"}
|
||||
chargers cp_id -> {"label", "guns": {"1": "display name"}} (UI only)
|
||||
session_secret signs login sessions; auto-generated once
|
||||
|
||||
There is no learn mode anymore: an unknown card is ALWAYS refused, but lands
|
||||
in pending_cards for the admin to approve or reject from the panel.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -29,9 +35,10 @@ LEGACY_CONFIG = HERE / "config.json"
|
||||
log = logging.getLogger("config")
|
||||
|
||||
DEFAULTS = {
|
||||
"learn_mode": True,
|
||||
"users": {},
|
||||
"authorized": {},
|
||||
"pending_cards": {},
|
||||
"denied_cards": {},
|
||||
"relays": {},
|
||||
"chargers": {},
|
||||
}
|
||||
@@ -46,6 +53,7 @@ def _load() -> dict:
|
||||
"config.json.migrated)", store.DB_PATH.name)
|
||||
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
|
||||
if not cfg.get("session_secret"):
|
||||
cfg["session_secret"] = secrets.token_hex(32)
|
||||
return cfg
|
||||
|
||||
+28
-11
@@ -27,8 +27,8 @@ from ocpp.v16.enums import (
|
||||
)
|
||||
|
||||
from . import store
|
||||
from .config import CONFIG, HERE
|
||||
from .journal import now, record_event, record_seen
|
||||
from .config import CONFIG, HERE, save
|
||||
from .journal import now, record_event
|
||||
|
||||
log = logging.getLogger("csms")
|
||||
|
||||
@@ -47,6 +47,16 @@ TRIGGERABLE = {
|
||||
}
|
||||
|
||||
|
||||
def _record_pending(id_tag: str, cp: Optional[str], connector: Optional[int]) -> None:
|
||||
"""An unknown card was tapped: queue it for the admin to approve or reject."""
|
||||
entry = CONFIG["pending_cards"].get(
|
||||
id_tag, {"first_seen": now(), "count": 0}
|
||||
)
|
||||
entry.update(last_seen=now(), count=entry["count"] + 1, cp=cp, connector=connector)
|
||||
CONFIG["pending_cards"][id_tag] = entry
|
||||
save()
|
||||
|
||||
|
||||
def decide(id_tag: str, context: str, connector: Optional[int] = None,
|
||||
cp: Optional[str] = None) -> AuthorizationStatus:
|
||||
"""The one gate every auth method flows through: is this idTag allowed?
|
||||
@@ -57,6 +67,9 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None,
|
||||
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.
|
||||
|
||||
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
|
||||
@@ -70,13 +83,13 @@ 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 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
|
||||
elif id_tag in CONFIG["denied_cards"]:
|
||||
log.warning("[NO] DENIED idTag=%r (admin-rejected card) via %s", id_tag, context)
|
||||
status = AuthorizationStatus.invalid
|
||||
else:
|
||||
log.warning("[NO] REJECTED unknown idTag=%r via %s", id_tag, context)
|
||||
record_seen(id_tag, context)
|
||||
log.warning("[??] UNKNOWN idTag=%r via %s -> refused, queued for admin approval",
|
||||
id_tag, context)
|
||||
_record_pending(id_tag, cp, connector)
|
||||
status = AuthorizationStatus.invalid
|
||||
AUTH_EVENTS.append(
|
||||
{"time": now(), "id_tag": id_tag, "context": context,
|
||||
@@ -126,7 +139,7 @@ class ChargePoint(OcppChargePoint):
|
||||
|
||||
@on(Action.authorize)
|
||||
async def on_authorize(self, id_tag, **kwargs):
|
||||
status = decide(id_tag, "Authorize (card/app)")
|
||||
status = decide(id_tag, "Authorize (card/app)", cp=self.id)
|
||||
record_event("Authorize", self.id, id_tag=id_tag, result=status.value)
|
||||
return call_result.Authorize(id_tag_info={"status": status})
|
||||
|
||||
@@ -138,12 +151,16 @@ 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")
|
||||
ACTIVE_TX[tx] = {
|
||||
"cp": self.id, "connector": connector_id, "id_tag": id_tag,
|
||||
"who": who, "meter_start": meter_start, "started": now(),
|
||||
"who": who, "method": method,
|
||||
"meter_start": meter_start, "started": now(),
|
||||
}
|
||||
store.start_session(tx, self.id, connector_id, id_tag, who,
|
||||
timestamp, meter_start)
|
||||
timestamp, meter_start, method=method)
|
||||
log.info("Transaction %s STARTED on connector %s by %s (meter_start=%s)",
|
||||
tx, connector_id, who, meter_start)
|
||||
else:
|
||||
|
||||
+3
-26
@@ -1,8 +1,6 @@
|
||||
"""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.
|
||||
"""Durable journal: events.jsonl — everything the charger tells us (and what
|
||||
we told it), one JSON line per event. Append-only, crash-safe, greppable; the
|
||||
raw ground truth behind the queryable store (store.py).
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -13,7 +11,6 @@ from typing import Optional
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
EVENTS_PATH = HERE / "events.jsonl"
|
||||
SEEN_PATH = HERE / "seen_tags.json"
|
||||
|
||||
log = logging.getLogger("journal")
|
||||
|
||||
@@ -39,23 +36,3 @@ def read_events(limit: int = 100, event: Optional[str] = None) -> list:
|
||||
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"))
|
||||
|
||||
+23
-17
@@ -17,13 +17,13 @@ from pathlib import Path
|
||||
|
||||
import uvicorn
|
||||
from fastapi import FastAPI, WebSocket
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
||||
from . import csms, routes
|
||||
from .config import CONFIG
|
||||
|
||||
STATIC = Path(__file__).resolve().parent / "static"
|
||||
# the built React app (frontend/: `npm run build` -> dist/)
|
||||
DIST = Path(__file__).resolve().parent.parent / "frontend" / "dist"
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -37,18 +37,23 @@ app = FastAPI(
|
||||
"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")
|
||||
# SPA serving: exact files from frontend/dist, anything else falls back to
|
||||
# index.html so React Router owns the URL space. Registered after the API
|
||||
# router, so /api/* and /docs keep winning.
|
||||
@app.get("/{full_path:path}", include_in_schema=False)
|
||||
async def spa(full_path: str):
|
||||
if not DIST.exists():
|
||||
return JSONResponse(
|
||||
{"detail": "frontend not built — run `npm run build` in frontend/ "
|
||||
"(or use the Vite dev server, which proxies /api here)"},
|
||||
status_code=503,
|
||||
)
|
||||
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")
|
||||
|
||||
|
||||
# Catch-all WS route so the charger may dial any path (it uses /<ChargerID>).
|
||||
@@ -59,11 +64,12 @@ async def ocpp_websocket(ws: WebSocket, cp_path: str):
|
||||
|
||||
|
||||
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"]),
|
||||
"CSMS ws://0.0.0.0:9000/<id> | API http://0.0.0.0:9000/docs | "
|
||||
"%d authorized id(s) | %d pending card(s) | %d user(s) | %d relay(s) | panel %s",
|
||||
len(CONFIG["authorized"]), len(CONFIG["pending_cards"]),
|
||||
len(CONFIG["users"]), len(CONFIG["relays"]),
|
||||
"ready" if DIST.exists() else "NOT BUILT (frontend/: npm run build)",
|
||||
)
|
||||
if not CONFIG["users"]:
|
||||
log.warning(
|
||||
|
||||
+85
-14
@@ -17,7 +17,7 @@ from pydantic import BaseModel
|
||||
|
||||
from . import csms, relays, store, users
|
||||
from .config import CONFIG, save
|
||||
from .journal import read_events, read_seen
|
||||
from .journal import now, read_events
|
||||
from ocpp.v16 import call
|
||||
|
||||
log = logging.getLogger("api")
|
||||
@@ -110,16 +110,18 @@ async def me(user: dict = Depends(current_user)):
|
||||
# ---- status & journals ----
|
||||
@router.get("/status")
|
||||
async def api_status(user: dict = Depends(current_user)):
|
||||
is_admin = users.allowed(user["scopes"], "admin")
|
||||
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),
|
||||
"recent_auth_events": list(csms.AUTH_EVENTS) if is_admin else [],
|
||||
"relays": _visible_relays(user),
|
||||
"chargers": CONFIG["chargers"], # display labels for the panel
|
||||
# the admin's notification bell: unknown cards awaiting a decision
|
||||
"pending_cards": len(CONFIG["pending_cards"]) if is_admin else 0,
|
||||
}
|
||||
|
||||
|
||||
@@ -238,11 +240,7 @@ class AllowlistEntry(BaseModel):
|
||||
@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(),
|
||||
}
|
||||
return {"authorized": CONFIG["authorized"]}
|
||||
|
||||
|
||||
@router.put("/allowlist/{id_tag}")
|
||||
@@ -267,14 +265,87 @@ async def allowlist_delete(id_tag: str, user: dict = Depends(current_user)):
|
||||
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."""
|
||||
# ---- pending cards: unknown taps awaiting the admin's decision ----
|
||||
class ApproveBody(BaseModel):
|
||||
name: str
|
||||
user: Optional[str] = None # link the card to its owner right here
|
||||
guns: Optional[list[str]] = None
|
||||
kind: str = "card"
|
||||
|
||||
|
||||
@router.get("/cards/pending")
|
||||
async def pending_list(user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
CONFIG["learn_mode"] = learn
|
||||
return CONFIG["pending_cards"]
|
||||
|
||||
|
||||
@router.post("/cards/pending/{id_tag}/approve")
|
||||
async def pending_approve(id_tag: str, body: ApproveBody,
|
||||
user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
if id_tag not in CONFIG["pending_cards"]:
|
||||
raise HTTPException(404, f"{id_tag!r} is not pending")
|
||||
if body.user is not None and body.user not in CONFIG["users"]:
|
||||
raise HTTPException(400, f"cannot link card to unknown user {body.user!r}")
|
||||
CONFIG["pending_cards"].pop(id_tag)
|
||||
CONFIG["authorized"][id_tag] = body.model_dump(exclude_none=True)
|
||||
save()
|
||||
log.warning("mode changed: %s", "LEARN" if learn else "ENFORCE")
|
||||
return {"mode": "learn" if learn else "enforce"}
|
||||
log.info("pending card %r APPROVED by %r as %r (user=%s)",
|
||||
id_tag, user["name"], body.name, body.user)
|
||||
return {"approved": id_tag, "authorized": CONFIG["authorized"]}
|
||||
|
||||
|
||||
@router.post("/cards/pending/{id_tag}/reject")
|
||||
async def pending_reject(id_tag: str, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
meta = CONFIG["pending_cards"].pop(id_tag, None)
|
||||
if meta is None:
|
||||
raise HTTPException(404, f"{id_tag!r} is not pending")
|
||||
CONFIG["denied_cards"][id_tag] = {
|
||||
"rejected_at": now(), "by": user["name"],
|
||||
**{k: meta[k] for k in ("first_seen", "count") if k in meta},
|
||||
}
|
||||
save()
|
||||
log.warning("pending card %r REJECTED by %r", id_tag, user["name"])
|
||||
return {"rejected": id_tag}
|
||||
|
||||
|
||||
@router.get("/cards/denied")
|
||||
async def denied_list(user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
return CONFIG["denied_cards"]
|
||||
|
||||
|
||||
@router.delete("/cards/denied/{id_tag}")
|
||||
async def denied_delete(id_tag: str, user: dict = Depends(current_user)):
|
||||
"""Un-reject: the card pends again on its next tap."""
|
||||
need(user, "admin")
|
||||
if CONFIG["denied_cards"].pop(id_tag, None) is None:
|
||||
raise HTTPException(404, f"{id_tag!r} is not denied")
|
||||
save()
|
||||
return {"undenied": id_tag}
|
||||
|
||||
|
||||
# ---- permission catalog: what CAN be granted (drives the UI matrix) ----
|
||||
@router.get("/permissions")
|
||||
async def permissions_catalog(user: dict = Depends(current_user)):
|
||||
"""Everything a scope could refer to, so the panel renders checkboxes
|
||||
instead of asking admins to type raw scope strings."""
|
||||
need(user, "admin")
|
||||
chargers = {}
|
||||
for cp_id, meta in CONFIG["chargers"].items():
|
||||
chargers[cp_id] = {"label": meta.get("label", cp_id),
|
||||
"guns": dict(meta.get("guns", {}))}
|
||||
# chargers that connected but were never given display labels
|
||||
for (cp_id, conn) in csms.CONNECTORS:
|
||||
if conn > 0:
|
||||
entry = chargers.setdefault(cp_id, {"label": cp_id, "guns": {}})
|
||||
entry["guns"].setdefault(str(conn), f"Gun {conn}")
|
||||
return {
|
||||
"chargers": chargers, # scope per gun: charger:<cp>:<conn>
|
||||
"relays": relays.configured(), # scope per relay: relay:<name>
|
||||
"admin_scope": "admin",
|
||||
}
|
||||
|
||||
|
||||
# ---- user management (admin) ----
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 201 B |
@@ -1,493 +0,0 @@
|
||||
<!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>⚡ 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>⚡ 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>Cards & tags</h2>
|
||||
<div class="scroll"><table>
|
||||
<thead><tr><th>idTag</th><th>Name</th><th>User</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. Card blue)" required>
|
||||
<select id="a-kind" style="width:110px"><option>card</option><option>app</option><option>car</option></select>
|
||||
</div>
|
||||
<div class="row">
|
||||
<select id="a-user"><option value="">No user linked</option></select>
|
||||
<input id="a-guns" placeholder="Guns, e.g. eu092025:2 — empty = all">
|
||||
</div>
|
||||
<div class="row"><button class="small">Save card</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')">⚡ Control</button>
|
||||
<button data-tab="history" onclick="showTab('history')">📊 History</button>
|
||||
<button data-tab="admin" class="hidden" onclick="showTab('admin')">⚙ 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 => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[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…</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>`;
|
||||
const cpCfg = (status.chargers || {})[cp] || {};
|
||||
for (const { conn, st } of conns) {
|
||||
let gunName = (cpCfg.guns || {})[conn] || `Gun ${conn}`;
|
||||
if (cps.length > 1) gunName = `${cpCfg.label || cp} · ${gunName}`;
|
||||
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 || " "}</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, users] = await Promise.all([api("/allowlist"), api("/users")]);
|
||||
$("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.user ? esc(e.user) : '<span class="sub">—</span>'}</td>
|
||||
<td class="sub">${e.guns ? esc(e.guns.join(", ")) : "all"}</td>
|
||||
<td><button class="danger small" onclick="delAllowlist('${esc(tag)}')">✕</button></td>
|
||||
</tr>`).join("");
|
||||
$("a-user").innerHTML = `<option value="">No user linked</option>` +
|
||||
users.map(u => `<option value="${esc(u.name)}">${esc(u.name)}</option>`).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)} (×${s.count})</div>
|
||||
<button class="small secondary" onclick="$('a-tag').value='${esc(tag)}';$('a-name').focus()">Enroll</button></div>`).join("")
|
||||
: "";
|
||||
$("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)}')">✕</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 };
|
||||
if ($("a-user").value) body.user = $("a-user").value;
|
||||
const guns = $("a-guns").value.trim();
|
||||
if (guns) body.guns = guns.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-guns").value = "";
|
||||
$("a-user").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>
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"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" }
|
||||
]
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
// 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", () => {});
|
||||
+11
-5
@@ -43,7 +43,8 @@ CREATE TABLE IF NOT EXISTS sessions (
|
||||
meter_start REAL NOT NULL,
|
||||
meter_stop REAL,
|
||||
wh REAL,
|
||||
reason TEXT
|
||||
reason TEXT,
|
||||
method TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS samples (
|
||||
tx INTEGER NOT NULL,
|
||||
@@ -63,6 +64,10 @@ def _db():
|
||||
con = sqlite3.connect(DB_PATH)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.executescript(_SCHEMA)
|
||||
# migration for dbs created before the audit column 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")
|
||||
return closing(con)
|
||||
|
||||
|
||||
@@ -89,12 +94,13 @@ def max_tx() -> int:
|
||||
|
||||
|
||||
def start_session(tx: int, cp: str, connector: int, id_tag: str, who: str,
|
||||
started: str, meter_start: float) -> None:
|
||||
started: str, meter_start: float, method: str = "unknown") -> 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),
|
||||
"INSERT OR REPLACE INTO sessions"
|
||||
" (tx, cp, connector, id_tag, who, started, meter_start, method)"
|
||||
" VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(tx, cp, connector, id_tag, who, started, meter_start, method),
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user