modbus-rtu
This crate provides helpers for building and decoding standard Modbus RTU request and response packets.
It now ships with a synchronous Master that can talk to a serial port directly, while still
exposing the lower-level building blocks for applications that prefer to manage framing themselves.
Usage
High-level master (auto write/read)
use ;
The master enforces the Modbus RTU silent interval (T3.5) before/after each transmission, flushes the TX buffer, reads until the slave stops talking, and automatically decodes the reply.
Async master (Tokio)
AsyncMaster ships enabled by default (feature async). You only need to wire up a Tokio runtime. Disable
async in Cargo.toml if you prefer the smaller blocking-only build.
[]
= "1.2"
= { = "1.38", = ["rt", "macros"] }
use ;
async
The async master mirrors the synchronous behavior but uses async sleeps and I/O to maintain the Modbus RTU silent interval between frames.
Queued async master (shared worker)
QueuedMaster wraps a single async worker task and an MPSC queue so multiple async callers can share
one serial link. The buffer argument is the channel depth; requests are buffered up to that limit
and passing 0 will panic inside tokio::sync::mpsc::channel.
use Duration;
use ;
async
You can clone the returned Arc<QueuedMaster> and call send from many tasks; the worker enforces
Modbus idle timing between frames and switches baud rate per request if needed.
Opting out of the master to shrink binaries
The synchronous and async masters (and their serial dependencies) are enabled by default. If you only
need the packet-building utilities, disable default features in your Cargo.toml:
[]
= { = "1.2", = false }
Then opt into what you need:
- Blocking master only (drops Tokio/async deps):
= { = "1.2", = false, = ["master"] } - Both masters (default behavior):
= { = "1.2", = false, = ["master", "async"] }
Manual packet construction
First, construct the function you want to issue.
The following example reads four input registers starting at address 0x1234.
use Function;
let starting_address: u16 = 0x1234;
let quantity: usize = 4;
let function = ReadInputRegisters ;
Next, build the request with the target device information and timeout.
use ;
...
let modbus_id: u8 = 1;
let timeout: Duration = from_millis;
let request = new;
Finally, convert the request into a Modbus RTU frame.
...
let packet: = request.to_bytes.expect;
You can now write packet through any transport of your choice (UART, TCP tunnel, etc.).
Receiving
With the original request available, attempt to decode the response bytes as shown below.
use Response;
...
let bytes: & = ... ; // user-implemented receive logic
let response = from_bytes.expect;
match response
If you disable default features, re-enable both master and async to access AsyncMaster.