Skip to main content

ControlForge CAN Bus: SocketCAN, CAN FD, J1939, OBD-II, and DBC

James M. Belcher Founder, JMB Technical Services LLC April 2026 | ControlForge v1.0.606


ControlForge speaks CAN bus natively on Linux. Open a SocketCAN interface from ST, send and receive classic CAN or CAN FD frames, decode J1939 heavy-duty data and OBD-II passenger-car PIDs with one-line function calls, and load manufacturer DBC files to auto-decode proprietary frames. No external daemons, no Python bridge, no bridge board — a raw AF_CAN socket in pure Go talking directly to the kernel CAN stack.

1. Why SocketCAN​

ControlForge already had a CAN path: the Teensy CAN bridge (TEENSY_CAN_*), which tunnels FlexCAN frames over USB serial. That path is still the right answer when you need hardware-isolated timing, three buses on one board, or you're running ControlForge on a host without a CAN controller. But it has limits:

  • USB serial hop adds jitter and a Teensy to the BOM
  • Classic CAN only (no CAN FD)
  • No kernel-level filtering, no candump/cansend interop

SocketCAN is the right answer when you're running ControlForge on a Linux SBC with a real CAN controller — an MCP2515 HAT on a Pi, a Waveshare dual-CAN, a BeagleBone DCAN, a BPI-R4, a USB-CAN adapter, or the kernel virtual vcan module for bench work. You get:

  • Direct kernel access via AF_CAN raw sockets (same stack can-utils uses)
  • CAN FD up to 64-byte payloads and bit-rate switching
  • Kernel-level hardware filters (CAN_RAW_FILTER) so unwanted frames never cross the userspace boundary
  • J1939, OBD-II, and DBC layers built on top
  • Coexistence with candump, Wireshark, and SocketCAN-aware tools on the same interface

2. Architecture​

Every open interface gets one raw socket, shared in the runtime by the CAN_* functions, TML, J1939, DBC, OBD-II and a CANopen master (only a CANopen slave node opens its own), with a background goroutine reading frames into a buffer (256 frames by default) and atomic TX/RX/error counters. Frames the socket sends itself are not put in the buffer: the kernel echoes each one back and the driver counts it as tx_confirmed in CAN_STATUS (since v1.0.1621). What that proves depends on the driver. Where the driver echoes only completed frames (ip link show can0 lists ECHO among the flags; FlexCAN does), a frame no other node acknowledges never completes, so tx_confirmed staying below tx_frames means frames are not completing on the wire — no acknowledgement, bus-off, bit errors — or are still in flight. On vcan and slcan the echo comes at once and proves only that the frame was queued. A kernel filter applies to the echo too: filter out your own transmit ids and their confirmations are not counted.

3. Kernel Setup​

SocketCAN is a kernel feature. The interface must exist and be UP before you call CAN_OPEN — ControlForge does not run ip link for you, and it does not set bit rates. Bring the link up once at boot with systemd-networkd or an /etc/network/interfaces.d/can0 stanza, or issue ip link commands by hand during development.

Bench testing with vcan (no hardware)​

sudo modprobe vcan
sudo ip link add dev vcan0 type vcan
sudo ip link set up vcan0

You now have a virtual CAN interface named vcan0. Every frame you transmit is delivered to every other socket on vcan0 — another ControlForge process, candump, a simulator. It is not delivered back to the socket that sent it, and the CAN_* functions, TML, J1939, DBC, OBD-II and a CANopen master share one socket per interface in a runtime, so a task sending on vcan0 and another task receiving on vcan0 in the same runtime do not see each other's frames. Run the peer as a separate process, or as a CANOPEN_SLAVE_CREATE node, which opens its own socket and does see them.

MCP2515 HAT on a Raspberry Pi​

Add to /boot/firmware/config.txt (Bookworm) or /boot/config.txt (older):

dtparam=spi=on
dtoverlay=mcp2515-can0,oscillator=16000000,interrupt=25

Reboot, then:

sudo ip link set can0 up type can bitrate 500000
ip -s link show can0

USB-CAN adapter (gs_usb family)​

Plug it in. The gs_usb driver is in-tree on modern Linux:

sudo ip link set can0 up type can bitrate 500000

Persistent bring-up with systemd-networkd​

Create /etc/systemd/network/80-can0.network:

[Match]
Name=can0

[CAN]
BitRate=500000
RestartSec=100ms

RestartSec is important: when the controller enters bus-off (too many errors), systemd-networkd will automatically restart it. Without this, a noisy bus will leave the interface down until you manually reset it.

4. Core CAN: Open, Send, Receive​

The smallest useful program: open vcan0, send a frame every second, log everything that arrives.

PROGRAM can_echo
VAR
opened : BOOL;
counter : DWORD := 0;
pending : DINT;
frame_json : STRING;
tx_ok : BOOL;
tick : TON;
END_VAR

IF NOT opened THEN
opened := CAN_OPEN('vcan0');
IF NOT opened THEN
RETURN; (* interface not up — bring it up with `ip link set up vcan0` *)
END_IF;
END_IF;

tick(IN := TRUE, PT := T#1S);
IF tick.Q THEN
tick(IN := FALSE);
counter := counter + 1;
(* 8-byte payload, first 4 bytes = counter, last 4 bytes = 0xCAFEBABE *)
tx_ok := CAN_SEND('vcan0', 16#123, 'DEADBEEFCAFEBABE', 8);
END_IF;

(* Drain the rx buffer every scan *)
pending := CAN_RECV_COUNT('vcan0');
WHILE pending > 0 DO
frame_json := CAN_RECV('vcan0');
IF LEN(frame_json) > 0 THEN
DEBUG('can', CONCAT('rx: ', frame_json));
END_IF;
pending := pending - 1;
END_WHILE;
END_PROGRAM

A few rules that are easy to miss:

  • Data is hex. CAN_SEND takes the payload as an uppercase hex string, two characters per byte, no separators. 'DEADBEEFCAFEBABE' is 8 bytes. An odd number of hex characters is rejected.
  • DLC is clamped. If you pass dlc=8 but give 4 hex bytes, the driver transmits 4 bytes. You cannot pad a short frame by over-declaring DLC.
  • Extended IDs use CAN_SEND_EXT. Classic 11-bit IDs use CAN_SEND. There is no flag — the function you call chooses the frame format.
  • CAN_RECV returns a JSON string or the empty string. Always check LEN(frame_json) > 0 before parsing. CAN_RECV_COUNT tells you how many frames are buffered so you can drain the queue in a bounded loop instead of spinning forever.
  • The buffer is 256 frames per interface by default. protocols.can.interfaces[].buffer sets another size; whichever opens the interface first sets it, and a CANopen master that opens it first makes it 512. On a busy bus, drain it every scan or set filters to drop what you don't care about. A frame that arrives while the runtime's buffer is full is lost and counted in rx_dropped in CAN_STATUS. Frames the kernel drops because its own socket queue overflowed are not reported in CAN_STATUS (the kernel counts them; SO_RXQ_OVFL would expose them).

Reading fields without JSON​

Picking the id and payload out of CAN_RECV's JSON in ST costs a statement per character. CAN_RECV_NEXT takes the next frame instead, and the CAN_RX_* functions read its fields as values. The taken frame is held per task, and every program in that task reads the same one. Two tasks reading one interface compete for its one buffer — each frame goes to whichever task takes it first — so read an interface from one task.

PROGRAM can_fields
VAR
n : DINT;
k : DINT;
id : DINT;
amps : REAL;
END_VAR

n := CAN_RECV_COUNT('can0');
k := 0;
WHILE k < n DO
IF CAN_RECV_NEXT('can0') THEN
id := CAN_RX_ID('can0');
IF CAN_RX_EXT('can0') AND id = 16#102A2 AND CAN_RX_LEN('can0') >= 2 THEN
(* little-endian u16, tenths of an amp *)
amps := DINT_TO_REAL(CAN_RX_BYTE('can0', 0) + 256 * CAN_RX_BYTE('can0', 1)) / 10.0;
END_IF;
k := k + 1;
ELSE
k := n; (* the buffer ran dry *)
END_IF;
END_WHILE;
END_PROGRAM

With no frame waiting, CAN_RECV_NEXT returns FALSE and forgets the frame it took before, so CAN_RX_ID and CAN_RX_LEN read -1, CAN_RX_BYTE reads -1, CAN_RX_EXT FALSE and CAN_RX_DATA '' until the next frame is taken. CAN_RX_BYTE also reads -1 for an index past the frame's length. A remote request frame carries no data — its DLC is the length asked for — so CAN_RX_RTR reads TRUE, CAN_RX_LEN 0, CAN_RX_DATA '' and CAN_RX_BYTE -1. CAN_RX_DATA is lowercase hex, like the data field of CAN_RECV.

Kernel filters​

CAN_SET_FILTER installs a hardware-level accept filter. The kernel drops non-matching frames before they reach the socket, so a tight filter is essentially free. Masks are the standard CAN match: a frame passes when (frame.id & mask) == (filter.id & mask).

(* Accept only IDs 0x100 through 0x10F *)
CAN_SET_FILTER('can0', 16#100, 16#7F0);

(* Accept exactly one ID *)
CAN_SET_FILTER('can0', 16#123, 16#7FF);

(* Wide open — receive everything *)
CAN_CLEAR_FILTERS('can0');

Filters are not cumulative: each CAN_SET_FILTER call replaces the interface's filter with that one accept rule. CAN_CLEAR_FILTERS returns the interface to the default "accept everything" state. The filter belongs to the interface's one shared socket, so it applies to every task and driver reading that interface in the runtime: a filter set for one protocol deafens TML, J1939, OBD-II or a CANopen master on the same interface. For an extended (29-bit) id, put 16#80000000 (the extended-frame flag) in both the id and the mask, and 16#40000000 (remote request) in the mask to refuse remote requests: CAN_SET_FILTER('can0', 16#800102A0, 16#DFFFFFFC) accepts extended data frames with ids 0x102A0–0x102A3 and nothing else.

5. CAN FD​

CAN FD ("Flexible Data Rate") allows payloads up to 64 bytes and an optional higher data-phase bit rate. Use it when you need more bandwidth per frame and your hardware supports it — MCP2515 does not; MCP2518FD does.

VAR
opened : BOOL;
tx_ok : BOOL;
END_VAR

opened := CAN_OPEN_FD('can0');

(* 32-byte payload, BRS=TRUE switches to the faster data-phase bit rate *)
tx_ok := CAN_SEND_FD('can0', 16#200,
'00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF',
TRUE);

CAN_OPEN_FD will fail if the kernel or controller doesn't support CAN FD. You can still send classic 8-byte frames on an FD-enabled socket with CAN_SEND, and received classic frames will still arrive on the rx channel — CAN FD is strictly additive.

The data-phase bit rate is set on the kernel interface when you bring the link up, not from ST:

sudo ip link set can0 up type can bitrate 500000 dbitrate 2000000 fd on

6. J1939 (Heavy Duty Vehicles)​

J1939 is the SAE standard used on commercial trucks, agricultural equipment, construction machinery, and marine engines. Frames use 29-bit extended IDs encoding a Parameter Group Number (PGN), source address, and priority. ControlForge's J1939 layer caches the last received value for every PGN and exposes both raw access and convenience getters for common signals.

Convenience getters​

VAR
rpm : REAL;
speed_kmh : REAL;
coolant_c : REAL;
fuel_lph : REAL;
engine_hours : REAL;
END_VAR

CAN_OPEN('can0');

rpm := J1939_ENGINE_RPM('can0'); (* PGN 61444 / EEC1 / SPN 190 *)
speed_kmh := J1939_VEHICLE_SPEED('can0'); (* PGN 65265 / CCVS1 / SPN 84 *)
coolant_c := J1939_COOLANT_TEMP('can0'); (* PGN 65262 / ET1 / SPN 110 *)
fuel_lph := J1939_FUEL_RATE('can0'); (* PGN 65266 / LFE1 / SPN 183 *)
engine_hours := J1939_ENGINE_HOURS('can0'); (* PGN 65253 / HOURS / SPN 247 *)

Each of these returns the last decoded value for that SPN. If no frame has been received yet, you get 0.0 — there is no "unknown" sentinel, so gate your logic on a freshness flag if you need to distinguish "really zero" from "never heard".

Raw PGN access​

For any PGN not covered by a convenience getter, use J1939_READ_PGN. It returns the raw payload of the last received frame for that PGN as a JSON string, or "" if nothing has been received.

VAR
pgn_data : STRING;
ok : BOOL;
END_VAR

(* PGN 65266 (LFE1) — Fuel Economy *)
pgn_data := J1939_READ_PGN('can0', 16#FEF2);

(* Send a PGN request (broadcast to source address 255) *)
ok := J1939_REQUEST_PGN('can0', 16#FEEC, 255);

(* Transmit a custom PGN *)
ok := J1939_SEND_PGN('can0', 16#FF00, 255, '0102030405060708');

J1939_SEND_PGN handles the 29-bit ID assembly and priority bits for you — you give it a PGN, destination address, and hex data, and it transmits the frame with priority 6 (the J1939 default).

7. OBD-II (Passenger Cars)​

OBD-II is the diagnostic protocol on every passenger car sold since 1996 (US) or 2001 (EU). On a 2008+ US car it rides on CAN via ISO 15765-4 using 11-bit IDs 0x7DF (broadcast request) and 0x7E8–0x7EF (ECU responses). ControlForge reads it through an adapter: a link to one vehicle owned by its own goroutine, which polls the signals you read and keeps the latest values. Your ST reads that cache — nothing in the scan waits on the car.

An adapter is either declared in the deployment config, or started by ST:

protocols:
can:
interfaces:
- name: can0
obd2:
adapters:
- name: car # what ST calls it
transport: socketcan
interface: can0
# an ELM327 on USB or Bluetooth instead:
# - name: car
# transport: elm327
# port: /dev/rfcomm0
VAR
started : BOOL;
rpm : REAL;
speed_kmh : REAL;
coolant_c : REAL;
iat_c : REAL;
iat_fresh : BOOL;
END_VAR

(* Only if the adapter is NOT in the config: start it from ST. Safe every
scan — TRUE while it runs. It belongs to the runtime: new settings replace
it, OBD2_ADAPTER_STOP stops it, a full reload stops it. Gated by
capabilities.can here (serial for a USB/Bluetooth ELM327, network.socket
for a Wi-Fi one). *)
started := OBD2_ADAPTER_START('car', 'socketcan', 'can0');

rpm := OBD2_RPM('car'); (* Mode 01, PID 0x0C; -1 = no fresh value *)
speed_kmh := OBD2_SPEED('car'); (* PID 0x0D *)
coolant_c := OBD2_COOLANT_TEMP('car'); (* PID 0x05 *)

(* Any other signal, by key or by PID in hex — decoded to engineering units *)
iat_c := OBD2_VALUE('car', 'intake_air_temp'); (* same as OBD2_VALUE('car', '0F') *)
iat_fresh := OBD2_FRESH('car', 'intake_air_temp');

All values come pre-scaled per the SAE J1979 formulas — rpm, km/h, °C, percentages 0–100, g/s. Reading a signal keeps it polled; GET /api/obd2/car/signals lists every key. The original functions (OBD2_RPM … OBD2_READ_PID) return -1 when there is no fresh value; OBD2_VALUE returns 0.0 then, so pair it with OBD2_FRESH (a fuel trim can legitimately be negative). OBD2_MIL, OBD2_DTCS, OBD2_VIN, OBD2_CONNECTED and OBD2_STATE report the vehicle; clearing codes is not an ST function (it is DELETE /api/obd2/car/dtcs?confirm=CLEAR, engineer, audited). The Scan Tool HMI is at /hmi/scantool.

One receive consumer per interface. A socketcan adapter reads the interface's shared receive queue for as long as it runs, like the J1939 decoder: do not run it beside raw CAN_RECV, the J1939 decoder, the OBD-II responder or a CANopen master on the same interface in one runtime (a config- or ST-created master uses that shared socket). An ELM327 adapter has its own serial link and no such limit.

Note: OBD-II requires the vehicle's ECU to be powered (key on, engine off is enough). Full reference: docs/features/obd2-scan-tool.md.

8. DBC Files​

DBC (Database CAN) files are the Vector Informatik file format for describing CAN messages: IDs, signal names, bit positions, byte order, scaling, offset, and units. Every vehicle manufacturer publishes internal DBCs for their engineering tools; many are public (the OpenDBC project has hundreds). Loading a DBC lets you read named signals instead of parsing raw bytes.

VAR
loaded : BOOL;
msgs_json : STRING;
latest : STRING;
engine_rpm : REAL;
coolant : REAL;
END_VAR

CAN_OPEN('can0');

(* Load a DBC file from the FileIO sandbox (data/ directory by default) *)
loaded := DBC_LOAD('vehicle', 'data/vehicle.dbc');

(* List every message defined in the DBC as a JSON array *)
msgs_json := DBC_LIST_MESSAGES('vehicle');

(* Decode the most recently received frame against the DBC and
return every signal as a JSON object *)
latest := DBC_DECODE('vehicle', 'can0');

(* Pull one signal value by name — returns the latest decoded value
for a signal we've been tracking on this interface *)
engine_rpm := DBC_GET_SIGNAL('vehicle', 'can0', 'EngineSpeed');
coolant := DBC_GET_SIGNAL('vehicle', 'can0', 'CoolantTemp');

(* When done *)
DBC_UNLOAD('vehicle');

The name argument is a local handle — you pick it when you load the DBC and use it to refer to the loaded database in later calls. You can load multiple DBCs (one per bus, for example) as long as the handles are unique.

DBC files are read from the FileIO sandbox. By default the sandbox root is the data/ directory next to your project file, so DBC_LOAD('vehicle', 'data/vehicle.dbc') works if the file is at data/vehicle.dbc. Absolute paths outside the sandbox are rejected.

9. ST Function Reference​

All 32 functions verified against the live function registry at ControlForge v1.0.606; CAN_RECV_NEXT and the six CAN_RX_* functions were added in v1.0.1621.

Core CAN​

FunctionPurpose
CAN_OPEN(interface: STRING) : BOOLOpen a SocketCAN interface in classic CAN mode
CAN_OPEN_FD(interface: STRING) : BOOLOpen in CAN FD mode (up to 64-byte payloads)
CAN_CLOSE(interface: STRING) : BOOLClose an open interface and release its socket
CAN_STATUS(interface: STRING) : STRINGJSON with the controller state, the bus condition (ok, open-circuit, shorted, degraded, down, unknown), TX/RX counts, error counters and bus-off count (§12)
CAN_LIST() : STRINGJSON array of every CAN/VCAN interface visible to the kernel
CAN_SET_FILTER(interface: STRING, id: DWORD, mask: DWORD) : BOOLAdd a kernel-level accept filter
CAN_CLEAR_FILTERS(interface: STRING) : BOOLRemove all filters (receive everything)
CAN_SEND(interface: STRING, id: DWORD, data: STRING, dlc: DINT) : BOOLSend classic 11-bit frame, hex payload
CAN_SEND_EXT(interface: STRING, id: DWORD, data: STRING, dlc: DINT) : BOOLSend classic 29-bit extended frame
CAN_SEND_FD(interface: STRING, id: DWORD, data: STRING, brs: BOOL) : BOOLSend CAN FD frame, optional bit-rate switch
CAN_RECV(interface: STRING) : STRINGPop one frame off the rx buffer as JSON, or ""
CAN_RECV_COUNT(interface: STRING) : DINTNumber of frames buffered, waiting to be popped
CAN_RECV_NEXT(interface: STRING) : BOOLTake the next frame for CAN_RX_* to read; FALSE when none (v1.0.1621)
CAN_RX_ID(interface: STRING) : DINTIdentifier of the taken frame, or -1
CAN_RX_EXT(interface: STRING) : BOOLTRUE if the taken frame is 29-bit extended
CAN_RX_RTR(interface: STRING) : BOOLTRUE if the taken frame is a remote request (no data)
CAN_RX_LEN(interface: STRING) : DINTData length of the taken frame (0 for a remote request), or -1
CAN_RX_DATA(interface: STRING) : STRINGData bytes of the taken frame as hex, or ''
CAN_RX_BYTE(interface: STRING, index: DINT) : DINTData byte at index (0-based), 0–255, or -1

J1939​

FunctionPurpose
J1939_READ_PGN(interface: STRING, pgn: DWORD) : STRINGLast received payload for this PGN as JSON
J1939_SEND_PGN(interface: STRING, pgn: DWORD, dest: DINT, data: STRING) : BOOLTransmit a PGN, hex data
J1939_REQUEST_PGN(interface: STRING, pgn: DWORD, dest: DINT) : BOOLRequest a PGN from another node
J1939_ENGINE_RPM(interface: STRING) : REALEngine RPM from EEC1 / PGN 61444
J1939_VEHICLE_SPEED(interface: STRING) : REALGround speed from CCVS1 / PGN 65265
J1939_COOLANT_TEMP(interface: STRING) : REALCoolant temperature from ET1 / PGN 65262
J1939_FUEL_RATE(interface: STRING) : REALFuel rate from LFE1 / PGN 65266
J1939_ENGINE_HOURS(interface: STRING) : REALTotal engine hours from HOURS / PGN 65253

OBD-II​

FunctionPurpose
OBD2_ADAPTER_START(name: STRING, transport: STRING, port: STRING) : BOOLStart an adapter from ST ('elm327' + serial device or host:port, 'socketcan' + interface, 'sim'); idempotent; stops on reload
OBD2_ADAPTER_STOP(name: STRING) : BOOLStop an adapter this program started
OBD2_VALUE(adapter: STRING, signal: STRING) : REALAny signal by key ('rpm', 'intake_air_temp' …) or PID hex ('0F'); 0.0 until read
OBD2_FRESH(adapter: STRING, signal: STRING) : BOOLThe signal has a value younger than the stale limit
OBD2_CONNECTED(adapter: STRING) : BOOL / OBD2_STATE(adapter: STRING) : STRINGLink state
OBD2_MIL(adapter: STRING) : BOOL / OBD2_DTC_COUNT : DINT / OBD2_DTCS : STRINGCheck-engine light, stored codes
OBD2_VIN(adapter: STRING) : STRING / OBD2_VOLTAGE(adapter: STRING) : REALVIN; connector voltage (ELM327)
OBD2_READ_PID(adapter: STRING, mode: DINT, pid: DINT) : REALFirst signal of a Mode 01 PID, decoded; -1 when none fresh
OBD2_RPM / OBD2_SPEED / OBD2_COOLANT_TEMP / OBD2_THROTTLE / OBD2_FUEL_LEVEL / OBD2_MAF (adapter: STRING) : REALPIDs 0C / 0D / 05 / 11 / 2F / 10; -1 when none fresh

DBC​

FunctionPurpose
DBC_LOAD(name: STRING, file_path: STRING) : BOOLLoad a DBC file under a handle
DBC_UNLOAD(name: STRING) : BOOLDrop a loaded DBC
DBC_LIST_MESSAGES(name: STRING) : STRINGJSON array of every message in the DBC
DBC_DECODE(name: STRING, interface: STRING) : STRINGDecode the latest frame on this bus against the DBC
DBC_GET_SIGNAL(name: STRING, interface: STRING, signal_name: STRING) : REALLatest value of one named signal

10. REST API​

Six endpoints for managing CAN interfaces without touching ST. Useful for one-shot testing from curl, or for integrating ControlForge CAN state into Grafana or Node-RED. All endpoints require authentication when RBAC is enabled — obtain a JWT via POST /api/auth/login and pass it as Authorization: Bearer <token>.

List visible and open interfaces​

curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8082/api/can
{
"interfaces": ["can0", "vcan0"],
"open": [
{"name":"vcan0","fd":false,"tx_frames":42,"rx_frames":42,"tx_errors":0,"rx_errors":0}
]
}

interfaces is every CAN/VCAN device the kernel knows about (open or not). open is stats for everything this ControlForge process has actually opened.

Per-interface stats​

curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8082/api/can/vcan0

Open an interface (optional CAN FD)​

curl -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"fd":false}' \
http://localhost:8082/api/can/vcan0/open

An empty body opens in classic CAN mode. {"fd":true} enables CAN FD.

Close an interface​

curl -X POST -H "Authorization: Bearer $TOKEN" \
http://localhost:8082/api/can/vcan0/close

Send a frame​

curl -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"id":291,"data":"DEADBEEF","extended":false}' \
http://localhost:8082/api/can/vcan0/send

id is the CAN arbitration ID (decimal or JSON hex literal). data is an uppercase hex string; spaces are allowed for readability. extended=true selects the 29-bit frame format. Response:

{"sent":true,"id":291,"dlc":4,"fd":false}

Read buffered frames​

curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8082/api/can/vcan0/recv

Returns up to 10 buffered frames in a single response. Each frame contains id, data, dlc, extended, fd, and timestamp. The same frames are removed from the buffer — calling /recv twice does not return the same frames twice.

11. Hardware Options​

HardwareInterfaceNotes
vcan kernel moduleVirtualFree, no hardware, full loopback — perfect for tests
MCP2515 HAT (Raspberry Pi)SPI → 1x CAN 2.0~$10. Classic CAN only
Waveshare 2-CH CAN HATSPI → 2x CAN 2.0, isolatedDual bus, opto-isolated inputs
MCP2518FD HATSPI → 1x CAN FD~$25. Actually supports CAN FD
BeagleBone Black DCANNative 2x CAN 2.0In-SoC CAN controllers, no add-on
Banana Pi BPI-R4Native CANBuilt into the router SoC
Gs_usb adapters (CANable, Innomaker USB2CAN)USB → CAN~$20–40. Plug-and-play on modern Linux
Kvaser LeafUSB → CANCommercial-grade, reliable kernel driver
Copperhill Triple CAN Teensy 4.1USB serial → 3x CAN (2x classic + 1x FD)Use the TEENSY_CAN_* path, not SocketCAN

12. Gotchas​

Interface must be UP before CAN_OPEN. ControlForge does not bring links up; it fails cleanly if the kernel device is DOWN. Check with ip -s link show can0. On vcan, the modprobe + ip link add + ip link set up sequence is all three commands, not just the first two.

Bus-off recovery is a kernel concern. When a CAN controller accumulates too many transmit errors it enters bus-off and stops. By default SocketCAN leaves it bus-off until someone brings the link down and back up. RestartSec=100ms in a systemd-networkd .network file tells the kernel to auto-reset. Without it, a single noisy burst can take your bus out until the next reboot.

Read the bus, not just the socket: state and bus in CAN_STATUS (since v1.0.1652). CAN_SEND returning TRUE means the kernel took the frame, not that anyone heard it: on a shorted bus with auto-restart, each restart empties the transmit queue and the next send is accepted again. So CAN_STATUS reports what the controller says:

FieldMeaning
stateThe controller's state: error-active, error-warning, error-passive, bus-off, stopped or sleeping. open on a link with no controller state (vcan, slcan); missing when the link has gone (a USB adapter unplugged, the link deleted); closed once the socket is closed
busWhat that means for the wire, one of the values below
tx_error_counter, rx_error_counterThe controller's error counters (TEC and REC)
bus_off_count, restart_countThe kernel's counts for the link since it was brought up
error_framesController error frames this socket received. They never reach CAN_RECV and are not counted in rx_errors
busCause
okerror-active
open-circuiterror-passive with TEC pinned at 128: no other node acknowledges. The cable is open, or this node is alone on the bus. A node in this state never goes bus-off
shortedbus-off now, or at any time in the last 10 seconds: bit errors, e.g. CAN_H or CAN_L shorted. With a restart interval the controller is often error-active between bus-offs, so the recent bus-off is what counts
degradederror-warning, or error-passive for another reason
downthe link is down or gone, the controller is stopped, or the socket is closed
unknowna link with no controller state other than vcan

The state comes from the controller's error frames, as they happen, and from the kernel's link state, read when the interface opens and once a second after that. A program driving motion should check bus = 'ok' before trusting that its commands arrived.

Classic and FD mix on an FD socket. Opening with CAN_OPEN_FD does not stop you from sending classic frames with CAN_SEND, and classic frames from other nodes still arrive on the rx channel. FD is purely additive. But the kernel and controller both have to actually support FD — on an MCP2515 you'll get an error the moment you try.

CAN_SEND is synchronous, CAN_RECV is non-blocking. Send blocks briefly while the kernel enqueues the frame (microseconds on a clear bus, milliseconds on a saturated one). Receive returns immediately with the empty string when the buffer is empty — there is no blocking wait. Use CAN_RECV_COUNT to avoid tight-looping on an empty bus.

The rx buffer is 256 frames by default. On a 500 kbps bus running at capacity you can receive ~8000 frames per second, which fills a 256-slot buffer in 32 ms. If your scan time is longer than that, add kernel filters to drop uninteresting IDs before they reach the buffer.

DBC files are sandboxed. Passing an absolute path like /etc/vehicle.dbc to DBC_LOAD is rejected. Put the file under data/ (the FileIO sandbox root) and reference it with a relative path. This is consistent with FILE_READ and every other file-touching ST function.

You never receive your own frames. Before v1.0.1621 every frame a runtime sent came back into its own rx buffer as if another node had sent it; a TML driver decoded its own request as a reply from an axis that does not exist. Now the kernel's echo of your frame only counts toward tx_confirmed. The flip side: two tasks in one runtime cannot talk to each other over vcan0 — put the peer in another process.

Protocol events ride the webhook pipeline. CAN bus state changes emit protocol.connect, protocol.disconnect, protocol.reconnect, and protocol.error events that flow through the same webhook/MQTT/Slack routes as every other driver. Subscribe to protocol.* in your event config to get CAN-level alerts for free.

13. Putting It All Together: Truck Dashboard​

A complete program that reads J1939 vitals from a heavy-duty truck, writes them into ST variables, and emits a status event when the engine coolant exceeds a threshold. Pair this with the Historian guide to log everything to InfluxDB, or with the HMI builder to render a live dashboard.

PROGRAM truck_dashboard
VAR
opened : BOOL;
rpm : REAL;
speed : REAL;
coolant_c : REAL;
fuel_lph : REAL;
hours : REAL;
coolant_high : BOOL;
last_coolant : BOOL;
event_json : STRING;
err : STRING;
END_VAR

IF NOT opened THEN
opened := CAN_OPEN('can0');
IF NOT opened THEN
err := CAN_STATUS('can0');
RETURN;
END_IF;
END_IF;

rpm := J1939_ENGINE_RPM('can0');
speed := J1939_VEHICLE_SPEED('can0');
coolant_c := J1939_COOLANT_TEMP('can0');
fuel_lph := J1939_FUEL_RATE('can0');
hours := J1939_ENGINE_HOURS('can0');

coolant_high := coolant_c > 100.0;

(* Edge-trigger the alert so we don't spam the event bus every scan *)
IF coolant_high AND NOT last_coolant THEN
event_json := CONCAT('{"coolant_c":', REAL_TO_STRING(coolant_c));
event_json := CONCAT(event_json, ',"rpm":');
event_json := CONCAT(event_json, REAL_TO_STRING(rpm));
event_json := CONCAT(event_json, '}');
EVENT_EMIT('protocol.error', 'can0', event_json);
END_IF;
last_coolant := coolant_high;

END_PROGRAM

Things worth noting in the pattern:

  • CAN_OPEN is called once, guarded by opened. Re-opening an already-open interface is not an error, but there's no reason to.
  • Every J1939 getter returns the last cached value — no blocking, no round-trip to the bus. Your scan time stays flat regardless of bus traffic.
  • The coolant alert is edge-triggered (coolant_high AND NOT last_coolant). Without this, you'd emit a protocol.error event every scan the coolant is high, which would pin the event bus and fill your webhook logs.
  • CAN_STATUS returns a JSON string — stash it into err on open failure so you can see it in the Live Variables panel without adding a breakpoint.

14. What's Next​

SocketCAN is production-ready today — classic CAN, CAN FD, J1939, OBD-II, and DBC decoding all ride on a single kernel socket per bus. Bolt it onto the existing features:

  • Historian → archive every J1939 SPN at 1 Hz to InfluxDB with deadband compression
  • Alarms → ISA-18.2 state machine on top of coolant_c > 100.0, with shelving and auto-ack
  • Events → protocol.* events fan out to Slack/PagerDuty/MQTT via the webhook pipeline
  • HMI builder → live gauges for RPM, speed, coolant, fuel rate
  • Node-RED → feed decoded frames into dashboards, rule flows, or cloud backends

For a working end-to-end example, see the Historian and Events guides in this directory.