# mbrtu
[](https://github.com/hz2/mbrtu/actions/workflows/ci.yml)
[](https://crates.io/crates/mbrtu)
[](https://docs.rs/mbrtu)
[](LICENSE)
[](#)
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`](https://github.com/pymodbus-dev/pymodbus),
a real reference implementation, not hand-derived bytes.
`tests/reference_corpus.rs` additionally cross-checks a larger batch of
varied frames generated and independently decoded with `pymodbus`.
- **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. `ModbusRequest` and `ModbusResponse` make that distinction
part of the type, rather than guessing.
- **Fuzz-tested with [proptest](https://docs.rs/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](#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`, no `alloc`**: 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](#formal-verification), not
just tests.
## Crates
| [`mbrtu`](crates/mbrtu) | The `no_std`, no-`alloc` parser/encoder library. |
| [`mbrtu-cli`](crates/mbrtu-cli) | A small command-line decoder (installs as `mbrtu`). |
| [`mbrtu-ffi`](crates/mbrtu-ffi) | C FFI bindings, for calling from C/C++. |
## Quick start
```rust
// 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 = mbrtu::decode_request(&frame_bytes)?;
let mbrtu::ModbusRequest::ReadHoldingRegisters(req) = request else {
panic!("expected a Read Holding Registers request");
};
println!("starting_address={} quantity={}", req.starting_address, req.quantity);
```
Encoding mirrors decoding:
```rust
let request = mbrtu::ModbusRequest::WriteSingleRegister(
mbrtu::message::WriteSingleRegister { address: 0x0001, value: 3 },
);
let mut buf = [0u8; mbrtu::frame::MAX_FRAME_LEN];
let n = mbrtu::encode_request(0x11, &request, &mut buf)?;
```
Add it to a project with:
```sh
cargo add mbrtu
```
## Function code coverage
| 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`](crates/mbrtu/src/lib.rs) for the crate's
module layout and [`crates/mbrtu/src/message`](crates/mbrtu/src/message)
for each function code, each with its own reference-verified tests.
## C FFI
[`mbrtu-ffi`](crates/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`](crates/mbrtu-ffi/include/mbrtu.h)
for the generated header and [`crates/mbrtu-ffi/tests/smoke.c`](crates/mbrtu-ffi/tests/smoke.c)
for a worked example.
## Building
This project is built and checked with [Nix](https://nixos.org/):
```sh
nix develop # dev shell: toolchain, rust-analyzer
nix flake check -L # fmt, clippy (pedantic), tests, no_std/no_alloc cross-compile, FFI header/smoke checks
nix build # mbrtu-cli (default package)
nix build .#mbrtu
nix build .#mbrtu-ffi
```
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](https://github.com/model-checking/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::parse` and the
broadcast-rejecting `Frame::parse_response`.
- Encoding a frame and parsing it back recovers the original address,
function code, and data exactly.
- Encoding a `ReadHoldingRegistersResponse`/`ReadCoilsResponse` never
panics for any `count`/`byte_count` value, 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`:
```sh
cargo install --locked kani-verifier
cargo kani setup
cargo kani -p mbrtu
```
## License
MIT. See [LICENSE](LICENSE).