rusty-modbus-frame 0.1.0

Modbus framing — MBAP/RTU codecs, CRC-16, owned Bytes types
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
//! Owned (`'static`, `Bytes`-backed) Modbus response types.
//!
//! These mirror the borrowed response types in `rusty_modbus_codec::response` but hold
//! variable-length payloads as `bytes::Bytes` instead of `&'buf [u8]`, making them
//! suitable for async contexts where the response must outlive the receive buffer.

// from_pdu takes Bytes by value intentionally — callers transfer ownership of the
// buffer into the owned struct, even though Bytes::slice() only needs &self.
#![allow(clippy::needless_pass_by_value)]

use bytes::Bytes;
use rusty_modbus_codec::error::DecodeError;
use rusty_modbus_codec::response::{
    EncapsulatedInterfaceResponse, ExceptionResponse, GetCommEventCounterResponse,
    GetCommEventLogResponse, MaskWriteRegisterResponse, ReadExceptionStatusResponse,
    ReadFifoQueueResponse, ReadFileRecordResponse, WriteFileRecordResponse,
    WriteMultipleCoilsResponse, WriteMultipleRegistersResponse, WriteSingleCoilResponse,
    WriteSingleRegisterResponse,
};
use rusty_modbus_types::{DiagnosticSubFunction, FunctionCode, MeiType};

fn pdu_data(pdu: &Bytes) -> Result<&[u8], DecodeError> {
    if pdu.is_empty() {
        return Err(DecodeError::Truncated {
            expected: 1,
            actual: 0,
        });
    }
    Ok(&pdu[1..])
}

// ---------------------------------------------------------------------------
// Owned bit-read responses
// ---------------------------------------------------------------------------

/// Owned variant of `ReadCoilsResponse` (FC 0x01).
#[derive(Debug, Clone)]
pub struct OwnedReadCoilsResponse {
    /// Number of data bytes that follow.
    pub byte_count: u8,
    /// Bit-packed coil status, LSB-first within each byte.
    pub coil_status: Bytes,
}

impl OwnedReadCoilsResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        if data.is_empty() {
            return Err(DecodeError::Truncated {
                expected: 1,
                actual: 0,
            });
        }
        let byte_count = data[0];
        let payload = &data[1..];
        if payload.len() != usize::from(byte_count) {
            return Err(DecodeError::ByteCountMismatch {
                declared: usize::from(byte_count),
                actual: payload.len(),
            });
        }
        let coil_status = pdu.slice(2..2 + usize::from(byte_count));
        Ok(Self {
            byte_count,
            coil_status,
        })
    }

    /// Returns the state of the coil at the given zero-based index.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of range for the coil status data.
    #[must_use]
    pub fn coil(&self, index: usize) -> bool {
        let byte_idx = index / 8;
        let bit_idx = index % 8;
        (self.coil_status[byte_idx] >> bit_idx) & 1 == 1
    }
}

/// Owned variant of `ReadDiscreteInputsResponse` (FC 0x02).
#[derive(Debug, Clone)]
pub struct OwnedReadDiscreteInputsResponse {
    /// Number of data bytes that follow.
    pub byte_count: u8,
    /// Bit-packed input status, LSB-first within each byte.
    pub input_status: Bytes,
}

impl OwnedReadDiscreteInputsResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        if data.is_empty() {
            return Err(DecodeError::Truncated {
                expected: 1,
                actual: 0,
            });
        }
        let byte_count = data[0];
        let payload = &data[1..];
        if payload.len() != usize::from(byte_count) {
            return Err(DecodeError::ByteCountMismatch {
                declared: usize::from(byte_count),
                actual: payload.len(),
            });
        }
        let input_status = pdu.slice(2..2 + usize::from(byte_count));
        Ok(Self {
            byte_count,
            input_status,
        })
    }

    /// Returns the state of the discrete input at the given zero-based index.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of range for the input status data.
    #[must_use]
    pub fn coil(&self, index: usize) -> bool {
        let byte_idx = index / 8;
        let bit_idx = index % 8;
        (self.input_status[byte_idx] >> bit_idx) & 1 == 1
    }
}

// ---------------------------------------------------------------------------
// Owned register-read responses
// ---------------------------------------------------------------------------

/// Owned variant of `ReadHoldingRegistersResponse` (FC 0x03).
#[derive(Debug, Clone)]
pub struct OwnedReadHoldingRegistersResponse {
    /// Number of data bytes that follow (should be 2 * register count).
    pub byte_count: u8,
    /// Raw register data in big-endian byte order.
    pub register_data: Bytes,
}

impl OwnedReadHoldingRegistersResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        if data.is_empty() {
            return Err(DecodeError::Truncated {
                expected: 1,
                actual: 0,
            });
        }
        let byte_count = data[0];
        let payload = &data[1..];
        if payload.len() != usize::from(byte_count) {
            return Err(DecodeError::ByteCountMismatch {
                declared: usize::from(byte_count),
                actual: payload.len(),
            });
        }
        let register_data = pdu.slice(2..2 + usize::from(byte_count));
        Ok(Self {
            byte_count,
            register_data,
        })
    }

    /// Returns the number of registers in this response.
    #[must_use]
    pub fn count(&self) -> usize {
        self.register_data.len() / 2
    }

    /// Returns the register value at the given zero-based index.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of range.
    #[must_use]
    pub fn register(&self, index: usize) -> u16 {
        let off = index * 2;
        u16::from_be_bytes([self.register_data[off], self.register_data[off + 1]])
    }

    /// Returns an iterator over all register values.
    pub fn registers(&self) -> impl Iterator<Item = u16> + '_ {
        self.register_data
            .chunks_exact(2)
            .map(|c| u16::from_be_bytes([c[0], c[1]]))
    }

    /// Returns the raw register data bytes.
    #[must_use]
    pub fn raw(&self) -> &[u8] {
        &self.register_data
    }
}

/// Owned variant of `ReadInputRegistersResponse` (FC 0x04).
#[derive(Debug, Clone)]
pub struct OwnedReadInputRegistersResponse {
    /// Number of data bytes that follow (should be 2 * register count).
    pub byte_count: u8,
    /// Raw register data in big-endian byte order.
    pub register_data: Bytes,
}

impl OwnedReadInputRegistersResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        if data.is_empty() {
            return Err(DecodeError::Truncated {
                expected: 1,
                actual: 0,
            });
        }
        let byte_count = data[0];
        let payload = &data[1..];
        if payload.len() != usize::from(byte_count) {
            return Err(DecodeError::ByteCountMismatch {
                declared: usize::from(byte_count),
                actual: payload.len(),
            });
        }
        let register_data = pdu.slice(2..2 + usize::from(byte_count));
        Ok(Self {
            byte_count,
            register_data,
        })
    }

    /// Returns the number of registers in this response.
    #[must_use]
    pub fn count(&self) -> usize {
        self.register_data.len() / 2
    }

    /// Returns the register value at the given zero-based index.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of range.
    #[must_use]
    pub fn register(&self, index: usize) -> u16 {
        let off = index * 2;
        u16::from_be_bytes([self.register_data[off], self.register_data[off + 1]])
    }

    /// Returns an iterator over all register values.
    pub fn registers(&self) -> impl Iterator<Item = u16> + '_ {
        self.register_data
            .chunks_exact(2)
            .map(|c| u16::from_be_bytes([c[0], c[1]]))
    }

    /// Returns the raw register data bytes.
    #[must_use]
    pub fn raw(&self) -> &[u8] {
        &self.register_data
    }
}

// ---------------------------------------------------------------------------
// Owned register read-write response
// ---------------------------------------------------------------------------

/// Owned variant of `ReadWriteMultipleRegistersResponse` (FC 0x17).
#[derive(Debug, Clone)]
pub struct OwnedReadWriteMultipleRegistersResponse {
    /// Number of data bytes that follow (should be 2 * register count).
    pub byte_count: u8,
    /// Raw register data in big-endian byte order.
    pub register_data: Bytes,
}

impl OwnedReadWriteMultipleRegistersResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        if data.is_empty() {
            return Err(DecodeError::Truncated {
                expected: 1,
                actual: 0,
            });
        }
        let byte_count = data[0];
        let payload = &data[1..];
        if payload.len() != usize::from(byte_count) {
            return Err(DecodeError::ByteCountMismatch {
                declared: usize::from(byte_count),
                actual: payload.len(),
            });
        }
        let register_data = pdu.slice(2..2 + usize::from(byte_count));
        Ok(Self {
            byte_count,
            register_data,
        })
    }

    /// Returns the number of registers in this response.
    #[must_use]
    pub fn count(&self) -> usize {
        self.register_data.len() / 2
    }

    /// Returns the register value at the given zero-based index.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of range.
    #[must_use]
    pub fn register(&self, index: usize) -> u16 {
        let off = index * 2;
        u16::from_be_bytes([self.register_data[off], self.register_data[off + 1]])
    }

    /// Returns an iterator over all register values.
    pub fn registers(&self) -> impl Iterator<Item = u16> + '_ {
        self.register_data
            .chunks_exact(2)
            .map(|c| u16::from_be_bytes([c[0], c[1]]))
    }

    /// Returns the raw register data bytes.
    #[must_use]
    pub fn raw(&self) -> &[u8] {
        &self.register_data
    }
}

// ---------------------------------------------------------------------------
// Owned FIFO response
// ---------------------------------------------------------------------------

/// Owned variant of `ReadFifoQueueResponse` (FC 0x18).
#[derive(Debug, Clone)]
pub struct OwnedReadFifoQueueResponse {
    /// Total number of bytes following this field.
    pub byte_count: u16,
    /// Number of FIFO register values (0..=31).
    pub fifo_count: u16,
    /// Raw FIFO register data in big-endian byte order.
    pub fifo_values: Bytes,
}

impl OwnedReadFifoQueueResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        let decoded = ReadFifoQueueResponse::decode(data)?;
        let fifo_values = pdu.slice(5..5 + decoded.fifo_values.len());
        Ok(Self {
            byte_count: decoded.byte_count,
            fifo_count: decoded.fifo_count,
            fifo_values,
        })
    }
}

// ---------------------------------------------------------------------------
// Owned file record responses
// ---------------------------------------------------------------------------

/// Owned variant of `ReadFileRecordResponse` (FC 0x14).
#[derive(Debug, Clone)]
pub struct OwnedReadFileRecordResponse {
    /// Total number of data bytes that follow.
    pub byte_count: u8,
    /// Raw sub-request response data.
    pub data: Bytes,
}

impl OwnedReadFileRecordResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        let decoded = ReadFileRecordResponse::decode(data)?;
        let owned_data = pdu.slice(2..2 + decoded.data.len());
        Ok(Self {
            byte_count: decoded.byte_count,
            data: owned_data,
        })
    }
}

/// Owned variant of `WriteFileRecordResponse` (FC 0x15).
#[derive(Debug, Clone)]
pub struct OwnedWriteFileRecordResponse {
    /// Total number of data bytes that follow.
    pub byte_count: u8,
    /// Raw sub-request response data.
    pub data: Bytes,
}

impl OwnedWriteFileRecordResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        let decoded = WriteFileRecordResponse::decode(data)?;
        let owned_data = pdu.slice(2..2 + decoded.data.len());
        Ok(Self {
            byte_count: decoded.byte_count,
            data: owned_data,
        })
    }
}

// ---------------------------------------------------------------------------
// Owned diagnostic responses
// ---------------------------------------------------------------------------

/// Owned variant of `DiagnosticsResponse` (FC 0x08).
#[derive(Debug, Clone)]
pub struct OwnedDiagnosticsResponse {
    /// The diagnostic sub-function code.
    pub sub_function: DiagnosticSubFunction,
    /// Diagnostic data bytes.
    pub data: Bytes,
}

impl OwnedDiagnosticsResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        if data.len() < 2 {
            return Err(DecodeError::Truncated {
                expected: 2,
                actual: data.len(),
            });
        }
        let raw_sub = u16::from_be_bytes([data[0], data[1]]);
        let sub_function = DiagnosticSubFunction::from_raw(raw_sub)
            .ok_or(DecodeError::UnknownDiagnosticSubFunction(raw_sub))?;
        let payload = &data[2..];
        if !payload.len().is_multiple_of(2) {
            return Err(DecodeError::InvalidDiagnosticDataLength {
                length: payload.len(),
            });
        }
        let owned_data = pdu.slice(3..);
        Ok(Self {
            sub_function,
            data: owned_data,
        })
    }
}

/// Owned variant of `GetCommEventLogResponse` (FC 0x0C).
#[derive(Debug, Clone)]
pub struct OwnedGetCommEventLogResponse {
    /// Number of bytes that follow.
    pub byte_count: u8,
    /// Status word (0x0000 = ready, 0xFFFF = busy).
    pub status: u16,
    /// Event counter value.
    pub event_count: u16,
    /// Message counter value.
    pub message_count: u16,
    /// Event log bytes.
    pub events: Bytes,
}

impl OwnedGetCommEventLogResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        let decoded = GetCommEventLogResponse::decode(data)?;
        let events = pdu.slice(8..8 + decoded.events.len());
        Ok(Self {
            byte_count: decoded.byte_count,
            status: decoded.status,
            event_count: decoded.event_count,
            message_count: decoded.message_count,
            events,
        })
    }
}

/// Owned variant of `ReportServerIdResponse` (FC 0x11).
#[derive(Debug, Clone)]
pub struct OwnedReportServerIdResponse {
    /// Number of data bytes that follow.
    pub byte_count: u8,
    /// Device-specific identification data.
    pub data: Bytes,
}

impl OwnedReportServerIdResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        if data.is_empty() {
            return Err(DecodeError::Truncated {
                expected: 1,
                actual: 0,
            });
        }
        let byte_count = data[0];
        let payload = &data[1..];
        if payload.len() != usize::from(byte_count) {
            return Err(DecodeError::ByteCountMismatch {
                declared: usize::from(byte_count),
                actual: payload.len(),
            });
        }
        let owned_data = pdu.slice(2..2 + usize::from(byte_count));
        Ok(Self {
            byte_count,
            data: owned_data,
        })
    }
}

// ---------------------------------------------------------------------------
// Owned MEI response
// ---------------------------------------------------------------------------

/// Owned variant of `EncapsulatedInterfaceResponse` (FC 0x2B).
#[derive(Debug, Clone)]
pub struct OwnedEncapsulatedInterfaceResponse {
    /// The MEI type code.
    pub mei_type: MeiType,
    /// MEI-specific data bytes.
    pub data: Bytes,
}

impl OwnedEncapsulatedInterfaceResponse {
    /// Decode from a full PDU (function-code byte + data).
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the PDU is malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        let data = pdu_data(&pdu)?;
        let decoded = EncapsulatedInterfaceResponse::decode(data)?;
        let owned_data = pdu.slice(2..);
        Ok(Self {
            mei_type: decoded.mei_type,
            data: owned_data,
        })
    }
}

// ---------------------------------------------------------------------------
// Collected device identification
// ---------------------------------------------------------------------------

/// Collected device identification from FC 0x2B / MEI 0x0E.
///
/// Contains the three mandatory basic objects. Fields are `None` if the
/// device did not include them.
#[derive(Debug, Clone, Default)]
pub struct OwnedDeviceIdentification {
    /// Vendor Name (object 0x00).
    pub vendor_name: Option<String>,
    /// Product Code (object 0x01).
    pub product_code: Option<String>,
    /// Major/Minor Revision (object 0x02).
    pub major_minor_revision: Option<String>,
}

// ---------------------------------------------------------------------------
// OwnedResponsePdu dispatch enum
// ---------------------------------------------------------------------------

/// Owned variant of a Modbus response PDU.
///
/// Variable-length responses use `Bytes`-backed owned types; fixed-size (Copy)
/// responses are used directly from `rusty_modbus_codec::response`.
#[derive(Debug)]
pub enum OwnedResponsePdu {
    /// FC 0x01 -- Read Coils.
    ReadCoils(OwnedReadCoilsResponse),
    /// FC 0x02 -- Read Discrete Inputs.
    ReadDiscreteInputs(OwnedReadDiscreteInputsResponse),
    /// FC 0x03 -- Read Holding Registers.
    ReadHoldingRegisters(OwnedReadHoldingRegistersResponse),
    /// FC 0x04 -- Read Input Registers.
    ReadInputRegisters(OwnedReadInputRegistersResponse),
    /// FC 0x05 -- Write Single Coil.
    WriteSingleCoil(WriteSingleCoilResponse),
    /// FC 0x06 -- Write Single Register.
    WriteSingleRegister(WriteSingleRegisterResponse),
    /// FC 0x07 -- Read Exception Status.
    ReadExceptionStatus(ReadExceptionStatusResponse),
    /// FC 0x08 -- Diagnostics.
    Diagnostics(OwnedDiagnosticsResponse),
    /// FC 0x0B -- Get Comm Event Counter.
    GetCommEventCounter(GetCommEventCounterResponse),
    /// FC 0x0C -- Get Comm Event Log.
    GetCommEventLog(OwnedGetCommEventLogResponse),
    /// FC 0x0F -- Write Multiple Coils.
    WriteMultipleCoils(WriteMultipleCoilsResponse),
    /// FC 0x10 -- Write Multiple Registers.
    WriteMultipleRegisters(WriteMultipleRegistersResponse),
    /// FC 0x11 -- Report Server ID.
    ReportServerId(OwnedReportServerIdResponse),
    /// FC 0x14 -- Read File Record.
    ReadFileRecord(OwnedReadFileRecordResponse),
    /// FC 0x15 -- Write File Record.
    WriteFileRecord(OwnedWriteFileRecordResponse),
    /// FC 0x16 -- Mask Write Register.
    MaskWriteRegister(MaskWriteRegisterResponse),
    /// FC 0x17 -- Read/Write Multiple Registers.
    ReadWriteMultipleRegisters(OwnedReadWriteMultipleRegistersResponse),
    /// FC 0x18 -- Read FIFO Queue.
    ReadFifoQueue(OwnedReadFifoQueueResponse),
    /// FC 0x2B -- Encapsulated Interface Transport.
    EncapsulatedInterface(OwnedEncapsulatedInterfaceResponse),
    /// Non-standard / vendor-specific response.
    Custom(u8, Bytes),
    /// Exception response (FC | 0x80).
    Exception(ExceptionResponse),
}

impl OwnedResponsePdu {
    /// Decode from a full PDU (`Bytes` starting with the function-code byte).
    ///
    /// Dispatches to the appropriate owned type based on the function code.
    ///
    /// # Errors
    ///
    /// Returns `DecodeError` if the function code is unknown or the payload is
    /// malformed.
    pub fn from_pdu(pdu: Bytes) -> Result<Self, DecodeError> {
        if pdu.is_empty() {
            return Err(DecodeError::Truncated {
                expected: 1,
                actual: 0,
            });
        }

        let fc_byte = pdu[0];

        // Check for exception response (high bit set).
        if FunctionCode::is_exception_response(fc_byte) {
            let resp = ExceptionResponse::decode(fc_byte, &pdu[1..])?;
            return Ok(Self::Exception(resp));
        }

        // Exception-flagged bytes handled above. from_raw returns Some for all
        // non-exception bytes (known → named, unknown → Custom).
        let fc = FunctionCode::from_raw(fc_byte).unwrap_or(FunctionCode::Custom(fc_byte));

        let data = &pdu[1..];

        match fc {
            FunctionCode::ReadCoils => OwnedReadCoilsResponse::from_pdu(pdu).map(Self::ReadCoils),
            FunctionCode::ReadDiscreteInputs => {
                OwnedReadDiscreteInputsResponse::from_pdu(pdu).map(Self::ReadDiscreteInputs)
            }
            FunctionCode::ReadHoldingRegisters => {
                OwnedReadHoldingRegistersResponse::from_pdu(pdu).map(Self::ReadHoldingRegisters)
            }
            FunctionCode::ReadInputRegisters => {
                OwnedReadInputRegistersResponse::from_pdu(pdu).map(Self::ReadInputRegisters)
            }
            FunctionCode::WriteSingleCoil => {
                WriteSingleCoilResponse::decode(data).map(Self::WriteSingleCoil)
            }
            FunctionCode::WriteSingleRegister => {
                WriteSingleRegisterResponse::decode(data).map(Self::WriteSingleRegister)
            }
            FunctionCode::ReadExceptionStatus => {
                ReadExceptionStatusResponse::decode(data).map(Self::ReadExceptionStatus)
            }
            FunctionCode::Diagnostics => {
                OwnedDiagnosticsResponse::from_pdu(pdu).map(Self::Diagnostics)
            }
            FunctionCode::GetCommEventCounter => {
                GetCommEventCounterResponse::decode(data).map(Self::GetCommEventCounter)
            }
            FunctionCode::GetCommEventLog => {
                OwnedGetCommEventLogResponse::from_pdu(pdu).map(Self::GetCommEventLog)
            }
            FunctionCode::WriteMultipleCoils => {
                WriteMultipleCoilsResponse::decode(data).map(Self::WriteMultipleCoils)
            }
            FunctionCode::WriteMultipleRegisters => {
                WriteMultipleRegistersResponse::decode(data).map(Self::WriteMultipleRegisters)
            }
            FunctionCode::ReportServerId => {
                OwnedReportServerIdResponse::from_pdu(pdu).map(Self::ReportServerId)
            }
            FunctionCode::ReadFileRecord => {
                OwnedReadFileRecordResponse::from_pdu(pdu).map(Self::ReadFileRecord)
            }
            FunctionCode::WriteFileRecord => {
                OwnedWriteFileRecordResponse::from_pdu(pdu).map(Self::WriteFileRecord)
            }
            FunctionCode::MaskWriteRegister => {
                MaskWriteRegisterResponse::decode(data).map(Self::MaskWriteRegister)
            }
            FunctionCode::ReadWriteMultipleRegisters => {
                OwnedReadWriteMultipleRegistersResponse::from_pdu(pdu)
                    .map(Self::ReadWriteMultipleRegisters)
            }
            FunctionCode::ReadFifoQueue => {
                OwnedReadFifoQueueResponse::from_pdu(pdu).map(Self::ReadFifoQueue)
            }
            FunctionCode::EncapsulatedInterfaceTransport => {
                OwnedEncapsulatedInterfaceResponse::from_pdu(pdu).map(Self::EncapsulatedInterface)
            }
            FunctionCode::Custom(fc) => Ok(Self::Custom(fc, pdu.slice(1..))),
        }
    }

    /// The function-code byte carried by this response.
    ///
    /// For [`Self::Exception`] this is the exception-flagged value
    /// (`original_fc | 0x80`); for [`Self::Custom`] it is the raw byte. Used by
    /// the client to verify the server echoed the requested function code.
    #[must_use]
    pub fn function_code(&self) -> u8 {
        match self {
            Self::ReadCoils(_) => FunctionCode::ReadCoils.code(),
            Self::ReadDiscreteInputs(_) => FunctionCode::ReadDiscreteInputs.code(),
            Self::ReadHoldingRegisters(_) => FunctionCode::ReadHoldingRegisters.code(),
            Self::ReadInputRegisters(_) => FunctionCode::ReadInputRegisters.code(),
            Self::WriteSingleCoil(_) => FunctionCode::WriteSingleCoil.code(),
            Self::WriteSingleRegister(_) => FunctionCode::WriteSingleRegister.code(),
            Self::ReadExceptionStatus(_) => FunctionCode::ReadExceptionStatus.code(),
            Self::Diagnostics(_) => FunctionCode::Diagnostics.code(),
            Self::GetCommEventCounter(_) => FunctionCode::GetCommEventCounter.code(),
            Self::GetCommEventLog(_) => FunctionCode::GetCommEventLog.code(),
            Self::WriteMultipleCoils(_) => FunctionCode::WriteMultipleCoils.code(),
            Self::WriteMultipleRegisters(_) => FunctionCode::WriteMultipleRegisters.code(),
            Self::ReportServerId(_) => FunctionCode::ReportServerId.code(),
            Self::ReadFileRecord(_) => FunctionCode::ReadFileRecord.code(),
            Self::WriteFileRecord(_) => FunctionCode::WriteFileRecord.code(),
            Self::MaskWriteRegister(_) => FunctionCode::MaskWriteRegister.code(),
            Self::ReadWriteMultipleRegisters(_) => FunctionCode::ReadWriteMultipleRegisters.code(),
            Self::ReadFifoQueue(_) => FunctionCode::ReadFifoQueue.code(),
            Self::EncapsulatedInterface(_) => FunctionCode::EncapsulatedInterfaceTransport.code(),
            Self::Custom(fc, _) => *fc,
            Self::Exception(e) => e.function_code.exception_code(),
        }
    }
}