Madbus
A Rust library for Modbus TCP communication.
It provides simple APIs for building both Modbus clients (masters) and servers (slaves) with automatic encoding/decoding of Modbus TCP frames.
Features
- Modbus TCP Client and Server utilities
- Automatic MBAP header handling
- Encoding/decoding of Modbus ADU/PDU
- Built-in exception handling
- Helper utilities for bit packing/unpacking
- Supports common Modbus function codes:
0x01Read Coils0x02Read Discrete Inputs0x03Read Holding Registers0x04Read Input Registers0x05Write Single Coil0x06Write Single Register0x0FWrite Multiple Coils0x10Write Multiple Registers
Project Structure
src/
├── main.rs # Client/Server implementation and ADU handling
├── function_codes.rs # Commands and responses
├── exception_codes.rs # Modbus exception definitions
└── helpers.rs # Utility helpers
Usage
Client Example
Send a request to a Modbus device:
use ;
use TcpStream;
let mut stream = connect.unwrap;
let cmd = ReadHolding ;
send_request.unwrap;
Read the response:
let =
read_response.unwrap;
println!;
Server Example
Reading a request from a client:
use Server;
let =
read_request.unwrap;
Sending a response:
use Response;
let response = read_holding;
send_resp.unwrap;
Sending an exception:
use Exception;
send_exception.unwrap;
Testing
cargo test
License
MIT