Skip to main content

viva_gige/
action.rs

1//! GVCP action command helpers.
2
3use std::collections::HashSet;
4use std::io;
5use std::io::ErrorKind;
6use std::net::{IpAddr, Ipv4Addr, SocketAddr};
7use std::time::{Duration, Instant};
8
9use bytes::{BufMut, BytesMut};
10use tokio::net::UdpSocket;
11use tokio::time;
12use tracing::{debug, info, trace, warn};
13
14use crate::consts;
15use crate::gvcp::{GVCP_PORT, GvcpAckHeader, GvcpRequestHeader};
16
17/// Size of an unscheduled action command payload in bytes.
18///
19/// `device_key` + `group_key` + `group_mask`, per the GigE Vision `ACTION_CMD`
20/// field table (Wireshark's `dissect_action_cmd` reads exactly these three).
21const ACTION_PAYLOAD: usize = 12;
22/// Size of a scheduled action command payload in bytes.
23///
24/// The base payload plus a 64-bit action time at offset 12, present only when
25/// bit 7 of the GVCP flags byte is set.
26const ACTION_PAYLOAD_SCHEDULED: usize = ACTION_PAYLOAD + 8;
27
28/// Parameters used to construct an action command.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ActionParams {
31    /// Vendor-specific device key used to authorise the action.
32    pub device_key: u32,
33    /// Group key identifying which devices should react to the action.
34    pub group_key: u32,
35    /// Group mask applied to the device key by receivers.
36    pub group_mask: u32,
37    /// Optional scheduled time expressed in device clock ticks.
38    ///
39    /// `Some` selects a scheduled action command: the time is appended to the
40    /// payload and bit 7 of the GVCP flags byte is set. A device that does not
41    /// implement scheduled actions rejects it, so leave this `None` unless the
42    /// camera advertises `GevSupportedOptionScheduledAction`.
43    pub scheduled_time: Option<u64>,
44}
45
46/// Summary of the broadcast performed by [`send_action`].
47#[derive(Debug, Default, Clone, PartialEq, Eq)]
48#[non_exhaustive]
49pub struct AckSummary {
50    /// Number of GVCP datagrams transmitted.
51    pub sent: usize,
52    /// Number of distinct acknowledgement sources observed.
53    pub acks: usize,
54    /// Devices that answered with an error status instead, each once.
55    pub refusals: Vec<ActionRefusal>,
56}
57
58/// A device's error answer to an action command: an Allied Vision Manta
59/// G-125B, whose GVCP Capability lacks the action bit, answered
60/// `NOT_IMPLEMENTED` under the command's own opcode, `0x0100`, rather than
61/// under `ACTION_ACK`.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct ActionRefusal {
64    /// Who answered.
65    pub source: IpAddr,
66    /// The status it answered with.
67    pub status: crate::GigeStatus,
68}
69
70fn encode_payload(params: &ActionParams) -> BytesMut {
71    let mut buf = BytesMut::with_capacity(ACTION_PAYLOAD_SCHEDULED);
72    buf.put_u32(params.device_key);
73    buf.put_u32(params.group_key);
74    buf.put_u32(params.group_mask);
75    // The action time is not a fixed field padded with zeros: an unscheduled
76    // command is 12 bytes and stops here. Sending the extra 8 bytes anyway
77    // makes the payload length disagree with the flags byte.
78    if let Some(ticks) = params.scheduled_time {
79        buf.put_u64(ticks);
80    }
81    buf
82}
83
84fn parse_ack(buf: &[u8]) -> io::Result<GvcpAckHeader> {
85    if buf.len() < 8 {
86        return Err(io::Error::new(
87            ErrorKind::InvalidData,
88            "acknowledgement shorter than GVCP header",
89        ));
90    }
91    let status = u16::from_be_bytes([buf[0], buf[1]]);
92    let opcode = u16::from_be_bytes([buf[2], buf[3]]);
93    let length = u16::from_be_bytes([buf[4], buf[5]]);
94    let request_id = u16::from_be_bytes([buf[6], buf[7]]);
95    Ok(GvcpAckHeader {
96        status: crate::GigeStatus::from_raw(status),
97        command: opcode,
98        length,
99        request_id,
100    })
101}
102
103fn is_broadcast(addr: &SocketAddr) -> bool {
104    matches!(addr.ip(), IpAddr::V4(ip) if ip == Ipv4Addr::BROADCAST)
105}
106
107/// Send a GVCP action command and collect acknowledgements.
108pub async fn send_action(
109    broadcast: SocketAddr,
110    params: &ActionParams,
111    timeout_ms: u64,
112) -> io::Result<AckSummary> {
113    let destination = SocketAddr::new(broadcast.ip(), GVCP_PORT);
114    let local_ip = match destination.ip() {
115        IpAddr::V4(_) => IpAddr::V4(Ipv4Addr::UNSPECIFIED),
116        IpAddr::V6(_) => {
117            return Err(io::Error::new(
118                ErrorKind::InvalidInput,
119                "IPv6 destinations are not supported for actions",
120            ));
121        }
122    };
123    let socket = UdpSocket::bind(SocketAddr::new(local_ip, 0)).await?;
124    // Every broadcast needs it, a subnet's own (192.168.2.255) as much as
125    // the limited one, and only a socket can tell which address is which:
126    // without it, macOS refuses a send to a subnet broadcast (`EACCES`).
127    socket.set_broadcast(true)?;
128
129    let mut summary = AckSummary::default();
130    let payload = encode_payload(params);
131    let request_id = fastrand::u16(0x8000..=0xFFFE);
132    let mut flags = viva_gencp::CommandFlags::ACK_REQUIRED;
133    if is_broadcast(&destination) {
134        flags |= viva_gencp::CommandFlags::BROADCAST;
135    }
136    if params.scheduled_time.is_some() {
137        flags |= viva_gencp::CommandFlags::SCHEDULED_ACTION;
138    }
139    let header = GvcpRequestHeader {
140        flags,
141        command: consts::ACTION_COMMAND,
142        length: payload.len() as u16,
143        request_id,
144    };
145    let packet = header.encode(&payload);
146    trace!(bytes = packet.len(), %destination, request_id, "sending action command");
147    socket.send_to(&packet, destination).await?;
148    summary.sent = 1;
149
150    let timeout = Duration::from_millis(timeout_ms);
151    if timeout.is_zero() {
152        info!(acks = 0, "action command sent (no wait)");
153        return Ok(summary);
154    }
155
156    let start = Instant::now();
157    let mut buf = vec![0u8; 512];
158    let mut seen = HashSet::new();
159    while let Some(remaining) = timeout.checked_sub(start.elapsed()) {
160        if remaining.is_zero() {
161            break;
162        }
163        match time::timeout(remaining, socket.recv_from(&mut buf)).await {
164            Ok(Ok((len, src))) => {
165                trace!(bytes = len, %src, "received acknowledgement");
166                let header = parse_ack(&buf[..len])?;
167                if header.request_id != request_id {
168                    debug!(
169                        expected = request_id,
170                        got = header.request_id,
171                        "acknowledgement id mismatch"
172                    );
173                    continue;
174                }
175                // A refusal may come back under the command's own opcode.
176                if !matches!(header.command, consts::ACTION_ACK | consts::ACTION_COMMAND) {
177                    debug!(
178                        opcode = header.command,
179                        "ignoring unrelated acknowledgement"
180                    );
181                    continue;
182                }
183                if !header.status.is_success() {
184                    warn!(status = %header.status, %src, "device refused the action command");
185                    if !summary.refusals.iter().any(|r| r.source == src.ip()) {
186                        summary.refusals.push(ActionRefusal {
187                            source: src.ip(),
188                            status: header.status,
189                        });
190                    }
191                    continue;
192                }
193                if header.command == consts::ACTION_ACK && seen.insert(src.ip()) {
194                    summary.acks += 1;
195                }
196            }
197            Ok(Err(err)) => {
198                warn!(?err, "error receiving acknowledgement");
199                break;
200            }
201            Err(_) => break,
202        }
203    }
204
205    info!(
206        acks = summary.acks,
207        refused = summary.refusals.len(),
208        "action command completed"
209    );
210    Ok(summary)
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    fn params() -> ActionParams {
218        ActionParams {
219            device_key: 0x1122_3344,
220            group_key: 0x5566_7788,
221            group_mask: 0xFFFF_0000,
222            scheduled_time: None,
223        }
224    }
225
226    /// The whole datagram, byte for byte, written out from the GigE Vision
227    /// `ACTION_CMD` field table rather than from our own encoder.
228    ///
229    /// This is the fixture that would have caught the 0x0080 collision: the
230    /// opcode is a literal here, so an encoder that emits `READREG` fails
231    /// rather than agreeing with itself (ADR-0019).
232    #[test]
233    fn unscheduled_action_matches_spec_bytes() {
234        let payload = encode_payload(&params());
235        let packet = GvcpRequestHeader {
236            flags: viva_gencp::CommandFlags::ACK_REQUIRED,
237            command: consts::ACTION_COMMAND,
238            length: payload.len() as u16,
239            request_id: 0xBEEF,
240        }
241        .encode(&payload);
242
243        #[rustfmt::skip]
244        let expected: [u8; 20] = [
245            0x42,                   // command key
246            0x01,                   // flags: acknowledge required
247            0x01, 0x00,             // ACTION_CMD — *not* 0x0080 (READREG)
248            0x00, 0x0C,             // length: 12, no action time
249            0xBE, 0xEF,             // request id
250            0x11, 0x22, 0x33, 0x44, // device key
251            0x55, 0x66, 0x77, 0x88, // group key
252            0xFF, 0xFF, 0x00, 0x00, // group mask
253        ];
254        assert_eq!(&packet[..], &expected[..]);
255    }
256
257    /// A scheduled action appends the 64-bit time *and* sets flags bit 7.
258    /// Either one alone is a malformed command.
259    #[test]
260    fn scheduled_action_sets_flag_and_appends_time() {
261        let mut p = params();
262        p.scheduled_time = Some(0x0102_0304_0506_0708);
263        let payload = encode_payload(&p);
264        let mut flags = viva_gencp::CommandFlags::ACK_REQUIRED;
265        flags |= viva_gencp::CommandFlags::SCHEDULED_ACTION;
266        let packet = GvcpRequestHeader {
267            flags,
268            command: consts::ACTION_COMMAND,
269            length: payload.len() as u16,
270            request_id: 0xBEEF,
271        }
272        .encode(&payload);
273
274        #[rustfmt::skip]
275        let expected: [u8; 28] = [
276            0x42,
277            0x81,                   // flags: acknowledge required | scheduled
278            0x01, 0x00,
279            0x00, 0x14,             // length: 20
280            0xBE, 0xEF,
281            0x11, 0x22, 0x33, 0x44,
282            0x55, 0x66, 0x77, 0x88,
283            0xFF, 0xFF, 0x00, 0x00,
284            0x01, 0x02, 0x03, 0x04, // action time, big-endian u64
285            0x05, 0x06, 0x07, 0x08,
286        ];
287        assert_eq!(&packet[..], &expected[..]);
288        assert_eq!(payload.len(), ACTION_PAYLOAD_SCHEDULED);
289    }
290
291    #[test]
292    fn unscheduled_payload_stops_at_twelve_bytes() {
293        assert_eq!(encode_payload(&params()).len(), ACTION_PAYLOAD);
294    }
295
296    /// The two opcodes an action must never be confused with.
297    #[test]
298    fn action_opcodes_do_not_collide_with_register_access() {
299        assert_eq!(consts::ACTION_COMMAND, 0x0100);
300        assert_eq!(consts::ACTION_ACK, 0x0101);
301        assert_ne!(consts::ACTION_COMMAND, 0x0080); // READREG_CMD
302        assert_ne!(consts::ACTION_ACK, 0x0081); // READREG_ACK
303    }
304
305    #[test]
306    fn ack_parser() {
307        let mut buf = BytesMut::with_capacity(8);
308        buf.put_u16(viva_gencp::StatusCode::Success.to_raw());
309        buf.put_u16(consts::ACTION_ACK);
310        buf.put_u16(0);
311        buf.put_u16(0xBEEF);
312        let ack = parse_ack(&buf).expect("ack");
313        assert_eq!(ack.command, consts::ACTION_ACK);
314        assert_eq!(ack.request_id, 0xBEEF);
315    }
316}