Skip to main content

viva_gencp/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2//! GenCP: generic control protocol encode/decode (transport-agnostic).
3
4use bitflags::bitflags;
5use bytes::{Buf, Bytes};
6use thiserror::Error;
7
8/// Size of the GenCP header (in bytes).
9pub const HEADER_SIZE: usize = 8;
10
11bitflags! {
12    /// Flags that can be set on a GenCP command packet.
13    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
14    pub struct CommandFlags: u16 {
15        /// Request an acknowledgement for this command.
16        const ACK_REQUIRED = 0x0001;
17        /// Mark the command as a broadcast.
18        const BROADCAST = 0x8000;
19        /// GVCP `ACTION_CMD` only: the payload carries a scheduled action time.
20        ///
21        /// These bit values are this crate's own representation; the mapping to
22        /// the single GVCP flags byte lives in `viva_gige::gvcp`.
23        const SCHEDULED_ACTION = 0x0002;
24    }
25}
26
27/// GenCP command ids (GenCP 1.2, Table 7) — what USB3 Vision carries.
28///
29/// These are not [`OpCode`]'s values: those are GVCP's opcodes, which GigE
30/// Vision uses for the same operations and which no GenCP device understands.
31/// A command id has its least significant bit clear; the acknowledge's is the
32/// same id with that bit set.
33pub mod command_id {
34    /// Read a block of the device's register map.
35    pub const READMEM_CMD: u16 = 0x0800;
36    /// Answer to [`READMEM_CMD`], carrying the data read.
37    pub const READMEM_ACK: u16 = 0x0801;
38    /// Write a block of the device's register map.
39    pub const WRITEMEM_CMD: u16 = 0x0802;
40    /// Answer to [`WRITEMEM_CMD`].
41    pub const WRITEMEM_ACK: u16 = 0x0803;
42    /// The device needs more time; see [`PENDING_ACK_COMMAND`](super::PENDING_ACK_COMMAND).
43    pub const PENDING_ACK: u16 = 0x0805;
44    /// An event the device sends unasked.
45    pub const EVENT_CMD: u16 = 0x0C00;
46    /// The host's answer to [`EVENT_CMD`].
47    pub const EVENT_ACK: u16 = 0x0C01;
48}
49
50/// Flag bits of a GenCP command's `flags` field (GenCP 1.2, Table 4).
51///
52/// Not [`CommandFlags`], whose bit values are this crate's GVCP
53/// representation: a GenCP device ignores a command without
54/// [`REQUEST_ACK`](ccd_flags::REQUEST_ACK) set, and answers nothing.
55pub mod ccd_flags {
56    /// The sender wants an acknowledge.
57    pub const REQUEST_ACK: u16 = 1 << 14;
58    /// The command is a retry of one whose acknowledge never arrived.
59    pub const COMMAND_RESEND: u16 = 1 << 15;
60}
61
62/// Command id of the GenCP pending-acknowledge.
63///
64/// A device that cannot answer within the controller's timeout replies with
65/// this instead of the real acknowledgement, and puts the extra time it wants
66/// in the SCD. It is a **command id, not a status** — the status field of a
67/// pending-ack is `SUCCESS`, so a receiver that only inspects the status
68/// cannot tell one from a real answer and will hand the timeout bytes back as
69/// payload. GVCP models the same mechanism the same way, as opcode `0x0089`
70/// (`viva_gige::consts::PENDING_ACK`).
71pub const PENDING_ACK_COMMAND: u16 = command_id::PENDING_ACK;
72
73/// GVCP operation codes for the GenCP-style operations GigE Vision carries.
74///
75/// The values are GVCP's (`READREG_CMD` `0x0080` …). A USB3 Vision device
76/// speaks GenCP proper and knows none of them: its ids are in [`command_id`].
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum OpCode {
79    /// Read a single bootstrap or device register.
80    ReadRegister,
81    /// Write a single bootstrap or device register.
82    WriteRegister,
83    /// Read a block of memory from the device.
84    ReadMem,
85    /// Write a block of memory to the device.
86    WriteMem,
87}
88
89impl OpCode {
90    /// Raw command value as GVCP defines it.
91    pub const fn command_code(self) -> u16 {
92        match self {
93            OpCode::ReadRegister => 0x0080,
94            OpCode::WriteRegister => 0x0082,
95            OpCode::ReadMem => 0x0084,
96            OpCode::WriteMem => 0x0086,
97        }
98    }
99
100    /// Raw acknowledgement value as defined by the specification.
101    pub const fn ack_code(self) -> u16 {
102        self.command_code() + 1
103    }
104
105    #[allow(dead_code)]
106    fn from_command(code: u16) -> Result<Self, GenCpError> {
107        match code {
108            0x0080 => Ok(OpCode::ReadRegister),
109            0x0082 => Ok(OpCode::WriteRegister),
110            0x0084 => Ok(OpCode::ReadMem),
111            0x0086 => Ok(OpCode::WriteMem),
112            _ => Err(GenCpError::UnknownOpcode(code)),
113        }
114    }
115
116    fn from_ack(code: u16) -> Result<Self, GenCpError> {
117        match code {
118            0x0081 => Ok(OpCode::ReadRegister),
119            0x0083 => Ok(OpCode::WriteRegister),
120            0x0085 => Ok(OpCode::ReadMem),
121            0x0087 => Ok(OpCode::WriteMem),
122            _ => Err(GenCpError::UnknownOpcode(code)),
123        }
124    }
125}
126
127/// Status codes shared by the GVCP and GenCP acknowledgement tables.
128///
129/// Only the codes **both** protocols define, under the same name and meaning,
130/// live here: `0x0000`, `0x8001`–`0x8007`, `0x800E`, `0x800F` and `0x8FFF`.
131/// Elsewhere the tables diverge, and at `0x800B` they actively disagree —
132/// GVCP calls it `NO_MSG` (deprecated), GenCP calls it `MSG_TIMEOUT` — so
133/// each transport decodes its acknowledgements with a status type of its own
134/// that wraps this one: `viva_gige::GigeStatus` and `viva_u3v::U3vStatus`
135/// (ADR-0020).
136///
137/// There is no `Unknown` here: [`StatusCode::from_raw`] returns `None` for a
138/// code outside the shared core, and the transport's own type names it or
139/// keeps it as unknown.
140///
141/// Values corroborated by Wireshark's GVCP dissector
142/// (`epan/dissectors/packet-gvcp.c`, `GEV_STATUS_*`) and aravis
143/// (`arvgvcpprivate.h`, `arvgvspprivate.h`, `arvuvcpprivate.h`), which agree
144/// with each other.
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
146#[non_exhaustive]
147pub enum StatusCode {
148    /// Command completed successfully.
149    Success,
150    /// The requested command is not implemented by the device.
151    NotImplemented,
152    /// One of the command parameters was invalid or out of range.
153    InvalidParameter,
154    /// The requested address does not exist on the device.
155    InvalidAddress,
156    /// Attempt to write to a read-only register.
157    ///
158    /// A permanent condition: retrying cannot make it succeed.
159    WriteProtect,
160    /// The access was not aligned as the underlying technology requires.
161    BadAlignment,
162    /// Attempt to read a non-readable, or write a non-writable, register.
163    ///
164    /// Distinct from [`StatusCode::WriteProtect`]: the register accepts
165    /// writes in principle but the device is refusing this one, typically
166    /// because a GenApi lock is engaged or control privilege is not held.
167    AccessDenied,
168    /// The device is busy and the command may succeed if retried.
169    ///
170    /// The only status in this table worth a retry.
171    Busy,
172    /// The command's header is invalid: its fields, or its length against
173    /// the bytes that arrived.
174    InvalidHeader,
175    /// The device's current configuration does not allow the command.
176    /// Deprecated in GigE Vision.
177    WrongConfig,
178    /// The device reported a generic error with nothing more specific.
179    GenericError,
180}
181
182impl StatusCode {
183    /// The shared meaning of a raw status, or `None` for a code outside the
184    /// shared core — one a transport defines, or one nobody does.
185    pub const fn from_raw(raw: u16) -> Option<Self> {
186        Some(match raw {
187            0x0000 => StatusCode::Success,
188            0x8001 => StatusCode::NotImplemented,
189            0x8002 => StatusCode::InvalidParameter,
190            0x8003 => StatusCode::InvalidAddress,
191            0x8004 => StatusCode::WriteProtect,
192            0x8005 => StatusCode::BadAlignment,
193            0x8006 => StatusCode::AccessDenied,
194            0x8007 => StatusCode::Busy,
195            0x800E => StatusCode::InvalidHeader,
196            0x800F => StatusCode::WrongConfig,
197            0x8FFF => StatusCode::GenericError,
198            _ => return None,
199        })
200    }
201
202    /// Convert to the raw value stored in the packet header.
203    pub const fn to_raw(self) -> u16 {
204        match self {
205            StatusCode::Success => 0x0000,
206            StatusCode::NotImplemented => 0x8001,
207            StatusCode::InvalidParameter => 0x8002,
208            StatusCode::InvalidAddress => 0x8003,
209            StatusCode::WriteProtect => 0x8004,
210            StatusCode::BadAlignment => 0x8005,
211            StatusCode::AccessDenied => 0x8006,
212            StatusCode::Busy => 0x8007,
213            StatusCode::InvalidHeader => 0x800E,
214            StatusCode::WrongConfig => 0x800F,
215            StatusCode::GenericError => 0x8FFF,
216        }
217    }
218
219    /// The specification's name for this code, for diagnostics.
220    pub const fn name(self) -> &'static str {
221        match self {
222            StatusCode::Success => "SUCCESS",
223            StatusCode::NotImplemented => "NOT_IMPLEMENTED",
224            StatusCode::InvalidParameter => "INVALID_PARAMETER",
225            StatusCode::InvalidAddress => "INVALID_ADDRESS",
226            StatusCode::WriteProtect => "WRITE_PROTECT",
227            StatusCode::BadAlignment => "BAD_ALIGNMENT",
228            StatusCode::AccessDenied => "ACCESS_DENIED",
229            StatusCode::Busy => "BUSY",
230            StatusCode::InvalidHeader => "INVALID_HEADER",
231            StatusCode::WrongConfig => "WRONG_CONFIG",
232            StatusCode::GenericError => "ERROR",
233        }
234    }
235
236    /// Whether retrying the command could plausibly succeed.
237    ///
238    /// True only for [`StatusCode::Busy`]. Notably *not* `WriteProtect` or
239    /// `AccessDenied`, which are refusals rather than congestion.
240    pub const fn is_retryable(self) -> bool {
241        matches!(self, StatusCode::Busy)
242    }
243}
244
245/// Prints the specification name **and** the raw hex value.
246///
247/// Both halves matter: the name is what makes an error actionable, and the
248/// raw value is what lets a reporter match it against a capture. A bare
249/// decimal — which is what `{:?}` on the old `Unknown(32774)` produced —
250/// sent a user to the issue tracker in #45 unable to tell us anything.
251impl std::fmt::Display for StatusCode {
252    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253        write!(f, "{} (0x{:04X})", self.name(), self.to_raw())
254    }
255}
256
257/// Defines a transport's status type: the shared [`StatusCode`] core, the
258/// transport's own codes, and `Unknown` for the rest (ADR-0020).
259///
260/// Used by `viva-gige` and `viva-u3v`, so the two types are built the same
261/// way and print the same way: the name and the raw hex, never bare decimal.
262#[macro_export]
263#[doc(hidden)]
264macro_rules! transport_status {
265    (
266        $(#[$meta:meta])*
267        $vis:vis enum $name:ident {
268            $(
269                $(#[$variant_meta:meta])*
270                $variant:ident = $raw:literal, $spec:literal;
271            )*
272        }
273    ) => {
274        $(#[$meta])*
275        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
276        #[non_exhaustive]
277        $vis enum $name {
278            /// A code GenCP and GigE Vision share: see
279            /// `viva_gencp::StatusCode`.
280            Common($crate::StatusCode),
281            $(
282                $(#[$variant_meta])*
283                $variant,
284            )*
285            /// A code neither this transport's table nor the shared core
286            /// names. Carries the raw value so it can still be reported.
287            Unknown(u16),
288        }
289
290        impl $name {
291            /// Decode the raw status field of an acknowledgement.
292            pub const fn from_raw(raw: u16) -> Self {
293                match raw {
294                    $($raw => $name::$variant,)*
295                    _ => match $crate::StatusCode::from_raw(raw) {
296                        Some(common) => $name::Common(common),
297                        None => $name::Unknown(raw),
298                    },
299                }
300            }
301
302            /// The raw value, as the acknowledgement carries it.
303            pub const fn to_raw(self) -> u16 {
304                match self {
305                    $name::Common(common) => common.to_raw(),
306                    $($name::$variant => $raw,)*
307                    $name::Unknown(raw) => raw,
308                }
309            }
310
311            /// The specification's name for this code, for diagnostics.
312            pub const fn name(self) -> &'static str {
313                match self {
314                    $name::Common(common) => common.name(),
315                    $($name::$variant => $spec,)*
316                    $name::Unknown(_) => "unknown status",
317                }
318            }
319
320            /// The shared meaning, for a code in the core both transports
321            /// define.
322            pub const fn common(self) -> Option<$crate::StatusCode> {
323                match self {
324                    $name::Common(common) => Some(common),
325                    _ => None,
326                }
327            }
328
329            /// Whether this is `SUCCESS`.
330            pub const fn is_success(self) -> bool {
331                matches!(self, $name::Common($crate::StatusCode::Success))
332            }
333
334            /// Whether retrying the command could plausibly succeed: only
335            /// `BUSY`.
336            pub const fn is_retryable(self) -> bool {
337                matches!(self, $name::Common($crate::StatusCode::Busy))
338            }
339        }
340
341        impl From<$crate::StatusCode> for $name {
342            fn from(common: $crate::StatusCode) -> Self {
343                $name::Common(common)
344            }
345        }
346
347        /// Prints the specification name and the raw hex value.
348        impl ::std::fmt::Display for $name {
349            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
350                write!(f, "{} (0x{:04X})", self.name(), self.to_raw())
351            }
352        }
353    };
354}
355
356/// Errors that can occur when dealing with GenCP packets.
357#[derive(Debug, Error)]
358#[non_exhaustive]
359pub enum GenCpError {
360    #[error("invalid packet: {0}")]
361    /// The packet is malformed: too short, or its length field disagrees.
362    InvalidPacket(&'static str),
363    #[error("unknown opcode: {0:#06x}")]
364    /// An acknowledgement carries a command id this crate does not know.
365    UnknownOpcode(u16),
366    #[error("io: {0}")]
367    /// A socket operation failed.
368    Io(#[from] std::io::Error),
369}
370
371/// Header of a GVCP acknowledgement.
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373pub struct AckHeader {
374    /// Status returned by the device, raw: GigE Vision decodes it with its own
375    /// table (`viva_gige::GigeStatus`), which [`StatusCode`] is the shared
376    /// core of.
377    pub status: u16,
378    /// Operation code associated with the acknowledgement.
379    pub opcode: OpCode,
380    /// Length of the payload in bytes.
381    pub length: u16,
382    /// Request identifier that this acknowledgement answers.
383    pub request_id: u16,
384}
385
386/// GenCP acknowledgement packet.
387#[derive(Debug, Clone)]
388pub struct GenCpAck {
389    /// Header fields returned by the device.
390    pub header: AckHeader,
391    /// Payload data (command specific).
392    pub payload: Bytes,
393}
394
395/// Decode a GenCP acknowledgement from raw bytes.
396pub fn decode_ack(buf: &[u8]) -> Result<GenCpAck, GenCpError> {
397    if buf.len() < HEADER_SIZE {
398        return Err(GenCpError::InvalidPacket("too short"));
399    }
400    let mut cursor = buf;
401    let status_raw = cursor.get_u16();
402    let opcode_raw = cursor.get_u16();
403    let length = cursor.get_u16();
404    let request_id = cursor.get_u16();
405
406    let expected = HEADER_SIZE + length as usize;
407    if buf.len() != expected {
408        return Err(GenCpError::InvalidPacket("length mismatch"));
409    }
410
411    let opcode = OpCode::from_ack(opcode_raw)?;
412
413    let payload = Bytes::copy_from_slice(&buf[HEADER_SIZE..]);
414    Ok(GenCpAck {
415        header: AckHeader {
416            status: status_raw,
417            opcode,
418            length,
419            request_id,
420        },
421        payload,
422    })
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use bytes::{BufMut, BytesMut};
429
430    /// The shared status table, written as literal values rather than derived
431    /// from `to_raw` — per ADR-0019, a fixture that reuses our own encoder
432    /// cannot catch our own misreading. Cross-checked against Wireshark's
433    /// `GEV_STATUS_*` defines and aravis's `ArvUvcpStatus`.
434    const SPEC_STATUS_TABLE: &[(u16, StatusCode, &str)] = &[
435        (0x0000, StatusCode::Success, "SUCCESS"),
436        (0x8001, StatusCode::NotImplemented, "NOT_IMPLEMENTED"),
437        (0x8002, StatusCode::InvalidParameter, "INVALID_PARAMETER"),
438        (0x8003, StatusCode::InvalidAddress, "INVALID_ADDRESS"),
439        (0x8004, StatusCode::WriteProtect, "WRITE_PROTECT"),
440        (0x8005, StatusCode::BadAlignment, "BAD_ALIGNMENT"),
441        (0x8006, StatusCode::AccessDenied, "ACCESS_DENIED"),
442        (0x8007, StatusCode::Busy, "BUSY"),
443        (0x800E, StatusCode::InvalidHeader, "INVALID_HEADER"),
444        (0x800F, StatusCode::WrongConfig, "WRONG_CONFIG"),
445        (0x8FFF, StatusCode::GenericError, "ERROR"),
446    ];
447
448    #[test]
449    fn status_table_matches_the_specification() {
450        for &(raw, expected, name) in SPEC_STATUS_TABLE {
451            assert_eq!(
452                StatusCode::from_raw(raw),
453                Some(expected),
454                "decoding {raw:#06x} ({name})"
455            );
456            assert_eq!(expected.to_raw(), raw, "re-encoding {name}");
457            assert_eq!(expected.name(), name);
458        }
459    }
460
461    #[test]
462    fn regression_the_three_codes_we_used_to_mislabel() {
463        // 0x8004 was `DeviceBusy`, so a write to a read-only register reported
464        // "device busy" and the GVCP retry loop kept retrying it.
465        assert_eq!(StatusCode::from_raw(0x8004), Some(StatusCode::WriteProtect));
466        assert!(!StatusCode::WriteProtect.is_retryable());
467
468        // 0x8005 was the catch-all `Error`.
469        assert_eq!(StatusCode::from_raw(0x8005), Some(StatusCode::BadAlignment));
470
471        // 0x8006 had no variant at all: #45's FLIR returned it on a locked
472        // node and the user saw `Unknown(32774)` — 32774 being 0x8006.
473        assert_eq!(StatusCode::from_raw(0x8006), Some(StatusCode::AccessDenied));
474        assert_eq!(StatusCode::from_raw(32774), Some(StatusCode::AccessDenied));
475
476        // 0x8007 is the one status a retry can help.
477        assert!(StatusCode::Busy.is_retryable());
478        assert!(!StatusCode::Success.is_retryable());
479    }
480
481    #[test]
482    fn display_carries_both_the_name_and_the_raw_value() {
483        assert_eq!(
484            StatusCode::AccessDenied.to_string(),
485            "ACCESS_DENIED (0x8006)"
486        );
487    }
488
489    #[test]
490    fn transport_specific_codes_are_not_in_the_shared_core() {
491        // 0x800B is the reason this enum holds only the shared core: GVCP
492        // calls it NO_MSG (deprecated), GenCP calls it MSG_TIMEOUT. Decoding
493        // it here would have to pick one and be wrong for the other
494        // transport, so it is left to the transport's own type (ADR-0020).
495        assert_eq!(StatusCode::from_raw(0x800B), None);
496        // Likewise the GVCP packet-resend family and the USB3 Vision 0xA0xx
497        // range.
498        assert_eq!(StatusCode::from_raw(0x800C), None);
499        assert_eq!(StatusCode::from_raw(0xA001), None);
500    }
501
502    // The macro's methods are `pub` for the transports' public types; on a
503    // test's private one they are unreachable, which is the point.
504    #[allow(unreachable_pub)]
505    mod example {
506        transport_status! {
507            /// A transport with one code of its own, to check the macro.
508            pub(crate) enum Example {
509                /// `0x800B`, as the example transport names it.
510                Mine = 0x800B, "MINE";
511            }
512        }
513    }
514    use example::Example;
515
516    #[test]
517    fn a_transport_status_wraps_the_core_and_keeps_the_rest() {
518        assert_eq!(Example::from_raw(0x800B), Example::Mine);
519        assert_eq!(
520            Example::from_raw(0x8006),
521            Example::Common(StatusCode::AccessDenied)
522        );
523        assert_eq!(Example::from_raw(0x8123), Example::Unknown(0x8123));
524        for raw in [0x0000, 0x800B, 0x8006, 0x8123] {
525            assert_eq!(Example::from_raw(raw).to_raw(), raw, "{raw:#06x}");
526        }
527        assert_eq!(Example::Mine.to_string(), "MINE (0x800B)");
528        assert_eq!(
529            Example::Unknown(0x8123).to_string(),
530            "unknown status (0x8123)"
531        );
532        assert!(Example::from_raw(0x8007).is_retryable());
533        assert!(Example::from_raw(0).is_success());
534        assert_eq!(Example::Mine.common(), None);
535    }
536
537    #[test]
538    fn pending_ack_is_a_command_id_not_a_status() {
539        // The bug this constant replaces: 0x8006 was treated as "pending".
540        assert_eq!(PENDING_ACK_COMMAND, 0x0805);
541        assert_ne!(PENDING_ACK_COMMAND, StatusCode::AccessDenied.to_raw());
542        // It sits in the command-id table beside the ones we already model.
543        assert_eq!(OpCode::ReadMem.command_code(), 0x0084);
544        assert_eq!(OpCode::WriteMem.command_code(), 0x0086);
545    }
546
547    #[test]
548    fn decode_read_register_ack() {
549        let value = 0x0000_0002u32;
550        let mut buf = BytesMut::with_capacity(HEADER_SIZE + 4);
551        buf.put_u16(0x0000);
552        buf.put_u16(0x0081);
553        buf.put_u16(4);
554        buf.put_u16(0x4141);
555        buf.put_u32(value);
556
557        let ack = decode_ack(&buf).expect("decode");
558        assert_eq!(ack.header.status, StatusCode::Success.to_raw());
559        assert_eq!(ack.header.opcode, OpCode::ReadRegister);
560        assert_eq!(ack.header.length, 4);
561        assert_eq!(ack.header.request_id, 0x4141);
562        assert_eq!(&ack.payload[..], &value.to_be_bytes());
563    }
564
565    #[test]
566    fn decode_write_register_ack() {
567        let index = 1u32;
568        let mut buf = BytesMut::with_capacity(HEADER_SIZE + 4);
569        buf.put_u16(0x0000);
570        buf.put_u16(0x0083);
571        buf.put_u16(4);
572        buf.put_u16(0x4343);
573        buf.put_u32(index);
574
575        let ack = decode_ack(&buf).expect("decode");
576        assert_eq!(ack.header.status, StatusCode::Success.to_raw());
577        assert_eq!(ack.header.opcode, OpCode::WriteRegister);
578        assert_eq!(ack.header.length, 4);
579        assert_eq!(ack.header.request_id, 0x4343);
580        assert_eq!(&ack.payload[..], &index.to_be_bytes());
581    }
582
583    #[test]
584    fn decode_read_mem_ack() {
585        let payload = vec![0xAA; 4];
586        let mut buf = BytesMut::with_capacity(HEADER_SIZE + payload.len());
587        buf.put_u16(0x0000);
588        buf.put_u16(0x0085);
589        buf.put_u16(payload.len() as u16);
590        buf.put_u16(0x4242);
591        buf.extend_from_slice(&payload);
592
593        let ack = decode_ack(&buf).expect("decode");
594        assert_eq!(ack.header.status, StatusCode::Success.to_raw());
595        assert_eq!(ack.header.opcode, OpCode::ReadMem);
596        assert_eq!(ack.header.length as usize, payload.len());
597        assert_eq!(ack.header.request_id, 0x4242);
598        assert_eq!(&ack.payload[..], &payload[..]);
599    }
600
601    #[test]
602    fn decode_write_mem_ack() {
603        let payload: Vec<u8> = Vec::new();
604        let mut buf = BytesMut::with_capacity(HEADER_SIZE + payload.len());
605        buf.put_u16(0x0000);
606        buf.put_u16(0x0087);
607        buf.put_u16(0);
608        buf.put_u16(0x1001);
609        let ack = decode_ack(&buf).expect("decode");
610        assert_eq!(ack.header.opcode, OpCode::WriteMem);
611        assert_eq!(ack.header.status, StatusCode::Success.to_raw());
612        assert_eq!(ack.payload.len(), 0);
613    }
614
615    // ── Spec-derived acknowledgement header (backlog TC-04) ────────────────
616    //
617    // The tests above build their input with the same `put_u16` calls the
618    // encoder uses, in the order the decoder reads them. That proves the two
619    // agree; it cannot show either matches the standard. These assert the
620    // header as a literal byte array written from the specification's field
621    // table, and index it by offset.
622    //
623    // | Offset | Size | Field                    |
624    // |--------|------|--------------------------|
625    // |      0 |    2 | Status                   |
626    // |      2 |    2 | Acknowledge command id   |
627    // |      4 |    2 | Length of the payload    |
628    // |      6 |    2 | Request id (echoed)      |
629    // |      8 |    n | Payload                  |
630    //
631    // All fields are big-endian.
632
633    /// A `READREG_ACK` returning `0x0000_3EF2`, byte for byte.
634    const GOLDEN_READ_REGISTER_ACK: [u8; 12] = [
635        0x00, 0x00, // status: SUCCESS
636        0x00, 0x81, // acknowledge command id: READREG_ACK
637        0x00, 0x04, // length: 4 — the payload alone
638        0x12, 0x34, // request id
639        0x00, 0x00, 0x3E, 0xF2, // payload: 16114
640    ];
641
642    #[test]
643    fn ack_header_fields_sit_at_the_specified_offsets() {
644        let b = &GOLDEN_READ_REGISTER_ACK;
645        assert_eq!(u16::from_be_bytes([b[0], b[1]]), 0x0000, "status at 0");
646        assert_eq!(u16::from_be_bytes([b[2], b[3]]), 0x0081, "ack id at 2");
647        assert_eq!(u16::from_be_bytes([b[4], b[5]]), 4, "length at 4");
648        assert_eq!(u16::from_be_bytes([b[6], b[7]]), 0x1234, "request id at 6");
649        assert_eq!(HEADER_SIZE, 8, "the payload begins at offset 8");
650
651        let ack = decode_ack(b).expect("decode the golden ack");
652        assert_eq!(ack.header.status, StatusCode::Success.to_raw());
653        assert_eq!(ack.header.opcode, OpCode::ReadRegister);
654        assert_eq!(ack.header.length, 4);
655        assert_eq!(ack.header.request_id, 0x1234);
656        assert_eq!(&ack.payload[..], &[0x00, 0x00, 0x3E, 0xF2]);
657    }
658
659    /// `length` counts the payload, not the whole datagram.
660    ///
661    /// Off by exactly `HEADER_SIZE`, a fake and a client still round-trip
662    /// perfectly with each other while every real device disagrees — the
663    /// ADR-0019 shape. Pin the interpretation rather than the arithmetic.
664    #[test]
665    fn ack_length_counts_the_payload_only() {
666        let mut counts_the_header = GOLDEN_READ_REGISTER_ACK;
667        counts_the_header[4..6].copy_from_slice(&12u16.to_be_bytes());
668        assert!(
669            decode_ack(&counts_the_header).is_err(),
670            "a length of 12 describes a 20-byte datagram, not this one"
671        );
672
673        // And the truncation case: the field promises more than arrived.
674        let mut over_promises = GOLDEN_READ_REGISTER_ACK;
675        over_promises[4..6].copy_from_slice(&8u16.to_be_bytes());
676        assert!(decode_ack(&over_promises).is_err());
677    }
678
679    /// The acknowledge command id is the command id plus one, and the decoder
680    /// must reject a *command* id arriving where an acknowledgement belongs.
681    #[test]
682    fn ack_ids_are_command_ids_plus_one() {
683        for (cmd, ack) in [
684            (0x0080u16, 0x0081u16),
685            (0x0082, 0x0083),
686            (0x0084, 0x0085),
687            (0x0086, 0x0087),
688        ] {
689            assert_eq!(
690                OpCode::from_command(cmd).expect("command id").ack_code(),
691                ack
692            );
693            assert!(
694                OpCode::from_ack(cmd).is_err(),
695                "{cmd:#06x} is a command id, not an acknowledgement"
696            );
697        }
698    }
699
700    /// A pending-acknowledge is a distinct command id carrying a *success*
701    /// status, so nothing about the status word distinguishes it from the real
702    /// answer (backlog TC-16). It must not decode as one.
703    #[test]
704    fn pending_ack_is_not_a_normal_acknowledgement() {
705        let mut pending = GOLDEN_READ_REGISTER_ACK;
706        pending[2..4].copy_from_slice(&PENDING_ACK_COMMAND.to_be_bytes());
707        assert_eq!(
708            u16::from_be_bytes([pending[0], pending[1]]),
709            0x0000,
710            "a pending-ack reports SUCCESS — the status cannot be the signal"
711        );
712        assert!(
713            decode_ack(&pending).is_err(),
714            "0x0805 is not an acknowledgement command id"
715        );
716    }
717}