voltage_modbus 0.4.4

A high-performance industrial Modbus library for Rust with TCP and RTU support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# Voltage Modbus

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Rust](https://img.shields.io/badge/rust-1.70+-blue.svg)](https://www.rust-lang.org)
[![GitHub](https://img.shields.io/badge/github-voltage_modbus-blue.svg)](https://github.com/EvanL1/voltage_modbus)
[![Crates.io](https://img.shields.io/crates/v/voltage_modbus.svg)](https://crates.io/crates/voltage_modbus)
[![docs.rs](https://docs.rs/voltage_modbus/badge.svg)](https://docs.rs/voltage_modbus)

> **High-Performance Modbus TCP/RTU/ASCII Library for Rust**
>
> **Author:** Evan Liu <liuyifanz.1996@gmail.com>
> **Version:** 0.4.3
> **License:** MIT

A comprehensive, high-performance Modbus TCP/RTU/ASCII implementation in pure Rust designed for industrial automation, IoT applications, and smart grid systems.

## โœจ Features

- **๐Ÿš€ High Performance**: Async/await support with Tokio for maximum throughput
- **๐Ÿ”ง Complete Protocol Support**: Modbus TCP, RTU, and ASCII protocols
- **๐Ÿ›ก๏ธ Memory Safe**: Pure Rust implementation with zero unsafe code
- **โšก Zero-Copy Operations**: Optimized for minimal memory allocations
- **๐Ÿ”„ Concurrent Processing**: Multi-client server support
- **๐Ÿ“Š Built-in Monitoring**: Comprehensive statistics and metrics
- **๐Ÿญ Production Ready**: Extensive testing and error handling
- **๐ŸŽฏ Smart Architecture**: Generic client design eliminates code duplication
- **๐Ÿงฉ Modular Design**: Clean separation of transport and application layers

## ๐Ÿญ Use Cases

This library is being used in production for:

| Category | Examples |
|----------|----------|
| **Energy Monitoring** | Smart electricity meters, power analyzers, energy management systems |
| **Solar/PV Systems** | Inverter monitoring, MPPT controllers, solar charge controllers |
| **Battery Systems** | BMS monitoring (SOC, temperature, cell voltages), UPS systems |
| **Industrial Control** | PLCs (Siemens, Allen-Bradley, Schneider), VFDs, motor controllers |
| **HVAC & Building** | Chillers, air handlers, environmental sensors, lighting control |
| **Utilities** | Water treatment plants, pump stations, flow meters, tank level monitoring |

> ๐Ÿ’ก *Using voltage_modbus in your project? [Share your use case]https://github.com/EvanL1/voltage_modbus/discussions - we'd love to hear from you!*

## ๐Ÿ“‹ Supported Function Codes

| Code | Function                 | Client | Server |
| ---- | ------------------------ | ------ | ------ |
| 0x01 | Read Coils               | โœ…     | ๐Ÿšง     |
| 0x02 | Read Discrete Inputs     | โœ…     | ๐Ÿšง     |
| 0x03 | Read Holding Registers   | โœ…     | ๐Ÿšง     |
| 0x04 | Read Input Registers     | โœ…     | ๐Ÿšง     |
| 0x05 | Write Single Coil        | โœ…     | ๐Ÿšง     |
| 0x06 | Write Single Register    | โœ…     | ๐Ÿšง     |
| 0x0F | Write Multiple Coils     | โœ…     | ๐Ÿšง     |
| 0x10 | Write Multiple Registers | โœ…     | ๐Ÿšง     |

> ๐Ÿšง Server functionality is planned for a future release.

## ๐Ÿš€ Quick Start

Add this to your `Cargo.toml`:

```toml
[dependencies]
voltage_modbus = "0.4.3"
# Note: tokio is re-exported by voltage_modbus, you can use voltage_modbus::tokio
```

### Client Examples

#### TCP Client

```rust
use voltage_modbus::{ModbusTcpClient, ModbusClient, ModbusResult};
use std::time::Duration;

#[tokio::main]
async fn main() -> ModbusResult<()> {
    // Connect to Modbus TCP server
    let mut client = ModbusTcpClient::from_address("127.0.0.1:502", Duration::from_secs(5)).await?;

    // Read holding registers (using function code name)
    let values = client.read_03(1, 0, 10).await?;
    println!("Read registers: {:?}", values);

    // Or use semantic name (alias)
    let values = client.read_holding_registers(1, 0, 10).await?;

    // Write single register
    client.write_06(1, 100, 0x1234).await?;

    client.close().await?;
    Ok(())
}
```

#### RTU Client

> โš ๏ธ **RTU Feature Required**: To use RTU (serial) support, enable the `rtu` feature:
> ```toml
> voltage_modbus = { version = "0.4.2", features = ["rtu"] }
> ```

```rust
use voltage_modbus::{ModbusRtuClient, ModbusClient, ModbusResult};

#[tokio::main]
async fn main() -> ModbusResult<()> {
    // Connect to Modbus RTU device
    let mut client = ModbusRtuClient::new("/dev/ttyUSB0", 9600)?;

    // Read coils
    let coils = client.read_01(1, 0, 8).await?;
    println!("Read coils: {:?}", coils);

    client.close().await?;
    Ok(())
}
```

### Server Example

> โš ๏ธ **Note**: Server functionality is not included in this release. The example below is for reference only and will be available in a future version.

```rust
use voltage_modbus::{
    ModbusTcpServer, ModbusTcpServerConfig, ModbusServer, ModbusRegisterBank
};
use std::sync::Arc;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create server configuration
    let config = ModbusTcpServerConfig {
        bind_address: "127.0.0.1:502".parse().unwrap(),
        max_connections: 50,
        request_timeout: Duration::from_secs(30),
        register_bank: Some(Arc::new(ModbusRegisterBank::new())),
    };

    // Start server
    let mut server = ModbusTcpServer::with_config(config)?;
    server.start().await?;

    // Server is now running...
    Ok(())
}
```

## ๐Ÿ“– Documentation

- **[API Reference]https://docs.rs/voltage_modbus** - Complete API documentation
- **[Crates.io]https://crates.io/crates/voltage_modbus** - Package information
- **[GitHub Repository]https://github.com/EvanL1/voltage_modbus** - Source code and issues

## ๐Ÿ—๏ธ Architecture

### Protocol Layer Insight

The library implements a key architectural insight: **Modbus TCP and RTU share identical application layer messages (PDU)**, differing only in transport encapsulation:

```text
TCP Frame: [MBAP Header (7 bytes)] + [PDU (Function Code + Data)]
RTU Frame: [Slave ID (1 byte)] + [PDU (Function Code + Data)] + [CRC (2 bytes)]
```

This enables code reuse through a generic client design:

```text
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    Application Layer                        โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                โ”‚
โ”‚  โ”‚ ModbusTcpClient โ”‚    โ”‚ ModbusRtuClient โ”‚                โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                โ”‚
โ”‚           โ”‚                       โ”‚                        โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”‚
โ”‚  โ”‚           GenericModbusClient<T>                        โ”‚โ”‚
โ”‚  โ”‚         (Shared Application Logic)                      โ”‚โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                          โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                   Transport Layer                           โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                โ”‚
โ”‚  โ”‚   TcpTransport  โ”‚    โ”‚   RtuTransport  โ”‚                โ”‚
โ”‚  โ”‚  (TCP Sockets)  โ”‚    โ”‚ (Serial Ports)  โ”‚                โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

### Core Modules

- **`error`** - Error types and result handling
- **`protocol`** - Modbus protocol definitions and message handling  
- **`transport`** - Network transport layer for TCP, RTU, and ASCII communication
- **`client`** - Generic and protocol-specific client implementations
- **`server`** - Modbus server implementations with concurrent support
- **`register_bank`** - Thread-safe register storage for server applications
- **`utils`** - Utility functions, data conversion, and performance monitoring

## ๐Ÿงช Examples and Testing

### Run Examples

```bash
# Start the demo server
cargo run --bin server_demo

# Run TCP client demo
cargo run --bin demo

# Test RTU functionality
cargo run --bin rtu_test

# Run performance benchmarks
cargo run --bin performance_test

# Test all function codes
cargo run --bin full_function_test
```

### Test Coverage

```bash
# Run all tests
cargo test

# Run with output
cargo test -- --nocapture

# Integration tests
cargo test --test integration_tests

# Documentation tests
cargo test --doc
```

**Test Results:**
- โœ… 34 unit tests passed
- โœ… 9 integration tests passed  
- โœ… 22 documentation tests passed
- โœ… All Modbus function codes tested
- โœ… Error handling and recovery tested
- โœ… Concurrent client connections tested

## ๐Ÿ“ˆ Performance

### Benchmarks

| Metric                     | Value              |
| -------------------------- | ------------------ |
| **Latency**                | < 1ms (local)      |
| **Throughput**             | 1000+ requests/sec |
| **Concurrent Connections** | 50+ clients        |
| **Memory Usage**           | < 10MB (baseline)  |
| **CPU Usage**              | < 5% (idle)        |

### Optimization Features

- **Async I/O**: Non-blocking operations with Tokio
- **Zero-Copy Operations**: Minimal memory allocations
- **Generic Architecture**: Code reuse eliminates duplication
- **Lock-Free Operations**: Where possible
- **Configurable Timeouts**: Adaptive timeout management

## ๐Ÿ”ง Configuration

### Advanced Client Configuration

```rust
use voltage_modbus::{ModbusTcpClient, ModbusRtuClient};
use std::time::Duration;

// TCP with custom timeout
let mut tcp_client = ModbusTcpClient::with_timeout(
    "192.168.1.100:502", 
    Duration::from_secs(10)
).await?;

// RTU with full configuration
let mut rtu_client = ModbusRtuClient::with_config(
    "/dev/ttyUSB0",
    9600,                                // Baud rate
    tokio_serial::DataBits::Eight,      // Data bits
    tokio_serial::StopBits::One,        // Stop bits  
    tokio_serial::Parity::None,         // Parity
    Duration::from_secs(1),             // Timeout
)?;
```

### Server Configuration

> โš ๏ธ **Note**: Server functionality is planned for a future release.

```rust
use voltage_modbus::{ModbusTcpServerConfig, ModbusRegisterBank};
use std::sync::Arc;

let config = ModbusTcpServerConfig {
    bind_address: "0.0.0.0:502".parse().unwrap(),
    max_connections: 100,
    request_timeout: Duration::from_secs(30),
    register_bank: Some(Arc::new(ModbusRegisterBank::with_sizes(
        10000, // coils
        10000, // discrete_inputs
        10000, // holding_registers
        10000, // input_registers
    ))),
};
```

## ๐Ÿ› ๏ธ Development

### Building from Source

```bash
git clone https://github.com/EvanL1/voltage_modbus.git
cd voltage-modbus
cargo build --release
```

### Development Tools

```bash
# Check code
cargo check

# Format code
cargo fmt

# Run linter
cargo clippy

# Generate documentation
cargo doc --no-deps --open
```

## ๐Ÿš€ Installation

### From Crates.io

```bash
cargo add voltage_modbus
```

### From Source

```bash
git clone https://github.com/EvanL1/voltage_modbus.git
cd voltage-modbus
cargo install --path .
```

## ๐Ÿค Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

1. **Clone the repository**
2. **Install Rust** (latest stable)
3. **Install dependencies**: `cargo build`
4. **Run tests**: `cargo test`
5. **Check formatting**: `cargo fmt --check`
6. **Run linter**: `cargo clippy`

## ๐Ÿ“ Changelog

See [CHANGELOG.md](CHANGELOG.md) for detailed release notes.

### v0.4.0 - Industrial Enhancement

- ๐Ÿญ **Industrial Data Types**: New `ModbusValue` enum supporting U16/I16/U32/I32/F32/F64/Bool/String
- ๐Ÿ”„ **Byte Order Support**: `ByteOrder` with BigEndian/LittleEndian/BigEndianSwap/LittleEndianSwap
- ๐Ÿ“ฆ **ModbusCodec**: Unified encoding/decoding for all industrial data types
- โšก **CommandBatcher**: Write command batching for optimized communication
- ๐ŸŽ›๏ธ **DeviceLimits**: Configurable protocol limits per device
- ๐Ÿงฑ **Stack-allocated PDU**: Fixed 253-byte array with zero heap allocation
- ๐ŸŽฏ **Simplified API**: Function code naming (`read_03`, `write_06`, etc.)
- ๐Ÿ“Š **CallbackLogger**: Flexible logging system with callback support
- ๐Ÿ“ˆ **PerformanceMetrics**: Built-in performance monitoring
- ๐Ÿšง **Server**: Temporarily not included (planned for future release)

### v0.3.1

- ๐Ÿ› Bug fixes and stability improvements

### v0.2.0

- โœจ **Generic Client Architecture**: Eliminated code duplication between TCP/RTU clients
- ๐ŸŽฏ **Improved API**: Cleaner, more intuitive client interfaces
- ๐Ÿ”ง **Enhanced RTU Support**: Full RTU client implementation
- ๐Ÿ“Š **Better Testing**: Comprehensive test coverage
- ๐Ÿ—๏ธ **Architectural Refinement**: Clean separation of transport and application layers

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

- **Modbus Organization** for the protocol specification
- **Tokio Team** for the excellent async runtime
- **Rust Community** for the amazing ecosystem

## ๐Ÿ“ž Support

- **Documentation**: https://docs.rs/voltage_modbus
- **Package**: https://crates.io/crates/voltage_modbus
- **Issues**: https://github.com/EvanL1/voltage_modbus/issues
- **Discussions**: https://github.com/EvanL1/voltage_modbus/discussions
- **Email**: liuyifanz.1996@gmail.com

---

**Built with โค๏ธ by Evan Liu for the Rust and Industrial Automation communities.**