mbrtu
A no_std, allocation-free parser and encoder for Modbus RTU, the
serial-line PDU encoding used by industrial PLCs, sensors, and other field
devices.
- Three function codes, decode and encode: Read Holding Registers,
Read Coils, and Write Single Register, plus generic exception response
handling that applies to any function code. Every fixture is
cross-checked against
pymodbus, a real reference implementation, not hand-derived bytes.tests/reference_corpus.rsadditionally cross-checks a larger batch of varied frames generated and independently decoded withpymodbus. - Requests and responses are separate types. A Modbus request and
response for the same function code can be the same length but mean
something different, and which one you're looking at isn't always
recoverable from the bytes alone - a real Modbus stack always tracks
this itself.
ModbusRequestandModbusResponsemake that distinction part of the type, rather than guessing. - Fuzz-tested with proptest: PDU decode never panics on arbitrary function codes and data, for both directions, and response encode never panics for any count/byte-count value either (see Formal verification for why that side needed checking too).
- Spec limits enforced on the way in, not just the way out: a request
or response quantity/byte-count over the Modbus spec's own maximum
(125 registers, 2000 coils) is rejected at decode time, and a response
frame carrying the broadcast address (
0) - never a real scenario, since Modbus RTU never replies to a broadcast request - is rejected too. no_std, noalloc: works on bare-metal targets with no allocator. Fixed-size arrays (sized to the Modbus spec's own limits: 125 registers, 2000 coils) hold variable-length response data.- Zero mandatory dependencies. The CRC-16 and frame codec are hand-rolled.
#![forbid(unsafe_code)].- Formal verification of the CRC-16, frame layer, and the two count-driven response encoders with Kani, not just tests.
Crates
| Crate | Description |
|---|---|
mbrtu |
The no_std, no-alloc parser/encoder library. |
mbrtu-cli |
A small command-line decoder (installs as mbrtu). |
mbrtu-ffi |
C FFI bindings, for calling from C/C++. |
Quick start
// A request and a response can share a function code and length, so
// decoding is direction-specific - the caller says which one this is.
let request = decode_request?;
let ReadHoldingRegisters = request else ;
println!;
Encoding mirrors decoding:
let request = WriteSingleRegister;
let mut buf = ;
let n = encode_request?;
Add it to a project with:
Function code coverage
| Code | What |
|---|---|
| 1 | Read Coils |
| 3 | Read Holding Registers |
| 6 | Write Single Register |
| any | 0x80 | Exception response |
Modbus RTU has no length field or preamble byte of its own - a real
receiver finds frame boundaries by inter-character timing (3.5 character
times of silence), not by anything encoded in the bytes. Frame::parse
therefore treats its whole input slice as exactly one frame, and
mbrtu-cli reads one hex-encoded frame per line rather than resyncing
through a continuous byte stream.
Frame::parse_response (used by decode_response, mbrtu-cli's
response mode, and mbrtu-ffi's mbrtu_decode_response) additionally
rejects the broadcast address (0): Modbus RTU never sends a response
to a broadcast request, so a response frame from address 0 means
something is wrong upstream, not a case a compliant device produces.
Frame::parse itself stays permissive, since address 0 is a normal,
valid address for a request.
See crates/mbrtu/src/lib.rs for the crate's
module layout and crates/mbrtu/src/message
for each function code, each with its own reference-verified tests.
C FFI
mbrtu-ffi exposes a C API over the core decoder:
opaque request/response handles, a small error enum, and one
mbrtu_request_as_<type>/mbrtu_response_as_<type> accessor per function
code. See crates/mbrtu-ffi/include/mbrtu.h
for the generated header and crates/mbrtu-ffi/tests/smoke.c
for a worked example.
Building
This project is built and checked with Nix:
CI runs the identical nix flake check -L, so there is one source of truth
for what "passing" means, locally and in GitHub Actions.
Without Nix, a standard cargo build / cargo test from the workspace root
also works with a recent stable Rust toolchain (edition 2024, MSRV tracked
in Cargo.toml).
Formal verification
The CRC-16 checksum, frame layer, and the two response types whose wire
encoding is driven by a public count/byte-count field
(src/crc.rs, src/frame.rs, src/message/read_holding_registers.rs,
src/message/read_coils.rs) are proven, not just tested, using
Kani, a bounded model checker
for Rust. Where the test suite samples inputs, these harnesses (gated
behind #[cfg(kani)], so they add nothing to normal builds) prove
properties over every input in a bounded space:
- CRC-16 computation never panics, for any input.
- Frame parsing never panics on arbitrary bytes, including malformed
lengths and checksums, for both
Frame::parseand the broadcast-rejectingFrame::parse_response. - Encoding a frame and parsing it back recovers the original address, function code, and data exactly.
- Encoding a
ReadHoldingRegistersResponse/ReadCoilsResponsenever panics for anycount/byte_countvalue, including ones a real decode would never produce - both fields are public, so a caller can construct one directly with a value wider than the struct's fixed-size backing array. This is exactly the class of bug that shipped in 0.1.0: encode trusted the declared count/byte-count instead of validating it, which either panicked (ReadCoilsResponse) or silently wrote a corrupted, truncated byte count (ReadHoldingRegistersResponse). Fixed in 0.1.1 by giving encode the same bounds check decode already had, and proven here so it can't regress.
Kani requires its own toolchain download (a pinned nightly + CBMC), which
needs network access and isn't run inside the hermetic Nix sandbox, so it's
a manual step rather than part of nix flake check:
License
MIT. See LICENSE.