Skip to content

Architecture

farzad edited this page Oct 7, 2026 · 2 revisions

Architecture

Layout

src/peykan/
  bus.py            python-can helpers (make_bus, read_frames, shutdown_bus)
  dbc.py            DBC loading/decoding
  obd.py            OBD-II requests/responses, PID decoding, DTC encode/decode, reply matching
  diagnostics.py    the DBC's UDS-style protocol (service IDs, read/write classification)
  j1939.py          J1939: 29-bit IDs, PGN/SPN catalog, DM1, Request PGN, BAM transport
  uds.py            UDS over ISO-TP client helpers, DID/DTC/VIN decoding
  logs.py           log loading, analysis, signal series, replay, recording
  safety.py         transmit policy + audit log (TransmitGuard, GuardedBus)
  parsing.py        int/hex ID and payload parsing shared by tools and CLI
  config.py         PEYKAN_* settings + logging (to stderr)
  models.py         internal Frame dataclass
  cli.py            Typer CLI
  data/             vehicle.dbc (sample DBC), sample_drive.asc (sample recording)
  simulator/
    state.py        the driving + cabin model (DrivingState, tick(), CORRELATED_SIGNALS)
    faults.py       fault presets, FaultState, activation protocol
    runner.py       SimThread, OBD/DBC-diagnostic responders, run_simulator()
    j1939_runner.py J1939 broadcasters, Request PGN responder, DM1 (with BAM)
    uds_ecu.py      engine ECU answering UDS and OBD Mode 09 over ISO-TP
    profiles.py     which DBC messages are sent and how often
  server/
    mcp_server.py   MCP tools, routes, build_http_app(), main()
    prompts.py      server instructions + MCP prompts
    schemas.py      Pydantic result models
    live_state.py   background bus listener: frame history + signal snapshot
    templates/dashboard.html

Protocol modules (obd, j1939, uds, logs, diagnostics) know nothing about MCP or the CLI; the server and CLI are thin layers over them.

Everything talks over a CAN bus

The simulator, server and CLI share no Python state: they communicate only by sending and receiving CAN frames (the virtual bus by default, or a real adapter). Fault activation is a control frame; OBD, UDS and J1939 requests are real requests.

The consequence: python-can's virtual bus only exists inside one Python process. Anything that needs to see the simulator's traffic must run in the same process, which is why peykan demo (and the Docker image) run simulator and server together. See Troubleshooting.

One bus instance per listener

A python-can Bus instance hands each received frame to one recv() call. Two threads reading the same instance silently split the traffic between them; this was a real shipped bug. Rule: every listener thread gets its own make_bus() instance (see run_simulator()); sharing an instance only for sending is fine.

The simulated vehicle

simulator/state.py holds one DrivingState, advanced every 200 ms by a pure tick() function:

  • Driving: throttle wanders, RPM and speed follow it with first-order lag, the engine warms toward 85 °C, fuel slowly drops, the battery charges to about 14.2 V while running.
  • Cabin and environment: ambient light drifts (headlights follow it, and rain); rain comes and goes (wipers follow it and speed); cabin temperature settles to a 21.5 °C setpoint; doors auto-lock above 15 km/h; whether a passenger is aboard is chosen once per run.

CORRELATED_SIGNALS maps every DBC signal to a function of that state, and a test fails if a broadcast signal is left out. Unmodelled signals used to be random per frame, which made a car at 60 km/h report crashes and open doors.

From that state:

  • SimThread (one per DBC message, profiles.py) encodes ENGINE_STATUS 50 ms, ABS_STATUS 100 ms, AIRBAG_STATUS 200 ms, BODY_STATUS 500 ms. Per signal: fault override first, then the state function. Values are clamped to what the signal's bit width can encode, because a declared DBC range isn't always reachable (ENGINE_TEMP declares 127.5 but 8 bits at scale 0.5 / offset -40 stop at 87.5).
  • OBDResponderThread answers Mode 01/03/09 from the same state.
  • UdsEcuThread answers UDS and the VIN over ISO-TP, with live DIDs from the state.
  • The J1939 threads broadcast PGNs from the same state.

Fault presets apply their state_effect to a copy of the state before any of these read it, so a fault is consistent across all protocols.

Server

  • live_state.py::LiveState: one background listener per server process, keeping a time-windowed frame history (frames_since()) and the last value of every DBC and J1939 signal (snapshot()). Passive tools and the dashboard read from it, so they return immediately and never lose frames between calls.
  • mcp_server.py::create_app() builds an MCPServer (mcp 2.x SDK) with the instructions and prompts from prompts.py, registers the tools, the DBC resource and the HTTP routes, and creates one TransmitGuard.
  • build_http_app() returns the ASGI app for the SSE or streamable-HTTP transport with CORS and, on loopback, DNS-rebinding protection; main() serves it with uvicorn, or runs stdio.
  • MCP 2.x runs sync tools on worker threads, so blocking bus waits don't stall the event loop.

Two kinds of tools

  • Passive (read_can_frames, filter_frames, monitor_signal, get_vehicle_snapshot, read_j1939_dtcs): read LiveState, never open a bus.
  • Request/response (OBD, UDS, J1939 request, DBC diagnostics, faults, replay): open a short-lived bus, wrap it with guard.wrap(bus, purpose, write=...), send, wait for the matching reply, and shut the raw bus down in finally. Timeouts are capped by PEYKAN_MAX_DURATION_S.

Safety layer

safety.py::TransmitGuard decides per frame: is transmitting allowed on this interface, is this a write service, is the ID allowlisted. It records every attempt. GuardedBus is a real can.BusABC subclass (can-isotp refuses anything else), whose send goes through the guard, so frames sent by libraries (ISO-TP flow control) are covered too. See Real Hardware and Safety.

Logs

logs.py loads a file through python-can's LogReader (cached by path, size and mtime), sorts by time, and analyses it in one pass: per-ID timing, per-(signal, message) statistics, OBD Mode 03 codes and DM1 codes through a TransportReassembler. LogReplayer replays with original spacing; record_bus writes with can.Logger. See Recorded CAN Logs.

Clone this wiki locally