
Recall first from CAN frames, SocketCAN, and can-utils
- Classical CAN supports 11-bit standard and 29-bit extended identifiers, and a data frame carries up to eight payload bytes.
- A dominant zero wins over a recessive one during arbitration, so lower identifiers have higher priority within the same identifier format.
- SocketCAN exposes CAN controllers as network interfaces and delivers complete frames to bound sockets.
Turn fieldbus readings into service samples
5 min readWith both fieldbuses available, this lesson connects them into the service layer and covers the error cases that bite in production.
A CAN controller can enter bus-off and stop participating in bus traffic. If a service simply stops publishing when that happens, an MQTT subscriber can still receive a retained reading from before the failure. The number in that reading may be correct for the time it was measured. A consumer needs the observation time and the source’s current health to decide whether it can use the value now. The Linux SocketCAN documentation describes bus-off and the controls available for recovery.
Put protocol details in the acquisition code. The Modbus adapter knows the server, unit, function and register address. The CAN adapter knows the interface, frame format, identifier, expected length and byte layout. Both hand the service a sample with a stable point name, decoded value, unit, source identity, time of observation and quality. For polled data, the observation time can be the time the service received the successful response. If the device supplies its own measurement timestamp, keep that separately. Use a monotonic clock for local freshness deadlines so a wall-clock correction cannot extend the lifetime of an old reading.
Use one mapping throughout this lesson. On the simulator, configure holding register address 0 at unit 1 with the value 250. The address is the zero-based protocol address passed to modbus_read_registers. Read one register and accept a sample when the function returns 1. The mapping treats the register as unsigned, in tenths of a degree Celsius. The service point tank.temperature therefore has a value of 25.0 in degC. This mapping is a lab definition, so use the equipment’s register map and encoding when you move to a real device.
Publish the sample on lab/tank/temperature. For the lab, the JSON fields value, unit and quality can contain 25.0, "degC" and "good". Add observed_at using the actual observation time. From the same successful read, send a standard CAN data frame with lab identifier 0x321 and two payload bytes. Encode the original unsigned count high byte first. For 250, that gives 00 FA. A consumer of this lab CAN format accepts the standard identifier and a data length of two, reconstructs the unsigned count, and applies the same scale. Check the frame format and length before reading payload bytes, and reject remote request frames for this mapping.
Production services can send decoded CAN and Modbus samples to MQTT, store them in a database, or do both. For history, store the point identifier, timestamp, value and quality. For a current-value view, update the latest sample by point and keep its original observation timestamp if a subsequent attempt fails. Track health changes separately so consumers can distinguish an old observation from a new report about the source. With retained MQTT telemetry, publish a quality change when a point becomes stale, and give subscribers an age limit they can apply if the gateway stops reporting entirely.
Acquisition has its own deadlines. If the broker disconnects or a database write takes longer than expected, keep polling and receiving on schedule. Pass samples to a bounded queue or a store that holds the latest sample per point. A current-value stream can replace a pending sample with a newer one. History that must survive a broker outage needs durable storage and a defined response when that storage fills. Track delivery status independently for each destination. A broker acknowledgment, database commit and CAN transmission are distinct events, and a single input reading can succeed at one destination while another is unavailable.
Going deeperModbus gateway polling and writes
In a Modbus-to-MQTT gateway, let a polling schedule drive reads and let subscriptions consume the resulting samples. Multiple MQTT subscribers can then use one acquisition result. Batch contiguous registers on the same unit when they use the same read function, have compatible refresh intervals, and the entire range is readable. Respect the device’s request limits and any consistency rules for multi-register values. Give frequently changing points a shorter interval and schedule slow points separately. On a shared serial link, give each unit a bounded share of the polling time so an offline unit cannot delay every healthy unit.
For writes, coalesce successive pending requests only where the register represents a desired final value and the application permits intermediate values to be skipped. For example, two queued updates to one configuration setpoint can become one write if neither has been sent and the caller’s contract allows replacement. Adjacent compatible holding-register values can use function 0x10, Write Multiple Registers, when supported by the device. Preserve the order of commands that trigger actions, such as a reset or a counter clear. Keep command acceptance and the device’s reported state distinct, and verify the resulting state when the device provides a suitable readback.
Identify CAN messages and test routing in software
4 min readA raw CAN identifier and payload layout work for a project-specific format like the lab’s 0x321. Equipment that uses SAE J1939 follows a different contract. J1939 uses 29-bit CAN identifiers that carry priority, addressing information and fields that identify a message group. A Parameter Group Number, the numeric identifier for a group of parameters carried by a J1939 message gives the service a starting point for selecting a decoder. The decoder still needs the payload definition to interpret byte positions, scales and unavailable values.
For destination-specific messages, the PDU Format field is below 240. The PDU Specific field then holds the destination address and is zeroed in the PGN supplied to the Linux J1939 API. When the PDU Format is 240 or higher, the PDU Specific field is a group extension and belongs in the PGN. The source address is separate in both cases. This matters when several devices send the same PGN. If the service must distinguish their readings, include sender identity in the mapping as well as the PGN.
Linux exposes the J1939 stack through socket(AF_CAN, SOCK_DGRAM, CAN_J1939). The application uses sockaddr_can to specify the interface and J1939 addressing parameters. The kernel handles J1939 transport segmentation and reassembly and tracks address claims, which associate a device’s J1939 NAME with a source address. An application that uses dynamic addressing still has to participate in address claiming. The service receives message payloads through the datagram interface and applies the equipment’s parameter definitions in user space.
Going deeperCAN FD frames and J1939 socket options
CAN FD allows up to 64 data bytes per frame. With bit rate switching enabled for a frame, the data phase can use a different, typically higher bit rate than the arbitration phase. In the Linux raw SocketCAN API, struct canfd_frame has can_id, len, flags and data[64], plus reserved bytes. len holds a byte count. CANFD_BRS in flags selects bit rate switching for transmission. Enable CAN_RAW_FD_FRAMES at the SOL_CAN_RAW socket level to exchange FD frames on a raw socket. When receiving into a buffer large enough for an FD frame, distinguish CAN_MTU from CANFD_MTU using the returned byte count before inspecting FD flags.
For a J1939 socket, use the SOL_CAN_J1939 socket level with options such as SO_J1939_FILTER, which applies receive filters for source address, source NAME or PGN using masks. SO_J1939_SEND_PRIO configures the socket’s transmit priority. These options control J1939 datagrams. The raw CAN FD frame interface is a separate SocketCAN API.
Use vcan to test the lab frame without a physical controller or transceiver. A single virtual interface is enough for a sender and an independent receiver on the same host. Two interfaces let you verify a forwarding rule. Linux’s CAN gateway forwards selected frames between interfaces in the kernel. The cangw utility configures it. On an Ubuntu 24.04 VM with vcan and can-gw support, create two unused lab interfaces and install one directional rule.
sudo modprobe vcan
sudo modprobe can-gw
sudo ip link add dev vcan0 type vcan
sudo ip link add dev vcan1 type vcan
sudo ip link set dev vcan0 up
sudo ip link set dev vcan1 up
sudo cangw -A -s vcan0 -d vcan1 -e -f 321:E00007FF
The filter matches standard data frames with identifier 0x321. The mask checks the standard ID bits and the extended, remote and error flag bits against the filter value. The -e option enables local echo for the forwarded frame so a local SocketCAN receiver on vcan1 can observe it. Start candump vcan1 in one terminal, then run the following commands in another.
cansend vcan0 321#00FA
cansend vcan0 322#00FA
Look for identifier 321 and bytes 00 FA on vcan1. The frame with identifier 322 should stay on vcan0. For the complete bridge, use the Modbus client from the register mapping lesson to supply the count to your service. For a minimal implementation, adapt the client to print the count only on a successful read and have a wrapper check its exit status, validate the unsigned value and format the CAN payload as four hex digits. Keep CAN transmission and MQTT publication results separately so a delivery error cannot be mistaken for a read error. Start mosquitto_sub -h localhost -t lab/tank/temperature -v before polling, and use your MQTT client or mosquitto_pub to publish the JSON. Compare the subscriber’s value with the count decoded independently from the forwarded CAN payload. Change the simulator register once and verify that both outputs follow the change. The separate cansend test verifies the forwarding rule, while the bridge test verifies the register-to-payload mapping.
Classify failures before retrying
4 min readA Modbus exception is a response. The server sets the high bit of the function code and returns an exception code describing the failure. 0x01 means Illegal Function, 0x02 means Illegal Data Address and 0x03 means Illegal Data Value. Check the function, address range and request fields before scheduling another identical request. 0x06, Server Device Busy, can justify a delayed retry within the poll’s deadline. A timeout is a different result. The client reached its response deadline without receiving the expected response, so it has no exception code to interpret.
For a failed libmodbus call, read errno immediately. For example, EMBXILADD identifies the Illegal Data Address exception, and ETIMEDOUT identifies a timeout reported by the library. Keep those outcomes separate in the service. An illegal address should mark the affected mapping as faulty and identify the unit and range in the diagnostic. A timeout can mark the attempt as failed while the last successful sample remains available with its original timestamp. Mark the sample stale when it exceeds the configured age limit.
Choose the response deadline from the device’s expected response time, then give each poll a total budget. For a read timeout, retry after a delay if an attempt remains and the deadline allows it. When the budget expires, advance the schedule and leave other units eligible to run. Back off across consecutive failures. After a timed-out write, the device may have acted before the response was lost. Read back the relevant state or use a device-defined confirmation before sending a command again. If the device exposes no confirmation for a write that triggers an action, surface the outcome as uncertain for the caller.
On physical CAN, transmit and receive error counters track errors at the controller. As errors accumulate, the controller can enter error-passive and, with sufficiently severe transmit errors, bus-off. In bus-off, normal frame transmission and reception stop on that controller. Inspect a real interface with ip -details -statistics link show dev can0. Where supported, the output exposes the controller state and transmit and receive error counters. The link statistics also expose cumulative events such as bus-off and restarts where the driver reports them. Repeated bus-off after recovery warrants checking bitrate, wiring and termination.
For event-driven diagnostics, configure a raw SocketCAN socket with CAN_RAW_ERR_FILTER at SOL_CAN_RAW and include CAN_ERR_BUSOFF and CAN_ERR_RESTARTED in the mask. Treat those error notifications as interface state changes. On bus-off, mark points on that interface unavailable and suspend outgoing traffic. A physical interface with kernel restart configured through restart-ms can attempt recovery automatically. A manual recovery policy can request a restart with ip link set dev can0 type can restart when the controller is bus-off and automatic restart is disabled. In either case, return a point to good quality when a fresh, valid measurement arrives. Repeated restart events give the service evidence that an interface is cycling through recovery.
Virtual CAN can verify frame routing and service behaviour when observations stop. To test bus-off handling on a VM, inject a simulated bus-off event at the service’s interface-event boundary and verify the resulting quality and transmit state. Use a physical controller and transceiver on a test bench to verify real error counters and controller recovery. When reviewing the bridge, ask which destinations received each reading and whether a consumer could recognise when it became stale.
The next lesson, The graphics stack from DRM to Qt, explains how a local interface can present device readings and their quality on an embedded display.
Key takeaways
- A service sample carries a decoded value, source identity, observation time and quality.
- J1939 groups messages by PGN, while source and destination addresses identify endpoints.
- vcan can verify frame encoding and routing in software.
- A Modbus timeout leaves a write outcome uncertain, and CAN bus-off stops normal controller participation.
Reflect
- Explain to a colleague, in two sentences: map a Modbus register and a CAN signal to a shared service sample.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Kernel documentationSocketCAN: CAN networking, virtual interfaces and controller errors
- Kernel documentationSAE J1939: Linux sockets, addressing and transport
Official documentation first. Links checked when the lesson was published.