Skip to main content

viva_gige/
gvcp.rs

1//! GVCP control plane utilities.
2
3use std::collections::HashMap;
4use std::io::{self, Cursor};
5use std::net::{IpAddr, Ipv4Addr, SocketAddr};
6use std::time::Duration;
7
8use bytes::{Buf, BufMut, Bytes, BytesMut};
9use fastrand::Rng;
10use if_addrs::{IfAddr, get_if_addrs};
11use thiserror::Error;
12use tokio::net::UdpSocket;
13use tokio::task::JoinSet;
14use tokio::time;
15use tracing::{debug, info, trace, warn};
16use viva_gencp::{AckHeader, CommandFlags, GenCpAck, OpCode, StatusCode, decode_ack};
17
18use crate::consts::{
19    self, GVCP_CMD_KEY, SCPS_DO_NOT_FRAGMENT, SCPS_FIRE_TEST_PACKET, STREAM_PACKET_SIZE_MASK,
20};
21use crate::nic::Iface;
22use crate::status::GigeStatus;
23
24/// Public alias for the GVCP well-known port.
25pub use consts::PORT as GVCP_PORT;
26
27/// Encode a `PACKETRESEND_CMD` asking the device to send packets
28/// `first_packet..=last_packet` of block `block_id` on stream channel
29/// `channel` again.
30///
31/// The command asks for **no acknowledgement**: the answer is the packets
32/// themselves, on the stream channel. With 16-bit block ids the payload is
33/// 12 bytes; with extended ids (`extended_ids`, flag `0x10`) it is 20:
34///
35/// | Bytes | Standard ids                   | Extended ids                |
36/// |-------|--------------------------------|-----------------------------|
37/// | 0–1   | stream channel index           | stream channel index        |
38/// | 2–3   | block id (16 bits)             | reserved, 0                 |
39/// | 4–7   | first packet id (24 bits)      | first packet id (32 bits)   |
40/// | 8–11  | last packet id (24 bits)       | last packet id (32 bits)    |
41/// | 12–19 | —                              | block id (64 bits)          |
42///
43/// The layout is the field table Wireshark's `packet-gvcp.c` dissects
44/// (`dissect_packetresend_cmd`, which reads the standard packet ids as the
45/// low 24 bits of each word). aravis builds the same bytes for channel 0
46/// (`arv_gvcp_packet_new_packet_resend_cmd`) — corroboration, not the rule.
47/// With standard ids the block id is truncated to its 16 bits and the packet
48/// ids to their 24, which is all those fields hold.
49pub fn encode_packet_resend(
50    request_id: u16,
51    channel: u16,
52    block_id: u64,
53    first_packet: u32,
54    last_packet: u32,
55    extended_ids: bool,
56) -> Bytes {
57    const PACKET_ID_24: u32 = 0x00FF_FFFF;
58    let length: u16 = if extended_ids { 20 } else { 12 };
59    let mut buf = BytesMut::with_capacity(viva_gencp::HEADER_SIZE + length as usize);
60    buf.put_u8(GVCP_CMD_KEY);
61    buf.put_u8(if extended_ids {
62        consts::PACKET_RESEND_EXTENDED_IDS
63    } else {
64        0
65    });
66    buf.put_u16(consts::PACKET_RESEND_COMMAND);
67    buf.put_u16(length);
68    buf.put_u16(request_id);
69    buf.put_u16(channel);
70    if extended_ids {
71        buf.put_u16(0);
72        buf.put_u32(first_packet);
73        buf.put_u32(last_packet);
74        buf.put_u64(block_id);
75    } else {
76        buf.put_u16(block_id as u16);
77        buf.put_u32(first_packet & PACKET_ID_24);
78        buf.put_u32(last_packet & PACKET_ID_24);
79    }
80    buf.freeze()
81}
82
83/// GVCP request header.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub(crate) struct GvcpRequestHeader {
86    /// Request flags (acknowledgement, broadcast).
87    pub flags: CommandFlags,
88    /// Raw command/opcode value.
89    pub command: u16,
90    /// Payload length in bytes.
91    pub length: u16,
92    /// Request identifier.
93    pub request_id: u16,
94}
95
96impl GvcpRequestHeader {
97    /// Encode the header into a `Bytes` buffer ready to be transmitted.
98    ///
99    /// Uses proper GVCP wire format: byte 0 = `0x42` (command key),
100    /// byte 1 = flags byte (bit 0 = ACK_REQUIRED, bit 4 = BROADCAST).
101    pub(crate) fn encode(self, payload: &[u8]) -> Bytes {
102        let mut buf = BytesMut::with_capacity(viva_gencp::HEADER_SIZE + payload.len());
103        // GVCP command header: key byte + flags byte (not a u16 flags field).
104        buf.put_u8(GVCP_CMD_KEY);
105        buf.put_u8(self.gvcp_flags_byte());
106        buf.put_u16(self.command);
107        buf.put_u16(self.length);
108        buf.put_u16(self.request_id);
109        buf.extend_from_slice(payload);
110        buf.freeze()
111    }
112
113    /// Convert `CommandFlags` to the single-byte GVCP flag field.
114    ///
115    /// Bit 4 is overloaded by the specification: it means "allow broadcast
116    /// acknowledge" on `DISCOVERY_CMD` and "64-bit block IDs" on
117    /// `PACKETRESEND_CMD`/`EVENT_CMD`/`EVENTDATA_CMD`. This header sets it only
118    /// as the former; [`encode_packet_resend`] writes its own flag byte.
119    fn gvcp_flags_byte(&self) -> u8 {
120        let mut byte = 0u8;
121        if self.flags.contains(CommandFlags::ACK_REQUIRED) {
122            byte |= 0x01;
123        }
124        if self.flags.contains(CommandFlags::BROADCAST) {
125            byte |= 0x10;
126        }
127        if self.flags.contains(CommandFlags::SCHEDULED_ACTION) {
128            byte |= 0x80;
129        }
130        byte
131    }
132}
133
134/// GVCP acknowledgement header wrapper.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub(crate) struct GvcpAckHeader {
137    /// Status reported by the device.
138    pub status: GigeStatus,
139    /// Raw command/opcode value.
140    pub command: u16,
141    /// Payload length in bytes.
142    pub length: u16,
143    /// Identifier of the answered request.
144    pub request_id: u16,
145}
146
147impl From<AckHeader> for GvcpAckHeader {
148    fn from(value: AckHeader) -> Self {
149        Self {
150            status: GigeStatus::from_raw(value.status),
151            command: value.opcode.ack_code(),
152            length: value.length,
153            request_id: value.request_id,
154        }
155    }
156}
157
158/// Errors that can occur when operating the GVCP control path.
159#[derive(Debug, Error)]
160#[non_exhaustive]
161pub enum GigeError {
162    /// A socket operation failed.
163    #[error("io: {0}")]
164    Io(#[from] std::io::Error),
165    /// No acknowledgement arrived within the control timeout, retries
166    /// included.
167    #[error("timeout waiting for acknowledgement")]
168    Timeout,
169    /// An acknowledgement's header could not be decoded.
170    #[error("GenCP: {0}")]
171    GenCp(#[from] viva_gencp::GenCpError),
172    /// The device answered with an error status, decoded with GigE Vision's
173    /// table (ADR-0020).
174    #[error("device reported status {0}")]
175    Status(GigeStatus),
176    /// An acknowledgement does not have the shape GVCP gives it.
177    #[error("malformed {command} acknowledgement: {problem}")]
178    MalformedAck {
179        /// The command it answers, such as `"READREG"`.
180        command: &'static str,
181        /// What is wrong, such as `"answers another command"`.
182        problem: &'static str,
183    },
184    /// An acknowledgement carries another payload length than its command
185    /// asked for.
186    #[error("{command} acknowledgement carries {got} bytes; expected {expected}")]
187    AckLength {
188        /// The command it answers.
189        command: &'static str,
190        /// The bytes asked for.
191        expected: usize,
192        /// The bytes it carries.
193        got: usize,
194    },
195    /// GigE Vision control runs over IPv4, and the address or interface
196    /// given has none.
197    #[error("GigE Vision control runs over IPv4, and the {0} has no IPv4 address")]
198    NotIpv4(&'static str),
199    /// A GVSP packet size wider than `GevSCPSPacketSize`'s 16-bit field.
200    #[error("GVSP packet size {0} does not fit GevSCPSPacketSize's 16 bits")]
201    PacketSize(u32),
202}
203
204/// Information returned by GVCP discovery packets.
205///
206/// Build one with [`DeviceInfo::from_ip`] and the fields you have
207/// (`DeviceInfo { model, ..DeviceInfo::from_ip(ip) }`).
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub struct DeviceInfo {
210    /// The camera's current IPv4 address.
211    pub ip: Ipv4Addr,
212    /// The camera's MAC address.
213    pub mac: [u8; 6],
214    /// Model name (Discovery ACK offset 104).
215    pub model: Option<String>,
216    /// Manufacturer name (Discovery ACK offset 72).
217    pub manufacturer: Option<String>,
218    /// Device version string (Discovery ACK offset 136).
219    pub version: Option<String>,
220    /// Serial number as printed on the device (Discovery ACK offset 216).
221    pub serial: Option<String>,
222    /// User-programmable device name (Discovery ACK offset 232).
223    pub user_name: Option<String>,
224    /// The host address the Discovery ACK arrived at: the local IPv4 of the
225    /// discovery socket, which names both the interface and, on a NIC with
226    /// several addresses, which of them reached the device. `None` for a
227    /// record discovery did not make. A broadcast meant for this device, such
228    /// as [`force_ip`], has to leave from it (`Iface::from_ipv4`).
229    pub local_ip: Option<Ipv4Addr>,
230    /// The camera's current subnet mask (Discovery ACK offset 52).
231    pub subnet: Option<Ipv4Addr>,
232    /// The camera's current default gateway (Discovery ACK offset 68).
233    pub gateway: Option<Ipv4Addr>,
234    /// The netmask of the host address in [`local_ip`](Self::local_ip).
235    pub local_netmask: Option<Ipv4Addr>,
236}
237
238impl DeviceInfo {
239    /// A minimal record for a device addressed directly by IP.
240    ///
241    /// Used when the caller names a camera by address and there is no
242    /// Discovery ACK to populate the identity fields.
243    pub fn from_ip(ip: Ipv4Addr) -> Self {
244        Self {
245            ip,
246            mac: [0; 6],
247            model: None,
248            manufacturer: None,
249            version: None,
250            serial: None,
251            user_name: None,
252            local_ip: None,
253            subnet: None,
254            gateway: None,
255            local_netmask: None,
256        }
257    }
258
259    /// Whether the camera and the host address that heard it are on one
260    /// subnet, by both masks: the camera's address inside the host's network,
261    /// and the host's inside the camera's. `None` when either side's address
262    /// or mask is unknown.
263    ///
264    /// A camera that answers discovery but fails this is configured for
265    /// another network. It answered a broadcast, but cannot be reached by
266    /// unicast — every connection to it fails — until its address is changed
267    /// (`force_ip`) or the host joins its network.
268    pub fn shares_subnet_with_host(&self) -> Option<bool> {
269        let (camera, camera_mask) = (u32::from(self.ip), u32::from(self.subnet?));
270        let host = u32::from(self.local_ip?);
271        let host_mask = u32::from(self.local_netmask?);
272        Some(camera & host_mask == host & host_mask && host & camera_mask == camera & camera_mask)
273    }
274
275    /// Format the MAC address as `AA:BB:CC:DD:EE:FF`.
276    pub fn mac_string(&self) -> String {
277        self.mac
278            .iter()
279            .map(|byte| format!("{byte:02X}"))
280            .collect::<Vec<_>>()
281            .join(":")
282    }
283}
284
285/// How [`discover_with`] looks for cameras.
286///
287/// The default: every IPv4 interface but loopback, and acknowledgements
288/// unicast to the host.
289#[derive(Debug, Clone, Default)]
290pub struct DiscoveryOptions {
291    interface: Option<String>,
292    include_loopback: bool,
293    allow_broadcast_ack: bool,
294}
295
296impl DiscoveryOptions {
297    /// The defaults.
298    pub fn new() -> Self {
299        Self::default()
300    }
301
302    /// Ask on this interface only, by its OS name. A named interface is
303    /// asked even when it is loopback.
304    pub fn interface(mut self, name: impl Into<String>) -> Self {
305        self.interface = Some(name.into());
306        self
307    }
308
309    /// Ask on loopback too, for simulated cameras bound to `127.0.0.1`.
310    pub fn include_loopback(mut self, include: bool) -> Self {
311        self.include_loopback = include;
312        self
313    }
314
315    /// Set the command's *allow broadcast acknowledge* flag (`0x10`): a
316    /// camera that cannot unicast its answer to the host — one configured
317    /// for another subnet, typically — may broadcast it instead (default:
318    /// off).
319    ///
320    /// Off, such a camera may stay silent. On, every listener on the subnet
321    /// receives its answer, which is why it is not the default.
322    pub fn allow_broadcast_ack(mut self, allow: bool) -> Self {
323        self.allow_broadcast_ack = allow;
324        self
325    }
326}
327
328/// Discover GigE Vision devices on the local network by broadcasting a GVCP discovery command.
329pub async fn discover(timeout: Duration) -> Result<Vec<DeviceInfo>, GigeError> {
330    discover_with(timeout, &DiscoveryOptions::new()).await
331}
332
333/// Discover devices only on the specified interface name.
334///
335/// When a user explicitly names an interface (including loopback like `lo0`),
336/// it is always included — the loopback filter only applies to the unfiltered
337/// [`discover`] call.
338pub async fn discover_on_interface(
339    timeout: Duration,
340    interface: &str,
341) -> Result<Vec<DeviceInfo>, GigeError> {
342    discover_with(timeout, &DiscoveryOptions::new().interface(interface)).await
343}
344
345/// Discover devices on all interfaces including loopback.
346///
347/// This is useful for testing with simulated cameras (e.g. `arv-fake-gv-camera`)
348/// bound to `127.0.0.1`.
349pub async fn discover_all(timeout: Duration) -> Result<Vec<DeviceInfo>, GigeError> {
350    discover_with(timeout, &DiscoveryOptions::new().include_loopback(true)).await
351}
352
353/// Discover devices as `options` say.
354///
355/// Each interface asks from a socket bound to its own address, sending to
356/// its subnet-directed broadcast and to the limited broadcast
357/// `255.255.255.255`: only the second reaches a camera configured for
358/// another subnet, which is the camera a user most needs to find.
359pub async fn discover_with(
360    timeout: Duration,
361    options: &DiscoveryOptions,
362) -> Result<Vec<DeviceInfo>, GigeError> {
363    discover_impl(timeout, options).await
364}
365
366/// Ask the camera at `ip` directly: a unicast `DISCOVERY_CMD` to its GVCP
367/// port, for a camera that broadcast discovery does not reach — across a
368/// router, say. `None` when nothing answers within `timeout`.
369pub async fn discover_ip(ip: Ipv4Addr, timeout: Duration) -> Result<Option<DeviceInfo>, GigeError> {
370    let socket = UdpSocket::bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)).await?;
371    socket
372        .connect(SocketAddr::new(IpAddr::V4(ip), consts::PORT))
373        .await?;
374    let local_ip = match socket.local_addr()?.ip() {
375        IpAddr::V4(local) => Some(local),
376        IpAddr::V6(_) => None,
377    };
378    let request_id = 0x0100;
379    let header = GvcpRequestHeader {
380        flags: discovery_flags(false),
381        command: consts::DISCOVERY_COMMAND,
382        length: 0,
383        request_id,
384    };
385    info!(%ip, "sending GVCP discovery by unicast");
386    socket.send(&header.encode(&[])).await?;
387    let mut buffer = vec![0u8; consts::DISCOVERY_BUFFER];
388    let deadline = time::Instant::now() + timeout;
389    loop {
390        let len = match time::timeout_at(deadline, socket.recv(&mut buffer)).await {
391            Err(_) => return Ok(None),
392            Ok(Ok(len)) => len,
393            // Nothing listens at that address: an answer, not a failure.
394            Ok(Err(err)) if is_icmp_error(&err) => return Ok(None),
395            Ok(Err(err)) => return Err(err.into()),
396        };
397        if let Some(mut info) = parse_discovery_ack(&buffer[..len], request_id) {
398            info.local_ip = local_ip;
399            info.local_netmask = local_ip.and_then(netmask_of);
400            return Ok(Some(info));
401        }
402    }
403}
404
405/// The netmask of this host's address `ip`, if an interface has it.
406fn netmask_of(ip: Ipv4Addr) -> Option<Ipv4Addr> {
407    get_if_addrs()
408        .ok()?
409        .into_iter()
410        .find_map(|iface| match iface.addr {
411            IfAddr::V4(v4) if v4.ip == ip => Some(v4.netmask),
412            _ => None,
413        })
414}
415
416/// Send a FORCEIP command to temporarily assign an IP address to a device.
417///
418/// FORCEIP is a broadcast command that targets a device by its MAC address.
419/// The assigned IP is temporary — it does not survive a power cycle. Use
420/// [`GigeDevice::write_persistent_ip`] + [`GigeDevice::enable_persistent_ip`]
421/// for permanent configuration.
422///
423/// FORCEIP payload layout (56 bytes, big-endian):
424/// ```text
425/// [0..2]   reserved
426/// [2..8]   target MAC address (6 bytes)
427/// [8..20]  reserved
428/// [20..24] static IP address
429/// [24..36] reserved
430/// [36..40] subnet mask
431/// [40..52] reserved
432/// [52..56] gateway
433/// ```
434pub async fn force_ip(
435    mac: [u8; 6],
436    ip: Ipv4Addr,
437    subnet: Ipv4Addr,
438    gateway: Ipv4Addr,
439    iface: Option<&Iface>,
440) -> Result<(), GigeError> {
441    // Build the 56-byte FORCEIP payload.
442    let payload = encode_forceip_payload(mac, ip, subnet, gateway);
443
444    let local_ip = match iface {
445        Some(iface) => iface.ipv4().ok_or(GigeError::NotIpv4("interface"))?,
446        None => Ipv4Addr::UNSPECIFIED,
447    };
448
449    let socket = UdpSocket::bind(SocketAddr::new(IpAddr::V4(local_ip), 0)).await?;
450    socket.set_broadcast(true)?;
451    let dest = SocketAddr::new(IpAddr::V4(Ipv4Addr::BROADCAST), consts::PORT);
452
453    let header = GvcpRequestHeader {
454        flags: CommandFlags::ACK_REQUIRED | CommandFlags::BROADCAST,
455        command: consts::FORCEIP_COMMAND,
456        length: payload.len() as u16,
457        request_id: 1,
458    };
459    let packet = header.encode(&payload);
460    info!(mac = ?mac, %ip, %subnet, %gateway, "sending FORCEIP command");
461    socket.send_to(&packet, dest).await?;
462
463    // Wait for FORCEIP_ACK.
464    let mut buf = vec![0u8; consts::DISCOVERY_BUFFER];
465    match time::timeout(consts::CONTROL_TIMEOUT, socket.recv_from(&mut buf)).await {
466        Ok(Ok((len, _src))) => {
467            if len < viva_gencp::HEADER_SIZE {
468                return Err(GigeError::MalformedAck {
469                    command: "FORCEIP",
470                    problem: "is shorter than a GVCP header",
471                });
472            }
473            let mut cursor = &buf[..];
474            let status = cursor.get_u16();
475            let command = cursor.get_u16();
476            if command != consts::FORCEIP_ACK {
477                debug!(
478                    command = format_args!("{command:#06x}"),
479                    "FORCEIP answered by another acknowledgement"
480                );
481                return Err(GigeError::MalformedAck {
482                    command: "FORCEIP",
483                    problem: "answers another command",
484                });
485            }
486            let status = GigeStatus::from_raw(status);
487            if !status.is_success() {
488                return Err(GigeError::Status(status));
489            }
490            info!(%ip, "FORCEIP accepted");
491            Ok(())
492        }
493        Ok(Err(e)) => Err(e.into()),
494        Err(_) => Err(GigeError::Timeout),
495    }
496}
497
498/// Encode the 56-byte FORCEIP payload.
499fn encode_forceip_payload(
500    mac: [u8; 6],
501    ip: Ipv4Addr,
502    subnet: Ipv4Addr,
503    gateway: Ipv4Addr,
504) -> Vec<u8> {
505    let mut buf = vec![0u8; 56];
506    // [0..2]   reserved
507    // [2..8]   MAC address
508    buf[2..8].copy_from_slice(&mac);
509    // [8..20]  reserved
510    // [20..24] IP address
511    buf[20..24].copy_from_slice(&ip.octets());
512    // [24..36] reserved
513    // [36..40] subnet mask
514    buf[36..40].copy_from_slice(&subnet.octets());
515    // [40..52] reserved
516    // [52..56] gateway
517    buf[52..56].copy_from_slice(&gateway.octets());
518    buf
519}
520
521async fn discover_impl(
522    timeout: Duration,
523    options: &DiscoveryOptions,
524) -> Result<Vec<DeviceInfo>, GigeError> {
525    let include_loopback = options.include_loopback || options.interface.is_some();
526    let mut interfaces = Vec::new();
527    for iface in get_if_addrs()? {
528        let IfAddr::V4(v4) = iface.addr else {
529            continue;
530        };
531        if !include_loopback && v4.ip.is_loopback() {
532            continue;
533        }
534        if let Some(filter) = &options.interface
535            && iface.name != *filter
536        {
537            continue;
538        }
539        interfaces.push((iface.name, iface.index, v4));
540    }
541    let flags = discovery_flags(options.allow_broadcast_ack);
542    let broadcast_ack = options.allow_broadcast_ack;
543
544    if interfaces.is_empty() {
545        return Ok(Vec::new());
546    }
547
548    let mut join_set = JoinSet::new();
549    for (idx, (name, index, v4)) in interfaces.into_iter().enumerate() {
550        let request_id = 0x0100u16.wrapping_add(idx as u16);
551        let interface_name = name.clone();
552        join_set.spawn(async move {
553            let pinned = if broadcast_ack && !v4.ip.is_loopback() {
554                broadcast_ack_socket(index, &interface_name)
555            } else {
556                None
557            };
558            let socket = match pinned {
559                Some(socket) => socket,
560                None => {
561                    let local_addr = SocketAddr::new(IpAddr::V4(v4.ip), 0);
562                    let socket = match UdpSocket::bind(local_addr).await {
563                        Ok(socket) => socket,
564                        Err(err) => {
565                            warn!(%interface_name, local = %v4.ip, error = %err,
566                                  "skipping interface: bind failed");
567                            return Vec::new();
568                        }
569                    };
570                    if !v4.ip.is_loopback() {
571                        if let Err(err) = socket.set_broadcast(true) {
572                            warn!(%interface_name, local = %v4.ip, error = %err,
573                                  "skipping interface: SO_BROADCAST failed");
574                            return Vec::new();
575                        }
576                        bind_to_interface(&socket, index, &interface_name);
577                    }
578                    socket
579                }
580            };
581
582            let header = GvcpRequestHeader {
583                flags,
584                command: consts::DISCOVERY_COMMAND,
585                length: 0,
586                request_id,
587            };
588            let packet = header.encode(&[]);
589            let mut sent = 0;
590            for dest in discovery_destinations(v4.ip, v4.netmask) {
591                let destination = SocketAddr::new(IpAddr::V4(dest), consts::PORT);
592                info!(%interface_name, local = %v4.ip, dest = %destination, "sending GVCP discovery");
593                match socket.send_to(&packet, destination).await {
594                    Ok(_) => sent += 1,
595                    Err(err) => warn!(%interface_name, dest = %destination, error = %err,
596                                      "discovery send failed"),
597                }
598            }
599            if sent == 0 {
600                warn!(%interface_name, "skipping interface: no discovery could be sent");
601                return Vec::new();
602            }
603
604            let mut responses = Vec::new();
605            let mut buffer = vec![0u8; consts::DISCOVERY_BUFFER];
606            let timer = time::sleep(timeout);
607            tokio::pin!(timer);
608            loop {
609                tokio::select! {
610                    _ = &mut timer => break,
611                    recv = socket.recv_from(&mut buffer) => {
612                        // A receive error must not discard the cameras we have
613                        // already found on this interface. Windows in particular
614                        // reports WSAECONNRESET (10054) here when an earlier
615                        // broadcast drew an ICMP port-unreachable (#57).
616                        let (len, src) = match recv {
617                            Ok(v) => v,
618                            // An ICMP reply to one of the broadcasts says
619                            // nothing about the cameras still answering.
620                            Err(err) if is_icmp_error(&err) => {
621                                debug!(%interface_name, error = %err,
622                                       "ignoring an ICMP error on the discovery socket");
623                                continue;
624                            }
625                            Err(err) => {
626                                debug!(%interface_name, error = %err,
627                                       "discovery receive failed; keeping results so far");
628                                break;
629                            }
630                        };
631                        info!(%interface_name, %src, "received GVCP response");
632                        trace!(%interface_name, bytes = len, "GVCP response length");
633                        if let Some(mut info) = parse_discovery_ack(&buffer[..len], request_id) {
634                            trace!(ip = %info.ip, mac = %info.mac_string(), "parsed discovery ack");
635                            info.local_ip = Some(v4.ip);
636                            info.local_netmask = Some(v4.netmask);
637                            responses.push(info);
638                        }
639                    }
640                }
641            }
642            responses
643        });
644    }
645
646    // One interface failing must never fail the whole call: a host commonly has
647    // a down NIC, a Hyper-V switch, or a VPN adapter alongside the one the
648    // camera is on.
649    let mut seen = HashMap::new();
650    while let Some(res) = join_set.join_next().await {
651        match res {
652            Ok(devices) => {
653                for dev in devices {
654                    seen.entry((dev.ip, dev.mac)).or_insert(dev);
655                }
656            }
657            Err(err) => warn!(error = %err, "discovery task failed"),
658        }
659    }
660
661    let mut devices: Vec<_> = seen.into_values().collect();
662    devices.sort_by_key(|d| d.ip);
663    Ok(devices)
664}
665
666/// Where an interface sends `DISCOVERY_CMD`.
667///
668/// On loopback, broadcast is not supported on some platforms (macOS), so the
669/// command goes to the local address itself.
670///
671/// Elsewhere it goes to the subnet-directed broadcast, which routers may
672/// forward, and to the limited broadcast `255.255.255.255`, which reaches
673/// every device on the link whatever its address — the camera configured for
674/// another subnet among them (aravis sends only the latter,
675/// `arvgvinterface.c`). A camera that hears both answers twice; discovery
676/// keeps one record per address and MAC.
677fn discovery_destinations(ip: Ipv4Addr, netmask: Ipv4Addr) -> Vec<Ipv4Addr> {
678    if ip.is_loopback() {
679        return vec![ip];
680    }
681    let directed = directed_broadcast(ip, netmask);
682    if directed == Ipv4Addr::BROADCAST {
683        return vec![directed];
684    }
685    vec![directed, Ipv4Addr::BROADCAST]
686}
687
688/// The flag byte of a `DISCOVERY_CMD`: an acknowledgement asked for, and
689/// *allow broadcast acknowledge* (`0x10`) only when the caller allows it.
690fn discovery_flags(allow_broadcast_ack: bool) -> CommandFlags {
691    if allow_broadcast_ack {
692        CommandFlags::ACK_REQUIRED | CommandFlags::BROADCAST
693    } else {
694        CommandFlags::ACK_REQUIRED
695    }
696}
697
698/// Whether `err` only reflects an ICMP reply to something the socket sent:
699/// `ECONNREFUSED` on Unix, `WSAECONNRESET` on Windows.
700fn is_icmp_error(err: &std::io::Error) -> bool {
701    matches!(
702        err.kind(),
703        std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::ConnectionReset
704    )
705}
706
707/// Keep a discovery socket's broadcasts on its own interface.
708///
709/// Linux sends a limited broadcast from the interface owning the socket's
710/// source address. macOS routes it like any other packet — out of the primary
711/// interface — unless the socket is bound to one (`IP_BOUND_IF`).
712fn bind_to_interface(socket: &UdpSocket, index: Option<u32>, name: &str) {
713    #[cfg(any(target_os = "macos", target_os = "ios"))]
714    {
715        let index = index.and_then(std::num::NonZeroU32::new);
716        if let Err(err) = socket2::SockRef::from(socket).bind_device_by_index_v4(index) {
717            debug!(name, error = %err, "IP_BOUND_IF failed; the limited broadcast may leave by another interface");
718        }
719    }
720    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
721    let _ = (socket, index, name);
722}
723
724/// A discovery socket that receives broadcast acknowledgements.
725///
726/// A camera that broadcasts its acknowledgement sends it to the limited
727/// broadcast, at the request's source port. macOS does not deliver that to a
728/// socket bound to the interface's unicast address (backlog TC-40, seen on a
729/// Manta G-125B), so this socket binds the unspecified address and is kept on
730/// its interface: `IP_BOUND_IF` on macOS, `SO_BINDTODEVICE` on Linux, which
731/// may need privileges. `None` where it cannot be kept there, since an
732/// unpinned `0.0.0.0` socket sends and receives on every interface; the
733/// caller then binds the interface's address as for any discovery.
734fn broadcast_ack_socket(index: Option<u32>, name: &str) -> Option<UdpSocket> {
735    let open = || -> std::io::Result<Option<UdpSocket>> {
736        let socket = socket2::Socket::new(
737            socket2::Domain::IPV4,
738            socket2::Type::DGRAM,
739            Some(socket2::Protocol::UDP),
740        )?;
741        socket.set_broadcast(true)?;
742        if !pin_to_interface(&socket, index, name)? {
743            return Ok(None);
744        }
745        socket.bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0).into())?;
746        socket.set_nonblocking(true)?;
747        Ok(Some(UdpSocket::from_std(socket.into())?))
748    };
749    match open() {
750        Ok(socket) => socket,
751        Err(err) => {
752            debug!(name, error = %err,
753                   "cannot keep an unbound discovery socket on its interface; broadcast acknowledgements may be missed");
754            None
755        }
756    }
757}
758
759/// Keep `socket` on one interface for sending and receiving; `false` where
760/// this OS offers no way to.
761#[cfg(any(target_os = "macos", target_os = "ios"))]
762fn pin_to_interface(
763    socket: &socket2::Socket,
764    index: Option<u32>,
765    _name: &str,
766) -> std::io::Result<bool> {
767    let Some(index) = index.and_then(std::num::NonZeroU32::new) else {
768        return Ok(false);
769    };
770    socket.bind_device_by_index_v4(Some(index))?;
771    Ok(true)
772}
773
774#[cfg(any(target_os = "linux", target_os = "android"))]
775fn pin_to_interface(
776    socket: &socket2::Socket,
777    _index: Option<u32>,
778    name: &str,
779) -> std::io::Result<bool> {
780    socket.bind_device(Some(name.as_bytes()))?;
781    Ok(true)
782}
783
784#[cfg(not(any(
785    target_os = "macos",
786    target_os = "ios",
787    target_os = "linux",
788    target_os = "android"
789)))]
790fn pin_to_interface(
791    _socket: &socket2::Socket,
792    _index: Option<u32>,
793    _name: &str,
794) -> std::io::Result<bool> {
795    Ok(false)
796}
797
798/// Derive an IPv4 directed-broadcast address from an interface address and
799/// netmask.
800///
801/// On Linux an address added without an explicit `brd` value can make
802/// `getifaddrs(3)` report the address itself through the broadcast union. That
803/// turns discovery into a unicast request, notably for a manually configured
804/// `169.254.0.0/16` address. The netmask remains authoritative, so calculate
805/// the broadcast address ourselves instead of trusting that optional field.
806fn directed_broadcast(ip: Ipv4Addr, netmask: Ipv4Addr) -> Ipv4Addr {
807    Ipv4Addr::from(u32::from(ip) | !u32::from(netmask))
808}
809
810/// Decode one datagram received on the discovery socket.
811///
812/// Returns `None` — never an error — for anything that is not a usable
813/// Discovery ACK for us. The socket is bound to an ephemeral port on a
814/// broadcast network, so unrelated GVCP traffic is expected; treating it as
815/// fatal would discard the cameras already found on this interface (#57).
816fn parse_discovery_ack(buf: &[u8], expected_request: u16) -> Option<DeviceInfo> {
817    if buf.len() < viva_gencp::HEADER_SIZE {
818        trace!(len = buf.len(), "ignoring short GVCP datagram");
819        return None;
820    }
821    let mut header = buf;
822    let status = header.get_u16();
823    let command = header.get_u16();
824    let length = header.get_u16() as usize;
825    let request_id = header.get_u16();
826    if request_id != expected_request {
827        return None;
828    }
829    if command != consts::DISCOVERY_ACK {
830        debug!(
831            opcode = format_args!("{command:#06x}"),
832            "ignoring non-discovery GVCP ack"
833        );
834        return None;
835    }
836    if status != 0 {
837        debug!(
838            status = format_args!("{status:#06x}"),
839            "discovery ack reported a non-zero status"
840        );
841        return None;
842    }
843    if buf.len() < viva_gencp::HEADER_SIZE + length {
844        debug!(
845            declared = length,
846            actual = buf.len() - viva_gencp::HEADER_SIZE,
847            "ignoring truncated discovery payload"
848        );
849        return None;
850    }
851    let payload = &buf[viva_gencp::HEADER_SIZE..viva_gencp::HEADER_SIZE + length];
852    match parse_discovery_payload(payload) {
853        Ok(info) => Some(info),
854        Err(err) => {
855            debug!(error = %err, "ignoring unparsable discovery payload");
856            None
857        }
858    }
859}
860
861/// Parse a GigE Vision Discovery ACK payload (248 bytes).
862///
863/// The payload mirrors the device's bootstrap register block, so the MAC is
864/// split across `DeviceMACAddressHigh` (0x08, whose low half holds the top two
865/// octets) and `DeviceMACAddressLow` (0x0C) — six contiguous bytes at offset
866/// **10**, not 12. Cross-checked against Wireshark's `dissect_discovery_ack()`,
867/// which reads the MAC from `offset + 10` and the IP, manufacturer and model
868/// from 36, 72 and 104. Reported in #57 against a JAI FS-3200T-10GE-NNC, whose
869/// `00:0C:DF:06:5B:2F` was read as `DF:06:5B:2F:C0:00`.
870///
871/// | Offset | Size | Field                        |
872/// |--------|------|------------------------------|
873/// |      0 |    2 | Spec version major           |
874/// |      2 |    2 | Spec version minor           |
875/// |      4 |    4 | Device mode                  |
876/// |      8 |    2 | Reserved (MAC-high padding)  |
877/// |     10 |    6 | MAC address                  |
878/// |     16 |    4 | Supported IP config          |
879/// |     20 |    4 | Current IP config            |
880/// |     24 |   12 | Reserved                     |
881/// |     36 |    4 | Current IP address           |
882/// |     40 |   12 | Reserved                     |
883/// |     52 |    4 | Current subnet mask          |
884/// |     56 |   12 | Reserved                     |
885/// |     68 |    4 | Default gateway              |
886/// |     72 |   32 | Manufacturer name            |
887/// |    104 |   32 | Model name                   |
888/// |    136 |   32 | Device version               |
889/// |    168 |   48 | Manufacturer specific info   |
890/// |    216 |   16 | Serial number                |
891/// |    232 |   16 | User defined name            |
892fn parse_discovery_payload(payload: &[u8]) -> Result<DeviceInfo, GigeError> {
893    // Minimum size to reach past the current IP field. Everything after it is
894    // read leniently: a short-but-valid ACK should still yield a usable device
895    // rather than failing discovery on that interface.
896    if payload.len() < 40 {
897        return Err(GigeError::AckLength {
898            command: "DISCOVERY",
899            expected: 40,
900            got: payload.len(),
901        });
902    }
903    let mut cursor = Cursor::new(payload);
904    let _spec_major = cursor.get_u16(); // 0
905    let _spec_minor = cursor.get_u16(); // 2
906    let _device_mode = cursor.get_u32(); // 4
907
908    // Only the two padding bytes of the MAC-high register precede the address.
909    cursor.advance(2); // 8..10
910
911    // MAC: 2 bytes from the high register + 4 from the low register.
912    let mut mac = [0u8; 6];
913    cursor.copy_to_slice(&mut mac); // 10..16
914
915    let _supported_ip_config = cursor.get_u32(); // 16
916    let _current_ip_config = cursor.get_u32(); // 20
917
918    // 12 bytes reserved before current IP.
919    cursor.advance(12); // 24..36
920    let ip = Ipv4Addr::from(cursor.get_u32()); // 36
921
922    // Everything past the IP is optional, so every step from here on has to
923    // tolerate the payload ending.
924    skip(&mut cursor, 12); // 40..52 reserved
925    let subnet = read_ipv4(&mut cursor); // 52
926    skip(&mut cursor, 12); // 56..68 reserved
927    let gateway = read_ipv4(&mut cursor); // 68
928
929    // String fields. All optional: a device that truncates the payload still
930    // gives us an addressable camera.
931    let manufacturer = read_fixed_string(&mut cursor, 32); // 72
932    let model = read_fixed_string(&mut cursor, 32); // 104
933    let version = read_fixed_string(&mut cursor, 32); // 136
934    skip(&mut cursor, 48); // 168 manufacturer-specific info
935    let serial = read_fixed_string(&mut cursor, 16); // 216
936    let user_name = read_fixed_string(&mut cursor, 16); // 232
937
938    Ok(DeviceInfo {
939        ip,
940        mac,
941        manufacturer,
942        model,
943        version,
944        serial,
945        user_name,
946        local_ip: None,
947        subnet,
948        gateway,
949        local_netmask: None,
950    })
951}
952
953/// Read an IPv4 address, or `None` if the payload ends early.
954fn read_ipv4(cursor: &mut Cursor<&[u8]>) -> Option<Ipv4Addr> {
955    (cursor.remaining() >= 4).then(|| Ipv4Addr::from(cursor.get_u32()))
956}
957
958/// Read a NUL-padded fixed-width string, or `None` if the payload ends early.
959fn read_fixed_string(cursor: &mut Cursor<&[u8]>, len: usize) -> Option<String> {
960    if cursor.remaining() < len {
961        return None;
962    }
963    let mut buf = vec![0u8; len];
964    cursor.copy_to_slice(&mut buf);
965    parse_string(&buf)
966}
967
968/// Advance past a field, stopping at the end of a truncated payload.
969fn skip(cursor: &mut Cursor<&[u8]>, len: usize) {
970    let n = len.min(cursor.remaining());
971    cursor.advance(n);
972}
973
974fn parse_string(bytes: &[u8]) -> Option<String> {
975    let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
976    let slice = &bytes[..end];
977    let s = String::from_utf8_lossy(slice).trim().to_string();
978    if s.is_empty() { None } else { Some(s) }
979}
980
981/// Outcome of waiting for one acknowledgement.
982///
983/// Mirrors the three cases the caller already distinguishes — a datagram, a
984/// socket error, and a deadline — so that PENDING_ACK handling can be factored
985/// out without changing the retry policy around it.
986enum AckRecv {
987    Received(usize),
988    Io(std::io::Error),
989    TimedOut,
990}
991
992/// Decode a GVCP PENDING_ACK, returning the request id it refers to and the
993/// extra time the device is asking for.
994///
995/// Returns `None` for anything that is not a PENDING_ACK, so the caller can
996/// hand the datagram to the normal GenCP decoder.
997///
998/// Layout per GigE Vision 1.2 section 18.5: the 8-byte GVCP acknowledgement
999/// header, then two reserved bytes and a 16-bit `time_to_completion` in
1000/// milliseconds.
1001///
1002/// This diverges deliberately from aravis, whose
1003/// `arv_gvcp_packet_get_pending_ack_timeout` reads all four payload bytes as a
1004/// big-endian `u32`. The two agree whenever the reserved field is zero, which
1005/// is what the specification requires of the device; reading the `u16` the
1006/// specification actually defines is the safer of the two, because a device
1007/// that leaves junk in the reserved field cannot then talk us into a wait
1008/// three orders of magnitude too long. Callers clamp the result regardless.
1009fn parse_pending_ack(buf: &[u8]) -> Option<(u16, Duration)> {
1010    if buf.len() < viva_gencp::HEADER_SIZE {
1011        return None;
1012    }
1013    if u16::from_be_bytes([buf[2], buf[3]]) != consts::PENDING_ACK {
1014        return None;
1015    }
1016    let request_id = u16::from_be_bytes([buf[6], buf[7]]);
1017    let payload = &buf[viva_gencp::HEADER_SIZE..];
1018    // A truncated PENDING_ACK is still an unambiguous request for more time;
1019    // grant the default rather than discarding it and resending the command.
1020    let millis = match payload {
1021        [_, _, hi, lo, ..] => u16::from_be_bytes([*hi, *lo]),
1022        _ => return Some((request_id, consts::CONTROL_TIMEOUT)),
1023    };
1024    Some((request_id, Duration::from_millis(u64::from(millis))))
1025}
1026
1027/// Environment variable that starts every [`GigeDevice`] on READMEM/WRITEMEM.
1028///
1029/// Any non-empty value other than `0` counts as set. The escape hatch for a
1030/// device that mishandles READREG/WRITEREG in a way the automatic fallback
1031/// cannot detect — answering with a wrong value rather than refusing — so a
1032/// user can get back to memory access without a rebuild.
1033pub const FORCE_READMEM_ENV: &str = "VIVA_GIGE_FORCE_READMEM";
1034
1035/// Whether a [`FORCE_READMEM_ENV`] value asks for memory access.
1036fn force_readmem_requested(value: Option<&std::ffi::OsStr>) -> bool {
1037    value.is_some_and(|v| !v.is_empty() && v != "0")
1038}
1039
1040/// The GVCP name of a register or memory command, for errors.
1041fn command_name(opcode: OpCode) -> &'static str {
1042    match opcode {
1043        OpCode::ReadRegister => "READREG",
1044        OpCode::WriteRegister => "WRITEREG",
1045        OpCode::ReadMem => "READMEM",
1046        OpCode::WriteMem => "WRITEMEM",
1047    }
1048}
1049
1050/// The READREG/WRITEREG address for an access that is exactly one register.
1051///
1052/// A GVCP register is a 32-bit word on a 32-bit boundary in the low 4 GiB, so
1053/// anything else stays READMEM/WRITEMEM. In particular an 8-byte access is
1054/// *not* split into two registers: a multi-register READREG has no defined
1055/// atomicity, so a latched 64-bit timestamp could tear silently, and a
1056/// WRITEREG acknowledgement carries only an index placeholder, so a partial
1057/// multi-register write could not even be reported (backlog TC-22).
1058fn single_register_address(addr: u64, len: usize) -> Option<u32> {
1059    if len != 4 || !addr.is_multiple_of(4) {
1060        return None;
1061    }
1062    u32::try_from(addr).ok()
1063}
1064
1065/// GVCP Capability (`0x0934`): which optional commands and behaviours the
1066/// device implements, one bit each.
1067///
1068/// Masks from Wireshark's `hf_gvcp_capability_*` fields; the specification
1069/// numbers bits from the most significant, so `0x20` is its bit 26. Only the
1070/// bits something here acts on, or a report shows, have a method; the rest
1071/// are in [`bits`](Self::bits).
1072#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1073pub struct GvcpCapability(u32);
1074
1075impl GvcpCapability {
1076    /// The capability word as read.
1077    pub const fn from_bits(bits: u32) -> Self {
1078        Self(bits)
1079    }
1080
1081    /// The raw word.
1082    pub const fn bits(self) -> u32 {
1083        self.0
1084    }
1085
1086    /// `PENDING_ACK` can be enabled in GVCP Configuration (`0x20`).
1087    pub const fn pending_ack(self) -> bool {
1088        self.0 & consts::CAPABILITY_PENDING_ACK != 0
1089    }
1090
1091    /// `PACKETRESEND_CMD` is answered (`0x04`).
1092    pub const fn packet_resend(self) -> bool {
1093        self.0 & consts::CAPABILITY_PACKET_RESEND != 0
1094    }
1095
1096    /// `WRITEMEM_CMD` is implemented (`0x02`).
1097    pub const fn writemem(self) -> bool {
1098        self.0 & 0x0000_0002 != 0
1099    }
1100
1101    /// Several registers in one READREG/WRITEREG (`0x01`).
1102    pub const fn concatenation(self) -> bool {
1103        self.0 & 0x0000_0001 != 0
1104    }
1105
1106    /// `EVENT_CMD` is sent (`0x08`).
1107    pub const fn event(self) -> bool {
1108        self.0 & 0x0000_0008 != 0
1109    }
1110
1111    /// `EVENTDATA_CMD` is sent (`0x10`).
1112    pub const fn event_data(self) -> bool {
1113        self.0 & 0x0000_0010 != 0
1114    }
1115
1116    /// `ACTION_CMD` is answered (`0x40`).
1117    pub const fn action(self) -> bool {
1118        self.0 & 0x0000_0040 != 0
1119    }
1120
1121    /// The heartbeat can be disabled in GVCP Configuration (`0x2000_0000`).
1122    pub const fn heartbeat_disable(self) -> bool {
1123        self.0 & 0x2000_0000 != 0
1124    }
1125
1126    /// The primary application's IP and port are readable (`0x0800_0000`).
1127    pub const fn ccp_application_port_ip(self) -> bool {
1128        self.0 & 0x0800_0000 != 0
1129    }
1130
1131    /// Control can be handed over with a switchover key (`0x0020_0000`).
1132    pub const fn primary_application_switchover(self) -> bool {
1133        self.0 & 0x0020_0000 != 0
1134    }
1135}
1136
1137/// GVCP device handle.
1138pub struct GigeDevice {
1139    socket: UdpSocket,
1140    remote: SocketAddr,
1141    control_timeout: Duration,
1142    inflight_keepalive_period: Option<Duration>,
1143    last_command_sent: time::Instant,
1144    request_id: u16,
1145    rng: Rng,
1146    /// Single-register access goes out as READMEM/WRITEMEM instead of
1147    /// READREG/WRITEREG. Set by [`FORCE_READMEM_ENV`] at open, or latched for
1148    /// the rest of the session once the device refuses a register command.
1149    memory_access_only: bool,
1150    /// Whether the device names its primary application (GVCP Capability
1151    /// `0x0800_0000`), read once when first needed.
1152    names_primary_application: Option<bool>,
1153    /// Claim exclusive access (CCP `0x1`) rather than control access.
1154    exclusive_access: bool,
1155}
1156
1157/// Stream negotiation outcome describing the values written to the device.
1158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1159pub struct StreamParams {
1160    /// Selected GVSP packet size (bytes).
1161    pub packet_size: u32,
1162    /// `GevSCPD` written, in timestamp ticks; `None` when the stream left the
1163    /// camera's own value alone.
1164    pub packet_delay: Option<u32>,
1165    /// Link MTU used to derive the packet size.
1166    pub mtu: u32,
1167    /// Host IPv4 address configured on the device.
1168    pub host: Ipv4Addr,
1169    /// Host port configured on the device.
1170    pub port: u16,
1171    /// Stream channel index.
1172    pub channel: u32,
1173    /// The camera's GVCP address, where packet resend requests go; `None`
1174    /// for a stream received on a socket of the caller's.
1175    pub camera: Option<SocketAddr>,
1176}
1177
1178impl GigeDevice {
1179    /// Connect to a device GVCP endpoint.
1180    ///
1181    /// The connection is ready for register read/write but does not claim
1182    /// control privilege. Call [`Self::claim_control`] before configuring streaming
1183    /// or starting acquisition.
1184    pub async fn open(addr: SocketAddr) -> Result<Self, GigeError> {
1185        let local_ip = match addr.ip() {
1186            IpAddr::V4(_) => IpAddr::V4(Ipv4Addr::UNSPECIFIED),
1187            IpAddr::V6(_) => {
1188                return Err(GigeError::NotIpv4("device"));
1189            }
1190        };
1191        let socket = UdpSocket::bind(SocketAddr::new(local_ip, 0)).await?;
1192        socket.connect(addr).await?;
1193        let memory_access_only =
1194            force_readmem_requested(std::env::var_os(FORCE_READMEM_ENV).as_deref());
1195        if memory_access_only {
1196            info!(%addr, "{FORCE_READMEM_ENV} is set; using READMEM/WRITEMEM for every register");
1197        }
1198        Ok(Self {
1199            socket,
1200            remote: addr,
1201            control_timeout: consts::CONTROL_TIMEOUT,
1202            inflight_keepalive_period: None,
1203            last_command_sent: time::Instant::now(),
1204            request_id: 1,
1205            rng: Rng::new(),
1206            memory_access_only,
1207            names_primary_application: None,
1208            exclusive_access: false,
1209        })
1210    }
1211
1212    /// Set the acknowledgement timeout per control transaction attempt.
1213    ///
1214    /// Applies to register/memory access, control privilege and packet resend.
1215    /// PENDING_ACK may extend this wait, but never shorten it. Automatic retries
1216    /// retain their existing limit. Zero requests an immediate timeout.
1217    pub fn set_control_timeout(&mut self, timeout: Duration) {
1218        self.control_timeout = timeout;
1219    }
1220
1221    /// Return the acknowledgement timeout per control transaction attempt.
1222    pub fn control_timeout(&self) -> Duration {
1223        self.control_timeout
1224    }
1225
1226    /// Configure control-channel probes while a transaction waits for its ACK.
1227    ///
1228    /// After this much silence on the socket, send an idempotent CCP read using
1229    /// the same source port and a separate request ID. Probe replies are drained
1230    /// without extending the original transaction's deadline. Use a period
1231    /// comfortably shorter than the device's heartbeat timeout.
1232    ///
1233    /// `None` or a zero period disables the probes (the default). This handles
1234    /// in-flight requests only; an idle connection still needs a keepalive.
1235    pub fn set_inflight_keepalive_period(&mut self, period: Option<Duration>) {
1236        self.inflight_keepalive_period = period.filter(|period| !period.is_zero());
1237    }
1238
1239    /// The in-flight heartbeat period, `None` while they are off.
1240    pub fn inflight_keepalive_period(&self) -> Option<Duration> {
1241        self.inflight_keepalive_period
1242    }
1243
1244    /// Send every single-register access as READMEM/WRITEMEM from now on.
1245    ///
1246    /// What [`FORCE_READMEM_ENV`] does at open, for a caller that knows its
1247    /// device better than the environment does. There is no way back within
1248    /// the session, as there is none from the automatic fallback.
1249    pub fn use_memory_access(&mut self) {
1250        self.memory_access_only = true;
1251    }
1252
1253    /// Whether single-register access currently goes out as READMEM/WRITEMEM.
1254    pub fn memory_access_only(&self) -> bool {
1255        self.memory_access_only
1256    }
1257
1258    /// Ask for exclusive access (CCP `0x1`, bit 31 in GigE Vision's
1259    /// numbering: no other application may even read) instead of control
1260    /// access (`0x2`) whenever this session claims control, the first claim
1261    /// and every later one alike.
1262    pub fn set_exclusive_access(&mut self, exclusive: bool) {
1263        self.exclusive_access = exclusive;
1264    }
1265
1266    /// Whether [`Self::claim_control`] asks for exclusive access.
1267    pub fn exclusive_access(&self) -> bool {
1268        self.exclusive_access
1269    }
1270
1271    /// Claim control channel privilege (CCP).
1272    ///
1273    /// Required by the GigE Vision specification before the device accepts
1274    /// stream configuration or acquisition commands.
1275    ///
1276    /// Asks for control access (CCP `0x2`), or exclusive access (`0x1`) once
1277    /// [`Self::set_exclusive_access`] says so. That bit alone is what the
1278    /// GigE Vision bit definitions call exclusive access; no camera has yet
1279    /// confirmed it, and aravis never writes it.
1280    pub async fn claim_control(&mut self) -> Result<(), GigeError> {
1281        let privilege = if self.exclusive_access {
1282            consts::CCP_EXCLUSIVE
1283        } else {
1284            consts::CCP_CONTROL
1285        };
1286        self.write_u32(consts::CONTROL_CHANNEL_PRIVILEGE, privilege)
1287            .await?;
1288        debug!(
1289            addr = %self.remote,
1290            exclusive = self.exclusive_access,
1291            "claimed control channel privilege"
1292        );
1293        Ok(())
1294    }
1295
1296    /// Release control channel privilege.
1297    pub async fn release_control(&mut self) -> Result<(), GigeError> {
1298        self.write_u32(consts::CONTROL_CHANNEL_PRIVILEGE, 0).await
1299    }
1300
1301    /// Send the release of control privilege (CCP ← 0) without waiting for
1302    /// its acknowledgement, and without a runtime to wait on.
1303    ///
1304    /// For a caller that cannot block — a `Drop` on a current-thread runtime's
1305    /// own thread. Best effort: a lost datagram leaves the device to time the
1306    /// privilege out. Prefer [`Self::release_control`].
1307    ///
1308    /// Sent as WRITEMEM once the session uses memory access
1309    /// ([`Self::memory_access_only`]), as every other register write is: a
1310    /// device that refuses WRITEREG would refuse the release too. Both
1311    /// commands carry the same eight bytes, the address and then the value.
1312    pub fn try_send_release(&mut self) -> std::io::Result<()> {
1313        let request_id = self.next_request_id();
1314        let mut payload = BytesMut::with_capacity(8);
1315        payload.put_u32(consts::CONTROL_CHANNEL_PRIVILEGE as u32);
1316        payload.put_u32(0);
1317        let opcode = if self.memory_access_only {
1318            OpCode::WriteMem
1319        } else {
1320            OpCode::WriteRegister
1321        };
1322        let header = GvcpRequestHeader {
1323            flags: CommandFlags::ACK_REQUIRED,
1324            command: opcode.command_code(),
1325            length: payload.len() as u16,
1326            request_id,
1327        };
1328        self.socket.try_send(&header.encode(&payload)).map(drop)
1329    }
1330
1331    /// Read `GevHeartbeatTimeout` (milliseconds).
1332    ///
1333    /// This is how long the device will keep control privilege granted with no
1334    /// GVCP command from the controlling application.
1335    pub async fn heartbeat_timeout_ms(&mut self) -> Result<u32, GigeError> {
1336        self.read_u32(consts::HEARTBEAT_TIMEOUT).await
1337    }
1338
1339    /// Refresh the device's heartbeat timer, and report whether this
1340    /// application still holds control privilege.
1341    ///
1342    /// Any GVCP command resets the timer, so this reads CCP rather than writing
1343    /// it: a read is idempotent, and its value doubles as the answer to "does
1344    /// the device still consider us the controller?". A device that revoked
1345    /// privilege — because an earlier heartbeat was lost, or because another
1346    /// application took control — is reported as `Ok(false)` here instead of
1347    /// failing the next configuration write with `ACCESS_DENIED`.
1348    ///
1349    /// Losing privilege is not a transport failure, so it is not an `Err`: the
1350    /// register read succeeded and the answer is simply "no". `Err` means the
1351    /// command itself did not complete.
1352    ///
1353    /// CCP alone cannot tell this application from another that took control
1354    /// after an expired heartbeat: both read as controlled. Where GVCP
1355    /// Capability says the device names its primary application (bit
1356    /// `0x0800_0000`), its IP and port are compared with this socket's too
1357    /// (backlog TC-38).
1358    pub async fn ping_control_channel(&mut self) -> Result<bool, GigeError> {
1359        let privilege = self.read_u32(consts::CONTROL_CHANNEL_PRIVILEGE).await?;
1360        if privilege & consts::CCP_CONTROLLER_BITS == 0 {
1361            return Ok(false);
1362        }
1363        self.primary_application_is_us().await
1364    }
1365
1366    /// Whether this application holds control privilege, asked after the
1367    /// device refused one of its writes with `ACCESS_DENIED`, which a
1368    /// register may also answer for reasons of its own.
1369    ///
1370    /// [`Self::ping_control_channel`] first. Where the device does not name
1371    /// its primary application, CCP reads as controlled whoever holds it,
1372    /// so the answer comes from claiming again (CCP ← this session's
1373    /// privilege): a device takes the claim from the application that holds
1374    /// control and refuses it to any other with `ACCESS_DENIED`. An Allied
1375    /// Vision Manta G-125B, which does not name its primary application,
1376    /// did both (backlog TC-38). The claim changes nothing for the holder,
1377    /// and nothing for another application, whose control the device keeps.
1378    pub async fn holds_control(&mut self) -> Result<bool, GigeError> {
1379        if !self.ping_control_channel().await? {
1380            return Ok(false);
1381        }
1382        if self.names_primary_application == Some(true) {
1383            return Ok(true);
1384        }
1385        match self.claim_control().await {
1386            Ok(()) => Ok(true),
1387            Err(GigeError::Status(GigeStatus::Common(StatusCode::AccessDenied))) => Ok(false),
1388            Err(err) => Err(err),
1389        }
1390    }
1391
1392    /// Whether the device's primary application is this socket, where the
1393    /// device says (`0x0A04` port, `0x0A14` IP); `true` where it does not.
1394    async fn primary_application_is_us(&mut self) -> Result<bool, GigeError> {
1395        let names_owner = match self.names_primary_application {
1396            Some(known) => known,
1397            None => {
1398                let known = self
1399                    .gvcp_capability()
1400                    .await
1401                    .map(GvcpCapability::ccp_application_port_ip)
1402                    .unwrap_or(false);
1403                self.names_primary_application = Some(known);
1404                known
1405            }
1406        };
1407        if !names_owner {
1408            return Ok(true);
1409        }
1410        let SocketAddr::V4(us) = self.socket.local_addr()? else {
1411            return Ok(true);
1412        };
1413        let port_register = self.read_u32(consts::PRIMARY_APPLICATION_PORT).await?;
1414        let ip_register = self.read_u32(consts::PRIMARY_APPLICATION_IP).await?;
1415        let our_port = u32::from(us.port());
1416        let our_ip = u32::from(*us.ip());
1417        let standard = port_register & 0xFFFF == our_port && ip_register == our_ip;
1418        // A maintainer-tested six-sensor GigE device reports the complete
1419        // controller IP at 0x0A04 and port at 0x0A14 (observed on hardware).
1420        // Accept that layout only when both full values name this socket;
1421        // in particular, do not truncate a malformed swapped port to 16 bits.
1422        let swapped = port_register == our_ip && ip_register == our_port;
1423        Ok(standard || swapped)
1424    }
1425
1426    /// Return the remote GVCP socket address associated with this device.
1427    pub fn remote_addr(&self) -> SocketAddr {
1428        self.remote
1429    }
1430
1431    /// The local address and port commands leave from: what the device
1432    /// knows this application by.
1433    pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
1434        self.socket.local_addr()
1435    }
1436
1437    fn next_request_id(&mut self) -> u16 {
1438        let id = self.request_id;
1439        self.request_id = self.request_id.wrapping_add(1);
1440        if self.request_id == 0 {
1441            self.request_id = 1;
1442        }
1443        id
1444    }
1445
1446    async fn transact_with_retry(
1447        &mut self,
1448        opcode: OpCode,
1449        payload: BytesMut,
1450    ) -> Result<GenCpAck, GigeError> {
1451        // Retries resend the same transaction. A device may finish a slow,
1452        // non-idempotent command after our first receive deadline; assigning a
1453        // new ID would turn its delayed acknowledgement into a mismatch and
1454        // could execute the command again.
1455        let request_id = self.next_request_id();
1456        let payload_bytes = payload.freeze();
1457        let header = GvcpRequestHeader {
1458            flags: CommandFlags::ACK_REQUIRED,
1459            command: opcode.command_code(),
1460            length: payload_bytes.len() as u16,
1461            request_id,
1462        };
1463        let encoded = header.encode(&payload_bytes);
1464        let mut attempt = 0usize;
1465        'retry: loop {
1466            attempt += 1;
1467            trace!(request_id, opcode = ?opcode, bytes = encoded.len(), attempt, "sending GVCP command");
1468            if let Err(err) = self.socket.send(&encoded).await {
1469                if attempt >= consts::MAX_RETRIES {
1470                    return Err(err.into());
1471                }
1472                warn!(request_id, ?opcode, attempt, "send failed, retrying");
1473                self.refresh_route_after_send_error(&err).await?;
1474                self.backoff(attempt).await;
1475                continue 'retry;
1476            }
1477            self.last_command_sent = time::Instant::now();
1478
1479            let mut buf = vec![
1480                0u8;
1481                viva_gencp::HEADER_SIZE
1482                    + consts::GENCP_MAX_BLOCK
1483                    + consts::GENCP_WRITE_OVERHEAD
1484            ];
1485            // Only this request's datagram comes back: `recv_for_request` drains
1486            // replies to other request IDs — a delayed ACK for an earlier
1487            // command, an in-flight heartbeat's reply — against this attempt's
1488            // deadline, so they can neither be mistaken for it nor extend it.
1489            match self.recv_absorbing_pending(&mut buf, request_id).await {
1490                AckRecv::Received(len) => {
1491                    trace!(request_id, bytes = len, attempt, "received GenCP ack");
1492                    let ack = decode_ack(&buf[..len])?;
1493                    if ack.header.opcode != opcode {
1494                        return Err(GigeError::MalformedAck {
1495                            command: command_name(opcode),
1496                            problem: "answers another command",
1497                        });
1498                    }
1499                    match GigeStatus::from_raw(ack.header.status) {
1500                        status if status.is_success() => return Ok(ack),
1501                        // Only `BUSY` (0x8007) is congestion. This used to
1502                        // match `DeviceBusy`, which was mapped to 0x8004 —
1503                        // `WRITE_PROTECT` — so the retry loop burned its
1504                        // budget on a read-only register that could never
1505                        // accept the write, and gave up immediately on the
1506                        // one status retrying is for.
1507                        status if status.is_retryable() && attempt < consts::MAX_RETRIES => {
1508                            warn!(request_id, attempt, %status, "device busy, retrying");
1509                            self.backoff(attempt).await;
1510                            continue 'retry;
1511                        }
1512                        other => return Err(GigeError::Status(other)),
1513                    }
1514                }
1515                AckRecv::Io(err) => {
1516                    if attempt >= consts::MAX_RETRIES {
1517                        return Err(err.into());
1518                    }
1519                    warn!(request_id, ?opcode, attempt, "receive error, retrying");
1520                    self.backoff(attempt).await;
1521                    continue 'retry;
1522                }
1523                AckRecv::TimedOut => {
1524                    if attempt >= consts::MAX_RETRIES {
1525                        return Err(GigeError::Timeout);
1526                    }
1527                    warn!(request_id, ?opcode, attempt, "command timeout, retrying");
1528                    self.backoff(attempt).await;
1529                    continue 'retry;
1530                }
1531            }
1532        }
1533    }
1534
1535    /// Send a heartbeat without recursively entering the active transaction.
1536    /// A FORCEIP can leave macOS's connected UDP route stale (TC-41).
1537    /// Reconnecting the same socket refreshes it without changing the port
1538    /// that identifies the controller. The caller retains its retry budget
1539    /// and transaction ID; this never replays a command after a receive error.
1540    async fn refresh_route_after_send_error(&self, error: &io::Error) -> Result<(), GigeError> {
1541        if error.kind() == io::ErrorKind::AddrNotAvailable {
1542            warn!(remote = %self.remote, local = %self.socket.local_addr()?,
1543                "refreshing GVCP route after address became unavailable");
1544            self.socket.connect(self.remote).await?;
1545        }
1546        Ok(())
1547    }
1548
1549    async fn send_inflight_keepalive(&mut self, active_request_id: u16) -> Result<(), GigeError> {
1550        let mut request_id = self.next_request_id();
1551        // A long transaction may outlive the 16-bit request-ID counter.
1552        if request_id == active_request_id {
1553            request_id = self.next_request_id();
1554        }
1555        let mut payload = BytesMut::with_capacity(8);
1556        payload.put_u32(consts::CONTROL_CHANNEL_PRIVILEGE as u32);
1557        let opcode = if self.memory_access_only {
1558            payload.put_u16(0);
1559            payload.put_u16(4);
1560            OpCode::ReadMem
1561        } else {
1562            OpCode::ReadRegister
1563        };
1564        let header = GvcpRequestHeader {
1565            flags: CommandFlags::ACK_REQUIRED,
1566            command: opcode.command_code(),
1567            length: payload.len() as u16,
1568            request_id,
1569        };
1570        self.socket.send(&header.encode(&payload)).await?;
1571        self.last_command_sent = time::Instant::now();
1572        trace!(
1573            request_id,
1574            active_request_id, "sent in-flight control keepalive"
1575        );
1576        Ok(())
1577    }
1578
1579    /// One socket reader owns both the active request and its heartbeat replies.
1580    /// Keep an absolute deadline so unrelated or duplicate ACKs cannot postpone
1581    /// a timeout, and never resend the active command merely to send a heartbeat.
1582    ///
1583    /// `committed` says the device already has the command — it answered with
1584    /// `PENDING_ACK` — so nothing on the socket may end the wait early: a
1585    /// resend could run it twice. An ICMP error after an in-flight heartbeat
1586    /// is ignored for the same reason (TC-26): it may be the heartbeat's, and
1587    /// the command it interrupts may be executing. Only an error the active
1588    /// command alone can have drawn ends the wait, so an absent device still
1589    /// fails fast.
1590    async fn recv_for_request(
1591        &mut self,
1592        buf: &mut [u8],
1593        request_id: u16,
1594        deadline: time::Instant,
1595        committed: bool,
1596    ) -> AckRecv {
1597        let mut tolerate_icmp = committed;
1598        loop {
1599            let heartbeat_deadline = self
1600                .inflight_keepalive_period
1601                .and_then(|period| self.last_command_sent.checked_add(period));
1602            tokio::select! {
1603                _ = time::sleep_until(deadline) => return AckRecv::TimedOut,
1604                _ = async {
1605                    if let Some(deadline) = heartbeat_deadline {
1606                        time::sleep_until(deadline).await;
1607                    } else {
1608                        std::future::pending::<()>().await;
1609                    }
1610                } => {
1611                    tolerate_icmp = true;
1612                    if let Err(err) = self.send_inflight_keepalive(request_id).await {
1613                        // The command is still waiting for its answer; a lost
1614                        // heartbeat costs at most this period's refresh.
1615                        debug!(request_id, error = %err, "in-flight heartbeat not sent; still waiting");
1616                        self.last_command_sent = time::Instant::now();
1617                    }
1618                }
1619                received = self.socket.recv(buf) => {
1620                    let len = match received {
1621                        Ok(len) => len,
1622                        Err(err) if tolerate_icmp && is_icmp_error(&err) => {
1623                            debug!(request_id, error = %err, "ignoring an ICMP error while the command is pending");
1624                            continue;
1625                        }
1626                        Err(err) => return AckRecv::Io(err),
1627                    };
1628                    let ack_id = buf.get(..len)
1629                        .and_then(|packet| packet.get(6..8))
1630                        .and_then(|bytes| bytes.try_into().ok())
1631                        .map(u16::from_be_bytes);
1632                    if let Some(ack_id) = ack_id
1633                        && ack_id != request_id
1634                    {
1635                        trace!(request_id, ack_id, "drained keepalive or delayed acknowledgement");
1636                        continue;
1637                    }
1638                    // Preserve existing validation of malformed matching ACKs.
1639                    return AckRecv::Received(len);
1640                }
1641            }
1642        }
1643    }
1644
1645    /// Receive one acknowledgement, granting the device the extra time it asks
1646    /// for via PENDING_ACK.
1647    ///
1648    /// A PENDING_ACK is not a failure and must not be retried: the command is
1649    /// still executing on the device, so resending it risks running it twice —
1650    /// which for a `WriteMem` to flash is exactly the operation you least want
1651    /// duplicated. The GigE Vision specification instead has the controller
1652    /// extend its own deadline by the time the device requests and keep
1653    /// waiting on the same request id.
1654    async fn recv_absorbing_pending(&mut self, buf: &mut [u8], request_id: u16) -> AckRecv {
1655        let mut wait = self.control_timeout;
1656        let mut pending_seen = 0usize;
1657        loop {
1658            let deadline = time::Instant::now() + wait;
1659            match self
1660                .recv_for_request(buf, request_id, deadline, pending_seen > 0)
1661                .await
1662            {
1663                AckRecv::Received(len) => {
1664                    // `recv_for_request` has already drained PENDING_ACKs for
1665                    // other request IDs, so this one is ours.
1666                    let Some((_, requested)) = parse_pending_ack(&buf[..len]) else {
1667                        return AckRecv::Received(len);
1668                    };
1669                    pending_seen += 1;
1670                    if pending_seen > consts::MAX_PENDING_ACKS {
1671                        warn!(
1672                            request_id,
1673                            pending_seen, "device kept requesting more time, giving up"
1674                        );
1675                        return AckRecv::TimedOut;
1676                    }
1677                    wait = requested
1678                        .clamp(consts::CONTROL_TIMEOUT, consts::MAX_PENDING_ACK_WAIT)
1679                        .max(self.control_timeout);
1680                    debug!(
1681                        request_id,
1682                        requested_ms = requested.as_millis() as u64,
1683                        waiting_ms = wait.as_millis() as u64,
1684                        pending_seen,
1685                        "device requested more time (PENDING_ACK)"
1686                    );
1687                }
1688                other => return other,
1689            }
1690        }
1691    }
1692
1693    async fn backoff(&mut self, attempt: usize) {
1694        let multiplier = 1u32 << (attempt.saturating_sub(1)).min(3);
1695        let base_ms = consts::RETRY_BASE_DELAY.as_millis() as u64;
1696        let base = Duration::from_millis(base_ms.saturating_mul(multiplier as u64).max(base_ms));
1697        let jitter_ms = self.rng.u64(..=consts::RETRY_JITTER.as_millis() as u64);
1698        let jitter = Duration::from_millis(jitter_ms);
1699        let delay = base + jitter;
1700        debug!(attempt, delay = ?delay, "gvcp retry backoff");
1701        time::sleep(delay).await;
1702    }
1703
1704    /// Read `len` bytes at `addr`, as READREG when that is exactly one
1705    /// register and READMEM otherwise.
1706    ///
1707    /// The READREG value is returned big-endian, which is byte-for-byte what
1708    /// READMEM returns for the same word: GVCP carries both in network order,
1709    /// and interpreting the bytes is GenApi's job, not the transport's.
1710    ///
1711    /// A device that answers READREG with `NOT_IMPLEMENTED`, or does not
1712    /// answer it at all, is switched to READMEM for the rest of the session
1713    /// and this access is retried there, so the caller still gets its value.
1714    /// Any other refusal — `ACCESS_DENIED`, `BAD_ALIGNMENT` — is the device's
1715    /// real answer about this register and is returned as it is.
1716    pub async fn read_register_or_mem(
1717        &mut self,
1718        addr: u64,
1719        len: usize,
1720    ) -> Result<Vec<u8>, GigeError> {
1721        let register = match single_register_address(addr, len) {
1722            Some(register) if !self.memory_access_only => register,
1723            _ => return self.read_mem(addr, len).await,
1724        };
1725        match self.read_register(register).await {
1726            Ok(value) => Ok(value.to_be_bytes().to_vec()),
1727            Err(GigeError::Status(GigeStatus::Common(StatusCode::NotImplemented))) => {
1728                self.latch_memory_access("READREG", addr, "NOT_IMPLEMENTED");
1729                self.read_mem(addr, len).await
1730            }
1731            Err(GigeError::Timeout) => {
1732                // Silence is ambiguous: the device may ignore READREG, or may
1733                // be gone. Latch only once READMEM proves it is still there,
1734                // so a cable pull does not cost the session its READREG.
1735                let data = self.read_mem(addr, len).await?;
1736                self.latch_memory_access("READREG", addr, "no reply");
1737                Ok(data)
1738            }
1739            Err(err) => Err(err),
1740        }
1741    }
1742
1743    /// Write `data` at `addr`, as WRITEREG when that is exactly one register
1744    /// and WRITEMEM otherwise.
1745    ///
1746    /// Falls back to WRITEMEM exactly as [`Self::read_register_or_mem`] falls
1747    /// back to READMEM. After a WRITEREG that got no reply the write is sent
1748    /// again as WRITEMEM; a device that did execute the first one but lost
1749    /// the acknowledgement sees it twice, which is the same exposure the
1750    /// command retry loop already has.
1751    pub async fn write_register_or_mem(&mut self, addr: u64, data: &[u8]) -> Result<(), GigeError> {
1752        let (register, value) = match (single_register_address(addr, data.len()), data) {
1753            (Some(register), &[b0, b1, b2, b3]) if !self.memory_access_only => {
1754                (register, u32::from_be_bytes([b0, b1, b2, b3]))
1755            }
1756            _ => return self.write_mem(addr, data).await,
1757        };
1758        match self.write_register(register, value).await {
1759            Ok(()) => Ok(()),
1760            Err(GigeError::Status(GigeStatus::Common(StatusCode::NotImplemented))) => {
1761                self.latch_memory_access("WRITEREG", addr, "NOT_IMPLEMENTED");
1762                self.write_mem(addr, data).await
1763            }
1764            Err(GigeError::Timeout) => {
1765                self.write_mem(addr, data).await?;
1766                self.latch_memory_access("WRITEREG", addr, "no reply");
1767                Ok(())
1768            }
1769            Err(err) => Err(err),
1770        }
1771    }
1772
1773    /// Switch this session to memory access, warning the first time only.
1774    fn latch_memory_access(&mut self, command: &str, addr: u64, why: &str) {
1775        if self.memory_access_only {
1776            return;
1777        }
1778        self.memory_access_only = true;
1779        warn!(
1780            device = %self.remote,
1781            addr = format!("0x{addr:08x}"),
1782            "device refused {command} ({why}); using READMEM/WRITEMEM for the rest of \
1783             this session (set {FORCE_READMEM_ENV}=1 to start that way)"
1784        );
1785    }
1786
1787    /// Read one 32-bit register through [`Self::read_register_or_mem`].
1788    async fn read_u32(&mut self, addr: u64) -> Result<u32, GigeError> {
1789        let data = self.read_register_or_mem(addr, 4).await?;
1790        let word: [u8; 4] = data
1791            .as_slice()
1792            .try_into()
1793            .map_err(|_| GigeError::AckLength {
1794                command: "READREG",
1795                expected: 4,
1796                got: data.len(),
1797            })?;
1798        Ok(u32::from_be_bytes(word))
1799    }
1800
1801    /// Write one 32-bit register through [`Self::write_register_or_mem`].
1802    async fn write_u32(&mut self, addr: u64, value: u32) -> Result<(), GigeError> {
1803        self.write_register_or_mem(addr, &value.to_be_bytes()).await
1804    }
1805
1806    /// Read a single 32-bit register with READREG, unconditionally.
1807    ///
1808    /// Uses GVCP READREG format: 4-byte register address.
1809    /// The acknowledgement carries the 4-byte register value.
1810    ///
1811    /// No fallback: prefer [`Self::read_register_or_mem`], which picks the
1812    /// command and honours a device that does not implement this one.
1813    pub async fn read_register(&mut self, addr: u32) -> Result<u32, GigeError> {
1814        let mut payload = BytesMut::with_capacity(4);
1815        payload.put_u32(addr);
1816        let ack = self
1817            .transact_with_retry(OpCode::ReadRegister, payload)
1818            .await?;
1819        if ack.payload.len() != 4 {
1820            return Err(GigeError::AckLength {
1821                command: "READREG",
1822                expected: 4,
1823                got: ack.payload.len(),
1824            });
1825        }
1826        let mut cursor = &ack.payload[..];
1827        Ok(cursor.get_u32())
1828    }
1829
1830    /// Write a single 32-bit register with WRITEREG, unconditionally.
1831    ///
1832    /// Uses GVCP WRITEREG format: 4-byte register address + 4-byte value.
1833    /// The acknowledgement carries a 4-byte data index placeholder.
1834    ///
1835    /// No fallback: prefer [`Self::write_register_or_mem`].
1836    pub async fn write_register(&mut self, addr: u32, value: u32) -> Result<(), GigeError> {
1837        let mut payload = BytesMut::with_capacity(8);
1838        payload.put_u32(addr);
1839        payload.put_u32(value);
1840        let ack = self
1841            .transact_with_retry(OpCode::WriteRegister, payload)
1842            .await?;
1843        if ack.payload.len() != 4 {
1844            return Err(GigeError::AckLength {
1845                command: "WRITEREG",
1846                expected: 4,
1847                got: ack.payload.len(),
1848            });
1849        }
1850        Ok(())
1851    }
1852
1853    /// Read a block of memory from the remote device with chunking and retries.
1854    ///
1855    /// Uses GVCP READMEM format: 4-byte address + 2-byte reserved + 2-byte count.
1856    /// The acknowledgement carries: 4-byte address echo + data bytes.
1857    pub async fn read_mem(&mut self, addr: u64, len: usize) -> Result<Vec<u8>, GigeError> {
1858        let mut remaining = len;
1859        let mut offset = 0usize;
1860        let mut data = Vec::with_capacity(len);
1861        while remaining > 0 {
1862            let chunk = remaining.min(consts::GENCP_MAX_BLOCK);
1863            // GVCP requires the READMEM byte count to be a multiple of 4.
1864            // Strict cameras (e.g. Hikrobot) reject unaligned counts with
1865            // InvalidParameter, so request the aligned size and drop the
1866            // padding bytes below. Device memory regions are 4-byte aligned,
1867            // so reading past the end of e.g. the XML blob is safe.
1868            let request = chunk.next_multiple_of(4);
1869            let mut payload = BytesMut::with_capacity(8);
1870            payload.put_u32((addr + offset as u64) as u32);
1871            payload.put_u16(0); // reserved
1872            payload.put_u16(request as u16);
1873            let ack = self.transact_with_retry(OpCode::ReadMem, payload).await?;
1874            // GVCP READMEM_ACK: 4-byte address prefix + data.
1875            let ack_data = if ack.payload.len() >= 4 + request {
1876                &ack.payload[4..4 + request]
1877            } else if ack.payload.len() == request {
1878                // Some devices omit the address echo.
1879                &ack.payload[..request]
1880            } else {
1881                return Err(GigeError::AckLength {
1882                    command: "READMEM",
1883                    expected: request,
1884                    got: ack.payload.len(),
1885                });
1886            };
1887            data.extend_from_slice(&ack_data[..chunk]);
1888            remaining -= chunk;
1889            offset += chunk;
1890        }
1891        Ok(data)
1892    }
1893
1894    /// Write a block of memory to the remote device with chunking and retries.
1895    ///
1896    /// Uses GVCP WRITEMEM format: 4-byte address + data bytes.
1897    /// The acknowledgement carries: 4-byte reserved (index).
1898    ///
1899    /// GVCP carries whole 32-bit words at 32-bit aligned addresses, as
1900    /// READMEM does (#35). A write that starts or ends inside a word — a
1901    /// one-byte register, a two-byte one at an odd half-word — goes out as
1902    /// the words around it, the bytes it does not cover read from the device
1903    /// first, so neighbouring registers keep their values (TC-32). aravis
1904    /// pads such a write with whatever its buffer held
1905    /// (`arv_gvcp_packet_new_write_memory_cmd`). If the read is refused, the
1906    /// write goes out as given, for the device to judge.
1907    pub async fn write_mem(&mut self, addr: u64, data: &[u8]) -> Result<(), GigeError> {
1908        let start = addr & !3;
1909        let end = (addr + data.len() as u64).next_multiple_of(4);
1910        if data.is_empty() || (start == addr && end == addr + data.len() as u64) {
1911            return self.write_mem_words(addr, data).await;
1912        }
1913        let mut words = match self.read_mem(start, (end - start) as usize).await {
1914            Ok(words) => words,
1915            Err(err) => {
1916                debug!(
1917                    addr = format!("0x{addr:08x}"),
1918                    len = data.len(),
1919                    error = %err,
1920                    "cannot read the words around an unaligned write; sending it as given"
1921                );
1922                return self.write_mem_words(addr, data).await;
1923            }
1924        };
1925        let offset = (addr - start) as usize;
1926        words[offset..offset + data.len()].copy_from_slice(data);
1927        self.write_mem_words(start, &words).await
1928    }
1929
1930    /// WRITEMEM `data` at `addr` as it is, in chunks of at most 508 bytes.
1931    async fn write_mem_words(&mut self, addr: u64, data: &[u8]) -> Result<(), GigeError> {
1932        /// GVCP WRITEMEM overhead: 4-byte address prefix.
1933        const GVCP_WRITE_OVERHEAD: usize = 4;
1934
1935        let mut offset = 0usize;
1936        while offset < data.len() {
1937            // Never zero: the loop runs while bytes remain, and a block holds
1938            // more than the address prefix.
1939            const _: () = assert!(consts::GENCP_MAX_BLOCK > GVCP_WRITE_OVERHEAD);
1940            let chunk = (data.len() - offset).min(consts::GENCP_MAX_BLOCK - GVCP_WRITE_OVERHEAD);
1941            let mut payload = BytesMut::with_capacity(GVCP_WRITE_OVERHEAD + chunk);
1942            payload.put_u32((addr + offset as u64) as u32);
1943            payload.extend_from_slice(&data[offset..offset + chunk]);
1944            let ack = self.transact_with_retry(OpCode::WriteMem, payload).await?;
1945            // GVCP WRITEMEM_ACK: 4-byte reserved payload.
1946            if ack.payload.len() > 4 {
1947                return Err(GigeError::AckLength {
1948                    command: "WRITEMEM",
1949                    expected: 4,
1950                    got: ack.payload.len(),
1951                });
1952            }
1953            offset += chunk;
1954        }
1955        Ok(())
1956    }
1957
1958    /// Configure the message channel destination address/port.
1959    pub async fn set_message_destination(
1960        &mut self,
1961        ip: Ipv4Addr,
1962        port: u16,
1963    ) -> Result<(), GigeError> {
1964        info!(%ip, port, "configuring message channel destination");
1965        self.write_u32(consts::MESSAGE_DESTINATION_ADDRESS, u32::from(ip))
1966            .await?;
1967        // GevMCP is a 32-bit register with the port in the low half. Writing
1968        // only the two port bytes lands them in the *high* half.
1969        self.write_u32(consts::MESSAGE_DESTINATION_PORT, u32::from(port))
1970            .await?;
1971        Ok(())
1972    }
1973
1974    fn stream_reg(channel: u32, offset: u64) -> u64 {
1975        consts::STREAM_CHANNEL_BASE + channel as u64 * consts::STREAM_CHANNEL_STRIDE + offset
1976    }
1977
1978    /// Configure the GVSP host destination for the provided channel.
1979    pub async fn set_stream_destination(
1980        &mut self,
1981        channel: u32,
1982        ip: Ipv4Addr,
1983        port: u16,
1984    ) -> Result<(), GigeError> {
1985        info!(channel, %ip, port, "configuring stream destination");
1986        let addr = Self::stream_reg(channel, consts::STREAM_DESTINATION_ADDRESS);
1987        self.write_u32(addr, u32::from(ip)).await?;
1988        let addr = Self::stream_reg(channel, consts::STREAM_DESTINATION_PORT);
1989        self.write_u32(addr, u32::from(port)).await?;
1990        Ok(())
1991    }
1992
1993    /// Read where stream channel `channel` sends: `GevSCDA` and the port in
1994    /// the low half of `GevSCPHostPort`. A multicast group here is how a
1995    /// camera streams to several hosts at once.
1996    pub async fn stream_destination(&mut self, channel: u32) -> Result<(Ipv4Addr, u16), GigeError> {
1997        let addr = Self::stream_reg(channel, consts::STREAM_DESTINATION_ADDRESS);
1998        let ip = Ipv4Addr::from(self.read_u32(addr).await?);
1999        let addr = Self::stream_reg(channel, consts::STREAM_DESTINATION_PORT);
2000        let port = (self.read_u32(addr).await? & 0xFFFF) as u16;
2001        Ok((ip, port))
2002    }
2003
2004    /// Configure the packet size for the stream channel.
2005    ///
2006    /// Only bits 0-15 of `GevSCPSPacketSize` hold the size; the high bits are
2007    /// reserved for the fire-test-packet and do-not-fragment flags. A larger
2008    /// value is refused rather than truncated, because truncation is silent and
2009    /// arrives as a stream that never completes a frame — writing 70 000 would
2010    /// configure 4 464.
2011    ///
2012    /// The flags the register holds are kept: an Allied Vision Manta G-125B
2013    /// stores do-not-fragment and reads it back (`0x400005DC`), and a write
2014    /// of the size alone cleared it. A register that cannot be read first is
2015    /// written with the size alone.
2016    pub async fn set_stream_packet_size(
2017        &mut self,
2018        channel: u32,
2019        packet_size: u32,
2020    ) -> Result<(), GigeError> {
2021        if packet_size > STREAM_PACKET_SIZE_MASK {
2022            return Err(GigeError::PacketSize(packet_size));
2023        }
2024        info!(channel, packet_size, "configuring stream packet size");
2025        let addr = Self::stream_reg(channel, consts::STREAM_PACKET_SIZE);
2026        let flags = match self.read_u32(addr).await {
2027            Ok(raw) => raw & !(STREAM_PACKET_SIZE_MASK | SCPS_FIRE_TEST_PACKET),
2028            Err(err) => {
2029                debug!(channel, error = %err, "GevSCPSPacketSize unreadable; writing the size alone");
2030                0
2031            }
2032        };
2033        self.write_u32(addr, flags | packet_size).await
2034    }
2035
2036    /// Whether `GevSCPSPacketSize` holds the do-not-fragment flag (bit 30).
2037    pub async fn stream_do_not_fragment(&mut self, channel: u32) -> Result<bool, GigeError> {
2038        let addr = Self::stream_reg(channel, consts::STREAM_PACKET_SIZE);
2039        Ok(self.read_u32(addr).await? & SCPS_DO_NOT_FRAGMENT != 0)
2040    }
2041
2042    /// Set or clear `GevSCPSPacketSize`'s do-not-fragment flag, keeping the
2043    /// size: how the packet-size probe, whose test packets set it, gives it
2044    /// back as it found it.
2045    pub async fn set_stream_do_not_fragment(
2046        &mut self,
2047        channel: u32,
2048        on: bool,
2049    ) -> Result<(), GigeError> {
2050        let addr = Self::stream_reg(channel, consts::STREAM_PACKET_SIZE);
2051        let raw = self.read_u32(addr).await? & !SCPS_FIRE_TEST_PACKET;
2052        let word = if on {
2053            raw | SCPS_DO_NOT_FRAGMENT
2054        } else {
2055            raw & !SCPS_DO_NOT_FRAGMENT
2056        };
2057        if word != raw {
2058            debug!(
2059                channel,
2060                on, "setting GevSCPSPacketSize's do-not-fragment flag"
2061            );
2062            self.write_u32(addr, word).await?;
2063        }
2064        Ok(())
2065    }
2066
2067    /// Ask the device to emit one GVSP test packet of `packet_size` bytes.
2068    ///
2069    /// Writes `GevSCPSPacketSize` with bit 31 (fire test packet) and bit 30
2070    /// (do not fragment) set. The size lands in the register as usual; the
2071    /// flags do not, and a device that echoed them back would report a packet
2072    /// size of over a billion, so [`GigeDevice::get_stream_packet_size`] masks.
2073    ///
2074    /// This does not wait for the packet — it arrives on the stream channel,
2075    /// which this type does not own. The caller listens.
2076    pub async fn request_test_packet(
2077        &mut self,
2078        channel: u32,
2079        packet_size: u32,
2080    ) -> Result<(), GigeError> {
2081        if packet_size > STREAM_PACKET_SIZE_MASK {
2082            return Err(GigeError::PacketSize(packet_size));
2083        }
2084        let addr = Self::stream_reg(channel, consts::STREAM_PACKET_SIZE);
2085        let word = packet_size | SCPS_FIRE_TEST_PACKET | SCPS_DO_NOT_FRAGMENT;
2086        debug!(channel, packet_size, "requesting GVSP test packet");
2087        self.write_u32(addr, word).await
2088    }
2089
2090    /// Read `GevSCPSPacketSize` back and return the size the device holds.
2091    ///
2092    /// A device is free to clamp a requested packet size to what it supports,
2093    /// and the request succeeds when it does — nothing on the wire distinguishes
2094    /// "accepted" from "accepted and reduced". Until the receive path follows
2095    /// the *effective* value it reassembles at the wrong pitch and no frame ever
2096    /// completes ([#112](https://github.com/VitalyVorobyev/viva-genicam/issues/112),
2097    /// backlog SR-02).
2098    ///
2099    /// Deliberately a GVCP register read rather than a GenApi node read: the
2100    /// write side bypasses the `NodeMap`, so a cached `GevSCPSPacketSize` node
2101    /// can report the pre-write value and turn this check into a second bug.
2102    pub async fn get_stream_packet_size(&mut self, channel: u32) -> Result<u32, GigeError> {
2103        let addr = Self::stream_reg(channel, consts::STREAM_PACKET_SIZE);
2104        let raw = self.read_u32(addr).await?;
2105        Ok(raw & STREAM_PACKET_SIZE_MASK)
2106    }
2107
2108    /// Read GVCP Capability (`0x0934`): which optional commands the device
2109    /// implements.
2110    pub async fn gvcp_capability(&mut self) -> Result<GvcpCapability, GigeError> {
2111        self.read_u32(consts::GVCP_CAPABILITY)
2112            .await
2113            .map(GvcpCapability::from_bits)
2114    }
2115
2116    /// Switch `PENDING_ACK` on, if GVCP Capability says the device has it:
2117    /// set its enable bit (`0x2`) in GVCP Configuration (`0x0954`), keeping
2118    /// the others. Returns whether it is on.
2119    ///
2120    /// A device sends `PENDING_ACK` only once enabled. Without it, a command
2121    /// that takes longer than the acknowledgement timeout — a flash write, a
2122    /// mode change — is retried as though lost, and may run twice. A write,
2123    /// so it needs control privilege.
2124    pub async fn enable_pending_ack(&mut self) -> Result<bool, GigeError> {
2125        if !self.gvcp_capability().await?.pending_ack() {
2126            return Ok(false);
2127        }
2128        let config = self.read_u32(consts::GVCP_CONFIGURATION).await?;
2129        if config & consts::CONFIGURATION_PENDING_ACK_ENABLE == 0 {
2130            self.write_u32(
2131                consts::GVCP_CONFIGURATION,
2132                config | consts::CONFIGURATION_PENDING_ACK_ENABLE,
2133            )
2134            .await?;
2135        }
2136        debug!(addr = %self.remote, "PENDING_ACK enabled");
2137        Ok(true)
2138    }
2139
2140    /// Read `GevNumberOfStreamChannels` (`0x0904`).
2141    pub async fn stream_channel_count(&mut self) -> Result<u32, GigeError> {
2142        self.read_u32(consts::NUMBER_OF_STREAM_CHANNELS).await
2143    }
2144
2145    /// Read the timestamp tick frequency in hertz (`0x093C` high, `0x0940`
2146    /// low): the unit of device timestamps and of `GevSCPD`. A device without
2147    /// a timestamp clock reports 0.
2148    pub async fn timestamp_tick_frequency(&mut self) -> Result<u64, GigeError> {
2149        let high = self.read_u32(consts::TIMESTAMP_TICK_FREQUENCY_HIGH).await?;
2150        let low = self.read_u32(consts::TIMESTAMP_TICK_FREQUENCY_LOW).await?;
2151        Ok((u64::from(high) << 32) | u64::from(low))
2152    }
2153
2154    /// Write `GevSCPD`, the delay between stream packets, in timestamp ticks
2155    /// (see [`GigeDevice::timestamp_tick_frequency`]).
2156    pub async fn set_stream_packet_delay(
2157        &mut self,
2158        channel: u32,
2159        packet_delay: u32,
2160    ) -> Result<(), GigeError> {
2161        debug!(channel, packet_delay, "configuring stream packet delay");
2162        let addr = Self::stream_reg(channel, consts::STREAM_PACKET_DELAY);
2163        self.write_u32(addr, packet_delay).await
2164    }
2165
2166    /// Read the persistent IP configuration from the device.
2167    ///
2168    /// Returns `(ip, subnet, gateway)`.
2169    pub async fn read_persistent_ip(
2170        &mut self,
2171    ) -> Result<(Ipv4Addr, Ipv4Addr, Ipv4Addr), GigeError> {
2172        let ip = Ipv4Addr::from(self.read_u32(consts::PERSISTENT_IP_ADDRESS).await?);
2173        let subnet = Ipv4Addr::from(self.read_u32(consts::PERSISTENT_SUBNET_MASK).await?);
2174        let gateway = Ipv4Addr::from(self.read_u32(consts::PERSISTENT_DEFAULT_GATEWAY).await?);
2175        Ok((ip, subnet, gateway))
2176    }
2177
2178    /// Write the persistent IP configuration to the device.
2179    pub async fn write_persistent_ip(
2180        &mut self,
2181        ip: Ipv4Addr,
2182        subnet: Ipv4Addr,
2183        gateway: Ipv4Addr,
2184    ) -> Result<(), GigeError> {
2185        self.write_u32(consts::PERSISTENT_IP_ADDRESS, u32::from(ip))
2186            .await?;
2187        self.write_u32(consts::PERSISTENT_SUBNET_MASK, u32::from(subnet))
2188            .await?;
2189        self.write_u32(consts::PERSISTENT_DEFAULT_GATEWAY, u32::from(gateway))
2190            .await?;
2191        info!(%ip, %subnet, %gateway, "wrote persistent IP configuration");
2192        Ok(())
2193    }
2194
2195    /// Enable persistent IP mode in the device configuration flags.
2196    ///
2197    /// Sets bit 1 (persistent IP) in the `CurrentIPConfiguration` register.
2198    pub async fn enable_persistent_ip(&mut self) -> Result<(), GigeError> {
2199        let current = self.read_u32(consts::CURRENT_IP_CONFIG).await?;
2200        let updated = current | 0x02; // bit 1 = persistent IP
2201        self.write_u32(consts::CURRENT_IP_CONFIG, updated).await?;
2202        info!(config = format!("0x{updated:08x}"), "enabled persistent IP");
2203        Ok(())
2204    }
2205}
2206
2207#[cfg(test)]
2208mod tests {
2209    use super::*;
2210
2211    /// Answer literal bootstrap addresses independently of the client's
2212    /// constants, so swapping those constants cannot make this test pass.
2213    async fn primary_application_probe(
2214        registers: impl FnOnce(std::net::SocketAddrV4) -> (u32, u32),
2215        names_owner: bool,
2216    ) -> bool {
2217        let peer = UdpSocket::bind("127.0.0.1:0").await.expect("peer");
2218        let mut device = GigeDevice::open(peer.local_addr().expect("peer address"))
2219            .await
2220            .expect("open");
2221        let SocketAddr::V4(local) = device.local_addr().expect("local address") else {
2222            panic!("IPv4 probe");
2223        };
2224        let (at_a04, at_a14) = registers(local);
2225        let server = tokio::spawn(async move {
2226            let expected: &[(u32, u32)] = if names_owner {
2227                &[
2228                    (0x0a00, 2),
2229                    (0x0934, 0x0800_0000),
2230                    (0x0a04, at_a04),
2231                    (0x0a14, at_a14),
2232                ]
2233            } else {
2234                &[(0x0a00, 2), (0x0934, 0)]
2235            };
2236            let mut bytes = [0; 128];
2237            for &(address, value) in expected {
2238                let (length, source) =
2239                    time::timeout(Duration::from_secs(1), peer.recv_from(&mut bytes))
2240                        .await
2241                        .expect("request deadline")
2242                        .expect("request");
2243                assert_eq!(length, 12);
2244                assert_eq!(&bytes[..6], &[0x42, 1, 0, 0x80, 0, 4]);
2245                assert_eq!(
2246                    u32::from_be_bytes(bytes[8..12].try_into().unwrap()),
2247                    address
2248                );
2249                assert_eq!(source, SocketAddr::V4(local));
2250                let mut reply = vec![0, 0, 0, 0x81, 0, 4, bytes[6], bytes[7]];
2251                reply.extend_from_slice(&value.to_be_bytes());
2252                peer.send_to(&reply, source).await.expect("reply");
2253            }
2254        });
2255        let held = time::timeout(Duration::from_secs(2), device.ping_control_channel())
2256            .await
2257            .expect("probe deadline")
2258            .expect("probe");
2259        server.await.expect("server");
2260        held
2261    }
2262
2263    #[tokio::test]
2264    async fn primary_application_standard_layout_matches_the_complete_endpoint() {
2265        assert!(
2266            primary_application_probe(|us| (u32::from(us.port()), u32::from(*us.ip())), true).await
2267        );
2268        // The standard port occupies the low half of its register.
2269        assert!(
2270            primary_application_probe(
2271                |us| (0x1234_0000 | u32::from(us.port()), u32::from(*us.ip())),
2272                true
2273            )
2274            .await
2275        );
2276        assert!(!primary_application_probe(|us| (u32::from(us.port()), 0x7f00_0002), true).await);
2277        assert!(
2278            !primary_application_probe(|us| (u32::from(us.port()) ^ 1, u32::from(*us.ip())), true)
2279                .await
2280        );
2281    }
2282
2283    #[tokio::test]
2284    async fn primary_application_swapped_layout_matches_the_complete_endpoint() {
2285        // Two separately opened source sockets must each match their own port.
2286        for _ in 0..2 {
2287            assert!(
2288                primary_application_probe(|us| (u32::from(*us.ip()), u32::from(us.port())), true)
2289                    .await
2290            );
2291        }
2292        assert!(!primary_application_probe(|us| (0x7f00_0002, u32::from(us.port())), true).await);
2293        assert!(
2294            !primary_application_probe(|us| (u32::from(*us.ip()), u32::from(us.port()) ^ 1), true)
2295                .await
2296        );
2297        assert!(
2298            !primary_application_probe(
2299                |us| (u32::from(*us.ip()), 0x0001_0000 | u32::from(us.port())),
2300                true
2301            )
2302            .await,
2303            "a swapped port with nonzero upper bits must not alias this socket"
2304        );
2305    }
2306
2307    #[tokio::test]
2308    async fn primary_application_without_owner_capability_does_not_read_owner_registers() {
2309        assert!(primary_application_probe(|_| (0, 0), false).await);
2310    }
2311
2312    #[tokio::test]
2313    async fn refreshing_a_stale_route_preserves_the_control_endpoint_and_request_id() {
2314        let peer = UdpSocket::bind("127.0.0.1:0").await.expect("peer");
2315        let device = GigeDevice::open(peer.local_addr().expect("address"))
2316            .await
2317            .expect("open");
2318        let local = device.local_addr().expect("local");
2319        let id = device.request_id;
2320        device
2321            .refresh_route_after_send_error(&io::Error::from(io::ErrorKind::AddrNotAvailable))
2322            .await
2323            .expect("refresh route");
2324        assert_eq!(device.local_addr().expect("local after refresh"), local);
2325        assert_eq!(device.request_id, id);
2326        device.socket.send(b"same controller").await.expect("send");
2327        let mut bytes = [0; 32];
2328        let (length, source) = time::timeout(Duration::from_secs(1), peer.recv_from(&mut bytes))
2329            .await
2330            .expect("deadline")
2331            .expect("receive");
2332        assert_eq!(source, local);
2333        assert_eq!(&bytes[..length], b"same controller");
2334        device
2335            .refresh_route_after_send_error(&io::Error::from(io::ErrorKind::PermissionDenied))
2336            .await
2337            .expect("other errors do not reconnect");
2338        assert_eq!(device.request_id, id);
2339    }
2340
2341    /// Reply after the upstream default deadline and count queued retries.
2342    async fn delayed_control_ack(
2343        opcode: u16,
2344        payload: Vec<u8>,
2345        pending: bool,
2346    ) -> (SocketAddr, tokio::task::JoinHandle<usize>) {
2347        let socket = UdpSocket::bind("127.0.0.1:0").await.expect("bind");
2348        let address = socket.local_addr().expect("address");
2349        let task = tokio::spawn(async move {
2350            let mut buffer = [0u8; 2048];
2351            let (_, peer) = socket.recv_from(&mut buffer).await.expect("request");
2352            assert_eq!(u16::from_be_bytes([buffer[2], buffer[3]]), opcode);
2353            let request_id = u16::from_be_bytes([buffer[6], buffer[7]]);
2354            if pending {
2355                socket
2356                    .send_to(&golden_pending_ack(request_id, 50), peer)
2357                    .await
2358                    .expect("pending ack");
2359            }
2360            time::sleep(Duration::from_millis(650)).await;
2361            let mut ack = Vec::new();
2362            ack.extend_from_slice(&0u16.to_be_bytes());
2363            ack.extend_from_slice(&(opcode + 1).to_be_bytes());
2364            ack.extend_from_slice(&(payload.len() as u16).to_be_bytes());
2365            ack.extend_from_slice(&request_id.to_be_bytes());
2366            ack.extend_from_slice(&payload);
2367            socket.send_to(&ack, peer).await.expect("ack");
2368            let mut requests = 1;
2369            while time::timeout(Duration::from_millis(50), socket.recv_from(&mut buffer))
2370                .await
2371                .is_ok()
2372            {
2373                requests += 1;
2374            }
2375            requests
2376        });
2377        (address, task)
2378    }
2379
2380    #[tokio::test]
2381    async fn configured_control_timeout_covers_register_and_memory_reads_and_writes() {
2382        for opcode in [0x0080, 0x0082, 0x0084, 0x0086] {
2383            let value = 0xCAFEBABEu32.to_be_bytes();
2384            let payload = match opcode {
2385                0x0080 => value.to_vec(),
2386                0x0084 => [0x2000u32.to_be_bytes(), value].concat(),
2387                _ => 0u32.to_be_bytes().to_vec(),
2388            };
2389            // A short PENDING_ACK must not shorten the configured timeout.
2390            let (address, server) = delayed_control_ack(opcode, payload, opcode == 0x0086).await;
2391            let mut device = GigeDevice::open(address).await.expect("open");
2392            assert_eq!(device.control_timeout(), consts::CONTROL_TIMEOUT);
2393            device.set_control_timeout(Duration::from_secs(2));
2394            match opcode {
2395                0x0080 => assert_eq!(
2396                    device.read_register(0x2000).await.expect("read"),
2397                    0xCAFEBABE
2398                ),
2399                0x0082 => device.write_register(0x2000, 1).await.expect("write"),
2400                0x0084 => assert_eq!(device.read_mem(0x2000, 4).await.expect("read"), value),
2401                0x0086 => device.write_mem(0x2000, &value).await.expect("write"),
2402                _ => unreachable!(),
2403            }
2404            assert_eq!(server.await.expect("server"), 1, "request was resent");
2405        }
2406    }
2407
2408    #[tokio::test]
2409    async fn a_short_configured_timeout_exhausts_the_existing_retry_budget() {
2410        // Keep the peer bound, but never acknowledge the command.
2411        let socket = UdpSocket::bind("127.0.0.1:0").await.expect("bind");
2412        let mut device = GigeDevice::open(socket.local_addr().expect("address"))
2413            .await
2414            .expect("open");
2415        device.set_control_timeout(Duration::from_millis(20));
2416        let result = time::timeout(Duration::from_secs(1), device.read_register(0x2000))
2417            .await
2418            .expect("configured timeout was ignored");
2419        assert!(matches!(result, Err(GigeError::Timeout)));
2420        let mut buffer = [0u8; 2048];
2421        for _ in 0..consts::MAX_RETRIES {
2422            socket.try_recv(&mut buffer).expect("retry");
2423        }
2424        assert!(socket.try_recv(&mut buffer).is_err());
2425    }
2426
2427    /// A Discovery ACK payload written out from the specification's field
2428    /// table, with a distinct recognisable value in every field.
2429    ///
2430    /// Built here rather than by round-tripping our own encoder: the point of
2431    /// this fixture is to disagree with the parser if the parser is wrong. See
2432    /// [ADR-0019]. The offsets are corroborated by Wireshark's
2433    /// `dissect_discovery_ack()`, which reads the MAC from `offset + 10` and
2434    /// the IP, manufacturer and model from 36, 72 and 104.
2435    ///
2436    /// [ADR-0019]: https://github.com/VitalyVorobyev/viva-genicam/blob/main/docs/adrs/adr0019-transport-conformance-and-spec-derived-fakes.md
2437    fn golden_discovery_payload() -> Vec<u8> {
2438        let mut p = vec![0u8; 248];
2439        p[0..2].copy_from_slice(&2u16.to_be_bytes()); // spec major
2440        p[2..4].copy_from_slice(&1u16.to_be_bytes()); // spec minor
2441        p[4..8].copy_from_slice(&0u32.to_be_bytes()); // device mode
2442        // 8..10 is the padding half of the MAC-high register.
2443        p[10..16].copy_from_slice(&[0x00, 0x0C, 0xDF, 0x06, 0x5B, 0x2F]); // MAC
2444        p[16..20].copy_from_slice(&7u32.to_be_bytes()); // supported IP config
2445        p[20..24].copy_from_slice(&5u32.to_be_bytes()); // current IP config
2446        p[36..40].copy_from_slice(&[169, 254, 78, 62]); // current IP
2447        p[52..56].copy_from_slice(&[255, 255, 0, 0]); // subnet
2448        p[68..72].copy_from_slice(&[169, 254, 0, 1]); // gateway
2449        let put =
2450            |p: &mut [u8], at: usize, s: &str| p[at..at + s.len()].copy_from_slice(s.as_bytes());
2451        put(&mut p, 72, "JAI Corporation"); // manufacturer
2452        put(&mut p, 104, "FS-3200T-10GE-NNC"); // model
2453        put(&mut p, 136, "1.2.3"); // device version
2454        put(&mut p, 168, "mfr-specific"); // manufacturer info
2455        put(&mut p, 216, "SN-12345"); // serial
2456        put(&mut p, 232, "left-camera"); // user-defined name
2457        p
2458    }
2459
2460    #[test]
2461    fn discovery_payload_matches_spec_offsets() {
2462        let info = parse_discovery_payload(&golden_discovery_payload()).expect("parse");
2463
2464        // The MAC begins at offset 10. Reading it at 12 — as we did before
2465        // #57 — yields DF:06:5B:2F:00:07, silently folding two bytes of
2466        // SupportedIPConfiguration into the address.
2467        assert_eq!(info.mac, [0x00, 0x0C, 0xDF, 0x06, 0x5B, 0x2F]);
2468        assert_eq!(info.mac_string(), "00:0C:DF:06:5B:2F");
2469        assert_eq!(info.ip, Ipv4Addr::new(169, 254, 78, 62));
2470        assert_eq!(info.manufacturer.as_deref(), Some("JAI Corporation"));
2471        assert_eq!(info.model.as_deref(), Some("FS-3200T-10GE-NNC"));
2472        assert_eq!(info.version.as_deref(), Some("1.2.3"));
2473        assert_eq!(info.serial.as_deref(), Some("SN-12345"));
2474        assert_eq!(info.user_name.as_deref(), Some("left-camera"));
2475        // TC-31: subnet at 52 and gateway at 68, which a camera on the wrong
2476        // network is diagnosed by.
2477        assert_eq!(info.subnet, Some(Ipv4Addr::new(255, 255, 0, 0)));
2478        assert_eq!(info.gateway, Some(Ipv4Addr::new(169, 254, 0, 1)));
2479    }
2480
2481    /// TC-31: an interface asks its own subnet and the limited broadcast;
2482    /// only the second reaches a camera configured for another network.
2483    #[test]
2484    fn discovery_goes_to_the_subnet_and_to_the_limited_broadcast() {
2485        assert_eq!(
2486            discovery_destinations(
2487                Ipv4Addr::new(192, 168, 1, 5),
2488                Ipv4Addr::new(255, 255, 255, 0)
2489            ),
2490            vec![Ipv4Addr::new(192, 168, 1, 255), Ipv4Addr::BROADCAST]
2491        );
2492        assert_eq!(
2493            discovery_destinations(Ipv4Addr::LOCALHOST, Ipv4Addr::new(255, 0, 0, 0)),
2494            vec![Ipv4Addr::LOCALHOST],
2495            "loopback is asked by unicast"
2496        );
2497    }
2498
2499    /// Subnet and gateway are compared both ways: the camera's address in the
2500    /// host's network and the host's in the camera's.
2501    #[test]
2502    fn a_camera_shares_the_host_subnet_only_by_both_masks() {
2503        let mut info = DeviceInfo::from_ip(Ipv4Addr::new(192, 168, 1, 20));
2504        assert_eq!(info.shares_subnet_with_host(), None, "nothing known");
2505        info.subnet = Some(Ipv4Addr::new(255, 255, 255, 0));
2506        info.local_ip = Some(Ipv4Addr::new(192, 168, 1, 5));
2507        info.local_netmask = Some(Ipv4Addr::new(255, 255, 255, 0));
2508        assert_eq!(info.shares_subnet_with_host(), Some(true));
2509        info.local_ip = Some(Ipv4Addr::new(169, 254, 3, 4));
2510        info.local_netmask = Some(Ipv4Addr::new(255, 255, 0, 0));
2511        assert_eq!(info.shares_subnet_with_host(), Some(false));
2512        // A /16 host holds a /24 camera's address, but the camera cannot
2513        // answer outside its /24.
2514        info.local_ip = Some(Ipv4Addr::new(192, 168, 9, 5));
2515        assert_eq!(info.shares_subnet_with_host(), Some(false));
2516    }
2517
2518    #[test]
2519    fn discovery_payload_tolerates_truncation() {
2520        // A device that stops after the IP field still yields an addressable
2521        // camera rather than failing discovery on that interface.
2522        let short = golden_discovery_payload()[..40].to_vec();
2523        let info = parse_discovery_payload(&short).expect("short payload should parse");
2524        assert_eq!(info.ip, Ipv4Addr::new(169, 254, 78, 62));
2525        assert_eq!(info.mac, [0x00, 0x0C, 0xDF, 0x06, 0x5B, 0x2F]);
2526        assert_eq!(info.manufacturer, None);
2527        assert_eq!(info.serial, None);
2528
2529        // Below the IP field there is nothing usable.
2530        assert!(parse_discovery_payload(&[0u8; 12]).is_err());
2531    }
2532
2533    #[test]
2534    fn discovery_ack_ignores_foreign_traffic() {
2535        let payload = golden_discovery_payload();
2536        let ack = |status: u16, command: u16, request_id: u16| {
2537            let mut buf = Vec::new();
2538            buf.extend_from_slice(&status.to_be_bytes());
2539            buf.extend_from_slice(&command.to_be_bytes());
2540            buf.extend_from_slice(&(payload.len() as u16).to_be_bytes());
2541            buf.extend_from_slice(&request_id.to_be_bytes());
2542            buf.extend_from_slice(&payload);
2543            buf
2544        };
2545
2546        // The real thing.
2547        assert!(parse_discovery_ack(&ack(0, consts::DISCOVERY_ACK, 0x0100), 0x0100).is_some());
2548        // Someone else's request id, a READREG ack that landed on our socket,
2549        // an error status, and a runt datagram must all be ignored rather than
2550        // failing discovery for every camera on the interface (#57).
2551        assert!(parse_discovery_ack(&ack(0, consts::DISCOVERY_ACK, 0x0999), 0x0100).is_none());
2552        assert!(parse_discovery_ack(&ack(0, 0x0081, 0x0100), 0x0100).is_none());
2553        assert!(parse_discovery_ack(&ack(0x8002, consts::DISCOVERY_ACK, 0x0100), 0x0100).is_none());
2554        assert!(parse_discovery_ack(&[0u8; 4], 0x0100).is_none());
2555    }
2556
2557    #[test]
2558    fn directed_broadcast_uses_netmask_for_link_local_address() {
2559        // Linux reports no `brd` field for an address added as
2560        // `169.254.1.10/16`; `if-addrs` then exposes the local address as the
2561        // broadcast destination. Deriving it from the netmask must still
2562        // reach every APIPA peer on the link.
2563        assert_eq!(
2564            directed_broadcast(
2565                Ipv4Addr::new(169, 254, 1, 10),
2566                Ipv4Addr::new(255, 255, 0, 0),
2567            ),
2568            Ipv4Addr::new(169, 254, 255, 255)
2569        );
2570    }
2571
2572    /// A PENDING_ACK written out from the specification's field table:
2573    /// the 8-byte acknowledgement header, two reserved bytes, then a 16-bit
2574    /// `time_to_completion` in milliseconds.
2575    fn golden_pending_ack(request_id: u16, millis: u16) -> Vec<u8> {
2576        let mut buf = Vec::new();
2577        buf.extend_from_slice(&0u16.to_be_bytes()); // status: success
2578        buf.extend_from_slice(&consts::PENDING_ACK.to_be_bytes()); // 0x0089
2579        buf.extend_from_slice(&4u16.to_be_bytes()); // payload length
2580        buf.extend_from_slice(&request_id.to_be_bytes());
2581        buf.extend_from_slice(&0u16.to_be_bytes()); // reserved
2582        buf.extend_from_slice(&millis.to_be_bytes()); // time to completion
2583        buf
2584    }
2585
2586    #[test]
2587    fn pending_ack_matches_spec_offsets() {
2588        let (id, wait) = parse_pending_ack(&golden_pending_ack(0x1234, 750)).expect("pending ack");
2589        assert_eq!(id, 0x1234);
2590        assert_eq!(wait, Duration::from_millis(750));
2591
2592        // The time is the u16 at payload offset 2, not a u32 over the whole
2593        // payload. The two readings agree only while the reserved field is
2594        // zero; a device that leaves junk there would ask aravis for
2595        // 0xDEAD_02EE ms — around 41 days — where we read 750.
2596        let mut junk = golden_pending_ack(0x1234, 750);
2597        junk[8..10].copy_from_slice(&0xDEADu16.to_be_bytes());
2598        assert_eq!(
2599            parse_pending_ack(&junk).expect("pending ack").1.as_millis(),
2600            750
2601        );
2602    }
2603
2604    #[test]
2605    fn pending_ack_is_distinguished_from_real_acks() {
2606        // A genuine READREG ack must not be mistaken for a request for time,
2607        // or every register read would hang until the retry budget ran out.
2608        let mut readreg = Vec::new();
2609        readreg.extend_from_slice(&0u16.to_be_bytes());
2610        readreg.extend_from_slice(&0x0081u16.to_be_bytes());
2611        readreg.extend_from_slice(&4u16.to_be_bytes());
2612        readreg.extend_from_slice(&0x1234u16.to_be_bytes());
2613        readreg.extend_from_slice(&0u32.to_be_bytes());
2614        assert!(parse_pending_ack(&readreg).is_none());
2615        assert!(parse_pending_ack(&[0u8; 4]).is_none());
2616
2617        // A device that truncates the payload is still asking for time.
2618        let truncated = &golden_pending_ack(0x1234, 750)[..viva_gencp::HEADER_SIZE];
2619        let (id, wait) = parse_pending_ack(truncated).expect("truncated pending ack");
2620        assert_eq!(id, 0x1234);
2621        assert_eq!(wait, consts::CONTROL_TIMEOUT);
2622    }
2623
2624    /// A minimal GVCP device that answers `pending` PENDING_ACKs before the
2625    /// real acknowledgement, counting how many commands it was actually sent.
2626    ///
2627    /// The count is the point: a controller that treats PENDING_ACK as a
2628    /// failure and retries would execute the command more than once.
2629    async fn pending_ack_device(
2630        pending: usize,
2631        wait_ms: u16,
2632        stale_ack: bool,
2633    ) -> (SocketAddr, tokio::task::JoinHandle<usize>) {
2634        let sock = UdpSocket::bind("127.0.0.1:0").await.expect("bind");
2635        let addr = sock.local_addr().expect("addr");
2636        let handle = tokio::spawn(async move {
2637            let mut buf = [0u8; 2048];
2638            let mut commands = 0usize;
2639            let (len, peer) = sock.recv_from(&mut buf).await.expect("recv");
2640            commands += 1;
2641            let request_id = u16::from_be_bytes([buf[6], buf[7]]);
2642            debug_assert!(len >= viva_gencp::HEADER_SIZE);
2643            for _ in 0..pending {
2644                let ack = golden_pending_ack(request_id, wait_ms);
2645                sock.send_to(&ack, peer).await.expect("send pending");
2646            }
2647            if stale_ack {
2648                let mut ack = Vec::new();
2649                ack.extend_from_slice(&0u16.to_be_bytes());
2650                ack.extend_from_slice(&0x0081u16.to_be_bytes());
2651                ack.extend_from_slice(&4u16.to_be_bytes());
2652                ack.extend_from_slice(&request_id.wrapping_add(1).to_be_bytes());
2653                ack.extend_from_slice(&0xDEADBEEFu32.to_be_bytes());
2654                sock.send_to(&ack, peer).await.expect("send stale ack");
2655            }
2656            // The real READREG ack: one 4-byte register value.
2657            let mut ack = Vec::new();
2658            ack.extend_from_slice(&0u16.to_be_bytes());
2659            ack.extend_from_slice(&0x0081u16.to_be_bytes());
2660            ack.extend_from_slice(&4u16.to_be_bytes());
2661            ack.extend_from_slice(&request_id.to_be_bytes());
2662            ack.extend_from_slice(&0xCAFEBABEu32.to_be_bytes());
2663            sock.send_to(&ack, peer).await.expect("send ack");
2664            // Drain any retry the controller wrongly sent, so the count is
2665            // observable rather than lost in the socket buffer.
2666            let drain = time::timeout(Duration::from_millis(200), sock.recv_from(&mut buf)).await;
2667            if drain.is_ok() {
2668                commands += 1;
2669            }
2670            commands
2671        });
2672        (addr, handle)
2673    }
2674
2675    #[tokio::test]
2676    async fn pending_ack_extends_the_deadline_without_resending() {
2677        let (addr, server) = pending_ack_device(1, 300, false).await;
2678        let mut device = GigeDevice::open(addr).await.expect("open");
2679        let value = device.read_register(0x0a00).await.expect("read register");
2680        assert_eq!(value, 0xCAFEBABE);
2681        assert_eq!(server.await.expect("join"), 1, "command must not be resent");
2682    }
2683
2684    #[tokio::test]
2685    async fn repeated_pending_acks_are_all_honoured() {
2686        // A flash write can take several rounds. Each one restarts the clock;
2687        // the command is still sent exactly once.
2688        let (addr, server) = pending_ack_device(3, 200, false).await;
2689        let mut device = GigeDevice::open(addr).await.expect("open");
2690        let value = device.read_register(0x0a00).await.expect("read register");
2691        assert_eq!(value, 0xCAFEBABE);
2692        assert_eq!(server.await.expect("join"), 1, "command must not be resent");
2693    }
2694
2695    #[tokio::test]
2696    async fn stale_acknowledgement_is_ignored_without_resending() {
2697        let (addr, server) = pending_ack_device(0, 0, true).await;
2698        let mut device = GigeDevice::open(addr).await.expect("open");
2699        let value = device.read_register(0x0a00).await.expect("read register");
2700        assert_eq!(value, 0xCAFEBABE);
2701        assert_eq!(server.await.expect("join"), 1, "command must not be resent");
2702    }
2703
2704    /// A device that answers `error_replies` commands with `status_raw` and
2705    /// then, if it is asked again, succeeds. Returns the number of commands it
2706    /// received, which is what distinguishes "retried" from "reported".
2707    /// TC-26: while a `PENDING_ACK`ed write waits, the camera is briefly
2708    /// unreachable, so heartbeats draw ICMP port-unreachable and the socket
2709    /// reports errors. The write is still pending on the device: it must not
2710    /// be sent again, and the wait goes on to its acknowledgement.
2711    #[tokio::test]
2712    async fn an_unreachable_moment_during_a_pending_wait_does_not_resend_the_command() {
2713        let sock = UdpSocket::bind("127.0.0.1:0").await.expect("bind");
2714        let addr = sock.local_addr().expect("addr");
2715        let server = tokio::spawn(async move {
2716            let mut buf = [0u8; 2048];
2717            let (_, peer) = sock.recv_from(&mut buf).await.expect("the write");
2718            let request_id = u16::from_be_bytes([buf[6], buf[7]]);
2719            sock.send_to(&golden_pending_ack(request_id, 1500), peer)
2720                .await
2721                .expect("send pending");
2722            drop(sock);
2723            time::sleep(Duration::from_millis(200)).await;
2724            let sock = UdpSocket::bind(addr).await.expect("rebind");
2725            // Longer than an attempt's 500 ms timeout: a controller that
2726            // gave up waiting on the PENDING_ACK resends within it.
2727            let mut resent = 0usize;
2728            let listen_until = time::Instant::now() + Duration::from_millis(700);
2729            while let Ok(Ok((len, from))) =
2730                time::timeout_at(listen_until, sock.recv_from(&mut buf)).await
2731            {
2732                let opcode = u16::from_be_bytes([buf[2], buf[3]]);
2733                let id = u16::from_be_bytes([buf[6], buf[7]]);
2734                if opcode == 0x0082 && id == request_id {
2735                    resent += 1;
2736                } else if opcode == 0x0080 && len >= 12 {
2737                    // A heartbeat: answer it, as the device would.
2738                    let mut ack = vec![0, 0, 0, 0x81, 0, 4];
2739                    ack.extend_from_slice(&id.to_be_bytes());
2740                    ack.extend_from_slice(&2u32.to_be_bytes());
2741                    sock.send_to(&ack, from).await.expect("heartbeat ack");
2742                }
2743            }
2744            let mut ack = vec![0, 0, 0, 0x83, 0, 4];
2745            ack.extend_from_slice(&request_id.to_be_bytes());
2746            ack.extend_from_slice(&[0, 0, 0, 0]);
2747            sock.send_to(&ack, peer).await.expect("write ack");
2748            resent
2749        });
2750        let mut device = GigeDevice::open(addr).await.expect("open");
2751        device.set_inflight_keepalive_period(Some(Duration::from_millis(30)));
2752        device
2753            .write_register(0x2000, 1)
2754            .await
2755            .expect("the pending write completes");
2756        assert_eq!(server.await.unwrap(), 0, "the pending write was sent again");
2757    }
2758
2759    async fn status_device(
2760        status_raw: u16,
2761        error_replies: usize,
2762    ) -> (SocketAddr, tokio::task::JoinHandle<usize>) {
2763        let sock = UdpSocket::bind("127.0.0.1:0").await.expect("bind");
2764        let addr = sock.local_addr().expect("addr");
2765        let handle = tokio::spawn(async move {
2766            let mut buf = [0u8; 2048];
2767            let mut commands = 0usize;
2768            loop {
2769                let recv =
2770                    time::timeout(Duration::from_millis(600), sock.recv_from(&mut buf)).await;
2771                let Ok(Ok((_len, peer))) = recv else { break };
2772                commands += 1;
2773                let request_id = u16::from_be_bytes([buf[6], buf[7]]);
2774                let mut ack = Vec::new();
2775                if commands <= error_replies {
2776                    ack.extend_from_slice(&status_raw.to_be_bytes());
2777                    ack.extend_from_slice(&0x0081u16.to_be_bytes());
2778                    ack.extend_from_slice(&0u16.to_be_bytes());
2779                    ack.extend_from_slice(&request_id.to_be_bytes());
2780                } else {
2781                    ack.extend_from_slice(&0u16.to_be_bytes());
2782                    ack.extend_from_slice(&0x0081u16.to_be_bytes());
2783                    ack.extend_from_slice(&4u16.to_be_bytes());
2784                    ack.extend_from_slice(&request_id.to_be_bytes());
2785                    ack.extend_from_slice(&0xCAFEBABEu32.to_be_bytes());
2786                }
2787                sock.send_to(&ack, peer).await.expect("send ack");
2788            }
2789            commands
2790        });
2791        (addr, handle)
2792    }
2793
2794    #[tokio::test]
2795    async fn busy_is_retried() {
2796        // 0x8007 BUSY is congestion: the command can succeed if asked again.
2797        let (addr, server) = status_device(0x8007, 1).await;
2798        let mut device = GigeDevice::open(addr).await.expect("open");
2799        let value = device.read_register(0x0a00).await.expect("read register");
2800        assert_eq!(value, 0xCAFEBABE);
2801        assert_eq!(
2802            server.await.expect("join"),
2803            2,
2804            "BUSY must be retried, so the device sees a second command"
2805        );
2806    }
2807
2808    #[tokio::test]
2809    async fn write_protect_is_reported_not_retried() {
2810        // 0x8004 WRITE_PROTECT is permanent. It used to be decoded as
2811        // `DeviceBusy`, so the retry loop spent its whole budget on a register
2812        // that could never accept the write.
2813        let (addr, server) = status_device(0x8004, usize::MAX).await;
2814        let mut device = GigeDevice::open(addr).await.expect("open");
2815        let err = device
2816            .read_register(0x0a00)
2817            .await
2818            .expect_err("write protect must surface");
2819        assert!(
2820            matches!(
2821                err,
2822                GigeError::Status(GigeStatus::Common(StatusCode::WriteProtect))
2823            ),
2824            "expected WRITE_PROTECT, got {err:?}"
2825        );
2826        assert_eq!(
2827            server.await.expect("join"),
2828            1,
2829            "a permanent refusal must not be retried"
2830        );
2831    }
2832
2833    #[tokio::test]
2834    async fn access_denied_names_itself_in_the_error() {
2835        // The #45 case: the user saw `Unknown(32774)` and could tell us nothing.
2836        let (addr, server) = status_device(0x8006, usize::MAX).await;
2837        let mut device = GigeDevice::open(addr).await.expect("open");
2838        let err = device
2839            .read_register(0x0a00)
2840            .await
2841            .expect_err("access denied must surface");
2842        assert_eq!(
2843            err.to_string(),
2844            "device reported status ACCESS_DENIED (0x8006)"
2845        );
2846        assert_eq!(server.await.expect("join"), 1);
2847    }
2848
2849    #[test]
2850    fn only_one_aligned_32_bit_word_is_a_register() {
2851        assert_eq!(single_register_address(0x0a00, 4), Some(0x0a00));
2852        assert_eq!(single_register_address(0xFFFF_FFFC, 4), Some(0xFFFF_FFFC));
2853        // Unaligned: the address stays READMEM, where TC-21 lives.
2854        assert_eq!(single_register_address(0x0a02, 4), None);
2855        // Not one register wide. Eight bytes is two registers, and is not
2856        // split: a multi-register READREG could tear a 64-bit value.
2857        assert_eq!(single_register_address(0x0a00, 8), None);
2858        assert_eq!(single_register_address(0x0a00, 2), None);
2859        assert_eq!(single_register_address(0x0a00, 0), None);
2860        // Beyond the 32-bit address a READREG can carry.
2861        assert_eq!(single_register_address(0x1_0000_0000, 4), None);
2862    }
2863
2864    #[test]
2865    fn force_readmem_env_accepts_anything_but_empty_and_zero() {
2866        use std::ffi::OsStr;
2867        assert!(!force_readmem_requested(None));
2868        assert!(!force_readmem_requested(Some(OsStr::new(""))));
2869        assert!(!force_readmem_requested(Some(OsStr::new("0"))));
2870        assert!(force_readmem_requested(Some(OsStr::new("1"))));
2871        assert!(force_readmem_requested(Some(OsStr::new("true"))));
2872        // Only the exact string "0" means off; this is not a number parser.
2873        assert!(force_readmem_requested(Some(OsStr::new("00"))));
2874    }
2875
2876    #[test]
2877    fn request_header_roundtrip() {
2878        let header = GvcpRequestHeader {
2879            flags: CommandFlags::ACK_REQUIRED,
2880            command: 0x1234,
2881            length: 4,
2882            request_id: 0xBEEF,
2883        };
2884        let payload = [1u8, 2, 3, 4];
2885        let encoded = header.encode(&payload);
2886        assert_eq!(encoded.len(), viva_gencp::HEADER_SIZE + payload.len());
2887        // GVCP wire format: byte 0 = 0x42 key, byte 1 = flags byte.
2888        assert_eq!(encoded[0], GVCP_CMD_KEY);
2889        assert_eq!(encoded[1], 0x01); // ACK_REQUIRED
2890        assert_eq!(&encoded[2..4], &header.command.to_be_bytes());
2891        assert_eq!(&encoded[4..6], &header.length.to_be_bytes());
2892        assert_eq!(&encoded[6..8], &header.request_id.to_be_bytes());
2893        assert_eq!(&encoded[8..], &payload);
2894    }
2895
2896    #[test]
2897    fn forceip_payload_encoding() {
2898        let mac = [0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE];
2899        let ip = Ipv4Addr::new(192, 168, 1, 100);
2900        let subnet = Ipv4Addr::new(255, 255, 255, 0);
2901        let gateway = Ipv4Addr::new(192, 168, 1, 1);
2902        let payload = encode_forceip_payload(mac, ip, subnet, gateway);
2903        assert_eq!(payload.len(), 56);
2904        // MAC at offset 2..8
2905        assert_eq!(&payload[2..8], &mac);
2906        // IP at offset 20..24
2907        assert_eq!(&payload[20..24], &ip.octets());
2908        // Subnet at offset 36..40
2909        assert_eq!(&payload[36..40], &subnet.octets());
2910        // Gateway at offset 52..56
2911        assert_eq!(&payload[52..56], &gateway.octets());
2912        // Reserved bytes should be zero
2913        assert_eq!(&payload[0..2], &[0, 0]);
2914        assert_eq!(&payload[8..20], &[0u8; 12]);
2915        assert_eq!(&payload[24..36], &[0u8; 12]);
2916        assert_eq!(&payload[40..52], &[0u8; 12]);
2917    }
2918
2919    #[test]
2920    fn ack_header_conversion() {
2921        let ack = AckHeader {
2922            status: 0x8007,
2923            opcode: OpCode::ReadMem,
2924            length: 12,
2925            request_id: 0x44,
2926        };
2927        let converted = GvcpAckHeader::from(ack);
2928        assert_eq!(converted.status, GigeStatus::Common(StatusCode::Busy));
2929        assert_eq!(converted.command, OpCode::ReadMem.ack_code());
2930        assert_eq!(converted.length, 12);
2931        assert_eq!(converted.request_id, 0x44);
2932    }
2933
2934    /// The standard `PACKETRESEND_CMD`, written out byte by byte from the
2935    /// field table (Wireshark `dissect_packetresend_cmd`), not from a round
2936    /// trip through any parser of ours.
2937    #[test]
2938    fn packet_resend_has_the_12_byte_standard_layout() {
2939        #[rustfmt::skip]
2940        let expected: &[u8] = &[
2941            0x42, 0x00,             // key, flags: no acknowledgement, 16-bit ids
2942            0x00, 0x40,             // PACKETRESEND_CMD
2943            0x00, 0x0C,             // 12 bytes
2944            0x12, 0x34,             // request id
2945            0x00, 0x02,             // stream channel 2
2946            0xBE, 0xEF,             // block id
2947            0x00, 0x00, 0x00, 0x05, // first packet id
2948            0x00, 0x12, 0x34, 0x56, // last packet id
2949        ];
2950        assert_eq!(
2951            encode_packet_resend(0x1234, 2, 0xBEEF, 5, 0x12_3456, false).as_ref(),
2952            expected
2953        );
2954        // The fields hold 16 and 24 bits; nothing spills into the neighbours.
2955        let truncated = encode_packet_resend(1, 0, 0x1_0002, 0xFF00_0001, 0xFF00_0002, false);
2956        assert_eq!(&truncated[10..], &[0x00, 0x02, 0, 0, 0, 1, 0, 0, 0, 2]);
2957    }
2958
2959    #[test]
2960    fn packet_resend_has_the_20_byte_extended_layout() {
2961        #[rustfmt::skip]
2962        let expected: &[u8] = &[
2963            0x42, 0x10,             // key, flags: extended ids, no acknowledgement
2964            0x00, 0x40,             // PACKETRESEND_CMD
2965            0x00, 0x14,             // 20 bytes
2966            0x00, 0x07,             // request id
2967            0x00, 0x01,             // stream channel 1
2968            0x00, 0x00,             // reserved
2969            0x01, 0x00, 0x00, 0x05, // first packet id, all 32 bits
2970            0x01, 0x00, 0x00, 0x09, // last packet id
2971            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, // block id
2972        ];
2973        assert_eq!(
2974            encode_packet_resend(7, 1, (1 << 32) | 2, 0x0100_0005, 0x0100_0009, true).as_ref(),
2975            expected
2976        );
2977    }
2978}