Expand description
§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 madbus::{Client, Command};
use std::net::TcpStream;
let mut stream = TcpStream::connect("127.0.0.1:502").unwrap();
let cmd = Command::ReadHolding {
start: 0,
count: 5
};
Client::send_request(&mut stream, cmd, 1).unwrap();Read the response:
let (response, unit_id, transaction_id) =
Client::read_response(&mut stream).unwrap();
println!("{:?}", response);§Server Example
Reading a request from a client:
use madbus::Server;
let (command, unit_id, transaction_id) =
Server::read_request(&mut stream).unwrap();Sending a response:
use madbus::Response;
let response = Response::read_holding(&[10, 20, 30]);
Server::send_resp(&mut stream, response, unit_id, transaction_id).unwrap();Sending an exception:
use madbus::Exception;
Server::send_exception(
&mut stream,
Exception::IllegalAddress,
3,
unit_id,
transaction_id
).unwrap();§Testing
cargo test§License
MIT
Structs§
- Client
- It is a master unit, whoever thought of calling it Client/Server instead of Master/Slave should burn in hell
- Server
- It is a slave unit, whoever thought of calling it Client/Server instead of Master/Slave should burn in hell