Skip to main content

viva_gige/
message.rs

1//! GVCP message/event channel handling.
2//!
3//! A device delivers events to the controller as GVCP **commands** on the
4//! message channel — `EVENT_CMD` (0x00C0) for bare notifications and
5//! `EVENTDATA_CMD` (0x00C2) when the event carries device-specific data. Both
6//! are commands, so a datagram begins with the 0x42 key byte and a flags byte,
7//! not with a status code, and both may ask the controller to acknowledge.
8//!
9//! One `EVENT_CMD` can pack several events: the payload is an array of
10//! fixed-size entries, 16 bytes each with 16-bit block IDs or 24 bytes each
11//! when the device sets the extended-ID flag (GigE Vision 2.0). Layout per
12//! entry, from the GigE Vision field table and corroborated by Wireshark's
13//! `dissect_event_cmd`:
14//!
15//! ```text
16//! 16-bit block IDs (16 bytes)      64-bit block IDs (24 bytes)
17//!  0  reserved            u16       0  reserved            u16
18//!  2  event identifier    u16       2  event identifier    u16
19//!  4  stream channel      u16       4  stream channel      u16
20//!  6  block id            u16       6  reserved            u16
21//!  8  timestamp           u64       8  block id            u64
22//!                                  16  timestamp           u64
23//! ```
24
25use std::collections::{HashMap, VecDeque};
26use std::io;
27use std::io::ErrorKind;
28use std::net::{IpAddr, SocketAddr, UdpSocket as StdUdpSocket};
29use std::sync::Arc;
30use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
31use std::time::Duration;
32
33use bytes::Bytes;
34#[cfg(test)]
35use bytes::{BufMut, BytesMut};
36use socket2::{Domain, Protocol, Socket, Type};
37use tokio::sync::Notify;
38use tracing::{debug, info, trace, warn};
39
40use crate::consts as gvcp;
41
42/// Constants related to GVCP message packets. Events arrive as commands from
43/// the device, not as acknowledgements — which is why the first two bytes are
44/// the key and the flags, and not a status code.
45mod consts {
46    pub(super) use crate::consts::{FLAG_ACK_REQUIRED, FLAG_EXTENDED_IDS, GVCP_CMD_KEY};
47    /// Size of the GVCP message header in bytes.
48    pub(super) const GVCP_HEADER: usize = crate::consts::GVCP_HEADER_SIZE;
49    /// Default receive buffer size requested for the UDP socket (bytes).
50    pub(super) const DEFAULT_RCVBUF: usize = 1 << 20; // 1 MiB.
51    /// Maximum datagram size accepted on the event channel (bytes).
52    pub(super) const MAX_EVENT_SIZE: usize = 2048;
53}
54
55/// Header of a datagram received on the GVCP message channel.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57struct MessageHeader {
58    command: u16,
59    length: usize,
60    request_id: u16,
61    ack_required: bool,
62    extended_ids: bool,
63}
64
65impl MessageHeader {
66    fn parse(data: &[u8]) -> io::Result<Self> {
67        if data.len() < consts::GVCP_HEADER {
68            return Err(io::Error::new(ErrorKind::InvalidData, "packet too short"));
69        }
70        if data.len() > consts::MAX_EVENT_SIZE {
71            return Err(io::Error::new(ErrorKind::InvalidData, "packet too large"));
72        }
73        if data[0] != consts::GVCP_CMD_KEY {
74            return Err(io::Error::new(
75                ErrorKind::InvalidData,
76                "not a GVCP command packet",
77            ));
78        }
79        let flags = data[1];
80        let command = u16::from_be_bytes([data[2], data[3]]);
81        let length = u16::from_be_bytes([data[4], data[5]]) as usize;
82        let request_id = u16::from_be_bytes([data[6], data[7]]);
83
84        if !matches!(command, gvcp::EVENT_COMMAND | gvcp::EVENTDATA_COMMAND) {
85            return Err(io::Error::new(
86                ErrorKind::InvalidData,
87                "unexpected opcode for event packet",
88            ));
89        }
90        if length + consts::GVCP_HEADER != data.len() {
91            return Err(io::Error::new(ErrorKind::InvalidData, "length mismatch"));
92        }
93
94        Ok(Self {
95            command,
96            length,
97            request_id,
98            ack_required: flags & consts::FLAG_ACK_REQUIRED != 0,
99            extended_ids: flags & consts::FLAG_EXTENDED_IDS != 0,
100        })
101    }
102
103    /// Opcode of the acknowledgement this command expects.
104    fn ack_opcode(&self) -> u16 {
105        match self.command {
106            gvcp::EVENTDATA_COMMAND => gvcp::EVENTDATA_ACK,
107            _ => gvcp::EVENT_ACK,
108        }
109    }
110
111    /// Size of one event entry given the extended-ID flag.
112    fn entry_size(&self) -> usize {
113        if self.extended_ids {
114            gvcp::EVENT_ENTRY_EXTENDED
115        } else {
116            gvcp::EVENT_ENTRY
117        }
118    }
119}
120
121/// Parsed representation of a single GVCP event.
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub struct EventPacket {
124    /// Source address of the datagram.
125    pub src: SocketAddr,
126    /// Event identifier reported by the device.
127    pub event_id: u16,
128    /// Device timestamp carried by the event (ticks).
129    pub timestamp_dev: u64,
130    /// Stream channel associated with the event.
131    pub stream_channel: u16,
132    /// GVSP block identifier associated with the event.
133    ///
134    /// 16-bit on GigE Vision 1.x devices, widened here so a 2.0 device using
135    /// extended block IDs fits without a second type.
136    pub block_id: u64,
137    /// Event data following the entry, empty for a bare `EVENT_CMD`.
138    pub payload: Bytes,
139    /// The whole event as the device sent it — the 16- or 24-byte entry, then
140    /// any data — which is what a GenApi event port addresses: every corpus
141    /// document that names an event's timestamp puts it at offset 0x8 of
142    /// this, where the 16-bit-block-id entry has it (ADR-0026).
143    pub raw: Bytes,
144}
145
146impl EventPacket {
147    /// Decode one event entry. `entry` must be at least `header.entry_size()`;
148    /// `raw` is the entry with any data after it.
149    fn parse_entry(
150        src: SocketAddr,
151        header: &MessageHeader,
152        entry: &[u8],
153        payload: Bytes,
154        raw: Bytes,
155    ) -> Self {
156        let event_id = u16::from_be_bytes([entry[2], entry[3]]);
157        let stream_channel = u16::from_be_bytes([entry[4], entry[5]]);
158        let (block_id, ts_at) = if header.extended_ids {
159            // entry[6..8] is reserved in the extended layout.
160            let id = u64::from_be_bytes([
161                entry[8], entry[9], entry[10], entry[11], entry[12], entry[13], entry[14],
162                entry[15],
163            ]);
164            (id, 16)
165        } else {
166            (u64::from(u16::from_be_bytes([entry[6], entry[7]])), 8)
167        };
168        let timestamp_dev = u64::from_be_bytes([
169            entry[ts_at],
170            entry[ts_at + 1],
171            entry[ts_at + 2],
172            entry[ts_at + 3],
173            entry[ts_at + 4],
174            entry[ts_at + 5],
175            entry[ts_at + 6],
176            entry[ts_at + 7],
177        ]);
178        Self {
179            src,
180            event_id,
181            timestamp_dev,
182            stream_channel,
183            block_id,
184            payload,
185            raw,
186        }
187    }
188
189    /// Decode every event carried by one message-channel datagram.
190    fn parse_datagram(src: SocketAddr, data: &[u8]) -> io::Result<(MessageHeader, Vec<Self>)> {
191        let header = MessageHeader::parse(data)?;
192        let entry_size = header.entry_size();
193        let body = &data[consts::GVCP_HEADER..];
194
195        if body.len() < entry_size {
196            return Err(io::Error::new(
197                ErrorKind::InvalidData,
198                "event payload shorter than one entry",
199            ));
200        }
201
202        let events = if header.command == gvcp::EVENTDATA_COMMAND {
203            // One entry, then device-specific data to the end of the datagram.
204            // Packing several variable-length events into one EVENTDATA_CMD
205            // needs the GEV 2.1 per-event size field, which we do not read;
206            // no corpus device has been observed doing it.
207            let raw = Bytes::copy_from_slice(body);
208            let payload = raw.slice(entry_size..);
209            vec![Self::parse_entry(src, &header, body, payload, raw)]
210        } else {
211            if header.length % entry_size != 0 {
212                return Err(io::Error::new(
213                    ErrorKind::InvalidData,
214                    "event payload is not a whole number of entries",
215                ));
216            }
217            body.chunks_exact(entry_size)
218                .map(|entry| {
219                    let raw = Bytes::copy_from_slice(entry);
220                    Self::parse_entry(src, &header, entry, Bytes::new(), raw)
221                })
222                .collect()
223        };
224
225        Ok((header, events))
226    }
227}
228
229/// Build the acknowledgement for a message-channel command.
230///
231/// GVCP acknowledgements carry no payload here: status, opcode, a zero length
232/// and the request id the device used.
233fn encode_ack(ack_opcode: u16, request_id: u16) -> [u8; consts::GVCP_HEADER] {
234    let mut buf = [0u8; consts::GVCP_HEADER];
235    buf[0..2].copy_from_slice(&viva_gencp::StatusCode::Success.to_raw().to_be_bytes());
236    buf[2..4].copy_from_slice(&ack_opcode.to_be_bytes());
237    buf[4..6].copy_from_slice(&0u16.to_be_bytes());
238    buf[6..8].copy_from_slice(&request_id.to_be_bytes());
239    buf
240}
241
242/// Events kept for the application before the oldest is dropped.
243pub const EVENT_QUEUE_CAPACITY: usize = 1024;
244
245/// How long the receive thread waits for a datagram before checking whether
246/// to stop.
247const RECEIVE_TICK: Duration = Duration::from_millis(20);
248
249/// What a GVCP message channel has received, counted by its receive thread.
250#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
251#[non_exhaustive]
252pub struct EventStats {
253    /// Datagrams that parsed as `EVENT_CMD` or `EVENTDATA_CMD`, copies
254    /// included.
255    pub messages: u64,
256    /// Messages that asked for an acknowledgement and were sent one.
257    pub acknowledged: u64,
258    /// Copies of the message before them, the device's retransmissions:
259    /// acknowledged again, their events not queued twice.
260    pub retransmissions: u64,
261    /// Events queued for the application.
262    pub events: u64,
263    /// Events dropped, oldest first, because the application left
264    /// [`EVENT_QUEUE_CAPACITY`] of them unread.
265    pub dropped: u64,
266    /// Datagrams that were not an event message.
267    pub malformed: u64,
268}
269
270#[derive(Default)]
271struct Counters {
272    messages: AtomicU64,
273    acknowledged: AtomicU64,
274    retransmissions: AtomicU64,
275    events: AtomicU64,
276    dropped: AtomicU64,
277    malformed: AtomicU64,
278}
279
280struct QueueState {
281    events: VecDeque<EventPacket>,
282    /// The receive thread's failure, reported once after the queue drains.
283    failed: Option<io::Error>,
284    /// The receive thread stopped.
285    ended: bool,
286}
287
288/// State a socket shares with its receive thread.
289struct Shared {
290    queue: std::sync::Mutex<QueueState>,
291    notify: Notify,
292    stop: AtomicBool,
293    counters: Counters,
294    capacity: usize,
295}
296
297impl Shared {
298    fn lock(&self) -> std::sync::MutexGuard<'_, QueueState> {
299        // A thread that panicked holding the lock left a queue of values,
300        // still coherent.
301        self.queue.lock().unwrap_or_else(|e| e.into_inner())
302    }
303}
304
305/// A GVCP message channel: the socket a device sends its events to.
306///
307/// Binding starts a receive thread. It **acknowledges each message as it
308/// arrives**, whether or not the application is reading, and queues its
309/// events for [`recv`](Self::recv), up to [`EVENT_QUEUE_CAPACITY`]; past
310/// that the oldest is dropped, counted in [`EventStats::dropped`] and
311/// logged. A device whose acknowledgement does not come resends the message
312/// every `GevMCTT` and holds back the events behind it: an Allied Vision
313/// Manta G-125B (`GevMCTT` 100 ms) sent one `ExposureEnd` twelve times to an
314/// application that read a second late when the acknowledgement waited for
315/// the read, and, left unread for ten seconds, kept 44 events and sent
316/// `EventOverflow` for the rest.
317///
318/// A retransmission repeats the request id and the bytes of the message
319/// before it; it is acknowledged again and its events are not queued twice.
320/// Distinct events under one request id are each queued. Dropping the
321/// socket stops the thread within one tick.
322pub struct EventSocket {
323    shared: Arc<Shared>,
324    local: SocketAddr,
325    thread: Option<std::thread::JoinHandle<()>>,
326}
327
328impl EventSocket {
329    /// Bind a GVCP message socket on the provided local address and start
330    /// its receive thread.
331    pub async fn bind(local_ip: IpAddr, port: u16) -> io::Result<Self> {
332        Self::bind_with_capacity(local_ip, port, EVENT_QUEUE_CAPACITY)
333    }
334
335    fn bind_with_capacity(local_ip: IpAddr, port: u16, capacity: usize) -> io::Result<Self> {
336        let domain = match local_ip {
337            IpAddr::V4(_) => Domain::IPV4,
338            IpAddr::V6(_) => Domain::IPV6,
339        };
340        let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
341        socket.set_reuse_address(true)?;
342        socket.set_nonblocking(true)?;
343        if let Err(err) = socket.set_recv_buffer_size(consts::DEFAULT_RCVBUF) {
344            warn!(?err, "failed to grow GVCP message buffer");
345        }
346        let addr = SocketAddr::new(local_ip, port);
347        socket.bind(&addr.into())?;
348        let socket: StdUdpSocket = socket.into();
349        let local = socket.local_addr()?;
350        info!(local = %local, "bound GVCP message socket");
351        let shared = Arc::new(Shared {
352            queue: std::sync::Mutex::new(QueueState {
353                events: VecDeque::new(),
354                failed: None,
355                ended: false,
356            }),
357            notify: Notify::new(),
358            stop: AtomicBool::new(false),
359            counters: Counters::default(),
360            capacity: capacity.max(1),
361        });
362        let thread = {
363            let shared = Arc::clone(&shared);
364            std::thread::Builder::new()
365                .name("viva-gige-events".into())
366                .spawn(move || receive_loop(&socket, &shared))?
367        };
368        Ok(Self {
369            shared,
370            local,
371            thread: Some(thread),
372        })
373    }
374
375    /// The next event, waiting until one arrives. Events come in the order
376    /// the device sent them; a datagram carrying several is queued whole.
377    ///
378    /// Cancel-safe: an event is taken only by the poll that returns it.
379    /// Concurrent callers are symmetric consumers of one queue. An error
380    /// once the receive thread has failed, after the events it queued.
381    pub async fn recv(&self) -> io::Result<EventPacket> {
382        loop {
383            let notified = self.shared.notify.notified();
384            tokio::pin!(notified);
385            // Register before checking, so an event queued in between still
386            // wakes us.
387            notified.as_mut().enable();
388            if let Some(result) = self.try_take() {
389                return result;
390            }
391            notified.await;
392        }
393    }
394
395    /// The next event if one is queued: `None` when none is, an error once
396    /// the receive thread has failed or stopped.
397    fn try_take(&self) -> Option<io::Result<EventPacket>> {
398        let mut state = self.shared.lock();
399        if let Some(event) = state.events.pop_front() {
400            return Some(Ok(event));
401        }
402        if let Some(err) = state.failed.take() {
403            return Some(Err(err));
404        }
405        state.ended.then(|| {
406            Err(io::Error::new(
407                ErrorKind::BrokenPipe,
408                "the GVCP message channel's receive thread has stopped",
409            ))
410        })
411    }
412
413    /// What the receive thread has counted so far.
414    pub fn stats(&self) -> EventStats {
415        let c = &self.shared.counters;
416        EventStats {
417            messages: c.messages.load(Ordering::Relaxed),
418            acknowledged: c.acknowledged.load(Ordering::Relaxed),
419            retransmissions: c.retransmissions.load(Ordering::Relaxed),
420            events: c.events.load(Ordering::Relaxed),
421            dropped: c.dropped.load(Ordering::Relaxed),
422            malformed: c.malformed.load(Ordering::Relaxed),
423        }
424    }
425
426    /// Return the local address bound to the socket.
427    pub fn local_addr(&self) -> io::Result<SocketAddr> {
428        Ok(self.local)
429    }
430}
431
432impl Drop for EventSocket {
433    fn drop(&mut self) {
434        self.shared.stop.store(true, Ordering::Release);
435        if let Some(thread) = self.thread.take() {
436            let _ = thread.join();
437        }
438    }
439}
440
441/// The receive thread: read, acknowledge, queue, until told to stop or the
442/// socket fails.
443fn receive_loop(socket: &StdUdpSocket, shared: &Shared) {
444    let mut buffer = vec![0u8; consts::MAX_EVENT_SIZE];
445    let mut last_message: HashMap<SocketAddr, (u16, Vec<u8>)> = HashMap::new();
446    let mut warned_overflow = false;
447    let failure = loop {
448        if shared.stop.load(Ordering::Acquire) {
449            break None;
450        }
451        match crate::nic::wait_readable(socket, RECEIVE_TICK) {
452            Ok(false) => continue,
453            Ok(true) => {}
454            Err(err) => break Some(err),
455        }
456        // Drain everything the socket holds before waiting again.
457        let failed = loop {
458            match socket.recv_from(&mut buffer) {
459                Ok((len, src)) => handle_datagram(
460                    socket,
461                    shared,
462                    &buffer[..len],
463                    src,
464                    &mut last_message,
465                    &mut warned_overflow,
466                ),
467                Err(err) if err.kind() == ErrorKind::WouldBlock => break None,
468                Err(err) if err.kind() == ErrorKind::Interrupted => {}
469                // An ICMP reply to an acknowledgement, reported on the next
470                // read: the socket is still good (SR-22).
471                Err(err)
472                    if matches!(
473                        err.kind(),
474                        ErrorKind::ConnectionReset | ErrorKind::ConnectionRefused
475                    ) =>
476                {
477                    debug!(error = %err, "ignoring a connection reset on the GVCP message socket");
478                }
479                Err(err) => break Some(err),
480            }
481        };
482        if failed.is_some() {
483            break failed;
484        }
485    };
486    let mut state = shared.lock();
487    if let Some(err) = failure {
488        warn!(error = %err, "GVCP message socket receive failed; no more events");
489        state.failed = Some(err);
490    }
491    state.ended = true;
492    drop(state);
493    shared.notify.notify_waiters();
494}
495
496/// One datagram: acknowledge it if asked, then queue its events unless it
497/// repeats the message before it.
498fn handle_datagram(
499    socket: &StdUdpSocket,
500    shared: &Shared,
501    data: &[u8],
502    src: SocketAddr,
503    last_message: &mut HashMap<SocketAddr, (u16, Vec<u8>)>,
504    warned_overflow: &mut bool,
505) {
506    trace!(bytes = data.len(), %src, "received GVCP message");
507    let counters = &shared.counters;
508    let (header, events) = match EventPacket::parse_datagram(src, data) {
509        Ok(parsed) => parsed,
510        Err(err) => {
511            counters.malformed.fetch_add(1, Ordering::Relaxed);
512            warn!(%src, error = %err, "discarding malformed event packet");
513            return;
514        }
515    };
516    counters.messages.fetch_add(1, Ordering::Relaxed);
517    if header.ack_required {
518        let ack = encode_ack(header.ack_opcode(), header.request_id);
519        match socket.send_to(&ack, src) {
520            Ok(_) => {
521                counters.acknowledged.fetch_add(1, Ordering::Relaxed);
522                trace!(%src, request_id = header.request_id, "acknowledged event");
523            }
524            Err(err) => warn!(%src, error = %err, "failed to acknowledge event"),
525        }
526    }
527    // A retransmission repeats both the request id and the events: a device
528    // that reuses one request id for distinct events still has them
529    // delivered, since their timestamps differ.
530    let message = (header.request_id, data[consts::GVCP_HEADER..].to_vec());
531    if last_message.insert(src, message.clone()).as_ref() == Some(&message) {
532        counters.retransmissions.fetch_add(1, Ordering::Relaxed);
533        debug!(%src, request_id = header.request_id, "dropping a retransmitted event");
534        return;
535    }
536    if events.is_empty() {
537        return;
538    }
539    let count = events.len() as u64;
540    let dropped = {
541        let mut state = shared.lock();
542        state.events.extend(events);
543        let excess = state.events.len().saturating_sub(shared.capacity);
544        state.events.drain(..excess);
545        excess as u64
546    };
547    counters.events.fetch_add(count, Ordering::Relaxed);
548    debug!(events = count, %src, "queueing GVCP events");
549    if dropped > 0 {
550        let total = counters.dropped.fetch_add(dropped, Ordering::Relaxed) + dropped;
551        if !*warned_overflow {
552            *warned_overflow = true;
553            warn!(
554                capacity = shared.capacity,
555                "events arrive faster than the application reads them; dropping the oldest \
556                 (counted in EventStats::dropped)"
557            );
558        } else {
559            debug!(dropped = total, "dropped unread events");
560        }
561    }
562    shared.notify.notify_waiters();
563}
564
565#[cfg(test)]
566mod tests {
567    use super::*;
568    use std::net::Ipv4Addr;
569    use tokio::net::UdpSocket;
570
571    fn src() -> SocketAddr {
572        SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 3956)
573    }
574
575    /// One `EVENT_CMD` with a single 16-byte entry, written out from the field
576    /// table rather than produced by our own encoder (ADR-0019).
577    ///
578    /// Every field in this fixture used to land somewhere else: the parser read
579    /// the event id out of the reserved word, the timestamp out of the stream
580    /// channel and block id, and rejected the packet outright because it
581    /// expected opcode 0x000D — which is not a GVCP opcode at all.
582    #[rustfmt::skip]
583    const EVENT_CMD_GOLDEN: [u8; 24] = [
584        0x42,                   // command key
585        0x01,                   // flags: acknowledge required
586        0x00, 0xC0,             // EVENT_CMD
587        0x00, 0x10,             // length: one 16-byte entry
588        0xCA, 0xFE,             // request id
589        0x00, 0x00,             // reserved
590        0x12, 0x34,             // event identifier
591        0x00, 0x07,             // stream channel index
592        0x00, 0x08,             // block id (16-bit)
593        0x00, 0x02, 0x00, 0x03, // timestamp, big-endian u64
594        0x00, 0x04, 0x00, 0x05,
595    ];
596
597    #[test]
598    fn event_cmd_matches_spec_offsets() {
599        let (header, events) =
600            EventPacket::parse_datagram(src(), &EVENT_CMD_GOLDEN).expect("parse");
601        assert_eq!(header.command, gvcp::EVENT_COMMAND);
602        assert!(header.ack_required);
603        assert!(!header.extended_ids);
604        assert_eq!(events.len(), 1);
605        let ev = &events[0];
606        assert_eq!(ev.event_id, 0x1234);
607        assert_eq!(ev.stream_channel, 7);
608        assert_eq!(ev.block_id, 8);
609        assert_eq!(ev.timestamp_dev, 0x0002_0003_0004_0005);
610        assert!(ev.payload.is_empty());
611        assert_eq!(
612            &ev.raw[..],
613            &EVENT_CMD_GOLDEN[8..],
614            "the entry, header included"
615        );
616    }
617
618    /// The opcode the parser used to demand. 0x000D is in the GenCP register
619    /// range, not the GVCP event range, so no device ever sent it.
620    #[test]
621    fn event_opcodes_are_in_the_gvcp_event_range() {
622        assert_eq!(gvcp::EVENT_COMMAND, 0x00C0);
623        assert_eq!(gvcp::EVENT_ACK, 0x00C1);
624        assert_eq!(gvcp::EVENTDATA_COMMAND, 0x00C2);
625        assert_eq!(gvcp::EVENTDATA_ACK, 0x00C3);
626
627        let mut wrong = EVENT_CMD_GOLDEN;
628        wrong[2..4].copy_from_slice(&0x000Du16.to_be_bytes());
629        assert!(EventPacket::parse_datagram(src(), &wrong).is_err());
630    }
631
632    #[test]
633    fn multiple_events_in_one_datagram_are_all_returned() {
634        let mut buf = BytesMut::new();
635        buf.put_u8(consts::GVCP_CMD_KEY);
636        buf.put_u8(0);
637        buf.put_u16(gvcp::EVENT_COMMAND);
638        buf.put_u16((gvcp::EVENT_ENTRY * 3) as u16);
639        buf.put_u16(0x0001);
640        for i in 0..3u16 {
641            buf.put_u16(0); // reserved
642            buf.put_u16(0x1000 + i); // event id
643            buf.put_u16(i); // stream channel
644            buf.put_u16(100 + i); // block id
645            buf.put_u64(u64::from(i) + 1);
646        }
647        let (_, events) = EventPacket::parse_datagram(src(), &buf).expect("parse");
648        assert_eq!(events.len(), 3);
649        assert_eq!(
650            events.iter().map(|e| e.event_id).collect::<Vec<_>>(),
651            vec![0x1000, 0x1001, 0x1002]
652        );
653        assert_eq!(events[2].block_id, 102);
654        assert_eq!(events[2].timestamp_dev, 3);
655    }
656
657    #[test]
658    fn extended_block_ids_shift_the_timestamp() {
659        let mut buf = BytesMut::new();
660        buf.put_u8(consts::GVCP_CMD_KEY);
661        buf.put_u8(consts::FLAG_EXTENDED_IDS);
662        buf.put_u16(gvcp::EVENT_COMMAND);
663        buf.put_u16(gvcp::EVENT_ENTRY_EXTENDED as u16);
664        buf.put_u16(0x0002);
665        buf.put_u16(0); // reserved
666        buf.put_u16(0x4321); // event id
667        buf.put_u16(3); // stream channel
668        buf.put_u16(0); // reserved
669        buf.put_u64(0x0102_0304_0506_0708); // 64-bit block id
670        buf.put_u64(0x1122_3344_5566_7788); // timestamp
671
672        let (header, events) = EventPacket::parse_datagram(src(), &buf).expect("parse");
673        assert!(header.extended_ids);
674        assert_eq!(events[0].event_id, 0x4321);
675        assert_eq!(events[0].block_id, 0x0102_0304_0506_0708);
676        assert_eq!(events[0].timestamp_dev, 0x1122_3344_5566_7788);
677    }
678
679    #[test]
680    fn eventdata_carries_a_payload() {
681        let data = [0xAAu8, 0xBB, 0xCC, 0xDD];
682        let mut buf = BytesMut::new();
683        buf.put_u8(consts::GVCP_CMD_KEY);
684        buf.put_u8(0);
685        buf.put_u16(gvcp::EVENTDATA_COMMAND);
686        buf.put_u16((gvcp::EVENT_ENTRY + data.len()) as u16);
687        buf.put_u16(0x0003);
688        buf.put_u16(0);
689        buf.put_u16(0x0009);
690        buf.put_u16(1);
691        buf.put_u16(42);
692        buf.put_u64(0xDEAD_BEEF);
693        buf.extend_from_slice(&data);
694
695        let (header, events) = EventPacket::parse_datagram(src(), &buf).expect("parse");
696        assert_eq!(header.ack_opcode(), gvcp::EVENTDATA_ACK);
697        assert_eq!(events.len(), 1);
698        assert_eq!(events[0].event_id, 0x0009);
699        assert_eq!(events[0].block_id, 42);
700        assert_eq!(&events[0].payload[..], &data);
701        assert_eq!(
702            &events[0].raw[..],
703            &buf[8..],
704            "entry and data, as the device sent them"
705        );
706        assert_eq!(&events[0].raw[16..], &data);
707    }
708
709    #[test]
710    fn ack_matches_spec_bytes() {
711        let ack = encode_ack(gvcp::EVENT_ACK, 0xCAFE);
712        assert_eq!(ack, [0x00, 0x00, 0x00, 0xC1, 0x00, 0x00, 0xCA, 0xFE]);
713    }
714
715    /// Two concurrent receivers must share a multi-event datagram.
716    ///
717    /// Both tasks start while the queue is empty, so both get past the fast
718    /// path and one blocks on the receive lock. When the datagram lands, the
719    /// winner queues both events, and the loser wakes holding a lock it must
720    /// not carry into `recv_from` — the device has already said everything it
721    /// is going to say. Without the recheck after acquiring the receive lock
722    /// this hangs with an event sitting in the queue.
723    ///
724    /// It does *not* cover the narrower ordering the recheck depends on:
725    /// publishing the decoded events before releasing the receive lock. That
726    /// window is a few instructions wide, so no timing test holds it open
727    /// reliably — which is why the events are published in one step inside the
728    /// lock rather than split into a returned first and a queued remainder.
729    #[tokio::test(flavor = "multi_thread")]
730    async fn a_queued_event_is_not_stranded_behind_the_receive_lock() {
731        let sock = Arc::new(
732            EventSocket::bind(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)
733                .await
734                .expect("bind"),
735        );
736        let dest = sock.local_addr().expect("local addr");
737
738        let first = tokio::spawn({
739            let sock = Arc::clone(&sock);
740            async move { sock.recv().await.expect("first event") }
741        });
742        let second = tokio::spawn({
743            let sock = Arc::clone(&sock);
744            async move { sock.recv().await.expect("second event") }
745        });
746
747        // Let both tasks reach the receive lock before any data exists.
748        tokio::time::sleep(Duration::from_millis(50)).await;
749
750        let mut buf = BytesMut::new();
751        buf.put_u8(consts::GVCP_CMD_KEY);
752        // Ask for an acknowledgement, as a device wanting delivery confirmed
753        // does: the ack is sent while the receive lock is held, so this also
754        // covers that sending it does not stall the second consumer.
755        buf.put_u8(consts::FLAG_ACK_REQUIRED);
756        buf.put_u16(gvcp::EVENT_COMMAND);
757        buf.put_u16((gvcp::EVENT_ENTRY * 2) as u16);
758        buf.put_u16(0x0001);
759        for i in 0..2u16 {
760            buf.put_u16(0); // reserved
761            buf.put_u16(0x2000 + i); // event id
762            buf.put_u16(0); // stream channel
763            buf.put_u16(i); // block id
764            buf.put_u64(u64::from(i));
765        }
766        let sender = UdpSocket::bind("127.0.0.1:0").await.expect("sender");
767        sender.send_to(&buf, dest).await.expect("send");
768
769        let both = tokio::time::timeout(Duration::from_secs(5), async {
770            (first.await.expect("join"), second.await.expect("join"))
771        })
772        .await
773        .expect("both receivers finished");
774
775        let mut ids = [both.0.event_id, both.1.event_id];
776        ids.sort_unstable();
777        assert_eq!(ids, [0x2000, 0x2001]);
778    }
779
780    /// An Allied Vision Manta G-125B (`GevMCTT` 100 ms) sent one
781    /// `ExposureEnd` event eleven times, each with request id 1, to an
782    /// application that read it a second late: a device resends a message
783    /// until it is acknowledged, under the same request id. Each copy is
784    /// acknowledged, and the event is delivered once.
785    #[tokio::test(flavor = "multi_thread")]
786    async fn a_retransmitted_event_is_acknowledged_and_delivered_once() {
787        let sock = EventSocket::bind(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)
788            .await
789            .expect("bind");
790        let dest = sock.local_addr().expect("local addr");
791        let device = UdpSocket::bind("127.0.0.1:0").await.expect("device");
792        let event = |request_id: u16, block_id: u16| {
793            let mut copy = EVENT_CMD_GOLDEN;
794            copy[6..8].copy_from_slice(&request_id.to_be_bytes());
795            copy[14..16].copy_from_slice(&block_id.to_be_bytes());
796            copy
797        };
798        for _ in 0..3 {
799            device.send_to(&event(1, 8), dest).await.expect("send");
800        }
801        device.send_to(&event(2, 9), dest).await.expect("send");
802
803        let first = sock.recv().await.expect("first event");
804        let second = tokio::time::timeout(Duration::from_secs(2), sock.recv())
805            .await
806            .expect("the next event")
807            .expect("second event");
808        assert_eq!((first.block_id, second.block_id), (8, 9), "each once");
809
810        let mut acks = Vec::new();
811        let mut buf = [0u8; 64];
812        while let Ok(Ok((len, _))) =
813            tokio::time::timeout(Duration::from_millis(200), device.recv_from(&mut buf)).await
814        {
815            acks.push(u16::from_be_bytes([buf[6], buf[7]]));
816            assert_eq!(len, consts::GVCP_HEADER);
817        }
818        assert_eq!(acks, [1, 1, 1, 2], "every copy acknowledged");
819        let stats = sock.stats();
820        assert_eq!((stats.messages, stats.acknowledged), (4, 4));
821        assert_eq!((stats.retransmissions, stats.events), (2, 2));
822    }
823
824    /// TC-42: the acknowledgement goes out when the message arrives, not
825    /// when the application reads it. Acknowledged at the read, a device
826    /// resends every `GevMCTT` until then: an Allied Vision Manta G-125B
827    /// sent one event twelve times to a reader a second late.
828    #[tokio::test(flavor = "multi_thread")]
829    async fn an_event_is_acknowledged_when_it_arrives_not_when_it_is_read() {
830        let sock = EventSocket::bind(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)
831            .await
832            .expect("bind");
833        let device = UdpSocket::bind("127.0.0.1:0").await.expect("device");
834        device
835            .send_to(&EVENT_CMD_GOLDEN, sock.local_addr().expect("local addr"))
836            .await
837            .expect("send");
838        let mut ack = [0u8; 64];
839        let (len, _) = tokio::time::timeout(Duration::from_millis(500), device.recv_from(&mut ack))
840            .await
841            .expect("acknowledged while nobody reads")
842            .expect("ack");
843        assert_eq!(&ack[..len], &encode_ack(gvcp::EVENT_ACK, 0xCAFE));
844        let event = sock.recv().await.expect("the event, read later");
845        assert_eq!(event.block_id, 8);
846    }
847
848    /// Events nobody reads are bounded: past the capacity the oldest goes,
849    /// and is counted.
850    #[tokio::test(flavor = "multi_thread")]
851    async fn unread_events_beyond_the_capacity_drop_the_oldest() {
852        let sock =
853            EventSocket::bind_with_capacity(IpAddr::V4(Ipv4Addr::LOCALHOST), 0, 2).expect("bind");
854        let dest = sock.local_addr().expect("local addr");
855        let device = UdpSocket::bind("127.0.0.1:0").await.expect("device");
856        for block in 1..=3u16 {
857            let mut event = EVENT_CMD_GOLDEN;
858            event[6..8].copy_from_slice(&block.to_be_bytes());
859            event[14..16].copy_from_slice(&block.to_be_bytes());
860            device.send_to(&event, dest).await.expect("send");
861        }
862        let deadline = std::time::Instant::now() + Duration::from_secs(2);
863        while sock.stats().events < 3 && std::time::Instant::now() < deadline {
864            tokio::time::sleep(Duration::from_millis(10)).await;
865        }
866        assert_eq!(sock.stats().dropped, 1);
867        let first = sock.recv().await.expect("event");
868        let second = sock.recv().await.expect("event");
869        assert_eq!(
870            (first.block_id, second.block_id),
871            (2, 3),
872            "the oldest dropped"
873        );
874    }
875
876    /// A device that gives every event the same request id — GigE Vision has
877    /// it increment, but a device that does not still sends distinct events —
878    /// loses none: a copy is a retransmission only when its events are the
879    /// same bytes, and distinct events differ at least in their timestamps.
880    #[tokio::test(flavor = "multi_thread")]
881    async fn distinct_events_under_one_request_id_are_all_delivered() {
882        let sock = EventSocket::bind(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)
883            .await
884            .expect("bind");
885        let dest = sock.local_addr().expect("local addr");
886        let device = UdpSocket::bind("127.0.0.1:0").await.expect("device");
887        for timestamp in [1u8, 2] {
888            let mut event = EVENT_CMD_GOLDEN;
889            event[23] = timestamp;
890            device.send_to(&event, dest).await.expect("send");
891        }
892        let first = sock.recv().await.expect("first event");
893        let second = tokio::time::timeout(Duration::from_secs(2), sock.recv())
894            .await
895            .expect("the second event is delivered")
896            .expect("second event");
897        assert_ne!(first.timestamp_dev, second.timestamp_dev);
898    }
899
900    #[test]
901    fn reject_short_packet() {
902        let err = EventPacket::parse_datagram(src(), &[0x42, 0x00, 0x00]).unwrap_err();
903        assert_eq!(err.kind(), ErrorKind::InvalidData);
904    }
905
906    #[test]
907    fn reject_ack_shaped_packet() {
908        // An acknowledgement, not a command: no 0x42 key byte.
909        let mut buf = EVENT_CMD_GOLDEN;
910        buf[0] = 0x00;
911        assert!(EventPacket::parse_datagram(src(), &buf).is_err());
912    }
913
914    #[test]
915    fn reject_partial_entry() {
916        let mut buf = EVENT_CMD_GOLDEN.to_vec();
917        buf.truncate(consts::GVCP_HEADER + 12);
918        buf[4..6].copy_from_slice(&12u16.to_be_bytes());
919        assert!(EventPacket::parse_datagram(src(), &buf).is_err());
920    }
921}