Skip to main content

viva_u3v/
control.rs

1//! GenCP control channel over USB3 Vision bulk endpoints.
2//!
3//! A command and its acknowledge each start with the `U3VC` prefix, then
4//! GenCP's common command data (GenCP 1.2, Tables 4-5), then the command's
5//! own data (Tables 8-12):
6//!
7//! ```text
8//! command      [ "U3VC" ][ flags ][ command_id ][ length ][ request_id ][ SCD ]
9//! acknowledge  [ "U3VC" ][ status ][ command_id ][ length ][ request_id ][ SCD ]
10//! ```
11//!
12//! Every field is little-endian. GenCP leaves the byte order to the
13//! technology but requires it to match the bootstrap registers' (§2.3), and
14//! for USB3 Vision both are little-endian: aravis (`arvuvcp.c`) and
15//! Wireshark (`packet-u3v.c`) encode and decode every field so, and a
16//! Grasshopper3's own XML declares its bootstrap registers `LittleEndian`
17//! (`PGR_GS3_U3_23S6M.xml`). Until backlog TC-27 this module sent GVCP's
18//! opcodes and flag bit with a big-endian address, which no conformant device
19//! answers.
20//!
21//! GenCP has no register commands; a register is a 4-byte memory access.
22
23use std::sync::Arc;
24use std::time::Duration;
25
26use bytes::{BufMut, BytesMut};
27use viva_gencp::{ccd_flags, command_id};
28
29use crate::U3vStatus;
30
31use crate::U3vError;
32use crate::usb::{GONE_GRACE, UsbTransfer, unless_gone};
33
34/// `U3VC` read as a little-endian `u32`: the prefix of every control-channel
35/// command and acknowledge. aravis `ARV_UVCP_MAGIC`; Wireshark
36/// `U3V_CONTROL_PREFIX`.
37const CONTROL_PREFIX: u32 = 0x4356_3355;
38
39/// Prefix plus common command data, in bytes.
40const HEADER_SIZE: usize = 12;
41
42/// A READMEM_CMD's SCD: address, reserved, read length (GenCP 1.2 Table 8).
43const READMEM_SCD_SIZE: usize = 12;
44
45/// The address in front of a WRITEMEM_CMD's data (GenCP 1.2 Table 10).
46const WRITEMEM_ADDRESS_SIZE: usize = 8;
47
48/// Maximum number of acknowledges read for one command before giving up:
49/// pending acknowledges and stale answers to earlier commands.
50const MAX_ACKS_PER_COMMAND: usize = 100;
51
52/// Upper bound on a single pending-acknowledge wait.
53///
54/// A device asking for more time should not be able to park a control
55/// transaction indefinitely, and `MAX_ACKS_PER_COMMAND` alone does not bound
56/// the total wait.
57const MAX_PENDING_WAIT: Duration = Duration::from_millis(10_000);
58
59/// Wait used when a pending-acknowledge carries no usable timeout field.
60const DEFAULT_PENDING_WAIT_MS: u64 = 100;
61
62/// Extract the requested wait from a pending-acknowledge SCD.
63///
64/// GenCP 1.2 Table 12: 2 reserved bytes followed by a little-endian `u16` of
65/// milliseconds. aravis reads the same field the same way
66/// (`ArvUvcpPendingAckInfos`, `GUINT16_FROM_LE`).
67///
68/// The previous reading took all four bytes as a **big-endian `u32`**, which
69/// is wrong in both offset and byte order: a device asking for 1 000 ms sends
70/// `00 00 E8 03`, which that reading turned into 59 395 ms. See backlog TC-12
71/// for the GVCP side of the same field, which is still unsettled against
72/// hardware.
73fn pending_ack_timeout_ms(scd: &[u8]) -> u64 {
74    if scd.len() < 4 {
75        return DEFAULT_PENDING_WAIT_MS;
76    }
77    let requested = u16::from_le_bytes([scd[2], scd[3]]) as u64;
78    if requested == 0 {
79        return DEFAULT_PENDING_WAIT_MS;
80    }
81    requested.min(MAX_PENDING_WAIT.as_millis() as u64)
82}
83
84/// Default control channel timeout, before the device's Maximum Device
85/// Response Time is known.
86pub(crate) const DEFAULT_TIMEOUT: Duration = Duration::from_millis(1000);
87
88/// GenCP control channel over a USB3 Vision bulk endpoint pair.
89///
90/// Sends READMEM and WRITEMEM commands and receives their acknowledges,
91/// splitting a large access across the device's maximum transfer sizes.
92pub struct ControlChannel<T: UsbTransfer> {
93    transport: Arc<T>,
94    ep_in: u8,
95    ep_out: u8,
96    /// The request id of the last command sent; 0 before the first.
97    request_id: u16,
98    max_cmd_transfer: u32,
99    max_ack_transfer: u32,
100    timeout: Duration,
101}
102
103impl<T: UsbTransfer> ControlChannel<T> {
104    /// Create a new control channel.
105    ///
106    /// `max_cmd_transfer` and `max_ack_transfer` cap the largest single bulk
107    /// transfer each way; the SBRM has the device's values, which
108    /// [`set_max_transfer`](Self::set_max_transfer) applies once read.
109    pub fn new(
110        transport: Arc<T>,
111        ep_in: u8,
112        ep_out: u8,
113        max_cmd_transfer: u32,
114        max_ack_transfer: u32,
115    ) -> Self {
116        Self {
117            transport,
118            ep_in,
119            ep_out,
120            request_id: 0,
121            max_cmd_transfer,
122            max_ack_transfer,
123            timeout: DEFAULT_TIMEOUT,
124        }
125    }
126
127    /// Use the device's transfer limits from now on, keeping the request id
128    /// sequence: a device answers a repeated id with its previous acknowledge
129    /// (GenCP §3.1), so the sequence must not restart mid-session.
130    pub fn set_max_transfer(&mut self, max_cmd_transfer: u32, max_ack_transfer: u32) {
131        self.max_cmd_transfer = max_cmd_transfer;
132        self.max_ack_transfer = max_ack_transfer;
133    }
134
135    /// Override the control transaction timeout.
136    pub fn set_timeout(&mut self, timeout: Duration) {
137        self.timeout = timeout;
138    }
139
140    /// The control transaction timeout.
141    pub fn timeout(&self) -> Duration {
142        self.timeout
143    }
144
145    /// Access the underlying transport (e.g. to share with a stream).
146    pub fn transport(&self) -> &Arc<T> {
147        &self.transport
148    }
149
150    /// Read `len` bytes starting at `addr`, split across the device's maximum
151    /// acknowledge transfer size.
152    pub fn read_mem(&mut self, addr: u64, len: usize) -> Result<Vec<u8>, U3vError> {
153        let max_payload = self.max_read_chunk()?;
154        let mut result = Vec::with_capacity(len);
155        let mut offset = 0usize;
156
157        while offset < len {
158            let chunk = (len - offset).min(max_payload);
159            let mut scd = BytesMut::with_capacity(READMEM_SCD_SIZE);
160            scd.put_u64_le(addr + offset as u64);
161            scd.put_u16_le(0); // reserved
162            scd.put_u16_le(chunk as u16);
163            let ack = self.transact(command_id::READMEM_CMD, command_id::READMEM_ACK, &scd)?;
164            if ack.len() != chunk {
165                return Err(U3vError::Length {
166                    what: "READMEM_ACK payload",
167                    expected: chunk,
168                    got: ack.len(),
169                });
170            }
171            result.extend_from_slice(&ack);
172            offset += chunk;
173        }
174        Ok(result)
175    }
176
177    /// Write `data` starting at `addr`, split across the device's maximum
178    /// command transfer size. The bytes go to the device as given: register
179    /// contents are in the device's own byte order, not the protocol's.
180    pub fn write_mem(&mut self, addr: u64, data: &[u8]) -> Result<(), U3vError> {
181        let max_payload = self.max_write_chunk()?;
182        let mut offset = 0usize;
183
184        while offset < data.len() {
185            let chunk = (data.len() - offset).min(max_payload);
186            let mut scd = BytesMut::with_capacity(WRITEMEM_ADDRESS_SIZE + chunk);
187            scd.put_u64_le(addr + offset as u64);
188            scd.extend_from_slice(&data[offset..offset + chunk]);
189            let ack = self.transact(command_id::WRITEMEM_CMD, command_id::WRITEMEM_ACK, &scd)?;
190            // GenCP 1.2 Table 11: a device with the Written Length Field
191            // capability answers with reserved + length_written; one without
192            // sends no SCD at all.
193            if ack.len() >= 4 {
194                let written = u16::from_le_bytes([ack[2], ack[3]]) as usize;
195                if written != chunk {
196                    return Err(U3vError::Length {
197                        what: "a WRITEMEM_ACK's bytes written",
198                        expected: chunk,
199                        got: written,
200                    });
201                }
202            }
203            offset += chunk;
204        }
205        Ok(())
206    }
207
208    /// Maximum read chunk size: the acknowledge transfer limit minus the
209    /// header, and no more than the `u16` read length can say.
210    fn max_read_chunk(&self) -> Result<usize, U3vError> {
211        let chunk = (self.max_ack_transfer as usize)
212            .saturating_sub(HEADER_SIZE)
213            .min(u16::MAX as usize);
214        if chunk == 0 {
215            return Err(U3vError::Device(
216                "has a maximum acknowledge transfer too small to carry data",
217            ));
218        }
219        Ok(chunk)
220    }
221
222    /// Maximum write chunk size: the command transfer limit minus the header
223    /// and the address, and no more than the `u16` length field can say.
224    fn max_write_chunk(&self) -> Result<usize, U3vError> {
225        let chunk = (self.max_cmd_transfer as usize)
226            .saturating_sub(HEADER_SIZE + WRITEMEM_ADDRESS_SIZE)
227            .min(u16::MAX as usize - WRITEMEM_ADDRESS_SIZE);
228        if chunk == 0 {
229            return Err(U3vError::Device(
230                "has a maximum command transfer too small to carry data",
231            ));
232        }
233        Ok(chunk)
234    }
235
236    // -----------------------------------------------------------------------
237    // Core transaction: encode → send → receive (with PENDING_ACK handling)
238    // -----------------------------------------------------------------------
239
240    fn transact(
241        &mut self,
242        command: u16,
243        expected_ack: u16,
244        scd: &[u8],
245    ) -> Result<Vec<u8>, U3vError> {
246        let request_id = self.next_request_id();
247        let packet = encode_command(command, request_id, scd);
248        // A failure that does not say whether the device is gone is checked
249        // against whether it is still listed: on macOS an unplugged
250        // camera's control endpoint answers `kIOReturnNotReady` (UV-03).
251        let present = || self.transport.is_present();
252        self.transport
253            .bulk_write(self.ep_out, &packet, self.timeout)
254            .map_err(|error| unless_gone(error, present, GONE_GRACE))?;
255
256        let mut ack_buf = vec![0u8; (self.max_ack_transfer as usize).max(HEADER_SIZE)];
257        let mut wait = self.timeout;
258        for _ in 0..MAX_ACKS_PER_COMMAND {
259            let n = self
260                .transport
261                .bulk_read(self.ep_in, &mut ack_buf, wait)
262                .map_err(|error| unless_gone(error, present, GONE_GRACE))?;
263            let ack = decode_ack(&ack_buf[..n])?;
264
265            // An answer to an earlier command — one that timed out here and
266            // was answered late — is not this command's answer.
267            if ack.request_id != request_id {
268                tracing::debug!(
269                    expected = request_id,
270                    got = ack.request_id,
271                    "discarding an acknowledge for another request"
272                );
273                continue;
274            }
275
276            // A pending-acknowledge is identified by its command id, before
277            // the status is consulted at all: its status is `SUCCESS`, so
278            // status-first dispatch would accept it as the real answer and
279            // return its timeout SCD as register data. aravis orders the two
280            // checks the same way (`arvuvdevice.c`). The time it asks for is
281            // a new deadline for this command, counted from now (GenCP 1.2
282            // §4.4.5).
283            if ack.command == command_id::PENDING_ACK {
284                let wait_ms = pending_ack_timeout_ms(&ack.payload);
285                tracing::debug!(wait_ms, "PENDING_ACK, extending deadline");
286                wait = Duration::from_millis(wait_ms) + self.timeout;
287                continue;
288            }
289
290            // Anything else must be the acknowledgement for the command we
291            // sent. Without this the request id alone was the only guard, so
292            // any other ack that happened to carry a matching id was accepted.
293            if ack.command != expected_ack {
294                tracing::debug!(
295                    command = format_args!("{:#06x}", ack.command),
296                    expected = format_args!("{expected_ack:#06x}"),
297                    "acknowledge answers another command"
298                );
299                return Err(U3vError::Malformed {
300                    packet: "acknowledge",
301                    problem: "answers another command",
302                });
303            }
304
305            return match ack.status {
306                status if status.is_success() => Ok(ack.payload),
307                status => Err(U3vError::Status(status)),
308            };
309        }
310        Err(U3vError::Timeout)
311    }
312
313    /// The next request id: never 0, which a device refuses on a write and
314    /// executes uncached on a read (GenCP §3.1), so the sequence wraps to 1.
315    fn next_request_id(&mut self) -> u16 {
316        self.request_id = match self.request_id {
317            u16::MAX => 1,
318            id => id + 1,
319        };
320        self.request_id
321    }
322}
323
324// ---------------------------------------------------------------------------
325// Wire encoding / decoding
326// ---------------------------------------------------------------------------
327
328/// Encode a command with RequestAck set: a device ignores a command without
329/// it and sends nothing back.
330fn encode_command(command: u16, request_id: u16, scd: &[u8]) -> Vec<u8> {
331    let mut buf = BytesMut::with_capacity(HEADER_SIZE + scd.len());
332    buf.put_u32_le(CONTROL_PREFIX);
333    buf.put_u16_le(ccd_flags::REQUEST_ACK);
334    buf.put_u16_le(command);
335    buf.put_u16_le(scd.len() as u16);
336    buf.put_u16_le(request_id);
337    buf.extend_from_slice(scd);
338    buf.to_vec()
339}
340
341/// Decoded U3V acknowledgement fields.
342struct AckPacket {
343    status: U3vStatus,
344    /// The acknowledgement's command id.
345    ///
346    /// Must be kept: a pending-acknowledge is distinguished from a real answer
347    /// by this field and not by `status`, which is `SUCCESS` on both.
348    command: u16,
349    request_id: u16,
350    payload: Vec<u8>,
351}
352
353/// Decode an acknowledge.
354fn decode_ack(buf: &[u8]) -> Result<AckPacket, U3vError> {
355    if buf.len() < HEADER_SIZE {
356        return Err(U3vError::Malformed {
357            packet: "acknowledge",
358            problem: "is shorter than its header",
359        });
360    }
361
362    let prefix = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]);
363    if prefix != CONTROL_PREFIX {
364        return Err(U3vError::Malformed {
365            packet: "acknowledge",
366            problem: "lacks the U3VC prefix",
367        });
368    }
369
370    let status_raw = u16::from_le_bytes([buf[4], buf[5]]);
371    let command = u16::from_le_bytes([buf[6], buf[7]]);
372    let length = u16::from_le_bytes([buf[8], buf[9]]) as usize;
373    let request_id = u16::from_le_bytes([buf[10], buf[11]]);
374
375    let expected = HEADER_SIZE + length;
376    if buf.len() < expected {
377        return Err(U3vError::Malformed {
378            packet: "acknowledge",
379            problem: "is shorter than its header says",
380        });
381    }
382
383    Ok(AckPacket {
384        status: U3vStatus::from_raw(status_raw),
385        command,
386        request_id,
387        payload: buf[HEADER_SIZE..expected].to_vec(),
388    })
389}
390
391// ---------------------------------------------------------------------------
392// Tests
393// ---------------------------------------------------------------------------
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398    use crate::usb::MockUsbTransfer;
399    use viva_gencp::StatusCode;
400
401    const EP_OUT: u8 = 0x01;
402    const EP_IN: u8 = 0x81;
403
404    /// Build an acknowledgement with an explicit command id.
405    ///
406    /// Every caller states the command it is impersonating: a fixture that
407    /// hardcoded one id once hid that the command id was never checked.
408    fn build_ack(command: u16, status: StatusCode, request_id: u16, payload: &[u8]) -> Vec<u8> {
409        let mut buf = BytesMut::with_capacity(HEADER_SIZE + payload.len());
410        buf.put_u32_le(CONTROL_PREFIX);
411        buf.put_u16_le(status.to_raw());
412        buf.put_u16_le(command);
413        buf.put_u16_le(payload.len() as u16);
414        buf.put_u16_le(request_id);
415        buf.extend_from_slice(payload);
416        buf.to_vec()
417    }
418
419    fn make_channel(mock: &Arc<MockUsbTransfer>) -> ControlChannel<MockUsbTransfer> {
420        ControlChannel::new(Arc::clone(mock), EP_IN, EP_OUT, 1024, 1024)
421    }
422
423    #[test]
424    fn decode_ack_success() {
425        let payload = vec![0x01, 0x02, 0x03, 0x04];
426        let buf = build_ack(
427            command_id::READMEM_ACK,
428            StatusCode::Success,
429            0x0042,
430            &payload,
431        );
432        let ack = decode_ack(&buf).unwrap();
433        assert!(ack.status.is_success());
434        assert_eq!(ack.request_id, 0x0042);
435        assert_eq!(ack.payload, payload);
436    }
437
438    /// An acknowledge carries the same `U3VC` prefix as a command; the
439    /// prefix this module once expected spelled `A3VC` on the wire.
440    #[test]
441    fn decode_ack_bad_prefix() {
442        let mut buf = build_ack(command_id::READMEM_ACK, StatusCode::Success, 0x0001, &[]);
443        assert_eq!(&buf[..4], b"U3VC");
444        buf[0] = b'A';
445        assert!(decode_ack(&buf).is_err());
446    }
447
448    #[test]
449    fn decode_ack_truncated() {
450        let buf = build_ack(
451            command_id::READMEM_ACK,
452            StatusCode::Success,
453            0x0001,
454            &[1, 2, 3, 4],
455        );
456        assert!(decode_ack(&buf[..HEADER_SIZE]).is_err());
457    }
458
459    /// UV-03 on macOS: a register read that fails with an unknown error —
460    /// `kIOReturnNotReady`, as an unplugged mvBlueFOX3-2004G's control
461    /// endpoint answered — on a device the operating system no longer lists
462    /// is a disconnect. On a device still listed it is the error it was.
463    #[test]
464    fn an_unknown_failure_is_a_disconnect_only_once_the_device_is_unlisted() {
465        let not_ready = || U3vError::usb("unknown (error 0xe00002d8)");
466        let mock = Arc::new(MockUsbTransfer::new());
467        let mut ch = make_channel(&mock);
468
469        mock.set_present(Some(true));
470        mock.enqueue_error(EP_IN, not_ready());
471        let listed = ch.read_mem(0x0, 4);
472        assert!(matches!(listed, Err(U3vError::Usb(_))), "{listed:?}");
473
474        mock.set_present(Some(false));
475        mock.enqueue_error(EP_IN, not_ready());
476        let unlisted = ch.read_mem(0x0, 4);
477        assert!(
478            matches!(unlisted, Err(U3vError::Disconnected)),
479            "{unlisted:?}"
480        );
481    }
482
483    #[test]
484    fn read_mem_single_chunk() {
485        let mock = Arc::new(MockUsbTransfer::new());
486        let mut ch = make_channel(&mock);
487
488        let data = vec![0xAA; 64];
489        mock.enqueue_read(
490            EP_IN,
491            build_ack(command_id::READMEM_ACK, StatusCode::Success, 1, &data),
492        );
493
494        assert_eq!(ch.read_mem(0x0000_2000, 64).unwrap(), data);
495    }
496
497    #[test]
498    fn read_mem_chunked() {
499        // max_read_chunk = max_ack_transfer - HEADER_SIZE = 48 - 12 = 36
500        let mock = Arc::new(MockUsbTransfer::new());
501        let mut ch = ControlChannel::new(Arc::clone(&mock), EP_IN, EP_OUT, 1024, 48);
502
503        let chunk1 = vec![0xAA; 36];
504        let chunk2 = vec![0xBB; 28];
505        mock.enqueue_read(
506            EP_IN,
507            build_ack(command_id::READMEM_ACK, StatusCode::Success, 1, &chunk1),
508        );
509        mock.enqueue_read(
510            EP_IN,
511            build_ack(command_id::READMEM_ACK, StatusCode::Success, 2, &chunk2),
512        );
513
514        let result = ch.read_mem(0x0000_3000, 64).unwrap();
515        assert_eq!(&result[..36], &chunk1[..]);
516        assert_eq!(&result[36..], &chunk2[..]);
517
518        let writes = mock.take_writes(EP_OUT);
519        assert_eq!(writes.len(), 2);
520        // The second command reads on from where the first stopped.
521        assert_eq!(&writes[1][12..20], &(0x3000u64 + 36).to_le_bytes());
522    }
523
524    #[test]
525    fn write_mem_chunked() {
526        let mock = Arc::new(MockUsbTransfer::new());
527        // max_write_chunk = 48 - 12 - 8 = 28
528        let mut ch = ControlChannel::new(Arc::clone(&mock), EP_IN, EP_OUT, 48, 1024);
529
530        mock.enqueue_read(
531            EP_IN,
532            build_ack(command_id::WRITEMEM_ACK, StatusCode::Success, 1, &[]),
533        );
534        mock.enqueue_read(
535            EP_IN,
536            build_ack(command_id::WRITEMEM_ACK, StatusCode::Success, 2, &[]),
537        );
538
539        ch.write_mem(0x0000_4000, &[0xCC; 50]).unwrap();
540        assert_eq!(mock.take_writes(EP_OUT).len(), 2);
541    }
542
543    /// A device with the Written Length Field capability says how much it
544    /// wrote (GenCP 1.2 Table 11); a short write is an error, not a success.
545    #[test]
546    fn a_short_write_is_reported() {
547        let mock = Arc::new(MockUsbTransfer::new());
548        let mut ch = make_channel(&mock);
549        mock.enqueue_read(
550            EP_IN,
551            build_ack(
552                command_id::WRITEMEM_ACK,
553                StatusCode::Success,
554                1,
555                &[0, 0, 2, 0],
556            ),
557        );
558
559        let err = ch.write_mem(0x1000, &[1, 2, 3, 4]).unwrap_err();
560        assert!(
561            matches!(
562                err,
563                U3vError::Length {
564                    expected: 4,
565                    got: 2,
566                    ..
567                }
568            ),
569            "{err:?}"
570        );
571    }
572
573    #[test]
574    fn pending_ack_retry() {
575        let mock = Arc::new(MockUsbTransfer::new());
576        let mut ch = make_channel(&mock);
577
578        // First ack: a real GenCP pending-acknowledge. Note the status is
579        // SUCCESS -- it is the command id that marks it -- and the SCD is
580        // 2 reserved bytes plus a little-endian u16 of milliseconds.
581        mock.enqueue_read(
582            EP_IN,
583            build_ack(command_id::PENDING_ACK, StatusCode::Success, 1, &[0; 4]),
584        );
585        let value = 0x1234_5678u32.to_le_bytes();
586        mock.enqueue_read(
587            EP_IN,
588            build_ack(command_id::READMEM_ACK, StatusCode::Success, 1, &value),
589        );
590
591        assert_eq!(ch.read_mem(0x0000_5000, 4).unwrap(), value);
592    }
593
594    #[test]
595    fn device_error_status() {
596        let mock = Arc::new(MockUsbTransfer::new());
597        let mut ch = make_channel(&mock);
598
599        mock.enqueue_read(
600            EP_IN,
601            build_ack(command_id::READMEM_ACK, StatusCode::InvalidAddress, 1, &[]),
602        );
603
604        let err = ch.read_mem(0xFFFF_FFFF, 4).unwrap_err();
605        assert!(matches!(
606            err,
607            U3vError::Status(U3vStatus::Common(StatusCode::InvalidAddress))
608        ));
609    }
610
611    #[test]
612    fn pending_ack_scd_is_a_little_endian_u16_after_two_reserved_bytes() {
613        // A device asking for 1000 ms sends 00 00 E8 03.
614        assert_eq!(pending_ack_timeout_ms(&[0x00, 0x00, 0xE8, 0x03]), 1000);
615        // The previous reading took all four bytes as a big-endian u32, which
616        // turned that same request into a 59-second sleep.
617        assert_ne!(
618            pending_ack_timeout_ms(&[0x00, 0x00, 0xE8, 0x03]),
619            u32::from_be_bytes([0x00, 0x00, 0xE8, 0x03]) as u64
620        );
621        // Too short, and zero, fall back rather than busy-looping.
622        assert_eq!(pending_ack_timeout_ms(&[0x00]), DEFAULT_PENDING_WAIT_MS);
623        assert_eq!(
624            pending_ack_timeout_ms(&[0x00, 0x00, 0x00, 0x00]),
625            DEFAULT_PENDING_WAIT_MS
626        );
627        // A device cannot park the transaction indefinitely.
628        assert_eq!(
629            pending_ack_timeout_ms(&[0x00, 0x00, 0xFF, 0xFF]),
630            MAX_PENDING_WAIT.as_millis() as u64
631        );
632    }
633
634    #[test]
635    fn access_denied_is_reported_not_retried_as_pending() {
636        // 0x8006 used to be read as "device needs more time", so a refusal was
637        // slept over 100 times and then reported as a timeout.
638        let mock = Arc::new(MockUsbTransfer::new());
639        let mut ch = make_channel(&mock);
640
641        mock.enqueue_read(
642            EP_IN,
643            build_ack(command_id::READMEM_ACK, StatusCode::AccessDenied, 1, &[]),
644        );
645
646        let err = ch.read_mem(0x0000_1000, 4).unwrap_err();
647        assert!(matches!(
648            err,
649            U3vError::Status(U3vStatus::Common(StatusCode::AccessDenied))
650        ));
651        // One exchange, not 100.
652        assert_eq!(mock.take_writes(EP_OUT).len(), 1);
653    }
654
655    #[test]
656    fn acknowledgement_for_another_command_is_rejected() {
657        let mock = Arc::new(MockUsbTransfer::new());
658        let mut ch = make_channel(&mock);
659
660        mock.enqueue_read(
661            EP_IN,
662            build_ack(
663                command_id::WRITEMEM_ACK,
664                StatusCode::Success,
665                1,
666                &0xDEAD_BEEFu32.to_le_bytes(),
667            ),
668        );
669
670        let err = ch.read_mem(0x0000_1000, 4).unwrap_err();
671        assert!(
672            matches!(
673                err,
674                U3vError::Malformed {
675                    problem: "answers another command",
676                    ..
677                }
678            ),
679            "expected an acknowledge for another command, got {err:?}"
680        );
681    }
682
683    /// A late answer to a command that already timed out here is skipped,
684    /// not taken for this command's answer.
685    #[test]
686    fn an_acknowledge_for_an_earlier_request_is_skipped() {
687        let mock = Arc::new(MockUsbTransfer::new());
688        let mut ch = make_channel(&mock);
689        mock.enqueue_read(
690            EP_IN,
691            build_ack(command_id::READMEM_ACK, StatusCode::Success, 7, &[9; 4]),
692        );
693        mock.enqueue_read(
694            EP_IN,
695            build_ack(command_id::READMEM_ACK, StatusCode::Success, 1, &[1; 4]),
696        );
697
698        assert_eq!(ch.read_mem(0x1000, 4).unwrap(), [1; 4]);
699    }
700
701    #[test]
702    fn request_ids_start_at_one_and_wrap_past_zero() {
703        let mock = Arc::new(MockUsbTransfer::new());
704        let mut ch = make_channel(&mock);
705        assert_eq!(ch.next_request_id(), 1);
706        assert_eq!(ch.next_request_id(), 2);
707        ch.request_id = u16::MAX - 1;
708        assert_eq!(ch.next_request_id(), u16::MAX);
709        // GenCP §3.1: wrap to 1, so id 0 is never reused.
710        assert_eq!(ch.next_request_id(), 1);
711    }
712}