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.
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
"""Minimal OCPP 1.6J central system for discovering/testing a charge point.
|
||||
|
||||
Accepts any charge point ID on ws://0.0.0.0:9000/<id>, answers the standard
|
||||
message set with "Accepted", and logs every raw frame in both directions.
|
||||
|
||||
Run: .venv/bin/python csms.py
|
||||
Then point the charger's OCPP backend URL at ws://<host-ip>:9000/
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import websockets
|
||||
|
||||
from ocpp.routing import on
|
||||
from ocpp.v16 import ChargePoint as OcppChargePoint
|
||||
from ocpp.v16 import call_result
|
||||
from ocpp.v16.enums import (
|
||||
Action,
|
||||
AuthorizationStatus,
|
||||
DataTransferStatus,
|
||||
RegistrationStatus,
|
||||
)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s | %(message)s",
|
||||
)
|
||||
log = logging.getLogger("csms")
|
||||
|
||||
|
||||
def now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
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):
|
||||
log.info(
|
||||
"StatusNotification: connector=%s status=%s error=%s extra=%r",
|
||||
connector_id, status, error_code, kwargs,
|
||||
)
|
||||
return call_result.StatusNotification()
|
||||
|
||||
@on(Action.authorize)
|
||||
async def on_authorize(self, id_tag, **kwargs):
|
||||
log.info("Authorize: id_tag=%r", id_tag)
|
||||
return call_result.Authorize(id_tag_info={"status": AuthorizationStatus.accepted})
|
||||
|
||||
@on(Action.start_transaction)
|
||||
async def on_start_transaction(self, connector_id, id_tag, meter_start, timestamp, **kwargs):
|
||||
log.info(
|
||||
"StartTransaction: connector=%s id_tag=%r meter_start=%s",
|
||||
connector_id, id_tag, meter_start,
|
||||
)
|
||||
return call_result.StartTransaction(
|
||||
transaction_id=1,
|
||||
id_tag_info={"status": AuthorizationStatus.accepted},
|
||||
)
|
||||
|
||||
@on(Action.stop_transaction)
|
||||
async def on_stop_transaction(self, meter_stop, timestamp, transaction_id, **kwargs):
|
||||
log.info(
|
||||
"StopTransaction: tx=%s meter_stop=%s extra=%r",
|
||||
transaction_id, meter_stop, kwargs,
|
||||
)
|
||||
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()
|
||||
|
||||
|
||||
async def on_connect(connection):
|
||||
path = connection.request.path
|
||||
charge_point_id = path.strip("/").split("/")[-1] or "unknown"
|
||||
log.info(
|
||||
"Connection from %s | path=%r -> charge_point_id=%r | subprotocol=%r",
|
||||
connection.remote_address, path, charge_point_id, connection.subprotocol,
|
||||
)
|
||||
if connection.subprotocol is None:
|
||||
log.warning(
|
||||
"Charge point %r connected WITHOUT an ocpp subprotocol header. "
|
||||
"Handling it anyway so we can see its traffic.",
|
||||
charge_point_id,
|
||||
)
|
||||
cp = ChargePoint(charge_point_id, connection)
|
||||
try:
|
||||
await cp.start()
|
||||
except websockets.exceptions.ConnectionClosed:
|
||||
log.info("Charge point %r disconnected", charge_point_id)
|
||||
|
||||
|
||||
async def process_request(connection, request):
|
||||
"""Log every inbound HTTP/WS request line so we see even failed attempts."""
|
||||
log.info(
|
||||
"HTTP request from %s: %s %s | headers=%s",
|
||||
connection.remote_address,
|
||||
request.method if hasattr(request, "method") else "?",
|
||||
request.path,
|
||||
dict(request.headers),
|
||||
)
|
||||
return None # let the handshake proceed normally
|
||||
|
||||
|
||||
async def main():
|
||||
# select_subprotocol tolerates clients that omit the ocpp1.6 header
|
||||
# (some cheap firmwares do), so we still see their traffic instead of a 400.
|
||||
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,
|
||||
process_request=process_request,
|
||||
)
|
||||
log.info("OCPP 1.6J CSMS listening on ws://0.0.0.0:9000/<charge_point_id>")
|
||||
await server.wait_closed()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Dumb TCP listener on :9000 — logs the raw first bytes of anything that
|
||||
connects, then closes. Use to see whether the charger reaches us at all and
|
||||
what it actually sends (valid WS handshake? garbage? YKC binary?).
|
||||
|
||||
Run: .venv/bin/python rawlisten.py (stop csms.py first — same port)
|
||||
"""
|
||||
import functools
|
||||
import socket
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
# force line-buffered output so logs appear immediately even when piped to a file
|
||||
print = functools.partial(print, flush=True) # noqa: A001
|
||||
sys.stdout.reconfigure(line_buffering=True)
|
||||
|
||||
HOST, PORT = "0.0.0.0", 9000
|
||||
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
s.bind((HOST, PORT))
|
||||
s.listen(5)
|
||||
print(f"raw TCP listener on {HOST}:{PORT} — waiting for any connection...")
|
||||
|
||||
while True:
|
||||
conn, addr = s.accept()
|
||||
ts = datetime.now().isoformat(timespec="seconds")
|
||||
print(f"\n[{ts}] CONNECTION from {addr[0]}:{addr[1]}")
|
||||
conn.settimeout(3.0)
|
||||
try:
|
||||
data = conn.recv(4096)
|
||||
if data:
|
||||
print(f" {len(data)} bytes, first line / hex:")
|
||||
# printable view
|
||||
try:
|
||||
text = data.decode("utf-8", errors="replace")
|
||||
for line in text.splitlines()[:20]:
|
||||
print(f" | {line}")
|
||||
except Exception:
|
||||
pass
|
||||
print(f" hex[:64]: {data[:64].hex(' ')}")
|
||||
else:
|
||||
print(" connected but sent no data (then closed)")
|
||||
except socket.timeout:
|
||||
print(" connected but sent nothing within 3s")
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,8 @@
|
||||
attrs==26.1.0
|
||||
jsonschema==4.26.0
|
||||
jsonschema-specifications==2025.9.1
|
||||
ocpp==2.1.0
|
||||
pypdf==6.14.2
|
||||
referencing==0.37.0
|
||||
rpds-py==2026.6.3
|
||||
websockets==16.0
|
||||
@@ -0,0 +1,251 @@
|
||||
"""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())
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"learn_mode": true,
|
||||
"authorized": {}
|
||||
}
|
||||
Reference in New Issue
Block a user