Files
julian 5c88e8fa3c feat(discovering): single-process CSMS on :9000 with discovery API + live session captures
station.py is now one FastAPI/uvicorn process owning port 9000: the OCPP 1.6J
WebSocket (catch-all path) plus an HTTP control API (status, events, tags,
probe, remote start/stop, trigger, unlock, setconfig). Adds the events.jsonl
journal and auto-interrogation on connect.

Includes the captures from the 2026-07-09 live test session: full
GetConfiguration dump of eu092025, real charging transactions on both guns
(RFID + remote start/stop), and the negative Autocharge/MacEnabled results.
Cards A/B + app-remote enrolled in station_config.json.
2026-07-11 18:57:55 +02:00

474 lines
18 KiB
Python

"""Private OCPP 1.6J controller for a home EV charger.
Beyond the minimal csms.py, this adds:
* An allowlist of authorized idTags (RFID cards, autocharge/vehicle IDs, app tokens).
* A "learn mode" that accepts + records any unseen idTag, so you can discover what
your cards send and whether your car presents an autocharge id on plug-in.
* Live state tracking + a registry of connected chargers, so a control app (added
next) can trigger RemoteStartTransaction / RemoteStopTransaction.
Config lives in station_config.json next to this file:
{
"learn_mode": true,
"authorized": { "<idTag>": {"name": "Home card", "kind": "card|car|app"} }
}
Workflow:
1. Run in learn_mode (default). Tap each card / plug in each car once.
2. Read the captured ids from the log or seen_tags.json.
3. Move the ones you want into "authorized" in station_config.json, name them.
4. Set "learn_mode": false and restart -> only your ids are accepted.
Discovery API (same port 9000 the charger dials — http://<host>:9000, docs at /docs):
GET /status connected chargers, guns, transactions, auth events
GET /events?limit=100&event=X tail the permanent event journal (events.jsonl)
GET /tags seen + authorized idTags
POST /probe GetConfiguration + trigger StatusNotification,
saved to discovery_<id>.json (also auto-runs on connect)
POST /start?id_tag=X&connector=1 RemoteStartTransaction
POST /stop/{tx} or POST /stop RemoteStopTransaction (no tx = the only active one)
POST /trigger/{status|meter|heartbeat|boot}?connector=N
POST /unlock/{connector} UnlockConnector
POST /setconfig?key=K&value=V ChangeConfiguration (e.g. MeterValueSampleInterval)
Run: venv/Scripts/python station.py
"""
import asyncio
import json
import logging
from collections import deque
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
import uvicorn
from fastapi import FastAPI, HTTPException, 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,
)
HERE = Path(__file__).resolve().parent
CONFIG_PATH = HERE / "station_config.json"
SEEN_PATH = HERE / "seen_tags.json"
EVENTS_PATH = HERE / "events.jsonl"
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s | %(message)s",
)
log = logging.getLogger("station")
def now() -> str:
return datetime.now(timezone.utc).isoformat()
# ---- shared runtime state (the control app added next reads/uses these) ----
CONNECTED: dict = {} # cp_id -> ChargePoint instance (for remote control)
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 app UI)
_tx_counter = {"n": 0}
def load_config() -> dict:
if CONFIG_PATH.exists():
cfg = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
else:
cfg = {"learn_mode": True, "authorized": {}}
CONFIG_PATH.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
log.info("Created default %s (learn_mode=on, empty allowlist)", CONFIG_PATH.name)
cfg.setdefault("learn_mode", True)
cfg.setdefault("authorized", {})
return cfg
CONFIG = load_config()
def record_event(event: str, cp_id: str, **data) -> None:
"""Append one JSON line to events.jsonl — the permanent journal of everything
the charger tells us (and what we told it). Survives restarts; grep/ingest later."""
entry = {"time": now(), "event": event, "cp": cp_id, **data}
try:
with EVENTS_PATH.open("a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n")
except Exception:
log.exception("failed to journal event %r", event)
def record_seen(id_tag: str, context: str) -> None:
"""Append/refresh an entry in seen_tags.json so you can harvest ids later."""
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 decide(id_tag: str, context: str) -> AuthorizationStatus:
"""The one gate every auth method flows through: is this idTag allowed?"""
known = id_tag in CONFIG["authorized"]
if known:
name = CONFIG["authorized"][id_tag].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. "
"Add it to 'authorized' in %s, then set learn_mode=false to enforce.",
id_tag, context, CONFIG_PATH.name,
)
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,
"result": status.value, "known": known}
)
return status
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):
# RFID card tap, or app pre-auth. Plug-in autocharge sometimes lands here too.
status = decide(id_tag, "Authorize (card/app/autocharge)")
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})")
if status == AuthorizationStatus.accepted:
_tx_counter["n"] += 1
tx = _tx_counter["n"]
ACTIVE_TX[tx] = {
"cp": self.id, "connector": connector_id, "id_tag": id_tag,
"meter_start": meter_start, "started": now(),
}
log.info("Transaction %s STARTED on connector %s (meter_start=%s)",
tx, connector_id, 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 "?"
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)
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):
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()
# ---- helpers the control app (added next) will call to drive the charger ----
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:
info = ACTIVE_TX.get(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
# ---- discovery: interrogate the charger about what it is and what it supports ----
async def interrogate(cp: ChargePoint) -> dict:
"""GetConfiguration + trigger a StatusNotification per gun; save to discovery_<id>.json.
GetConfiguration with no keys asks for *everything* the charger exposes:
NumberOfConnectors, SupportedFeatureProfiles, meter settings, local-auth
support, ... A rejected/timed-out probe is itself a finding — record it.
"""
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")
log.info(
"Discovery report -> %s (%d config keys, guns seen: %s)",
path.name, len(report.get("configuration") or []),
list(report["connectors_seen"]) or "none yet",
)
return report
async def _auto_interrogate(cp: ChargePoint):
await asyncio.sleep(5) # let BootNotification land first
try:
await interrogate(cp)
except Exception:
log.exception("auto-interrogation of %r failed", cp.id)
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)
# ---- discovery HTTP API (curl / browser / phone over NetBird) ----
api = FastAPI(
title="Charger Discovery API",
description="Poke the charger over its live OCPP socket. Interactive docs: /docs",
)
TRIGGERABLE = {
"status": MessageTrigger.status_notification,
"meter": MessageTrigger.meter_values,
"heartbeat": MessageTrigger.heartbeat,
"boot": MessageTrigger.boot_notification,
}
@api.websocket("/{cp_path:path}")
async def ocpp_websocket(ws: WebSocket, cp_path: str):
"""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()
]
if not offered:
log.warning(
"Charger %r connected WITHOUT an ocpp subprotocol header. "
"Handling it anyway so we can see its traffic.", cp_id,
)
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
asyncio.create_task(_auto_interrogate(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:
if cp_id is not None:
cp = CONNECTED.get(cp_id)
if cp is None:
raise HTTPException(404, f"charge point {cp_id!r} is not connected")
return cp
if len(CONNECTED) == 1:
return next(iter(CONNECTED.values()))
raise HTTPException(409, f"specify ?cp=<id>; currently connected: {list(CONNECTED)}")
async def _ocpp(coro):
"""Run an OCPP call for an HTTP handler, mapping failures to HTTP errors."""
try:
return await coro
except HTTPException:
raise
except Exception as exc:
raise HTTPException(502, f"OCPP call failed: {exc!r}")
@api.get("/status")
async def api_status():
return {
"mode": "learn" if CONFIG.get("learn_mode") else "enforce",
"connected": {cp_id: getattr(cp, "boot_info", None) for cp_id, cp in CONNECTED.items()},
"connectors": {f"{cp_id}/{conn}": s for (cp_id, conn), s in CONNECTORS.items()},
"active_transactions": ACTIVE_TX,
"recent_auth_events": list(AUTH_EVENTS),
}
@api.get("/events")
async def api_events(limit: int = 100, event: Optional[str] = None):
"""Tail the event journal; filter with ?event=MeterValues etc."""
if not EVENTS_PATH.exists():
return []
lines = EVENTS_PATH.read_text(encoding="utf-8").splitlines()
entries = [json.loads(line) for line in lines if line.strip()]
if event is not None:
entries = [e for e in entries if e.get("event") == event]
return entries[-limit:]
@api.get("/tags")
async def api_tags():
seen = json.loads(SEEN_PATH.read_text(encoding="utf-8")) if SEEN_PATH.exists() else {}
return {"authorized": CONFIG["authorized"], "seen": seen}
@api.post("/probe")
async def api_probe(cp: Optional[str] = None):
return await _ocpp(interrogate(_pick_cp(cp)))
@api.post("/start")
async def api_start(id_tag: str = "app-remote", connector: int = 1, cp: Optional[str] = None):
status = await _ocpp(remote_start(_pick_cp(cp).id, id_tag, connector))
return {"remote_start": status}
@api.post("/stop")
@api.post("/stop/{tx}")
async def api_stop(tx: Optional[int] = None):
if tx is None:
if len(ACTIVE_TX) != 1:
raise HTTPException(409, f"specify /stop/<tx>; active: {list(ACTIVE_TX)}")
tx = next(iter(ACTIVE_TX))
status = await _ocpp(remote_stop(tx))
return {"remote_stop": status, "transaction": tx}
@api.post("/trigger/{what}")
async def api_trigger(what: str, connector: Optional[int] = None, cp: Optional[str] = None):
if what not in TRIGGERABLE:
raise HTTPException(400, f"unknown trigger {what!r}; options: {list(TRIGGERABLE)}")
payload = call.TriggerMessage(requested_message=TRIGGERABLE[what], connector_id=connector)
resp = await _ocpp(_pick_cp(cp).call(payload))
return {"trigger": what, "status": resp.status}
@api.post("/unlock/{connector}")
async def api_unlock(connector: int, cp: Optional[str] = None):
resp = await _ocpp(_pick_cp(cp).call(call.UnlockConnector(connector_id=connector)))
return {"unlock": connector, "status": resp.status}
@api.post("/setconfig")
async def api_setconfig(key: str, value: str, cp: Optional[str] = None):
resp = await _ocpp(_pick_cp(cp).call(call.ChangeConfiguration(key=key, value=value)))
return {"key": key, "value": value, "status": resp.status}
async def main():
mode = "LEARN (accepting & recording new ids)" if CONFIG["learn_mode"] else "ENFORCING allowlist"
log.info(
"Private CSMS on ws://0.0.0.0:9000/<id> | discovery API http://0.0.0.0:9000/docs"
" | mode: %s | %d authorized id(s)",
mode, len(CONFIG["authorized"]),
)
await uvicorn.Server(
uvicorn.Config(api, host="0.0.0.0", port=9000, log_config=None)
).serve()
if __name__ == "__main__":
asyncio.run(main())