Files
charging_station/discovering/station.py
T
julian 2e5960fae3 feat: bootstrap wiki for Anfu home EV charger OCPP integration project
- Created initial wiki structure with CLAUDE.md schema, index.md, and log.md.
- Ingested findings and requirements document into the wiki.
- Added concepts for authorization methods, network topology, OCPP protocol, and troubleshooting.
- Documented entities including the Anfu charger, JC-6620 controller, and CSMS toolkit.
- Established configuration files for Obsidian app settings and workspace layout.
- Implemented core plugins and appearance settings for the wiki.
2026-07-09 15:29:26 +02:00

252 lines
9.6 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.
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
import websockets
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,
RegistrationStatus,
)
HERE = Path(__file__).resolve().parent
CONFIG_PATH = HERE / "station_config.json"
SEEN_PATH = HERE / "seen_tags.json"
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_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):
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
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)")
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
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 "?"
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):
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
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)
CONNECTED[cp_id] = cp
try:
await cp.start()
except websockets.exceptions.ConnectionClosed:
log.info("Charger %r disconnected", cp_id)
finally:
CONNECTED.pop(cp_id, None)
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()
if __name__ == "__main__":
asyncio.run(main())