modbus-impl 0.6.0

A small `no_std` Modbus RTU helper library designed to run on embedded Rust targets
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
#![no_std]
/// RegisterRead:支持 is_valid(addr) 用于越界检查
/// 支持03/04寄存器的读取(Hreg/Ireg)
pub trait RegisterRead {
    fn get(&self, addr: u16) -> u16;
    fn is_valid(&self, addr: u16) -> bool;
}

/// 用于 FC06 写单保持寄存器
pub trait RegisterWrite {
    fn set_reg(&mut self, addr: u16, val: u16);
}

/// 支持 01/02 的位读取(Coil/ISTS)
pub trait BitRead {
    fn get(&self, addr: u16) -> bool;
    fn is_valid(&self, addr: u16) -> bool;
}

/// 用于 FC05 写单线圈
pub trait BitWrite {
    fn set_bit(&mut self, addr: u16, val: bool);
}

/// Coil 结构体(FC01)
pub struct Coil<const N: usize> {
    regs: [bool; N],
}
impl<const N: usize> Coil<N> {
    pub const fn new() -> Self {
        Self { regs: [false; N] }
    }
    pub fn set_bit(&mut self, addr: u16, val: bool) {
        let i = addr as usize;
        if i < N {
            self.regs[i] = val;
        }
    }
    pub fn as_bits(&self) -> &[bool] {
        &self.regs
    }
}

impl<const N: usize> BitRead for Coil<N> {
    fn get(&self, addr: u16) -> bool {
        let i = addr as usize;
        if i < N {
            self.regs[i]
        } else {
            false
        }
    }
    fn is_valid(&self, addr: u16) -> bool {
        (addr as usize) < N
    }
}

impl<const N: usize> BitWrite for Coil<N> {
    fn set_bit(&mut self, addr: u16, val: bool) {
        Coil::set_bit(self, addr, val);
    }
}

/// ISTS(离散输入)结构体(FC02)
pub struct Ists<const N: usize> {
    regs: [bool; N],
}
impl<const N: usize> Ists<N> {
    pub const fn new() -> Self {
        Self { regs: [false; N] }
    }
    pub fn set_bit(&mut self, addr: u16, val: bool) {
        let i = addr as usize;
        if i < N {
            self.regs[i] = val;
        }
    }
}
impl<const N: usize> BitRead for Ists<N> {
    fn get(&self, addr: u16) -> bool {
        let i = addr as usize;
        if i < N {
            self.regs[i]
        } else {
            false
        }
    }
    fn is_valid(&self, addr: u16) -> bool {
        (addr as usize) < N
    }
}

/// IREG(输入寄存器)结构体(FC04)
pub struct Ireg<const N: usize> {
    regs: [u16; N],
}
impl<const N: usize> Ireg<N> {
    pub const fn new() -> Self {
        Self { regs: [0; N] }
    }
    pub fn set(&mut self, addr: u16, val: u16) {
        let i = addr as usize;
        if i < N {
            self.regs[i] = val;
        }
    }
}
impl<const N: usize> RegisterRead for Ireg<N> {
    fn get(&self, addr: u16) -> u16 {
        let i = addr as usize;
        if i < N {
            self.regs[i]
        } else {
            0
        }
    }
    fn is_valid(&self, addr: u16) -> bool {
        (addr as usize) < N
    }
}

///HREG(保持寄存器)结构体(FC03)
pub struct Hreg<const N: usize> {
    regs: [u16; N],
}

impl<const N: usize> Hreg<N> {
    pub const fn new() -> Self {
        Self { regs: [0; N] }
    }

    pub fn set(&mut self, addr: u16, val: u16) {
        let i = addr as usize;
        if i < N {
            self.regs[i] = val;
        }
    }

    pub fn as_slice(&self) -> &[u16] {
        &self.regs
    }
}

// RegisterRead 实现:提供 get + is_valid
impl<const N: usize> RegisterRead for Hreg<N> {
    fn get(&self, addr: u16) -> u16 {
        let i = addr as usize;
        if i < N {
            self.regs[i]
        } else {
            0
        }
    }
    fn is_valid(&self, addr: u16) -> bool {
        (addr as usize) < N
    }
}

impl<const N: usize> RegisterWrite for Hreg<N> {
    fn set_reg(&mut self, addr: u16, val: u16) {
        Hreg::set(self, addr, val);
    }
}

///////////////////////////////////////////////////////////////////////////////
// 2) random(start_val, end_val)  —— no_std 伪随机
///////////////////////////////////////////////////////////////////////////////

// xorshift32 seed:单线程场景足够用
static mut SEED: u32 = 0x1234_5678;

#[inline]
fn xorshift32_next() -> u32 {
    // SAFETY: 单线程典型嵌入式用法;如需多核/中断并发请告诉我再改为更安全的方案
    unsafe {
        let mut x = SEED;
        x ^= x << 13;
        x ^= x >> 17;
        x ^= x << 5;
        SEED = x;
        x
    }
}

/// 生成闭区间 [min(start_val,end_val), max(...)] 内的随机 u16
pub fn random(start_val: u16, end_val: u16) -> u16 {
    let (lo, hi) = if start_val <= end_val {
        (start_val, end_val)
    } else {
        (end_val, start_val)
    };

    let span = (hi as u32).wrapping_sub(lo as u32).wrapping_add(1);
    let r = xorshift32_next() % span;
    (lo as u32 + r) as u16
}

#[derive(Clone, Copy, Debug)]
pub struct Req03 {
    pub unit_id: u8,
    pub start_addr: u16,
    pub quantity: u16,
}

pub mod exc {
    pub const ILLEGAL_FUNCTION: u8 = 0x01;
    pub const ILLEGAL_DATA_ADDRESS: u8 = 0x02;
    pub const ILLEGAL_DATA_VALUE: u8 = 0x03;
}

/// Modbus RTU CRC16,用于生成CRC16验证码
pub fn crc16_modbus(data: &[u8]) -> u16 {
    let mut crc: u16 = 0xFFFF;
    for &b in data {
        crc ^= b as u16;
        for _ in 0..8 {
            if (crc & 0x0001) != 0 {
                crc = (crc >> 1) ^ 0xA001;
            } else {
                crc >>= 1;
            }
        }
    }
    crc
}

/// 组装 FC01 / FC02 响应:
/*
  Unit(1) + Func(1) + ByteCount(1) + PackedBits(N) + CRC(2)

  packed bits:Modbus 规定每字节 bit0 是第一个位(LSB-first)
*/
pub fn build_resp_bit_reads<const MAX_QTY: usize, B: BitRead>(
    out: &mut [u8],
    unit_id: u8,
    func: u8, // 0x01 or 0x02
    start_addr: u16,
    quantity: u16,
    bits: &B,
) -> usize {
    let qty = quantity as usize;
    let byte_cnt = (qty + 7) / 8;

    out[0] = unit_id;
    out[1] = func;
    out[2] = byte_cnt as u8;

    // 清零位区
    for i in 0..byte_cnt {
        out[3 + i] = 0;
    }

    for j in 0..qty {
        let addr = start_addr.wrapping_add(j as u16);
        let bit = bits.get(addr);
        if bit {
            let byte_i = j / 8;
            let bit_i = j % 8;
            out[3 + byte_i] |= 1u8 << bit_i; // LSB-first
        }
    }

    let body_len = 3 + byte_cnt;
    let crc = crc16_modbus(&out[..body_len]);
    out[body_len] = (crc & 0xFF) as u8;
    out[body_len + 1] = (crc >> 8) as u8;
    body_len + 2
}

/// 组装异常响应:Function=03|0x80 + ExceptionCode(1) + CRC(2)
pub fn build_exception_resp<const BUF: usize>(
    out: &mut [u8; BUF],
    unit_id: u8,
    function_exception: u8, // 例如 0x83
    exception_code: u8,
) -> usize {
    out[0] = unit_id;
    out[1] = function_exception;
    out[2] = exception_code;

    let crc = crc16_modbus(&out[..3]);
    out[3] = (crc & 0xFF) as u8;
    out[4] = (crc >> 8) as u8;
    5
}

///ModbusCtx,用于沟通上下文
pub struct ModbusCtx<'a, H, I, C, D> {
    pub holdings: &'a mut H, // FC03
    pub inputs: &'a mut I,   // FC04
    pub coils: &'a mut C,    // FC01
    pub ists: &'a mut D,     // FC02
}

impl<'a, H, I, C, D> ModbusCtx<'a, H, I, C, D>
where
    H: RegisterRead + RegisterWrite,
    I: RegisterRead,
    C: BitRead + BitWrite,
    D: BitRead,
{
    /// pharse_pdu: 解析固定 8 字节 Modbus RTU 请求,并组装响应/异常
    /// 返回值:
    /// - 正常响应:返回 out_tx 中的长度
    /// - 异常响应:写入 out_exc,并返回 5
    pub fn pharse_pdu<const MAX_QTY: usize>(
        &mut self,
        req8: &[u8; 8],
        out_tx: &mut [u8],
        out_exc: &mut [u8; 5],
    ) -> usize {
        let unit_id = req8[0];
        let func = req8[1];

        // -------- CRC check --------
        let expected_crc = u16::from_le_bytes([req8[6], req8[7]]);
        let calc_crc = crc16_modbus(&req8[..6]);
        if expected_crc != calc_crc {
            // CRC 错:返回 ILLEGAL_DATA_VALUE,功能码用请求 func|0x80
            return build_exception_resp_fixed::<5>(
                out_exc,
                unit_id,
                func | 0x80,
                exc::ILLEGAL_DATA_VALUE,
            );
        }

        // -------- common fields --------
        let start_addr = u16::from_be_bytes([req8[2], req8[3]]);
        let quantity = u16::from_be_bytes([req8[4], req8[5]]);

        match func {
            0x01 => {
                // quantity 校验
                if quantity == 0 || (quantity as usize) > MAX_QTY {
                    return build_exception_resp_fixed::<5>(
                        out_exc,
                        unit_id,
                        func | 0x80,
                        exc::ILLEGAL_DATA_VALUE,
                    );
                }
                // FC01 Read Coils
                let end = start_addr.wrapping_add(quantity.saturating_sub(1));
                if !self.coils.is_valid(start_addr) || !self.coils.is_valid(end) {
                    return build_exception_resp_fixed::<5>(
                        out_exc,
                        unit_id,
                        func | 0x80,
                        exc::ILLEGAL_DATA_ADDRESS,
                    );
                }
                build_resp_bit_reads::<MAX_QTY, _>(
                    out_tx, unit_id, 0x01, start_addr, quantity, self.coils,
                )
            }

            0x02 => {
                // quantity 校验
                if quantity == 0 || (quantity as usize) > MAX_QTY {
                    return build_exception_resp_fixed::<5>(
                        out_exc,
                        unit_id,
                        func | 0x80,
                        exc::ILLEGAL_DATA_VALUE,
                    );
                }
                // FC02 Read Discrete Inputs
                let end = start_addr.wrapping_add(quantity.saturating_sub(1));
                if !self.ists.is_valid(start_addr) || !self.ists.is_valid(end) {
                    return build_exception_resp_fixed::<5>(
                        out_exc,
                        unit_id,
                        func | 0x80,
                        exc::ILLEGAL_DATA_ADDRESS,
                    );
                }
                build_resp_bit_reads::<MAX_QTY, _>(
                    out_tx, unit_id, 0x02, start_addr, quantity, self.ists,
                )
            }

            0x03 => {
                // quantity 校验
                if quantity == 0 || (quantity as usize) > MAX_QTY {
                    return build_exception_resp_fixed::<5>(
                        out_exc,
                        unit_id,
                        func | 0x80,
                        exc::ILLEGAL_DATA_VALUE,
                    );
                }
                // FC03 Read Holding Registers
                let end = start_addr.wrapping_add(quantity.saturating_sub(1));
                if !self.holdings.is_valid(start_addr) || !self.holdings.is_valid(end) {
                    return build_exception_resp_fixed::<5>(
                        out_exc,
                        unit_id,
                        func | 0x80,
                        exc::ILLEGAL_DATA_ADDRESS,
                    );
                }
                build_resp_regs::<MAX_QTY, _>(
                    out_tx,
                    unit_id,
                    0x03,
                    start_addr,
                    quantity,
                    self.holdings,
                )
            }

            0x04 => {
                // quantity 校验
                if quantity == 0 || (quantity as usize) > MAX_QTY {
                    return build_exception_resp_fixed::<5>(
                        out_exc,
                        unit_id,
                        func | 0x80,
                        exc::ILLEGAL_DATA_VALUE,
                    );
                }
                // FC04 Read Input Registers
                let end = start_addr.wrapping_add(quantity.saturating_sub(1));
                if !self.inputs.is_valid(start_addr) || !self.inputs.is_valid(end) {
                    return build_exception_resp_fixed::<5>(
                        out_exc,
                        unit_id,
                        func | 0x80,
                        exc::ILLEGAL_DATA_ADDRESS,
                    );
                }
                build_resp_regs::<MAX_QTY, _>(
                    out_tx,
                    unit_id,
                    0x04,
                    start_addr,
                    quantity,
                    self.inputs,
                )
            }

            0x05 => {
                // FC05: addr=start_addr, value=quantity(0xFF00/0x0000)
                let coil_value = quantity;

                let bit = match coil_value {
                    0xFF00 => true,
                    0x0000 => false,
                    _ => {
                        return build_exception_resp_fixed::<5>(
                            out_exc,
                            unit_id,
                            0x05 | 0x80,
                            exc::ILLEGAL_DATA_VALUE,
                        );
                    }
                };

                if !self.coils.is_valid(start_addr) {
                    return build_exception_resp_fixed::<5>(
                        out_exc,
                        unit_id,
                        0x05 | 0x80,
                        exc::ILLEGAL_DATA_ADDRESS,
                    );
                }

                self.coils.set_bit(start_addr, bit);

                // 正常响应:回显请求前6字节 + CRC
                out_tx[0] = unit_id;
                out_tx[1] = 0x05;
                out_tx[2] = (start_addr >> 8) as u8;
                out_tx[3] = (start_addr & 0xFF) as u8;
                out_tx[4] = (coil_value >> 8) as u8;
                out_tx[5] = (coil_value & 0xFF) as u8;

                let crc = crc16_modbus(&out_tx[..6]);
                out_tx[6] = (crc & 0xFF) as u8;
                out_tx[7] = (crc >> 8) as u8;
                8
            }

            0x06 => {
                // FC06: 写单保持寄存器:addr=start_addr, value=quantity(任意 u16)
                let reg_value = quantity;

                if !self.holdings.is_valid(start_addr) {
                    return build_exception_resp_fixed::<5>(
                        out_exc,
                        unit_id,
                        0x06 | 0x80,
                        exc::ILLEGAL_DATA_ADDRESS,
                    );
                }

                self.holdings.set_reg(start_addr, reg_value);

                // 正常响应:回显请求前6字节 + CRC
                out_tx[0] = unit_id;
                out_tx[1] = 0x06;
                out_tx[2] = (start_addr >> 8) as u8;
                out_tx[3] = (start_addr & 0xFF) as u8;
                out_tx[4] = (reg_value >> 8) as u8;
                out_tx[5] = (reg_value & 0xFF) as u8;

                let crc = crc16_modbus(&out_tx[..6]);
                out_tx[6] = (crc & 0xFF) as u8;
                out_tx[7] = (crc >> 8) as u8;
                8
            }

            _ => {
                // 不支持功能码
                build_exception_resp_fixed::<5>(
                    out_exc,
                    unit_id,
                    func | 0x80,
                    exc::ILLEGAL_FUNCTION,
                )
            }
        }
    }
}

// ---------------- helper:异常帧(固定 5 字节) ----------------
fn build_exception_resp_fixed<const BUF: usize>(
    out_exc: &mut [u8; 5],
    unit_id: u8,
    function_exception: u8,
    exception_code: u8,
) -> usize {
    out_exc[0] = unit_id;
    out_exc[1] = function_exception;
    out_exc[2] = exception_code;

    let crc = crc16_modbus(&out_exc[..3]);
    out_exc[3] = (crc & 0xFF) as u8;
    out_exc[4] = (crc >> 8) as u8;
    5
}
// ---------------- helper:reg 读取响应(FC03/FC04) ----------------
// out_tx 需要至少 >= 3 + MAX_QTY*2 + 2
fn build_resp_regs<const MAX_QTY: usize, R: RegisterRead>(
    out_tx: &mut [u8],
    unit_id: u8,
    func: u8,
    start_addr: u16,
    quantity: u16,
    regs: &R,
) -> usize {
    let qty = quantity as usize;

    out_tx[0] = unit_id;
    out_tx[1] = func;
    out_tx[2] = (qty as u8) * 2;

    for i in 0..qty {
        let addr = start_addr.wrapping_add(i as u16);
        let v = regs.get(addr);
        let base = 3 + i * 2;
        out_tx[base] = (v >> 8) as u8;
        out_tx[base + 1] = (v & 0xFF) as u8;
    }

    let body_len = 3 + qty * 2;
    let crc = crc16_modbus(&out_tx[..body_len]);
    out_tx[body_len] = (crc & 0xFF) as u8;
    out_tx[body_len + 1] = (crc >> 8) as u8;

    body_len + 2
}