netget-tool 0.3.4

Network protocol stubbing toolkit: ~280 protocol servers and clients whose responses come from an LLM, a script, a static rule or a person.
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
//! Modbus TCP wire format: MBAP header + PDU.
//!
//! Reference: *MODBUS Application Protocol Specification V1.1b3* and
//! *MODBUS Messaging on TCP/IP Implementation Guide V1.0b*.
//!
//! This module is deliberately free of any I/O, LLM or state: it turns bytes into
//! [`ModbusRequest`] values and turns answers back into bytes. Everything that the
//! specification determines mechanically (frame legality, quantity limits, the shape of
//! a write echo) lives here; everything a device would *decide* (what a register reads
//! as, whether a write is accepted) lives in `actions.rs` and is answered by the model.
//!
//! There is no register file here, by design — see `src/server/modbus/CLAUDE.md`.

/// Length of the MBAP header: transaction id (2), protocol id (2), length (2), unit id (1).
pub const MBAP_HEADER_LEN: usize = 7;

/// Protocol identifier reserved for Modbus in the MBAP header.
pub const MODBUS_PROTOCOL_ID: u16 = 0;

/// Largest legal PDU (function code + data), per the Modbus spec.
pub const MAX_PDU_LEN: usize = 253;

/// Largest legal ADU on TCP: MBAP header + PDU.
pub const MAX_ADU_LEN: usize = MBAP_HEADER_LEN + MAX_PDU_LEN;

// ---------------------------------------------------------------------------
// Function codes
// ---------------------------------------------------------------------------

pub const FC_READ_COILS: u8 = 0x01;
pub const FC_READ_DISCRETE_INPUTS: u8 = 0x02;
pub const FC_READ_HOLDING_REGISTERS: u8 = 0x03;
pub const FC_READ_INPUT_REGISTERS: u8 = 0x04;
pub const FC_WRITE_SINGLE_COIL: u8 = 0x05;
pub const FC_WRITE_SINGLE_REGISTER: u8 = 0x06;
pub const FC_WRITE_MULTIPLE_COILS: u8 = 0x0F;
pub const FC_WRITE_MULTIPLE_REGISTERS: u8 = 0x10;

/// Bit OR-ed into the function code of an exception response.
pub const EXCEPTION_FLAG: u8 = 0x80;

// ---------------------------------------------------------------------------
// Exception codes
// ---------------------------------------------------------------------------

pub const EXC_ILLEGAL_FUNCTION: u8 = 0x01;
pub const EXC_ILLEGAL_DATA_ADDRESS: u8 = 0x02;
pub const EXC_ILLEGAL_DATA_VALUE: u8 = 0x03;
pub const EXC_SERVER_DEVICE_FAILURE: u8 = 0x04;
pub const EXC_ACKNOWLEDGE: u8 = 0x05;
pub const EXC_SERVER_DEVICE_BUSY: u8 = 0x06;
pub const EXC_MEMORY_PARITY_ERROR: u8 = 0x08;
pub const EXC_GATEWAY_PATH_UNAVAILABLE: u8 = 0x0A;
pub const EXC_GATEWAY_TARGET_FAILED: u8 = 0x0B;

/// What [`exception_name`] returns for a code the specification does not define.
///
/// Named rather than spelled out at each site: `execute_action` refuses any code that maps
/// to it, so the two have to agree.
pub const UNKNOWN_EXCEPTION: &str = "unknown_exception";

/// Canonical name for an exception code, for logs and for the model's vocabulary.
pub fn exception_name(code: u8) -> &'static str {
    match code {
        EXC_ILLEGAL_FUNCTION => "illegal_function",
        EXC_ILLEGAL_DATA_ADDRESS => "illegal_data_address",
        EXC_ILLEGAL_DATA_VALUE => "illegal_data_value",
        EXC_SERVER_DEVICE_FAILURE => "server_device_failure",
        EXC_ACKNOWLEDGE => "acknowledge",
        EXC_SERVER_DEVICE_BUSY => "server_device_busy",
        EXC_MEMORY_PARITY_ERROR => "memory_parity_error",
        EXC_GATEWAY_PATH_UNAVAILABLE => "gateway_path_unavailable",
        EXC_GATEWAY_TARGET_FAILED => "gateway_target_device_failed_to_respond",
        _ => UNKNOWN_EXCEPTION,
    }
}

/// Map a canonical exception name back to its code.
pub fn exception_code_from_name(name: &str) -> Option<u8> {
    match name.trim().to_ascii_lowercase().as_str() {
        "illegal_function" | "illegal function" => Some(EXC_ILLEGAL_FUNCTION),
        "illegal_data_address" | "illegal data address" => Some(EXC_ILLEGAL_DATA_ADDRESS),
        "illegal_data_value" | "illegal data value" => Some(EXC_ILLEGAL_DATA_VALUE),
        "server_device_failure" | "server device failure" | "device_failure" => {
            Some(EXC_SERVER_DEVICE_FAILURE)
        }
        "acknowledge" => Some(EXC_ACKNOWLEDGE),
        "server_device_busy" | "server device busy" | "device_busy" => Some(EXC_SERVER_DEVICE_BUSY),
        "memory_parity_error" | "memory parity error" => Some(EXC_MEMORY_PARITY_ERROR),
        "gateway_path_unavailable" | "gateway path unavailable" => {
            Some(EXC_GATEWAY_PATH_UNAVAILABLE)
        }
        "gateway_target_device_failed_to_respond" | "gateway_target_failed" => {
            Some(EXC_GATEWAY_TARGET_FAILED)
        }
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Framing
// ---------------------------------------------------------------------------

/// Why a byte stream could not be turned into a Modbus ADU.
///
/// Both variants are fatal for the connection: neither can be answered with a Modbus
/// exception, because we no longer know where the next frame begins.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FrameError {
    /// The MBAP protocol identifier was not 0, so this is not Modbus at all.
    NotModbus { protocol_id: u16 },
    /// The MBAP length field is outside the legal range `2..=254`
    /// (unit id + 1..=253 PDU bytes).
    BadLength { length: u16 },
}

impl std::fmt::Display for FrameError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FrameError::NotModbus { protocol_id } => write!(
                f,
                "MBAP protocol identifier {protocol_id} is not 0; this is not a Modbus/TCP stream"
            ),
            FrameError::BadLength { length } => write!(
                f,
                "MBAP length field {length} is outside the legal range 2..=254"
            ),
        }
    }
}

/// A value the encoder refuses to put on the wire.
///
/// The mirror image of [`FrameError`], and it exists because the two directions disagreed:
/// [`try_parse_adu`] enforced `2..=254` against a hostile peer while [`encode_adu`] enforced
/// nothing at all against the caller, so a 254-byte PDU produced a frame this codec's own
/// parser rejects. The rule is refuse, never narrow: a byte count silently wrapped by an
/// `as u8` is a frame that claims to carry a different number of registers than it does, and
/// on this protocol a register value is a plant reading.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EncodeError {
    /// The PDU is empty or longer than [`MAX_PDU_LEN`], so the MBAP length field would land
    /// outside the `2..=254` range `try_parse_adu` accepts.
    PduLength { len: usize },
    /// A read response's byte count would not fit the one-octet field, or the PDU it heads
    /// would not fit [`MAX_PDU_LEN`].
    ByteCount { values: usize, bytes: usize },
}

impl std::fmt::Display for EncodeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EncodeError::PduLength { len } => write!(
                f,
                "a Modbus PDU is 1..={MAX_PDU_LEN} octets; {len} given, which the MBAP length \
                 field cannot describe"
            ),
            EncodeError::ByteCount { values, bytes } => write!(
                f,
                "{values} value(s) need {bytes} octets of data, past the {} a read response's \
                 one-octet byte count and the {MAX_PDU_LEN}-octet PDU can carry",
                MAX_PDU_LEN - 2
            ),
        }
    }
}

impl std::error::Error for EncodeError {}

/// A complete Modbus/TCP Application Data Unit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Adu {
    pub transaction_id: u16,
    pub unit_id: u8,
    pub pdu: Vec<u8>,
}

/// Try to pull one complete ADU off the front of `buf`.
///
/// Returns `Ok(None)` when more bytes are needed (the caller should accumulate and retry),
/// `Ok(Some((adu, consumed)))` on success, and `Err` when the stream is not Modbus.
pub fn try_parse_adu(buf: &[u8]) -> Result<Option<(Adu, usize)>, FrameError> {
    if buf.len() < MBAP_HEADER_LEN {
        return Ok(None);
    }

    let transaction_id = u16::from_be_bytes([buf[0], buf[1]]);
    let protocol_id = u16::from_be_bytes([buf[2], buf[3]]);
    let length = u16::from_be_bytes([buf[4], buf[5]]);

    if protocol_id != MODBUS_PROTOCOL_ID {
        return Err(FrameError::NotModbus { protocol_id });
    }

    // `length` counts the unit id plus the PDU.
    if length < 2 || length as usize > MAX_PDU_LEN + 1 {
        return Err(FrameError::BadLength { length });
    }

    let total = 6 + length as usize;
    if buf.len() < total {
        return Ok(None);
    }

    let unit_id = buf[6];
    let pdu = buf[MBAP_HEADER_LEN..total].to_vec();

    Ok(Some((
        Adu {
            transaction_id,
            unit_id,
            pdu,
        },
        total,
    )))
}

/// Wrap a PDU in an MBAP header addressed back to the requester.
///
/// Refuses any PDU [`try_parse_adu`] would not accept back. Without the check a 254-byte PDU
/// produced a length field of 255 — outside the `2..=254` the parser enforces — and past
/// 65534 octets the `(pdu.len() as u16) + 1` overflowed, which panics in every debug and test
/// build and wrapped silently before `[profile.release] overflow-checks` was turned on.
pub fn encode_adu(transaction_id: u16, unit_id: u8, pdu: &[u8]) -> Result<Vec<u8>, EncodeError> {
    if pdu.is_empty() || pdu.len() > MAX_PDU_LEN {
        return Err(EncodeError::PduLength { len: pdu.len() });
    }
    let mut out = Vec::with_capacity(MBAP_HEADER_LEN + pdu.len());
    out.extend_from_slice(&transaction_id.to_be_bytes());
    out.extend_from_slice(&MODBUS_PROTOCOL_ID.to_be_bytes());
    // Range-checked above, so neither the cast nor the increment can wrap.
    out.extend_from_slice(&((pdu.len() as u16) + 1).to_be_bytes());
    out.push(unit_id);
    out.extend_from_slice(pdu);
    Ok(out)
}

// ---------------------------------------------------------------------------
// Requests
// ---------------------------------------------------------------------------

/// A decoded, spec-legal Modbus request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModbusRequest {
    ReadCoils { start: u16, quantity: u16 },
    ReadDiscreteInputs { start: u16, quantity: u16 },
    ReadHoldingRegisters { start: u16, quantity: u16 },
    ReadInputRegisters { start: u16, quantity: u16 },
    WriteSingleCoil { address: u16, value: bool },
    WriteSingleRegister { address: u16, value: u16 },
    WriteMultipleCoils { start: u16, values: Vec<bool> },
    WriteMultipleRegisters { start: u16, values: Vec<u16> },
}

impl ModbusRequest {
    pub fn function_code(&self) -> u8 {
        match self {
            ModbusRequest::ReadCoils { .. } => FC_READ_COILS,
            ModbusRequest::ReadDiscreteInputs { .. } => FC_READ_DISCRETE_INPUTS,
            ModbusRequest::ReadHoldingRegisters { .. } => FC_READ_HOLDING_REGISTERS,
            ModbusRequest::ReadInputRegisters { .. } => FC_READ_INPUT_REGISTERS,
            ModbusRequest::WriteSingleCoil { .. } => FC_WRITE_SINGLE_COIL,
            ModbusRequest::WriteSingleRegister { .. } => FC_WRITE_SINGLE_REGISTER,
            ModbusRequest::WriteMultipleCoils { .. } => FC_WRITE_MULTIPLE_COILS,
            ModbusRequest::WriteMultipleRegisters { .. } => FC_WRITE_MULTIPLE_REGISTERS,
        }
    }

    /// Stable, human/model-readable name of the function.
    pub fn function_name(&self) -> &'static str {
        match self {
            ModbusRequest::ReadCoils { .. } => "read_coils",
            ModbusRequest::ReadDiscreteInputs { .. } => "read_discrete_inputs",
            ModbusRequest::ReadHoldingRegisters { .. } => "read_holding_registers",
            ModbusRequest::ReadInputRegisters { .. } => "read_input_registers",
            ModbusRequest::WriteSingleCoil { .. } => "write_single_coil",
            ModbusRequest::WriteSingleRegister { .. } => "write_single_register",
            ModbusRequest::WriteMultipleCoils { .. } => "write_multiple_coils",
            ModbusRequest::WriteMultipleRegisters { .. } => "write_multiple_registers",
        }
    }

    /// First address touched by this request.
    pub fn start_address(&self) -> u16 {
        match self {
            ModbusRequest::ReadCoils { start, .. }
            | ModbusRequest::ReadDiscreteInputs { start, .. }
            | ModbusRequest::ReadHoldingRegisters { start, .. }
            | ModbusRequest::ReadInputRegisters { start, .. }
            | ModbusRequest::WriteMultipleCoils { start, .. }
            | ModbusRequest::WriteMultipleRegisters { start, .. } => *start,
            ModbusRequest::WriteSingleCoil { address, .. }
            | ModbusRequest::WriteSingleRegister { address, .. } => *address,
        }
    }

    /// How many coils/registers this request touches.
    pub fn quantity(&self) -> u16 {
        match self {
            ModbusRequest::ReadCoils { quantity, .. }
            | ModbusRequest::ReadDiscreteInputs { quantity, .. }
            | ModbusRequest::ReadHoldingRegisters { quantity, .. }
            | ModbusRequest::ReadInputRegisters { quantity, .. } => *quantity,
            ModbusRequest::WriteSingleCoil { .. } | ModbusRequest::WriteSingleRegister { .. } => 1,
            ModbusRequest::WriteMultipleCoils { values, .. } => values.len() as u16,
            ModbusRequest::WriteMultipleRegisters { values, .. } => values.len() as u16,
        }
    }

    /// True for FC 1/2 — the answer is a list of bits.
    pub fn is_bit_read(&self) -> bool {
        matches!(
            self,
            ModbusRequest::ReadCoils { .. } | ModbusRequest::ReadDiscreteInputs { .. }
        )
    }

    /// True for FC 3/4 — the answer is a list of 16-bit registers.
    pub fn is_register_read(&self) -> bool {
        matches!(
            self,
            ModbusRequest::ReadHoldingRegisters { .. } | ModbusRequest::ReadInputRegisters { .. }
        )
    }

    /// True for FC 5/6/15/16.
    pub fn is_write(&self) -> bool {
        !self.is_bit_read() && !self.is_register_read()
    }
}

/// Decode a PDU.
///
/// The error carries the exception code the specification prescribes, which the caller
/// answers with directly — no model round-trip, because none of these is a decision:
/// an unknown function code is *always* `0x01`, a quantity of 0 is *always* `0x03`.
pub fn parse_request(pdu: &[u8]) -> Result<ModbusRequest, u8> {
    let Some(&fc) = pdu.first() else {
        return Err(EXC_ILLEGAL_FUNCTION);
    };
    let body = &pdu[1..];

    // Reads and the two "write multiple" headers all start with a u16 pair.
    let pair = |b: &[u8]| -> Option<(u16, u16)> {
        if b.len() < 4 {
            None
        } else {
            Some((
                u16::from_be_bytes([b[0], b[1]]),
                u16::from_be_bytes([b[2], b[3]]),
            ))
        }
    };

    match fc {
        FC_READ_COILS | FC_READ_DISCRETE_INPUTS => {
            let (start, quantity) = pair(body).ok_or(EXC_ILLEGAL_DATA_VALUE)?;
            if !(1..=2000).contains(&quantity) {
                return Err(EXC_ILLEGAL_DATA_VALUE);
            }
            check_range(start, quantity)?;
            Ok(if fc == FC_READ_COILS {
                ModbusRequest::ReadCoils { start, quantity }
            } else {
                ModbusRequest::ReadDiscreteInputs { start, quantity }
            })
        }
        FC_READ_HOLDING_REGISTERS | FC_READ_INPUT_REGISTERS => {
            let (start, quantity) = pair(body).ok_or(EXC_ILLEGAL_DATA_VALUE)?;
            if !(1..=125).contains(&quantity) {
                return Err(EXC_ILLEGAL_DATA_VALUE);
            }
            check_range(start, quantity)?;
            Ok(if fc == FC_READ_HOLDING_REGISTERS {
                ModbusRequest::ReadHoldingRegisters { start, quantity }
            } else {
                ModbusRequest::ReadInputRegisters { start, quantity }
            })
        }
        FC_WRITE_SINGLE_COIL => {
            let (address, raw) = pair(body).ok_or(EXC_ILLEGAL_DATA_VALUE)?;
            let value = match raw {
                0x0000 => false,
                0xFF00 => true,
                // The spec allows exactly these two encodings; anything else is a
                // data-value error, not a device decision.
                _ => return Err(EXC_ILLEGAL_DATA_VALUE),
            };
            Ok(ModbusRequest::WriteSingleCoil { address, value })
        }
        FC_WRITE_SINGLE_REGISTER => {
            let (address, value) = pair(body).ok_or(EXC_ILLEGAL_DATA_VALUE)?;
            Ok(ModbusRequest::WriteSingleRegister { address, value })
        }
        FC_WRITE_MULTIPLE_COILS => {
            let (start, quantity) = pair(body).ok_or(EXC_ILLEGAL_DATA_VALUE)?;
            if !(1..=1968).contains(&quantity) {
                return Err(EXC_ILLEGAL_DATA_VALUE);
            }
            check_range(start, quantity)?;
            let byte_count = *body.get(4).ok_or(EXC_ILLEGAL_DATA_VALUE)? as usize;
            let expected = quantity.div_ceil(8) as usize;
            if byte_count != expected || body.len() < 5 + byte_count {
                return Err(EXC_ILLEGAL_DATA_VALUE);
            }
            let data = &body[5..5 + byte_count];
            let values = (0..quantity as usize)
                .map(|i| data[i / 8] & (1 << (i % 8)) != 0)
                .collect();
            Ok(ModbusRequest::WriteMultipleCoils { start, values })
        }
        FC_WRITE_MULTIPLE_REGISTERS => {
            let (start, quantity) = pair(body).ok_or(EXC_ILLEGAL_DATA_VALUE)?;
            if !(1..=123).contains(&quantity) {
                return Err(EXC_ILLEGAL_DATA_VALUE);
            }
            check_range(start, quantity)?;
            let byte_count = *body.get(4).ok_or(EXC_ILLEGAL_DATA_VALUE)? as usize;
            if byte_count != quantity as usize * 2 || body.len() < 5 + byte_count {
                return Err(EXC_ILLEGAL_DATA_VALUE);
            }
            let data = &body[5..5 + byte_count];
            let values = data
                .chunks_exact(2)
                .map(|c| u16::from_be_bytes([c[0], c[1]]))
                .collect();
            Ok(ModbusRequest::WriteMultipleRegisters { start, values })
        }
        _ => Err(EXC_ILLEGAL_FUNCTION),
    }
}

/// `start + quantity` must stay inside the 16-bit address space.
fn check_range(start: u16, quantity: u16) -> Result<(), u8> {
    if start as u32 + quantity as u32 > 0x1_0000 {
        Err(EXC_ILLEGAL_DATA_ADDRESS)
    } else {
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Responses
// ---------------------------------------------------------------------------

/// Most data octets a read response can carry: the PDU ceiling less the function code and the
/// byte-count octet. The byte count is one octet, and `MAX_PDU_LEN - 2` is 251, so the PDU
/// bound is the tighter of the two and the only one that has to be stated.
pub const MAX_READ_RESPONSE_DATA: usize = MAX_PDU_LEN - 2;

/// PDU for a FC 1/2 read response: byte count then packed bits, least-significant bit
/// of the first byte carrying the first requested coil.
///
/// Refuses a value list whose byte count would not fit rather than narrowing it with an
/// `as u8`. At 2040 bits the narrowed count was 255 and at 2048 it was 0, both followed by
/// the full data — a frame that lies about its own length.
pub fn encode_bits_response(function_code: u8, values: &[bool]) -> Result<Vec<u8>, EncodeError> {
    let byte_count = values.len().div_ceil(8);
    if byte_count > MAX_READ_RESPONSE_DATA {
        return Err(EncodeError::ByteCount {
            values: values.len(),
            bytes: byte_count,
        });
    }
    let mut pdu = Vec::with_capacity(2 + byte_count);
    pdu.push(function_code);
    // Range-checked above, so the cast cannot lose a bit.
    pdu.push(byte_count as u8);
    let mut packed = vec![0u8; byte_count];
    for (i, &on) in values.iter().enumerate() {
        if on {
            packed[i / 8] |= 1 << (i % 8);
        }
    }
    pdu.extend_from_slice(&packed);
    Ok(pdu)
}

/// PDU for a FC 3/4 read response: byte count then big-endian registers.
///
/// Refuses past [`MAX_READ_RESPONSE_DATA`]. At 128 registers the old `(values.len() * 2) as u8`
/// declared a byte count of **0** and then wrote 256 octets of data behind it.
pub fn encode_registers_response(
    function_code: u8,
    values: &[u16],
) -> Result<Vec<u8>, EncodeError> {
    let byte_count = values.len() * 2;
    if byte_count > MAX_READ_RESPONSE_DATA {
        return Err(EncodeError::ByteCount {
            values: values.len(),
            bytes: byte_count,
        });
    }
    let mut pdu = Vec::with_capacity(2 + byte_count);
    pdu.push(function_code);
    // Range-checked above, so the cast cannot lose a bit.
    pdu.push(byte_count as u8);
    for v in values {
        pdu.extend_from_slice(&v.to_be_bytes());
    }
    Ok(pdu)
}

/// PDU acknowledging a write.
///
/// FC 5 and 6 echo the request verbatim; FC 15 and 16 echo the starting address and the
/// quantity written. Reconstructed from the parsed request rather than copied from the
/// input bytes, so a malformed echo cannot be produced.
pub fn encode_write_ack(request: &ModbusRequest) -> Vec<u8> {
    let mut pdu = Vec::with_capacity(5);
    pdu.push(request.function_code());
    match request {
        ModbusRequest::WriteSingleCoil { address, value } => {
            pdu.extend_from_slice(&address.to_be_bytes());
            pdu.extend_from_slice(&if *value { 0xFF00u16 } else { 0x0000u16 }.to_be_bytes());
        }
        ModbusRequest::WriteSingleRegister { address, value } => {
            pdu.extend_from_slice(&address.to_be_bytes());
            pdu.extend_from_slice(&value.to_be_bytes());
        }
        ModbusRequest::WriteMultipleCoils { start, values } => {
            pdu.extend_from_slice(&start.to_be_bytes());
            pdu.extend_from_slice(&(values.len() as u16).to_be_bytes());
        }
        ModbusRequest::WriteMultipleRegisters { start, values } => {
            pdu.extend_from_slice(&start.to_be_bytes());
            pdu.extend_from_slice(&(values.len() as u16).to_be_bytes());
        }
        // Not a write; the caller checks this, but produce something legal rather than
        // panicking on a programming error.
        _ => {
            pdu.clear();
            pdu.push(request.function_code() | EXCEPTION_FLAG);
            pdu.push(EXC_SERVER_DEVICE_FAILURE);
        }
    }
    pdu
}

/// PDU for an exception response: `function_code | 0x80`, then the exception code.
pub fn encode_exception(function_code: u8, exception_code: u8) -> Vec<u8> {
    vec![function_code | EXCEPTION_FLAG, exception_code]
}

// ---------------------------------------------------------------------------
// The client side: requests out, responses in
// ---------------------------------------------------------------------------
//
// The same grammar read the other way round, for `src/client/modbus`. It lives here rather than
// in the client so the two directions cannot drift: the client's encoder is checked against
// this module's own `parse_request`, the decoder the server answers real masters with.

/// Encode a request's PDU.
///
/// Refuses anything [`parse_request`] would answer with an exception — a quantity outside the
/// function's range, an address range past `0xFFFF` — so the client never puts on the wire a
/// request the specification already says no to. The refusal names the reason.
pub fn encode_request(request: &ModbusRequest) -> Result<Vec<u8>, String> {
    let mut pdu = Vec::with_capacity(8);
    pdu.push(request.function_code());
    let quantity_of = |n: usize, what: &str| -> Result<u16, String> {
        u16::try_from(n).map_err(|_| format!("{n} {what} do not fit a Modbus quantity"))
    };
    let byte_count_of = |octets: usize, n: usize, what: &str| -> Result<u8, String> {
        u8::try_from(octets)
            .map_err(|_| format!("{n} {what} need {octets} octets, past a one-octet byte count"))
    };
    match request {
        ModbusRequest::ReadCoils { start, quantity }
        | ModbusRequest::ReadDiscreteInputs { start, quantity }
        | ModbusRequest::ReadHoldingRegisters { start, quantity }
        | ModbusRequest::ReadInputRegisters { start, quantity } => {
            pdu.extend_from_slice(&start.to_be_bytes());
            pdu.extend_from_slice(&quantity.to_be_bytes());
        }
        ModbusRequest::WriteSingleCoil { address, value } => {
            pdu.extend_from_slice(&address.to_be_bytes());
            pdu.extend_from_slice(&if *value { 0xFF00u16 } else { 0x0000 }.to_be_bytes());
        }
        ModbusRequest::WriteSingleRegister { address, value } => {
            pdu.extend_from_slice(&address.to_be_bytes());
            pdu.extend_from_slice(&value.to_be_bytes());
        }
        ModbusRequest::WriteMultipleCoils { start, values } => {
            let quantity = quantity_of(values.len(), "coils")?;
            let octets = values.len().div_ceil(8);
            pdu.extend_from_slice(&start.to_be_bytes());
            pdu.extend_from_slice(&quantity.to_be_bytes());
            pdu.push(byte_count_of(octets, values.len(), "coils")?);
            let mut packed = vec![0u8; octets];
            for (i, &on) in values.iter().enumerate() {
                if on {
                    packed[i / 8] |= 1 << (i % 8);
                }
            }
            pdu.extend_from_slice(&packed);
        }
        ModbusRequest::WriteMultipleRegisters { start, values } => {
            let quantity = quantity_of(values.len(), "registers")?;
            let octets = values.len() * 2;
            pdu.extend_from_slice(&start.to_be_bytes());
            pdu.extend_from_slice(&quantity.to_be_bytes());
            pdu.push(byte_count_of(octets, values.len(), "registers")?);
            for v in values {
                pdu.extend_from_slice(&v.to_be_bytes());
            }
        }
    }
    match parse_request(&pdu) {
        Ok(decoded) if &decoded == request => Ok(pdu),
        Ok(_) => Err("the request does not survive its own encoding".to_string()),
        Err(code) => Err(format!(
            "{} at address {} for {} item(s) is not a legal Modbus request ({})",
            request.function_name(),
            request.start_address(),
            request.quantity(),
            exception_name(code)
        )),
    }
}

/// A decoded response, checked against the request it answers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModbusResponse {
    /// FC 1/2: exactly the requested number of bits, first requested item first.
    Bits(Vec<bool>),
    /// FC 3/4: exactly the requested number of registers.
    Registers(Vec<u16>),
    /// FC 5/6/15/16: the acknowledgement echoed the request.
    WriteAck,
    /// `function | 0x80`, then the exception code.
    Exception { code: u8 },
}

/// Decode a response PDU against the request it answers.
///
/// Every field the specification fixes is checked, because a response that disagrees with its
/// request is a server answering a different question: the function code (or its exception
/// form), the byte count against the quantity asked for, the PDU length against the byte count,
/// and a write's acknowledgement against what was written. The error says which.
pub fn parse_response(pdu: &[u8], request: &ModbusRequest) -> Result<ModbusResponse, String> {
    let fc = request.function_code();
    let Some(&got) = pdu.first() else {
        return Err("empty response PDU".to_string());
    };
    if got == fc | EXCEPTION_FLAG {
        return match pdu {
            [_, code] => Ok(ModbusResponse::Exception { code: *code }),
            _ => Err(format!(
                "exception response is {} octets; it is exactly 2",
                pdu.len()
            )),
        };
    }
    if got != fc {
        return Err(format!(
            "response carries function code {got:#04x}; the request was {fc:#04x}"
        ));
    }
    let quantity = usize::from(request.quantity());
    if request.is_bit_read() || request.is_register_read() {
        let Some((&byte_count, data)) = pdu[1..].split_first() else {
            return Err("read response has no byte count".to_string());
        };
        let expected = if request.is_bit_read() {
            quantity.div_ceil(8)
        } else {
            quantity * 2
        };
        if usize::from(byte_count) != expected || data.len() != expected {
            return Err(format!(
                "read response declares {byte_count} octets and carries {}; {quantity} \
                 item(s) need {expected}",
                data.len()
            ));
        }
        return Ok(if request.is_bit_read() {
            ModbusResponse::Bits(
                (0..quantity)
                    .map(|i| data[i / 8] & (1 << (i % 8)) != 0)
                    .collect(),
            )
        } else {
            ModbusResponse::Registers(
                data.chunks_exact(2)
                    .map(|c| u16::from_be_bytes([c[0], c[1]]))
                    .collect(),
            )
        });
    }
    // A write: the acknowledgement is fixed by the request, so compare it byte for byte.
    let echo = encode_write_ack(request);
    if pdu == echo.as_slice() {
        Ok(ModbusResponse::WriteAck)
    } else {
        Err(format!(
            "write acknowledgement {} does not echo the request {}",
            hex::encode(pdu),
            hex::encode(&echo)
        ))
    }
}