1use 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
24pub use consts::PORT as GVCP_PORT;
26
27pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub(crate) struct GvcpRequestHeader {
86 pub flags: CommandFlags,
88 pub command: u16,
90 pub length: u16,
92 pub request_id: u16,
94}
95
96impl GvcpRequestHeader {
97 pub(crate) fn encode(self, payload: &[u8]) -> Bytes {
102 let mut buf = BytesMut::with_capacity(viva_gencp::HEADER_SIZE + payload.len());
103 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub(crate) struct GvcpAckHeader {
137 pub status: GigeStatus,
139 pub command: u16,
141 pub length: u16,
143 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#[derive(Debug, Error)]
160#[non_exhaustive]
161pub enum GigeError {
162 #[error("io: {0}")]
164 Io(#[from] std::io::Error),
165 #[error("timeout waiting for acknowledgement")]
168 Timeout,
169 #[error("GenCP: {0}")]
171 GenCp(#[from] viva_gencp::GenCpError),
172 #[error("device reported status {0}")]
175 Status(GigeStatus),
176 #[error("malformed {command} acknowledgement: {problem}")]
178 MalformedAck {
179 command: &'static str,
181 problem: &'static str,
183 },
184 #[error("{command} acknowledgement carries {got} bytes; expected {expected}")]
187 AckLength {
188 command: &'static str,
190 expected: usize,
192 got: usize,
194 },
195 #[error("GigE Vision control runs over IPv4, and the {0} has no IPv4 address")]
198 NotIpv4(&'static str),
199 #[error("GVSP packet size {0} does not fit GevSCPSPacketSize's 16 bits")]
201 PacketSize(u32),
202}
203
204#[derive(Debug, Clone, PartialEq, Eq)]
209pub struct DeviceInfo {
210 pub ip: Ipv4Addr,
212 pub mac: [u8; 6],
214 pub model: Option<String>,
216 pub manufacturer: Option<String>,
218 pub version: Option<String>,
220 pub serial: Option<String>,
222 pub user_name: Option<String>,
224 pub local_ip: Option<Ipv4Addr>,
230 pub subnet: Option<Ipv4Addr>,
232 pub gateway: Option<Ipv4Addr>,
234 pub local_netmask: Option<Ipv4Addr>,
236}
237
238impl DeviceInfo {
239 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 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 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#[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 pub fn new() -> Self {
299 Self::default()
300 }
301
302 pub fn interface(mut self, name: impl Into<String>) -> Self {
305 self.interface = Some(name.into());
306 self
307 }
308
309 pub fn include_loopback(mut self, include: bool) -> Self {
311 self.include_loopback = include;
312 self
313 }
314
315 pub fn allow_broadcast_ack(mut self, allow: bool) -> Self {
323 self.allow_broadcast_ack = allow;
324 self
325 }
326}
327
328pub async fn discover(timeout: Duration) -> Result<Vec<DeviceInfo>, GigeError> {
330 discover_with(timeout, &DiscoveryOptions::new()).await
331}
332
333pub 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
345pub async fn discover_all(timeout: Duration) -> Result<Vec<DeviceInfo>, GigeError> {
350 discover_with(timeout, &DiscoveryOptions::new().include_loopback(true)).await
351}
352
353pub async fn discover_with(
360 timeout: Duration,
361 options: &DiscoveryOptions,
362) -> Result<Vec<DeviceInfo>, GigeError> {
363 discover_impl(timeout, options).await
364}
365
366pub 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 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
405fn 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
416pub 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 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 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
498fn 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 buf[2..8].copy_from_slice(&mac);
509 buf[20..24].copy_from_slice(&ip.octets());
512 buf[36..40].copy_from_slice(&subnet.octets());
515 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 let (len, src) = match recv {
617 Ok(v) => v,
618 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 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
666fn 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
688fn 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
698fn 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
707fn 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
724fn 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#[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
798fn directed_broadcast(ip: Ipv4Addr, netmask: Ipv4Addr) -> Ipv4Addr {
807 Ipv4Addr::from(u32::from(ip) | !u32::from(netmask))
808}
809
810fn 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
861fn parse_discovery_payload(payload: &[u8]) -> Result<DeviceInfo, GigeError> {
893 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(); let _spec_minor = cursor.get_u16(); let _device_mode = cursor.get_u32(); cursor.advance(2); let mut mac = [0u8; 6];
913 cursor.copy_to_slice(&mut mac); let _supported_ip_config = cursor.get_u32(); let _current_ip_config = cursor.get_u32(); cursor.advance(12); let ip = Ipv4Addr::from(cursor.get_u32()); skip(&mut cursor, 12); let subnet = read_ipv4(&mut cursor); skip(&mut cursor, 12); let gateway = read_ipv4(&mut cursor); let manufacturer = read_fixed_string(&mut cursor, 32); let model = read_fixed_string(&mut cursor, 32); let version = read_fixed_string(&mut cursor, 32); skip(&mut cursor, 48); let serial = read_fixed_string(&mut cursor, 16); let user_name = read_fixed_string(&mut cursor, 16); 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
953fn read_ipv4(cursor: &mut Cursor<&[u8]>) -> Option<Ipv4Addr> {
955 (cursor.remaining() >= 4).then(|| Ipv4Addr::from(cursor.get_u32()))
956}
957
958fn 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
968fn 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
981enum AckRecv {
987 Received(usize),
988 Io(std::io::Error),
989 TimedOut,
990}
991
992fn 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 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
1027pub const FORCE_READMEM_ENV: &str = "VIVA_GIGE_FORCE_READMEM";
1034
1035fn force_readmem_requested(value: Option<&std::ffi::OsStr>) -> bool {
1037 value.is_some_and(|v| !v.is_empty() && v != "0")
1038}
1039
1040fn 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
1050fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1073pub struct GvcpCapability(u32);
1074
1075impl GvcpCapability {
1076 pub const fn from_bits(bits: u32) -> Self {
1078 Self(bits)
1079 }
1080
1081 pub const fn bits(self) -> u32 {
1083 self.0
1084 }
1085
1086 pub const fn pending_ack(self) -> bool {
1088 self.0 & consts::CAPABILITY_PENDING_ACK != 0
1089 }
1090
1091 pub const fn packet_resend(self) -> bool {
1093 self.0 & consts::CAPABILITY_PACKET_RESEND != 0
1094 }
1095
1096 pub const fn writemem(self) -> bool {
1098 self.0 & 0x0000_0002 != 0
1099 }
1100
1101 pub const fn concatenation(self) -> bool {
1103 self.0 & 0x0000_0001 != 0
1104 }
1105
1106 pub const fn event(self) -> bool {
1108 self.0 & 0x0000_0008 != 0
1109 }
1110
1111 pub const fn event_data(self) -> bool {
1113 self.0 & 0x0000_0010 != 0
1114 }
1115
1116 pub const fn action(self) -> bool {
1118 self.0 & 0x0000_0040 != 0
1119 }
1120
1121 pub const fn heartbeat_disable(self) -> bool {
1123 self.0 & 0x2000_0000 != 0
1124 }
1125
1126 pub const fn ccp_application_port_ip(self) -> bool {
1128 self.0 & 0x0800_0000 != 0
1129 }
1130
1131 pub const fn primary_application_switchover(self) -> bool {
1133 self.0 & 0x0020_0000 != 0
1134 }
1135}
1136
1137pub 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 memory_access_only: bool,
1150 names_primary_application: Option<bool>,
1153 exclusive_access: bool,
1155}
1156
1157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1159pub struct StreamParams {
1160 pub packet_size: u32,
1162 pub packet_delay: Option<u32>,
1165 pub mtu: u32,
1167 pub host: Ipv4Addr,
1169 pub port: u16,
1171 pub channel: u32,
1173 pub camera: Option<SocketAddr>,
1176}
1177
1178impl GigeDevice {
1179 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 pub fn set_control_timeout(&mut self, timeout: Duration) {
1218 self.control_timeout = timeout;
1219 }
1220
1221 pub fn control_timeout(&self) -> Duration {
1223 self.control_timeout
1224 }
1225
1226 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 pub fn inflight_keepalive_period(&self) -> Option<Duration> {
1241 self.inflight_keepalive_period
1242 }
1243
1244 pub fn use_memory_access(&mut self) {
1250 self.memory_access_only = true;
1251 }
1252
1253 pub fn memory_access_only(&self) -> bool {
1255 self.memory_access_only
1256 }
1257
1258 pub fn set_exclusive_access(&mut self, exclusive: bool) {
1263 self.exclusive_access = exclusive;
1264 }
1265
1266 pub fn exclusive_access(&self) -> bool {
1268 self.exclusive_access
1269 }
1270
1271 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 pub async fn release_control(&mut self) -> Result<(), GigeError> {
1298 self.write_u32(consts::CONTROL_CHANNEL_PRIVILEGE, 0).await
1299 }
1300
1301 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 pub async fn heartbeat_timeout_ms(&mut self) -> Result<u32, GigeError> {
1336 self.read_u32(consts::HEARTBEAT_TIMEOUT).await
1337 }
1338
1339 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 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 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 let swapped = port_register == our_ip && ip_register == our_port;
1423 Ok(standard || swapped)
1424 }
1425
1426 pub fn remote_addr(&self) -> SocketAddr {
1428 self.remote
1429 }
1430
1431 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 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 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 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 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 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 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 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 return AckRecv::Received(len);
1640 }
1641 }
1642 }
1643 }
1644
1645 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 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 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 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 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 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 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 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 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 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 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 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); payload.put_u16(request as u16);
1873 let ack = self.transact_with_retry(OpCode::ReadMem, payload).await?;
1874 let ack_data = if ack.payload.len() >= 4 + request {
1876 &ack.payload[4..4 + request]
1877 } else if ack.payload.len() == request {
1878 &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 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 async fn write_mem_words(&mut self, addr: u64, data: &[u8]) -> Result<(), GigeError> {
1932 const GVCP_WRITE_OVERHEAD: usize = 4;
1934
1935 let mut offset = 0usize;
1936 while offset < data.len() {
1937 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 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 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 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 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 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 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 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 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 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 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 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 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 pub async fn stream_channel_count(&mut self) -> Result<u32, GigeError> {
2142 self.read_u32(consts::NUMBER_OF_STREAM_CHANNELS).await
2143 }
2144
2145 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 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 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 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 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; 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 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 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 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 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 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 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 fn golden_discovery_payload() -> Vec<u8> {
2438 let mut p = vec![0u8; 248];
2439 p[0..2].copy_from_slice(&2u16.to_be_bytes()); p[2..4].copy_from_slice(&1u16.to_be_bytes()); p[4..8].copy_from_slice(&0u32.to_be_bytes()); p[10..16].copy_from_slice(&[0x00, 0x0C, 0xDF, 0x06, 0x5B, 0x2F]); p[16..20].copy_from_slice(&7u32.to_be_bytes()); p[20..24].copy_from_slice(&5u32.to_be_bytes()); p[36..40].copy_from_slice(&[169, 254, 78, 62]); p[52..56].copy_from_slice(&[255, 255, 0, 0]); p[68..72].copy_from_slice(&[169, 254, 0, 1]); 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"); put(&mut p, 104, "FS-3200T-10GE-NNC"); put(&mut p, 136, "1.2.3"); put(&mut p, 168, "mfr-specific"); put(&mut p, 216, "SN-12345"); put(&mut p, 232, "left-camera"); 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 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 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 #[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 #[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 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 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 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 assert!(parse_discovery_ack(&ack(0, consts::DISCOVERY_ACK, 0x0100), 0x0100).is_some());
2548 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 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 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()); buf.extend_from_slice(&consts::PENDING_ACK.to_be_bytes()); buf.extend_from_slice(&4u16.to_be_bytes()); buf.extend_from_slice(&request_id.to_be_bytes());
2581 buf.extend_from_slice(&0u16.to_be_bytes()); buf.extend_from_slice(&millis.to_be_bytes()); 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 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 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 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 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 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 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 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 #[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 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 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 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 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 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 assert_eq!(single_register_address(0x0a02, 4), None);
2855 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 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 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 assert_eq!(encoded[0], GVCP_CMD_KEY);
2889 assert_eq!(encoded[1], 0x01); 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 assert_eq!(&payload[2..8], &mac);
2906 assert_eq!(&payload[20..24], &ip.octets());
2908 assert_eq!(&payload[36..40], &subnet.octets());
2910 assert_eq!(&payload[52..56], &gateway.octets());
2912 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 #[test]
2938 fn packet_resend_has_the_12_byte_standard_layout() {
2939 #[rustfmt::skip]
2940 let expected: &[u8] = &[
2941 0x42, 0x00, 0x00, 0x40, 0x00, 0x0C, 0x12, 0x34, 0x00, 0x02, 0xBE, 0xEF, 0x00, 0x00, 0x00, 0x05, 0x00, 0x12, 0x34, 0x56, ];
2950 assert_eq!(
2951 encode_packet_resend(0x1234, 2, 0xBEEF, 5, 0x12_3456, false).as_ref(),
2952 expected
2953 );
2954 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, 0x00, 0x40, 0x00, 0x14, 0x00, 0x07, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x05, 0x01, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, ];
2973 assert_eq!(
2974 encode_packet_resend(7, 1, (1 << 32) | 2, 0x0100_0005, 0x0100_0009, true).as_ref(),
2975 expected
2976 );
2977 }
2978}