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.
This commit is contained in:
+241
-19
@@ -19,6 +19,18 @@ Workflow:
|
||||
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
|
||||
"""
|
||||
|
||||
@@ -28,8 +40,10 @@ import logging
|
||||
from collections import deque
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import websockets
|
||||
import uvicorn
|
||||
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
|
||||
|
||||
from ocpp.routing import on
|
||||
from ocpp.v16 import ChargePoint as OcppChargePoint
|
||||
@@ -38,12 +52,14 @@ 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,
|
||||
@@ -79,6 +95,17 @@ def load_config() -> dict:
|
||||
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:
|
||||
@@ -123,6 +150,8 @@ def decide(id_tag: str, context: str) -> AuthorizationStatus:
|
||||
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(
|
||||
@@ -136,6 +165,8 @@ class ChargePoint(OcppChargePoint):
|
||||
@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()
|
||||
@@ -144,6 +175,7 @@ class ChargePoint(OcppChargePoint):
|
||||
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)
|
||||
@@ -160,6 +192,8 @@ class ChargePoint(OcppChargePoint):
|
||||
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}
|
||||
)
|
||||
@@ -168,6 +202,8 @@ class ChargePoint(OcppChargePoint):
|
||||
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(
|
||||
@@ -176,6 +212,8 @@ class ChargePoint(OcppChargePoint):
|
||||
|
||||
@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()
|
||||
|
||||
@@ -217,34 +255,218 @@ async def remote_stop(transaction_id: int) -> str:
|
||||
return resp.status
|
||||
|
||||
|
||||
async def on_connect(connection):
|
||||
path = connection.request.path
|
||||
cp_id = path.strip("/").split("/")[-1] or "unknown"
|
||||
log.info("Charger connected: id=%r from %s subprotocol=%r",
|
||||
cp_id, connection.remote_address, connection.subprotocol)
|
||||
cp = ChargePoint(cp_id, connection)
|
||||
# ---- 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 websockets.exceptions.ConnectionClosed:
|
||||
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():
|
||||
def select_subprotocol(connection, subprotocols):
|
||||
return "ocpp1.6"
|
||||
|
||||
server = await websockets.serve(
|
||||
on_connect, "0.0.0.0", 9000,
|
||||
subprotocols=["ocpp1.6"],
|
||||
select_subprotocol=select_subprotocol,
|
||||
)
|
||||
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> | mode: %s | %d authorized id(s)",
|
||||
mode, len(CONFIG["authorized"]))
|
||||
await server.wait_closed()
|
||||
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__":
|
||||
|
||||
Reference in New Issue
Block a user