oms-modbus 0.2.0

[Preview] High-performance, transport-generic Modbus library. Full Master (client) and Slave (server) for TCP, RTU, ASCII — unified API, passive bus monitoring, spec-compliant timing.
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
// SPDX-License-Identifier: MIT OR Apache-2.0
//!
//! Modbus frame types — Request, Response, Exception, FunctionCode.

use std::borrow::Cow;
use std::convert::TryFrom;
use std::io::{Error, ErrorKind};

use bytes::{Buf, BufMut, Bytes, BytesMut};
use thiserror::Error;

/// Maximum PDU size per MODBUS Application Protocol V1.1b3 §4.1.
/// The PDU is function_code (1 byte) + data (max 252 bytes) = 253 bytes.
pub const MAX_PDU_SIZE: usize = 253;

/// Maximum number of coils per request per MODBUS Application Protocol V1.1b3.
/// Functions: ReadCoils (FC=1), WriteMultipleCoils (FC=15).
pub const MAX_COILS: u16 = 2000;

/// Maximum number of registers per request per MODBUS Application Protocol V1.1b3.
/// Functions: ReadHoldingRegisters (FC=3), ReadInputRegisters (FC=4),
/// WriteMultipleRegisters (FC=16), ReadWriteMultipleRegisters (FC=23).
pub const MAX_REGISTERS: u16 = 125;

/// Safe conversion from `usize` to `u8`, returning an error on overflow.
/// Used for byte-count fields in Modbus frames where counts must fit in u8.
#[inline]
fn safe_u8(val: usize, context: &str) -> Result<u8, Error> {
    u8::try_from(val).map_err(|_| {
        Error::new(
            ErrorKind::InvalidData,
            format!("{context}: value {val} exceeds u8 range"),
        )
    })
}

/// Validate that a response's payload size will fit within the Modbus PDU limit.
/// Called by `encode_response_into` before encoding to catch oversized payloads.
fn validate_response_size(rsp: &Response) -> Result<(), Error> {
    let byte_count = match rsp {
        Response::ReadCoils(bits) | Response::ReadDiscreteInputs(bits) => bits.len().div_ceil(8),
        Response::ReadHoldingRegisters(regs)
        | Response::ReadInputRegisters(regs)
        | Response::ReadWriteMultipleRegisters(regs) => regs
            .len()
            .checked_mul(2)
            .ok_or_else(|| Error::new(ErrorKind::InvalidData, "response too large"))?,
        _ => return Ok(()), // fixed-size responses always fit
    };
    safe_u8(byte_count, "response byte count")?;
    Ok(())
}

// ── Function Code ─────────────────────────────────────────────────────────

/// Modbus function code (1-127 for standard, 128-255 for exception responses).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FunctionCode(u8);

impl FunctionCode {
    #[inline]
    pub const fn new(value: u8) -> Self {
        Self(value)
    }
    #[inline]
    pub const fn value(self) -> u8 {
        self.0
    }
}

/// Returns `true` if `b` is a known Modbus function code or its exception
/// variant (standard FC + 0x80). Used by server-side frame parsers to
/// distinguish valid frames from noise on the wire.
///
/// Known standard function codes: 1–6, 8, 15, 16, 22, 23.
/// Exception variants: standard + 0x80 (bit 7 set).
#[inline]
pub(crate) fn is_known_function_code(b: u8) -> bool {
    // Strip exception bit (bit 7) and check standard range.
    let base = b & 0x7F;
    matches!(base, 1..=6 | 8 | 15 | 16 | 22 | 23)
}

// ── Address & Quantity ────────────────────────────────────────────────────

/// Modbus register/coil address (0–65535, 0-based per spec).
pub type Address = u16;
/// Number of registers or coils to read/write.
pub type Quantity = u16;

// ── Request ───────────────────────────────────────────────────────────────

/// A Modbus request PDU — one variant per standard function code.
///
/// Use [`Request::function_code`] to get the numeric FC, and
/// [`encode_request_into`] or [`TryFrom`]`<`[`Bytes`]`>` to serialize.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Request<'a> {
    ReadCoils(Address, Quantity),
    ReadDiscreteInputs(Address, Quantity),
    ReadHoldingRegisters(Address, Quantity),
    ReadInputRegisters(Address, Quantity),
    WriteSingleCoil(Address, bool),
    WriteSingleRegister(Address, u16),
    WriteMultipleCoils(Address, Cow<'a, [bool]>),
    WriteMultipleRegisters(Address, Cow<'a, [u16]>),
    ReadWriteMultipleRegisters(Address, Quantity, Address, Cow<'a, [u16]>),
    MaskWriteRegister(Address, u16, u16),
    /// Diagnostic (FC 08). First `u16` is sub-function code (e.g. 0x0000 =
    /// Return Query Data, 0x000A = Clear Counters, 0x000B-0x000E = counter
    /// reads). Second `u16` is the data field.
    Diagnostic(u16, u16),
    Disconnect,
}

impl Request<'_> {
    /// The Modbus function code for this request variant.
    pub const fn function_code(&self) -> FunctionCode {
        use Request::*;
        match self {
            ReadCoils(..) => FunctionCode::new(1),
            ReadDiscreteInputs(..) => FunctionCode::new(2),
            ReadHoldingRegisters(..) => FunctionCode::new(3),
            ReadInputRegisters(..) => FunctionCode::new(4),
            WriteSingleCoil(..) => FunctionCode::new(5),
            WriteSingleRegister(..) => FunctionCode::new(6),
            ReadWriteMultipleRegisters(..) => FunctionCode::new(23),
            WriteMultipleCoils(..) => FunctionCode::new(15),
            WriteMultipleRegisters(..) => FunctionCode::new(16),
            MaskWriteRegister(..) => FunctionCode::new(22),
            Diagnostic(..) => FunctionCode::new(8),
            Disconnect => FunctionCode::new(0),
        }
    }

    /// Convert any borrowed data to `'static` owned data. Useful for storing
    /// requests across await points or sending them to another task.
    pub fn into_owned(self) -> Request<'static> {
        match self {
            Request::ReadCoils(a, q) => Request::ReadCoils(a, q),
            Request::ReadDiscreteInputs(a, q) => Request::ReadDiscreteInputs(a, q),
            Request::ReadHoldingRegisters(a, q) => Request::ReadHoldingRegisters(a, q),
            Request::ReadInputRegisters(a, q) => Request::ReadInputRegisters(a, q),
            Request::WriteSingleCoil(a, v) => Request::WriteSingleCoil(a, v),
            Request::WriteSingleRegister(a, v) => Request::WriteSingleRegister(a, v),
            Request::WriteMultipleCoils(a, v) => {
                Request::WriteMultipleCoils(a, Cow::Owned(v.into_owned()))
            }
            Request::WriteMultipleRegisters(a, v) => {
                Request::WriteMultipleRegisters(a, Cow::Owned(v.into_owned()))
            }
            Request::ReadWriteMultipleRegisters(a, q, w, d) => {
                Request::ReadWriteMultipleRegisters(a, q, w, Cow::Owned(d.into_owned()))
            }
            Request::MaskWriteRegister(a, b, c) => Request::MaskWriteRegister(a, b, c),
            Request::Diagnostic(sf, d) => Request::Diagnostic(sf, d),
            Request::Disconnect => Request::Disconnect,
        }
    }
}

// ── Response ──────────────────────────────────────────────────────────────

/// A Modbus response PDU — one variant per function code, plus [`Exception`].
///
/// Use [`Response::function_code`] to get the numeric FC (MSB set for exceptions),
/// and [`encode_response_into`] or [`From`]`<`[`Bytes`]`>` to serialize.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Response {
    ReadCoils(Vec<bool>),
    ReadDiscreteInputs(Vec<bool>),
    ReadHoldingRegisters(Vec<u16>),
    ReadInputRegisters(Vec<u16>),
    WriteSingleCoil(Address, bool),
    WriteSingleRegister(Address, u16),
    WriteMultipleCoils(Address, u16),
    WriteMultipleRegisters(Address, u16),
    ReadWriteMultipleRegisters(Vec<u16>),
    MaskWriteRegister(Address, u16, u16),
    Diagnostic(u16, u16),
    Exception(u8, Exception),
}

impl Response {
    /// The Modbus function code for this response.
    /// Returns `fc | 0x80` for [`Exception`](Response::Exception) variants.
    pub const fn function_code(&self) -> FunctionCode {
        use Response::*;
        match self {
            ReadCoils(..) => FunctionCode::new(1),
            ReadDiscreteInputs(..) => FunctionCode::new(2),
            ReadHoldingRegisters(..) => FunctionCode::new(3),
            ReadInputRegisters(..) => FunctionCode::new(4),
            WriteSingleCoil(..) => FunctionCode::new(5),
            WriteSingleRegister(..) => FunctionCode::new(6),
            WriteMultipleCoils(..) => FunctionCode::new(15),
            WriteMultipleRegisters(..) => FunctionCode::new(16),
            ReadWriteMultipleRegisters(..) => FunctionCode::new(23),
            MaskWriteRegister(..) => FunctionCode::new(22),
            Diagnostic(..) => FunctionCode::new(8),
            Exception(fc, _) => FunctionCode::new(*fc | 0x80),
        }
    }
}

// ── Response → ModbusError conversion ─────────────────────────────────────

impl From<Response> for crate::error::ModbusError {
    /// Convert a `Response` to a `ModbusError`.
    ///
    /// - `Response::Exception` → `ModbusError::Exception`
    /// - Everything else        → `ModbusError::Protocol` (unexpected success response
    ///   in an error context — prefer [`unexpected_response`](crate::client)
    ///   for direct handling in `ModbusClient` default methods)
    fn from(rsp: Response) -> Self {
        match rsp {
            Response::Exception(fc, ex) => crate::error::ModbusError::exception(fc, u8::from(ex)),
            other => crate::error::ModbusError::protocol(format!(
                "unexpected success response in error context: {other:?}"
            )),
        }
    }
}

// ── Exception ─────────────────────────────────────────────────────────────

/// Standard Modbus exception codes (1–8, 10–11) plus [`Custom(u8)`](Exception::Custom).
///
/// Implements `From<u8>` and `Into<u8>` for wire-format conversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[repr(u8)]
#[non_exhaustive]
pub enum Exception {
    #[error("Illegal function")]
    IllegalFunction = 1,
    #[error("Illegal data address")]
    IllegalDataAddress = 2,
    #[error("Illegal data value")]
    IllegalDataValue = 3,
    #[error("Server device failure")]
    ServerDeviceFailure = 4,
    #[error("Acknowledge")]
    Acknowledge = 5,
    #[error("Server device busy")]
    ServerDeviceBusy = 6,
    #[error("Negative acknowledge")]
    NegativeAcknowledge = 7,
    #[error("Memory parity error")]
    MemoryParityError = 8,
    #[error("Gateway path unavailable")]
    GatewayPathUnavailable = 10,
    #[error("Gateway target device failed to respond")]
    GatewayTargetDeviceFailedToRespond = 11,
    #[error("Custom({0})")]
    Custom(u8),
}

impl From<u8> for Exception {
    fn from(code: u8) -> Self {
        match code {
            1 => Exception::IllegalFunction,
            2 => Exception::IllegalDataAddress,
            3 => Exception::IllegalDataValue,
            4 => Exception::ServerDeviceFailure,
            5 => Exception::Acknowledge,
            6 => Exception::ServerDeviceBusy,
            7 => Exception::NegativeAcknowledge,
            8 => Exception::MemoryParityError,
            10 => Exception::GatewayPathUnavailable,
            11 => Exception::GatewayTargetDeviceFailedToRespond,
            n => Exception::Custom(n),
        }
    }
}

impl From<Exception> for u8 {
    fn from(e: Exception) -> u8 {
        match e {
            Exception::IllegalFunction => 1,
            Exception::IllegalDataAddress => 2,
            Exception::IllegalDataValue => 3,
            Exception::ServerDeviceFailure => 4,
            Exception::Acknowledge => 5,
            Exception::ServerDeviceBusy => 6,
            Exception::NegativeAcknowledge => 7,
            Exception::MemoryParityError => 8,
            Exception::GatewayPathUnavailable => 10,
            Exception::GatewayTargetDeviceFailedToRespond => 11,
            Exception::Custom(n) => n,
        }
    }
}

// ── Exception Response ────────────────────────────────────────────────────

/// A decoded Modbus exception response: function code and exception code.
///
/// Converts to [`ModbusError`](crate::ModbusError) via `From`.
#[derive(Debug, Clone, Error)]
#[error("Modbus exception {exception:?} for function {function:?}")]
pub struct ExceptionResponse {
    pub function: FunctionCode,
    pub exception: Exception,
}

impl From<ExceptionResponse> for crate::error::ModbusError {
    fn from(er: ExceptionResponse) -> Self {
        crate::error::ModbusError::exception(er.function.value(), u8::from(er.exception))
    }
}

// ── PDU Serialization ─────────────────────────────────────────────────────
//
// These are the ONLY conversion functions for Request ↔ Bytes and
// Response ↔ Bytes.  Everything else goes through these.
//
// For zero-copy framing, transports should call `encode_request_into` /
// `encode_response_into` directly with a reused `BytesMut` buffer instead of
// round-tripping through `Bytes`.

/// Encode a request PDU into an existing buffer (no intermediate allocation).
///
/// # Errors
///
/// Returns an error if the PDU exceeds the Modbus spec limit of 253 bytes.
pub fn encode_request_into(req: &Request<'_>, buf: &mut BytesMut) -> Result<(), Error> {
    let start = buf.len();
    encode_request(req, buf)?;
    let pdu_len = buf.len() - start;
    if pdu_len > MAX_PDU_SIZE {
        buf.truncate(start);
        return Err(Error::new(
            ErrorKind::InvalidData,
            format!("PDU size {pdu_len} exceeds Modbus limit of {MAX_PDU_SIZE}"),
        ));
    }
    Ok(())
}

/// Encode a response PDU into an existing buffer (no intermediate allocation).
///
/// # Errors
///
/// Returns an error if the response byte count overflows a `u8` or the
/// resulting PDU exceeds the Modbus spec limit of 253 bytes.
pub fn encode_response_into(rsp: &Response, buf: &mut BytesMut) -> Result<(), Error> {
    // Validate byte counts before encoding to catch oversized responses early.
    // The Modbus spec guarantees these bounds (≤2000 coils → ≤250 bytes,
    // ≤125 registers → ≤250 bytes), but we validate here for defense in depth.
    validate_response_size(rsp)?;
    let start = buf.len();
    encode_response(rsp, buf)?;
    let pdu_len = buf.len() - start;
    if pdu_len > MAX_PDU_SIZE {
        buf.truncate(start);
        return Err(Error::new(
            ErrorKind::InvalidData,
            format!("PDU size {pdu_len} exceeds Modbus limit of {MAX_PDU_SIZE}"),
        ));
    }
    Ok(())
}

impl<'a> TryFrom<Request<'a>> for Bytes {
    type Error = Error;
    fn try_from(req: Request<'a>) -> Result<Self, Self::Error> {
        let mut buf = BytesMut::new();
        encode_request_into(&req, &mut buf)?;
        Ok(buf.freeze())
    }
}

impl TryFrom<Bytes> for Request<'static> {
    type Error = Error;
    fn try_from(mut bytes: Bytes) -> Result<Self, Self::Error> {
        if bytes.is_empty() {
            return Err(Error::new(ErrorKind::InvalidData, "empty PDU"));
        }
        let fc = bytes[0];
        bytes.advance(1);
        decode_request(fc, &mut bytes)
    }
}

/// Converts a [`Response`] into its wire-format PDU bytes.
///
/// Uses [`encode_response_into`] internally for validation. If the
/// response violates the Modbus spec (e.g., `>2000` coils or `>125`
/// registers), an empty `Bytes` is returned rather than truncating or
/// panicking. Prefer [`encode_response_into`] directly when you need
/// error feedback.
impl From<Response> for Bytes {
    /// Converts a [`Response`] into its wire-format PDU bytes.
    ///
    /// Uses [`encode_response_into`] internally for validation. If the
    /// response violates the Modbus spec (e.g., `>2000` coils or `>125`
    /// registers), an empty `Bytes` is returned rather than truncating or
    /// panicking. When you need error feedback on oversized payloads, use
    /// [`encode_response_into`] directly — it returns `Result` so encoding
    /// failures are surfaced rather than silently discarded.
    fn from(rsp: Response) -> Self {
        let mut buf = BytesMut::new();
        let _ = encode_response_into(&rsp, &mut buf);
        buf.freeze()
    }
}

impl TryFrom<Bytes> for Response {
    type Error = Error;
    fn try_from(mut bytes: Bytes) -> Result<Self, Self::Error> {
        if bytes.is_empty() {
            return Err(Error::new(ErrorKind::InvalidData, "empty PDU"));
        }
        let fc = bytes[0];
        // Check for exception response (function code + 0x80)
        if fc & 0x80 != 0 {
            if bytes.len() < 2 {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    "truncated exception PDU",
                ));
            }
            let exception_code = bytes[1];
            return Ok(Response::Exception(
                fc & 0x7f,
                Exception::from(exception_code),
            ));
        }
        bytes.advance(1);
        decode_response(fc, &mut bytes)
    }
}

// ── Encoders ──────────────────────────────────────────────────────────────

#[inline]
fn push_u16(buf: &mut BytesMut, v: u16) {
    buf.put_u16(v);
}

fn encode_request(req: &Request<'_>, buf: &mut BytesMut) -> Result<(), Error> {
    // Disconnect sends nothing on the wire
    if matches!(req, Request::Disconnect) {
        return Ok(());
    }
    buf.put_u8(req.function_code().value());
    match req {
        Request::ReadCoils(addr, qty)
        | Request::ReadDiscreteInputs(addr, qty)
        | Request::ReadHoldingRegisters(addr, qty)
        | Request::ReadInputRegisters(addr, qty) => {
            push_u16(buf, *addr);
            push_u16(buf, *qty);
        }
        Request::WriteSingleCoil(addr, value) => {
            push_u16(buf, *addr);
            buf.put_u16(if *value { 0xFF00 } else { 0x0000 });
        }
        Request::WriteSingleRegister(addr, value) => {
            push_u16(buf, *addr);
            push_u16(buf, *value);
        }
        Request::WriteMultipleCoils(addr, values) => {
            push_u16(buf, *addr);
            push_u16(buf, values.len() as u16);
            let byte_count = safe_u8(values.len().div_ceil(8), "coil byte count")?;
            buf.put_u8(byte_count);
            for chunk in values.chunks(8) {
                let mut byte = 0u8;
                for (i, &v) in chunk.iter().enumerate() {
                    if v {
                        byte |= 1 << i;
                    }
                }
                buf.put_u8(byte);
            }
        }
        Request::WriteMultipleRegisters(addr, values) => {
            push_u16(buf, *addr);
            push_u16(buf, values.len() as u16);
            let byte_count = safe_u8(values.len() * 2, "write multiple reg byte count")?;
            buf.put_u8(byte_count);
            for &v in values.iter() {
                push_u16(buf, v);
            }
        }
        Request::ReadWriteMultipleRegisters(read_addr, read_qty, write_addr, data) => {
            push_u16(buf, *read_addr);
            push_u16(buf, *read_qty);
            push_u16(buf, *write_addr);
            push_u16(buf, data.len() as u16);
            let byte_count = safe_u8(data.len() * 2, "read-write reg byte count")?;
            buf.put_u8(byte_count);
            for &v in data.iter() {
                push_u16(buf, v);
            }
        }
        Request::MaskWriteRegister(addr, and_mask, or_mask) => {
            push_u16(buf, *addr);
            push_u16(buf, *and_mask);
            push_u16(buf, *or_mask);
        }
        Request::Diagnostic(sf, data) => {
            push_u16(buf, *sf);
            push_u16(buf, *data);
        }
        // Disconnect is a virtual request — produces no bytes on the wire.
        // The caller (AsciiClient::send_recv) checks for it before calling encode.
        Request::Disconnect => {}
    }
    Ok(())
}

fn decode_request(fc: u8, data: &mut Bytes) -> Result<Request<'static>, Error> {
    // Macro to read u16 with bounds check — never panics on malformed data
    macro_rules! read_u16 {
        ($data:expr) => {{
            if $data.remaining() < 2 {
                return Err(Error::new(ErrorKind::UnexpectedEof, "truncated PDU"));
            }
            $data.get_u16()
        }};
    }
    macro_rules! read_u8 {
        ($data:expr) => {{
            if $data.remaining() < 1 {
                return Err(Error::new(ErrorKind::UnexpectedEof, "truncated PDU"));
            }
            $data.get_u8()
        }};
    }

    Ok(match fc {
        1 => {
            let addr = read_u16!(data);
            let qty = read_u16!(data);
            if qty == 0 || qty > MAX_COILS {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("ReadCoils: qty {qty} not in 1..={MAX_COILS}"),
                ));
            }
            if addr as u32 + qty as u32 > 0x10000 {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("ReadCoils: addr {addr} + qty {qty} exceeds 0xFFFF"),
                ));
            }
            Request::ReadCoils(addr, qty)
        }
        2 => {
            let addr = read_u16!(data);
            let qty = read_u16!(data);
            if qty == 0 || qty > MAX_COILS {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("ReadDiscreteInputs: qty {qty} not in 1..={MAX_COILS}"),
                ));
            }
            if addr as u32 + qty as u32 > 0x10000 {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("ReadDiscreteInputs: addr {addr} + qty {qty} exceeds 0xFFFF"),
                ));
            }
            Request::ReadDiscreteInputs(addr, qty)
        }
        3 => {
            let addr = read_u16!(data);
            let qty = read_u16!(data);
            if qty == 0 || qty > MAX_REGISTERS {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("ReadHoldingRegisters: qty {qty} not in 1..={MAX_REGISTERS}"),
                ));
            }
            if addr as u32 + qty as u32 > 0x10000 {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("ReadHoldingRegisters: addr {addr} + qty {qty} exceeds 0xFFFF"),
                ));
            }
            Request::ReadHoldingRegisters(addr, qty)
        }
        4 => {
            let addr = read_u16!(data);
            let qty = read_u16!(data);
            if qty == 0 || qty > MAX_REGISTERS {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("ReadInputRegisters: qty {qty} not in 1..={MAX_REGISTERS}"),
                ));
            }
            if addr as u32 + qty as u32 > 0x10000 {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("ReadInputRegisters: addr {addr} + qty {qty} exceeds 0xFFFF"),
                ));
            }
            Request::ReadInputRegisters(addr, qty)
        }
        5 => {
            let addr = read_u16!(data);
            let raw = read_u16!(data);
            let val = match raw {
                0xFF00 => true,
                0x0000 => false,
                other => return Err(Error::new(ErrorKind::InvalidData,
                    format!("WriteSingleCoil: invalid coil value {other:#06X}, expected 0xFF00 or 0x0000"))),
            };
            Request::WriteSingleCoil(addr, val)
        }
        6 => {
            let addr = read_u16!(data);
            let val = read_u16!(data);
            Request::WriteSingleRegister(addr, val)
        }
        15 => {
            let addr = read_u16!(data);
            let qty = read_u16!(data);
            if qty == 0 || qty > MAX_COILS {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("WriteMultipleCoils: qty {qty} not in 1..={MAX_COILS}"),
                ));
            }
            if addr as u32 + qty as u32 > 0x10000 {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("WriteMultipleCoils: addr {addr} + qty {qty} exceeds 0xFFFF"),
                ));
            }
            let qty = qty as usize;
            let byte_count = read_u8!(data) as usize;
            let expected_byte_count = qty.div_ceil(8);
            if byte_count != expected_byte_count {
                return Err(Error::new(ErrorKind::InvalidData,
                    format!("WriteMultipleCoils: byte_count {byte_count} != ceil(qty/8) ({expected_byte_count})")));
            }
            if data.remaining() < byte_count {
                return Err(Error::new(ErrorKind::UnexpectedEof, "truncated coil data"));
            }
            let mut values = Vec::with_capacity(byte_count * 8);
            for _ in 0..byte_count {
                let byte = data.get_u8();
                for i in 0..8 {
                    values.push(byte & (1 << i) != 0);
                    if values.len() >= qty {
                        break;
                    }
                }
            }
            values.truncate(qty);
            Request::WriteMultipleCoils(addr, Cow::Owned(values))
        }
        16 => {
            let addr = read_u16!(data);
            let qty = read_u16!(data);
            if qty == 0 || qty > MAX_REGISTERS {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("WriteMultipleRegisters: qty {qty} not in 1..={MAX_REGISTERS}"),
                ));
            }
            if addr as u32 + qty as u32 > 0x10000 {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("WriteMultipleRegisters: addr {addr} + qty {qty} exceeds 0xFFFF"),
                ));
            }
            let qty = qty as usize;
            let byte_count = read_u8!(data) as usize;
            if byte_count != qty * 2 {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!(
                        "WriteMultipleRegisters: byte_count {byte_count} != qty*2 ({})",
                        qty * 2
                    ),
                ));
            }
            if data.remaining() < qty * 2 {
                return Err(Error::new(
                    ErrorKind::UnexpectedEof,
                    "truncated register data",
                ));
            }
            let mut values = Vec::with_capacity(qty);
            for _ in 0..qty {
                values.push(data.get_u16());
            }
            Request::WriteMultipleRegisters(addr, Cow::Owned(values))
        }
        22 => {
            let addr = read_u16!(data);
            let and_mask = read_u16!(data);
            let or_mask = read_u16!(data);
            Request::MaskWriteRegister(addr, and_mask, or_mask)
        }
        23 => {
            let read_addr = read_u16!(data);
            let read_qty = read_u16!(data);
            if read_qty == 0 || read_qty > MAX_REGISTERS {
                return Err(Error::new(ErrorKind::InvalidData,
                    format!("ReadWriteMultipleRegisters: read_qty {read_qty} not in 1..={MAX_REGISTERS}")));
            }
            if read_addr as u32 + read_qty as u32 > 0x10000 {
                return Err(Error::new(ErrorKind::InvalidData,
                    format!("ReadWriteMultipleRegisters: read_addr {read_addr} + read_qty {read_qty} exceeds 0xFFFF")));
            }
            let write_addr = read_u16!(data);
            let write_qty = read_u16!(data);
            if write_qty == 0 || write_qty > MAX_REGISTERS {
                return Err(Error::new(ErrorKind::InvalidData,
                    format!("ReadWriteMultipleRegisters: write_qty {write_qty} not in 1..={MAX_REGISTERS}")));
            }
            if write_addr as u32 + write_qty as u32 > 0x10000 {
                return Err(Error::new(ErrorKind::InvalidData,
                    format!("ReadWriteMultipleRegisters: write_addr {write_addr} + write_qty {write_qty} exceeds 0xFFFF")));
            }
            let write_qty = write_qty as usize;
            let byte_count = read_u8!(data) as usize;
            if byte_count != write_qty * 2 {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!(
                        "ReadWriteMultipleRegisters: byte_count {byte_count} != write_qty*2 ({})",
                        write_qty * 2
                    ),
                ));
            }
            if data.remaining() < write_qty * 2 {
                return Err(Error::new(
                    ErrorKind::UnexpectedEof,
                    "truncated R/W register data",
                ));
            }
            let mut values = Vec::with_capacity(write_qty);
            for _ in 0..write_qty {
                values.push(data.get_u16());
            }
            Request::ReadWriteMultipleRegisters(read_addr, read_qty, write_addr, Cow::Owned(values))
        }
        8 => {
            let sf = read_u16!(data);
            let d = read_u16!(data);
            Request::Diagnostic(sf, d)
        }
        _ => {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("unknown function code: {fc:#04X}"),
            ))
        }
    })
}

fn encode_response(rsp: &Response, buf: &mut BytesMut) -> Result<(), Error> {
    match rsp {
        Response::ReadCoils(bits) | Response::ReadDiscreteInputs(bits) => {
            let byte_count = safe_u8(bits.len().div_ceil(8), "coil byte count")?;
            buf.put_u8(rsp.function_code().value());
            buf.put_u8(byte_count);
            for chunk in bits.chunks(8) {
                let mut byte = 0u8;
                for (i, &v) in chunk.iter().enumerate() {
                    if v {
                        byte |= 1 << i;
                    }
                }
                buf.put_u8(byte);
            }
        }
        Response::ReadHoldingRegisters(regs) | Response::ReadInputRegisters(regs) => {
            buf.put_u8(rsp.function_code().value());
            buf.put_u8(safe_u8(regs.len() * 2, "register byte count")?);
            for &v in regs {
                push_u16(buf, v);
            }
        }
        Response::ReadWriteMultipleRegisters(regs) => {
            buf.put_u8(rsp.function_code().value());
            buf.put_u8(safe_u8(regs.len() * 2, "register byte count")?);
            for &v in regs {
                push_u16(buf, v);
            }
        }
        Response::WriteSingleCoil(addr, val) => {
            buf.put_u8(rsp.function_code().value());
            push_u16(buf, *addr);
            buf.put_u16(if *val { 0xFF00 } else { 0x0000 });
        }
        Response::WriteSingleRegister(addr, val) => {
            buf.put_u8(rsp.function_code().value());
            push_u16(buf, *addr);
            push_u16(buf, *val);
        }
        Response::WriteMultipleCoils(addr, qty) => {
            buf.put_u8(rsp.function_code().value());
            push_u16(buf, *addr);
            push_u16(buf, *qty);
        }
        Response::WriteMultipleRegisters(addr, qty) => {
            buf.put_u8(rsp.function_code().value());
            push_u16(buf, *addr);
            push_u16(buf, *qty);
        }
        Response::MaskWriteRegister(addr, and_mask, or_mask) => {
            buf.put_u8(rsp.function_code().value());
            push_u16(buf, *addr);
            push_u16(buf, *and_mask);
            push_u16(buf, *or_mask);
        }
        Response::Diagnostic(sf, data) => {
            buf.put_u8(rsp.function_code().value());
            push_u16(buf, *sf);
            push_u16(buf, *data);
        }
        Response::Exception(fc, exception) => {
            buf.put_u8(*fc | 0x80);
            buf.put_u8(u8::from(*exception));
        }
    }
    Ok(())
}

fn decode_response(fc: u8, data: &mut Bytes) -> Result<Response, Error> {
    macro_rules! read_u16 {
        ($data:expr) => {{
            if $data.remaining() < 2 {
                return Err(Error::new(
                    ErrorKind::UnexpectedEof,
                    "truncated response PDU",
                ));
            }
            $data.get_u16()
        }};
    }
    macro_rules! read_u8 {
        ($data:expr) => {{
            if $data.remaining() < 1 {
                return Err(Error::new(
                    ErrorKind::UnexpectedEof,
                    "truncated response PDU",
                ));
            }
            $data.get_u8()
        }};
    }

    Ok(match fc {
        1 | 2 => {
            let byte_count = read_u8!(data) as usize;
            if data.remaining() < byte_count {
                return Err(Error::new(
                    ErrorKind::UnexpectedEof,
                    "truncated coil response",
                ));
            }
            let mut bits = Vec::with_capacity(byte_count * 8);
            for _ in 0..byte_count {
                let byte = data.get_u8();
                for i in 0..8 {
                    bits.push(byte & (1 << i) != 0);
                }
            }
            if fc == 1 {
                Response::ReadCoils(bits)
            } else {
                Response::ReadDiscreteInputs(bits)
            }
        }
        3 | 4 => {
            let byte_count = read_u8!(data) as usize;
            if byte_count % 2 != 0 {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("register response: byte_count {byte_count} is not even"),
                ));
            }
            if data.remaining() < byte_count {
                return Err(Error::new(
                    ErrorKind::UnexpectedEof,
                    "truncated register response",
                ));
            }
            let mut regs = Vec::with_capacity(byte_count / 2);
            for _ in 0..(byte_count / 2) {
                regs.push(data.get_u16());
            }
            if fc == 3 {
                Response::ReadHoldingRegisters(regs)
            } else {
                Response::ReadInputRegisters(regs)
            }
        }
        5 => {
            let addr = read_u16!(data);
            let val = read_u16!(data) == 0xFF00;
            Response::WriteSingleCoil(addr, val)
        }
        6 => {
            let addr = read_u16!(data);
            let val = read_u16!(data);
            Response::WriteSingleRegister(addr, val)
        }
        15 => {
            let addr = read_u16!(data);
            let qty = read_u16!(data);
            Response::WriteMultipleCoils(addr, qty)
        }
        16 => {
            let addr = read_u16!(data);
            let qty = read_u16!(data);
            Response::WriteMultipleRegisters(addr, qty)
        }
        22 => {
            let addr = read_u16!(data);
            let and_mask = read_u16!(data);
            let or_mask = read_u16!(data);
            Response::MaskWriteRegister(addr, and_mask, or_mask)
        }
        23 => {
            let byte_count = read_u8!(data) as usize;
            if byte_count % 2 != 0 {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!(
                        "ReadWriteMultipleRegisters response: byte_count {byte_count} is not even"
                    ),
                ));
            }
            if data.remaining() < byte_count {
                return Err(Error::new(
                    ErrorKind::UnexpectedEof,
                    "truncated R/W response",
                ));
            }
            let mut regs = Vec::with_capacity(byte_count / 2);
            for _ in 0..(byte_count / 2) {
                regs.push(data.get_u16());
            }
            Response::ReadWriteMultipleRegisters(regs)
        }
        8 => {
            let sf = read_u16!(data);
            let d = read_u16!(data);
            Response::Diagnostic(sf, d)
        }
        _ => {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("unknown response function code: {fc}"),
            ))
        }
    })
}

// ── Tests ────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn known_function_codes_accepted() {
        // Standard FCs: 1-6, 8, 15, 16, 22, 23
        for fc in [1u8, 2, 3, 4, 5, 6, 8, 15, 16, 22, 23] {
            assert!(
                is_known_function_code(fc),
                "standard FC {fc} should be known"
            );
        }
        // Exception variants: standard + 0x80
        for fc in [
            0x81u8, 0x82, 0x83, 0x84, 0x85, 0x86, 0x88, 0x8F, 0x90, 0x96, 0x97,
        ] {
            assert!(
                is_known_function_code(fc),
                "exception FC 0x{fc:02X} should be known"
            );
        }
    }

    #[test]
    fn unknown_function_codes_rejected() {
        for fc in [0u8, 7, 9, 14, 18, 24, 0x80, 0x87, 0xFF] {
            assert!(
                !is_known_function_code(fc),
                "unknown FC {fc} should NOT be known"
            );
        }
    }
}