Files
charging_station/backend/csms.py
T
julian a9b8436f2c refactor(backend): user app idTags validated against the user record, not the allowlist
'app token of <name>' synthetic allowlist entries are gone: decide()
recognizes a user's personal idTag directly, enforces the user's own
charger:<cp>:<gun> scopes at the charger-side gate, and attributes the
session (who=user, method=app). charger_start no longer auto-enrolls;
PUT /api/allowlist/<user-tag> returns 400; stale entries auto-drop at
startup. Zero-user open mode still authorizes 'app-remote' for
bootstrap. Smoke: 63 checks.
2026-07-12 09:50:27 +02:00

383 lines
17 KiB
Python

"""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 fnmatch import fnmatch
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, users
from .config import CONFIG, HERE, save
from .journal import now, record_event
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 _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?
An allowlist entry may carry "guns": ["eu092025:2"] to restrict a card to
specific guns of specific chargers (fnmatch patterns, so "eu092025:*"
works). 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.
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"]):
log.warning("[NO] REJECTED idTag=%r (%s) not allowed on %s (allowed: %s)",
id_tag, entry.get("name", "?"), gun, entry["guns"])
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 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
else:
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,
"connector": connector, "result": status.value, "known": known}
)
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."""
entry = CONFIG["authorized"].get(id_tag)
if entry:
if entry.get("user"):
return entry["user"]
if 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)", cp=self.id)
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, cp=self.id)
if status == AuthorizationStatus.accepted:
_tx_counter["n"] += 1
tx = _tx_counter["n"]
who = resolve_who(id_tag)
# 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,
"meter_start": meter_start, "started": now(),
}
store.start_session(tx, self.id, connector_id, id_tag, who,
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:
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, 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):
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
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()),
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()
@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)}")