Files
charging_station/backend/csms.py
T
julian 70c2fe1210 feat(backend): link cards to users; charger-qualified gun restrictions; config-driven gun labels
- Allowlist entries take "user": <username> — sessions started with that
  card attribute to the person, and the owner sees their card's history
  even without gun-wide permissions (ownership looked up live)
- "guns": ["eu092025:2"] (fnmatch) replaces the charger-blind
  "connectors": [2] restriction — safe with multiple chargers
- New "chargers" config section provides per-charger/per-gun display
  names; the panel no longer hardcodes the Anfu gun labels
- Panel admin tab: owner dropdown + guns field on card entries
- Smoke test: 42 checks, incl. retroactive history visibility after
  linking a card and rejection of links to unknown users
2026-07-11 20:03:36 +02:00

322 lines
14 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
from .config import CONFIG, HERE
from .journal import now, record_event, record_seen
log = logging.getLogger("csms")
# ---- shared runtime state (the REST routes read/drive these) ----
CONNECTED: dict = {} # cp_id -> ChargePoint instance
CONNECTORS: dict = {} # (cp_id, connector_id) -> latest status string
ACTIVE_TX: dict = {} # transaction_id -> {cp, connector, id_tag, meter_start, started}
AUTH_EVENTS = deque(maxlen=50) # recent authorization attempts (for the panel UI)
_tx_counter = {"n": store.max_tx()} # tx ids continue across restarts
TRIGGERABLE = {
"status": MessageTrigger.status_notification,
"meter": MessageTrigger.meter_values,
"heartbeat": MessageTrigger.heartbeat,
"boot": MessageTrigger.boot_notification,
}
def decide(id_tag: str, context: str, connector: Optional[int] = None,
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.
"""
entry = CONFIG["authorized"].get(id_tag)
known = entry is not None
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 CONFIG.get("learn_mode"):
log.warning("[LEARN] NEW idTag=%r via %s -> accepting & recording.", id_tag, context)
record_seen(id_tag, context)
status = AuthorizationStatus.accepted
else:
log.warning("[NO] REJECTED unknown idTag=%r via %s", id_tag, context)
record_seen(id_tag, context)
status = AuthorizationStatus.invalid
AUTH_EVENTS.append(
{"time": now(), "id_tag": id_tag, "context": context,
"connector": connector, "result": status.value, "known": known}
)
return status
def resolve_who(id_tag: str) -> str:
"""Human label for a session: 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)")
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)
ACTIVE_TX[tx] = {
"cp": self.id, "connector": connector_id, "id_tag": id_tag,
"who": who, "meter_start": meter_start, "started": now(),
}
store.start_session(tx, self.id, connector_id, id_tag, who,
timestamp, meter_start)
log.info("Transaction %s STARTED on connector %s by %s (meter_start=%s)",
tx, connector_id, who, meter_start)
else:
tx = 0 # 0 tells the charger the transaction is not authorized
record_event("StartTransaction", self.id, connector=connector_id,
id_tag=id_tag, meter_start=meter_start, result=status.value, tx=tx)
return call_result.StartTransaction(
transaction_id=tx, id_tag_info={"status": status}
)
@on(Action.stop_transaction)
async def on_stop_transaction(self, meter_stop, timestamp, transaction_id, **kwargs):
info = ACTIVE_TX.pop(transaction_id, None)
used = (meter_stop - info["meter_start"]) if info else "?"
store.end_session(transaction_id, timestamp, meter_stop,
reason=kwargs.get("reason"))
record_event("StopTransaction", self.id, tx=transaction_id,
meter_stop=meter_stop, delivered_wh=used, **kwargs)
log.info("Transaction %s STOPPED (meter_stop=%s, delivered=%s Wh)",
transaction_id, meter_stop, used)
return call_result.StopTransaction(
id_tag_info={"status": AuthorizationStatus.accepted}
)
@on(Action.meter_values)
async def on_meter_values(self, connector_id, meter_value, **kwargs):
record_event("MeterValues", self.id, connector=connector_id,
values=meter_value, **kwargs)
tx = kwargs.get("transaction_id")
if tx is not None:
for entry in meter_value or []:
reading = {}
for sv in entry.get("sampled_value") or []:
# measurand defaults to the energy register when omitted
measurand = sv.get("measurand", "Energy.Active.Import.Register")
try:
value = float(sv.get("value"))
except (TypeError, ValueError):
continue
if measurand == "Energy.Active.Import.Register":
# some firmwares report kWh; normalize to Wh
reading["energy_wh"] = value * 1000 if sv.get("unit") == "kWh" else value
elif measurand == "Power.Active.Import":
reading["power_w"] = value * 1000 if sv.get("unit") == "kW" else value
elif measurand == "SoC":
reading["soc"] = value
if reading:
store.add_sample(tx, entry.get("timestamp", now()),
reading.get("energy_wh"), reading.get("power_w"),
reading.get("soc"))
log.info("MeterValues: connector=%s values=%r", connector_id, meter_value)
return call_result.MeterValues()
@on(Action.data_transfer)
async def on_data_transfer(self, vendor_id, **kwargs):
# Journaled because a vendor DataTransfer frame is the long-shot lead
# for the charger ever surfacing the vehicle VIN (wiki: authorization).
record_event("DataTransfer", self.id, vendor_id=vendor_id, **kwargs)
log.info("DataTransfer: vendor_id=%r extra=%r", vendor_id, kwargs)
return call_result.DataTransfer(status=DataTransferStatus.accepted)
@on(Action.firmware_status_notification)
async def on_firmware_status(self, status, **kwargs):
log.info("FirmwareStatusNotification: %s", status)
return call_result.FirmwareStatusNotification()
@on(Action.diagnostics_status_notification)
async def on_diagnostics_status(self, status, **kwargs):
log.info("DiagnosticsStatusNotification: %s", status)
return call_result.DiagnosticsStatusNotification()
# ---- outbound OCPP commands (called by the REST routes) ----
async def remote_start(cp_id: str, id_tag: str, connector_id: int = 1) -> str:
cp = CONNECTED.get(cp_id)
if cp is None:
raise RuntimeError(f"charge point {cp_id!r} is not connected")
resp = await cp.call(call.RemoteStartTransaction(id_tag=id_tag, connector_id=connector_id))
log.info("RemoteStartTransaction(%s, connector=%s) -> %s", id_tag, connector_id, resp.status)
return resp.status
async def remote_stop(transaction_id: int) -> str:
# fall back to the store so sessions still running after a backend restart
# (charger keeps them alive) remain stoppable
info = ACTIVE_TX.get(transaction_id) or store.open_session(transaction_id)
if info is None:
raise RuntimeError(f"no active transaction {transaction_id}")
cp = CONNECTED.get(info["cp"])
if cp is None:
raise RuntimeError("charge point is not connected")
resp = await cp.call(call.RemoteStopTransaction(transaction_id=transaction_id))
log.info("RemoteStopTransaction(%s) -> %s", transaction_id, resp.status)
return resp.status
async def interrogate(cp: ChargePoint) -> dict:
"""GetConfiguration + trigger a StatusNotification; save to discovery_<id>.json."""
report = {
"charge_point": cp.id,
"probed_at": now(),
"boot_info": getattr(cp, "boot_info", None),
}
try:
resp = await cp.call(call.GetConfiguration())
report["configuration"] = resp.configuration_key
report["unknown_keys"] = resp.unknown_key
except Exception as exc:
report["configuration_error"] = repr(exc)
try:
resp = await cp.call(
call.TriggerMessage(requested_message=MessageTrigger.status_notification)
)
report["trigger_status_notification"] = resp.status
await asyncio.sleep(2) # give the triggered StatusNotifications time to arrive
except Exception as exc:
report["trigger_error"] = repr(exc)
report["connectors_seen"] = {
str(conn): status for (cp_id, conn), status in CONNECTORS.items() if cp_id == cp.id
}
path = HERE / f"discovery_{cp.id}.json"
path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
return report
class _WSAdapter:
"""Bridge a Starlette WebSocket to the recv()/send() interface the ocpp lib expects."""
def __init__(self, ws: WebSocket):
self._ws = ws
async def recv(self) -> str:
return await self._ws.receive_text()
async def send(self, message: str) -> None:
await self._ws.send_text(message)
async def close(self, code: int = 1000, reason: str = "") -> None:
await self._ws.close(code=code)
async def ocpp_socket(ws: WebSocket, cp_path: str) -> None:
"""The OCPP endpoint the JC-6620 dials: ws://<host>:9000/<ChargerID>."""
cp_id = cp_path.strip("/").split("/")[-1] or "unknown"
offered = [
p.strip()
for p in ws.headers.get("sec-websocket-protocol", "").split(",")
if p.strip()
]
await ws.accept(subprotocol="ocpp1.6" if "ocpp1.6" in offered else None)
log.info("Charger connected: id=%r from %s subprotocols=%r", cp_id, ws.client, offered)
record_event("connected", cp_id, client=str(ws.client), subprotocols=offered)
cp = ChargePoint(cp_id, _WSAdapter(ws))
CONNECTED[cp_id] = cp
try:
await cp.start()
except WebSocketDisconnect:
log.info("Charger %r disconnected", cp_id)
finally:
record_event("disconnected", cp_id)
CONNECTED.pop(cp_id, None)
for key in [k for k in CONNECTORS if k[0] == cp_id]:
CONNECTORS.pop(key, None)
def pick_cp(cp_id: Optional[str]) -> ChargePoint:
"""Resolve which charger a REST call targets; auto-select when only one is connected."""
if cp_id is not None:
cp = CONNECTED.get(cp_id)
if cp is None:
raise KeyError(f"charge point {cp_id!r} is not connected")
return cp
if len(CONNECTED) == 1:
return next(iter(CONNECTED.values()))
raise KeyError(f"specify ?cp=<id>; currently connected: {list(CONNECTED)}")