A Modbus gateway written in Rust is a three-line program in a tutorial and a scheduling problem in a plant. The protocol is simple enough that almost anyone can parse a frame; the failures that stop production are queue collisions on a half-duplex wire, word-order mistakes on 32-bit values, and a reconnect path that silently dies after the first CRC error. tokio-modbus 0.17 gives you the framing, the CRC and the async plumbing. It does not give you the scheduler, and that is where the engineering lives.
This guide works through the parts that decide whether a gateway survives a year on a machine tool network. The examples below target tokio-modbus 0.17.0. The runnable snippets are checked together with these dependencies before publishing.
[dependencies]
tokio = { version = "=1.54.1", features = ["rt", "macros", "sync", "time"] }
tokio-modbus = { version = "=0.17.0", default-features = false, features = ["rtu"] }
tokio-serial = "=5.5.0"
What tokio-modbus actually provides
The crate splits into a client, a server and a codec layer. For a gateway you want the client, and in 0.17 the entry points are concrete functions rather than the trait-object style older tutorials show:
| What you need | Function | Signature |
|---|---|---|
| Modbus TCP, explicit unit id | tcp::connect_slave | async fn(SocketAddr, Slave) -> io::Result<Context> |
| Modbus TCP, default unit id | tcp::connect | async fn(SocketAddr) -> io::Result<Context> |
| RTU over an existing serial stream | rtu::attach_slave | fn(T, Slave) -> Context |
| RTU over any transport | rtu::attach | fn(T) -> Context |
The read/write methods come from the Reader and Writer traits, which the prelude re-exports:
async fn read_input_registers(&mut self, addr: Address, cnt: Quantity)
-> tokio_modbus::Result<Vec<u16>>;
async fn read_holding_registers(&mut self, addr: Address, cnt: Quantity)
-> tokio_modbus::Result<Vec<u16>>;
Address and Quantity are u16, and register values are u16. The crate result has two error layers: a transport/protocol error and a Modbus exception response. In particular, so a register count larger than 125 is rejected by the protocol rather than by your code — worth knowing before you write a helper that requests 500 registers at once and wonders why the slave answers with an exception.
The RTU half-duplex problem nobody mentions in the README
RS-485 is a two-wire bus. Every device shares one pair, and a transceiver can talk or listen but not both. On a USB-to-RS-485 adapter the driver raises RTS to enable the transmitter, sends, and drops RTS to release the line. The gap between the last stop bit leaving the wire and the line actually being released is the turnaround time, and it is measured in hundreds of microseconds on cheap adapters — not nanoseconds.

Two consequences follow, and both cause production bugs:
- You cannot pipeline requests. If slave 3 takes 40 ms to answer and you fire a request at slave 4 after 10 ms, both replies collide. Every request to a given port must be serialised, regardless of how many slaves exist.
- The inter-frame silent interval is a protocol requirement. Modbus RTU requires at least 3.5 character times of silence between frames. At 9600 baud with 11 bits per character that is about 4 ms; at 115200 it rounds up to roughly 1.75 ms because the specification sets a fixed floor for speeds above 19200.
A purely asynchronous design that spawns one task per slave looks elegant and fails the first time two tasks write to the same port. The fix is a single owner task per physical port with an mpsc channel in front of it:
// compile-check: library
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_serial::{Parity, SerialStream, StopBits};
use tokio_modbus::prelude::*;
struct PollRequest {
// Slave is a newtype over u8 with From<u8>, so callers can pass 3.into().
slave: Slave,
addr: u16,
count: u16,
reply: tokio::sync::oneshot::Sender<Result<Vec<u16>, String>>,
}
/// One task owns the wire. Nothing else may touch the port.
async fn rtu_owner(
port: String,
mut rx: mpsc::Receiver<PollRequest>,
frame_gap: Duration,
) {
// This example uses 8E1. Match the device manual; Modbus without parity
// normally uses two stop bits (8N2). Adapter turnaround is driver-owned.
let builder = tokio_serial::new(&port, 19200)
.parity(Parity::Even)
.stop_bits(StopBits::One);
loop {
let Some(req) = rx.recv().await else { break };
// Reconnect lazily: an unplugged adapter must not kill the task.
let stream = match SerialStream::open(&builder) {
Ok(s) => s,
Err(e) => {
let _ = req.reply.send(Err(format!("open {port}: {e}")));
tokio::time::sleep(Duration::from_secs(1)).await;
continue;
}
};
// attach_slave takes the transport by value and the Slave newtype.
let mut ctx = rtu::attach_slave(stream, req.slave);
let result = tokio::time::timeout(
Duration::from_millis(500),
ctx.read_holding_registers(req.addr, req.count),
)
.await;
let mapped = match result {
Ok(Ok(Ok(words))) => Ok(words),
Ok(Ok(Err(exception))) => Err(format!("slave {} exception: {exception:?}", req.slave)),
Ok(Err(error)) => Err(format!("slave {} transport: {error}", req.slave)),
Err(_) => Err(format!("slave {} timed out", req.slave)),
};
let _ = req.reply.send(mapped);
// Honour the 3.5-character silent interval before the next frame.
tokio::time::sleep(frame_gap).await;
}
}
Two details in that sketch matter more than the code. First, the port is reopened per request. That looks wasteful, but it means a USB adapter that re-enumerates after an ESD event recovers without restarting the process — and at 19200 baud the open cost is invisible next to the frame time. Second, the timeout wraps the request, not the whole task, so one dead slave returns an error to its caller instead of stalling the queue.
If you prefer to hold the port open, keep the same single-owner structure and only reopen on Err from the context. Either works; the invariant that must not break is one writer per port.
Word order: the bug that survives every test
A 32-bit value occupies two Modbus registers. Which register comes first is not defined by the protocol — the device manual defines it, and vendors disagree. The four common layouts are usually named after the byte sequence of a 32-bit float:
| Name | Register order | Byte order in each register |
|---|---|---|
| ABCD | high word first | big endian |
| CDAB | low word first | big endian |
| BADC | high word first | little endian |
| DCBA | low word first | little endian |
The failure mode is nasty because it is silent. A value of 1234.5 read with the wrong order does not error; it produces a plausible-looking number, and the trend graph looks fine until someone compares it against the local display.
Do not leave this to a runtime flag. Encode it in the type that reads the register pair, so the compiler forces you to state the layout at every call site:
// compile-check: library
#[derive(Clone, Copy)]
enum WordOrder { Abcd, Cdab, Badc, Dcba }
fn f32_from(regs: &[u16], order: WordOrder) -> Option<f32> {
let [a, b, ..] = regs else { return None };
let [a_hi, a_lo] = a.to_be_bytes();
let [b_hi, b_lo] = b.to_be_bytes();
let bytes = match order {
WordOrder::Abcd => [a_hi, a_lo, b_hi, b_lo],
WordOrder::Cdab => [b_hi, b_lo, a_hi, a_lo],
WordOrder::Badc => [a_lo, a_hi, b_lo, b_hi],
WordOrder::Dcba => [b_lo, b_hi, a_lo, a_hi],
};
Some(f32::from_be_bytes(bytes))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decodes_every_word_order_and_rejects_short_reads() {
for (regs, order) in [
([0x3f80, 0x0000], WordOrder::Abcd),
([0x0000, 0x3f80], WordOrder::Cdab),
([0x803f, 0x0000], WordOrder::Badc),
([0x0000, 0x803f], WordOrder::Dcba),
] {
assert_eq!(f32_from(®s, order), Some(1.0));
}
assert_eq!(f32_from(&[], WordOrder::Abcd), None);
assert_eq!(f32_from(&[0], WordOrder::Abcd), None);
}
}
For energy meters and drives, the same problem appears on 64-bit totals: four registers, 24 possible permutations, and a documented order in a manual that nobody reads until the billing report is wrong by a factor of 65536.
Scheduling a bus with mixed response times
Real RS-485 segments contain devices that all answer at different speeds. A flow meter replies in 8 ms; a 1990s drive replies in 120 ms. If you poll them round-robin, the fast device is stuck behind the slow one and its data arrives at the slow device's rate.
The practical arrangement is to schedule by deadline rather than by rotation. Each tag carries a period, the scheduler keeps a min-heap of due times, and the owner task requests work from that heap:
- Give fast-changing values (flow, position) a 200 ms period.
- Give slow process values (temperature, tank level) a 2 s period.
- Never give anything a period shorter than its own round-trip time plus the frame gap, or the queue grows without bound.
On a 19200 baud segment a 12-register read uses 8 request bytes and 29 response bytes. At 11 bits per character that is about 21.2 ms of wire time, before device processing, turnaround and the silent interval. Even with only one 3.5-character gap, the idealised ceiling is below 44 requests per second. Measure the complete transaction on your segment — not the throughput of your CPU.
One further trap: many gateways report a communications failure by returning the last known value. That is defensible for a trend, indefensible for a control decision. Mark every value with a quality flag and a timestamp taken at the moment of the reply, and let the consumer decide whether stale data is acceptable.
Health and reconnection
The gateway will spend its life on a network where devices are switched off, cables are cut and adapters are unplugged. Three counters tell you more than any log line:
| Counter | Meaning | Action threshold |
|---|---|---|
| Timeout rate per slave | No reply within the configured window | Sustained > 1 % means a wiring or address problem |
| CRC / framing errors | Electrical noise or wrong baud/parity | Any steady rate is a fault, not a statistic |
| Exception responses | Slave rejected the request | Illegal data address usually means a wrong register map |
Expose them over your own interface — a small HTTP endpoint, MQTT, or an OPC UA node set — and alarm on rate rather than on absolute count. A single timeout after a plant-wide power dip is normal. Ten per minute on one slave is a cable.
Where this design does not belong
A gateway that owns a wire and polls on a schedule is a supervisory tool. It is not a safety function and it is not a substitute for deterministic fieldbus: safety devices belong on a certified network with a certified protocol, and interlock logic belongs in a safety controller, not in a Rust task with a timeout. If a machine's protection depends on a value arriving, the value must not travel through an application-level poll.
tokio-modbus is also the wrong layer for anything that needs sub-millisecond jitter. Modbus RTU at 19200 baud has a frame time measured in milliseconds; if your control loop needs better than that, you are using the wrong protocol, and no amount of Rust will change the wire.



