Skip to main content

viva_genicam/
events.rs

1//! High-level helpers for the GVCP message/event channel.
2
3use std::net::{IpAddr, Ipv4Addr};
4use std::sync::Arc;
5use std::time::SystemTime;
6
7use bytes::Bytes;
8use tracing::{debug, info};
9use viva_gige::consts as gvcp_consts;
10use viva_gige::{EventPacket, EventSocket};
11
12use crate::GenicamError;
13use viva_gige::TimeSync;
14
15/// Public representation of a GigE Vision event.
16///
17/// Its features — `EventExposureEndTimestamp`, `EventExposureEndFrameID` and
18/// the rest — are read through GenApi from the port whose `<EventID>` matches
19/// [`Event::id`]: see [`Camera::with_event`](crate::Camera::with_event).
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Event {
22    /// Event identifier reported by the device.
23    pub id: u16,
24    /// Stream channel the event concerns, when it concerns one.
25    pub stream_channel: u16,
26    /// GVSP block the event concerns: 16 bits widened, or the 64-bit
27    /// extended id.
28    pub block_id: u64,
29    /// Device timestamp associated with the event (ticks).
30    pub ts_dev: u64,
31    /// Host time the device timestamp maps to: `None` until the camera's
32    /// clock is fitted ([`Camera::time_calibrate`](crate::Camera::time_calibrate)),
33    /// as for a frame. Never the time the event arrived, passed off as the
34    /// device's (backlog API-20).
35    pub ts_host: Option<SystemTime>,
36    /// Event data following the event header; empty for an `EVENT_CMD`.
37    pub data: Bytes,
38    /// The whole event as the device sent it, header included: what the
39    /// camera's event port addresses.
40    pub raw: Bytes,
41}
42
43/// Asynchronous stream of events delivered over the GVCP message channel.
44///
45/// A receive thread acknowledges each message as it arrives and queues its
46/// events, so a late reader costs the camera no retransmission;
47/// [`EventSocket`] says how many it keeps and what it does with more.
48pub struct EventStream {
49    socket: EventSocket,
50    time_sync: Option<Arc<TimeSync>>,
51}
52
53impl EventStream {
54    pub(crate) fn new(socket: EventSocket, time_sync: Option<Arc<TimeSync>>) -> Self {
55        Self { socket, time_sync }
56    }
57
58    /// Receive the next event emitted by the device.
59    pub async fn next(&self) -> Result<Event, GenicamError> {
60        let packet = self
61            .socket
62            .recv()
63            .await
64            .map_err(crate::error::network("receive a GVCP event"))?;
65        debug!(
66            event_id = packet.event_id,
67            ts_dev = packet.timestamp_dev,
68            "event received"
69        );
70        Ok(Self::map_packet(packet, self.time_sync.clone()))
71    }
72
73    /// What the message channel has received: messages, acknowledgements,
74    /// the camera's retransmissions, events queued and events dropped
75    /// unread.
76    pub fn stats(&self) -> viva_gige::EventStats {
77        self.socket.stats()
78    }
79
80    /// Access the local socket address used by the stream.
81    pub fn local_addr(&self) -> Result<std::net::SocketAddr, GenicamError> {
82        self.socket
83            .local_addr()
84            .map_err(crate::error::network("read the event socket's address"))
85    }
86
87    fn map_packet(packet: EventPacket, sync: Option<Arc<TimeSync>>) -> Event {
88        // A host time only from a fitted clock, as a frame's (DOC-11).
89        let ts_host = sync.and_then(|sync| sync.to_host_time(packet.timestamp_dev));
90        Event {
91            id: packet.event_id,
92            stream_channel: packet.stream_channel,
93            block_id: packet.block_id,
94            ts_dev: packet.timestamp_dev,
95            ts_host,
96            data: packet.payload,
97            raw: packet.raw,
98        }
99    }
100}
101
102/// Events from a USB3 Vision camera's event interface, read on a thread of
103/// its own (backlog TC-27 (4)).
104///
105/// Each is an [`Event`] whose `raw` is the event as GenCP lays it out — its
106/// ID at 0x2, its timestamp at 0x4, its data at 0xC — which is what the
107/// camera's event ports address ([`Camera::with_event`](crate::Camera::with_event)).
108/// USB3 Vision events have no stream channel or block id of their own: both
109/// are 0. Dropping the stream stops the reader and restores the device's
110/// previous EventEnable control word. Use [`U3vEventStream::shutdown`] for
111/// awaited cleanup with restoration errors.
112#[cfg(feature = "u3v")]
113#[cfg_attr(docsrs, doc(cfg(feature = "u3v")))]
114pub struct U3vEventStream {
115    shared: Arc<U3vEventShared>,
116    reader: Option<std::thread::JoinHandle<()>>,
117    disable: Option<Box<dyn FnOnce() -> Result<(), GenicamError> + Send + Sync>>,
118}
119
120#[cfg(feature = "u3v")]
121struct U3vEventShared {
122    queue: crate::stream::EventQueue,
123    stop: std::sync::atomic::AtomicBool,
124}
125
126/// How long the event reader waits before checking whether to stop.
127#[cfg(feature = "u3v")]
128const U3V_EVENT_POLL: std::time::Duration = std::time::Duration::from_millis(50);
129
130/// Events kept for the application before the oldest is dropped.
131#[cfg(feature = "u3v")]
132const U3V_EVENT_CAPACITY: usize = 256;
133
134#[cfg(feature = "u3v")]
135pub(crate) fn open_u3v_event_stream<T: viva_u3v::UsbTransfer + 'static>(
136    transport: &crate::U3vRegisterIo<T>,
137    time_sync: Option<TimeSync>,
138) -> Result<U3vEventStream, GenicamError> {
139    let device = transport.shared_device();
140    let opened = (|| {
141        let mut device = device
142            .lock()
143            .map_err(|_| GenicamError::Panicked("a thread holding the camera's device lock"))?;
144        let address = device
145            .read_eirm()
146            .map_err(|source| GenicamError::U3v {
147                during: "read the event interface",
148                source,
149            })?
150            .base
151            + viva_u3v::registers::eirm::CONTROL;
152        let previous = device
153            .read_mem(address, 4)
154            .map_err(|source| GenicamError::U3v {
155                during: "save EventEnable",
156                source,
157            })?;
158        match device.open_events() {
159            Ok(events) => Ok((events, address, previous)),
160            Err(source) => {
161                // A disconnected device is not written; loss is noted below.
162                if !matches!(source, viva_u3v::U3vError::Disconnected)
163                    && let Err(error) = device.write_mem(address, &previous)
164                {
165                    debug!(%error, "restoring EventEnable after event setup failed");
166                }
167                Err(GenicamError::U3v {
168                    during: "open the event stream",
169                    source,
170                })
171            }
172        }
173    })();
174    let (mut events, enable_address, previous_enable) = opened.inspect_err(|error| {
175        if matches!(
176            error,
177            GenicamError::U3v {
178                source: viva_u3v::U3vError::Disconnected,
179                ..
180            }
181        ) {
182            transport.mark_lost();
183        }
184    })?;
185    let shared = Arc::new(U3vEventShared {
186        queue: crate::stream::EventQueue::new(U3V_EVENT_CAPACITY),
187        stop: std::sync::atomic::AtomicBool::new(false),
188    });
189    let lost = transport.lost_flag();
190    let reader = {
191        let shared = Arc::clone(&shared);
192        std::thread::Builder::new()
193            .name("viva-u3v-events".into())
194            .spawn(move || {
195                use std::sync::atomic::Ordering;
196                while !shared.stop.load(Ordering::Acquire) {
197                    match events.next_event_within(U3V_EVENT_POLL) {
198                        Ok(None) => {}
199                        Ok(Some(event)) => {
200                            let ts_host = time_sync
201                                .as_ref()
202                                .and_then(|sync| sync.to_host_time(event.timestamp));
203                            debug!(
204                                event_id = event.id,
205                                ts_dev = event.timestamp,
206                                "event received"
207                            );
208                            shared.queue.push(Event {
209                                id: event.id,
210                                stream_channel: 0,
211                                block_id: 0,
212                                ts_dev: event.timestamp,
213                                ts_host,
214                                data: event.data,
215                                raw: event.raw,
216                            });
217                        }
218                        Err(error) => {
219                            if matches!(error, viva_u3v::U3vError::Disconnected) {
220                                lost.store(true, Ordering::Release);
221                            }
222                            shared.queue.fail("read an event", error);
223                            break;
224                        }
225                    }
226                }
227                shared.queue.finish();
228            })
229    };
230    let connection = transport.connection();
231    let disable = Box::new(move || {
232        if connection.is_lost() {
233            return Err(GenicamError::U3v {
234                during: "restore EventEnable",
235                source: viva_u3v::U3vError::Disconnected,
236            });
237        }
238        let mut device = device
239            .lock()
240            .map_err(|_| GenicamError::Panicked("a thread holding the camera's device lock"))?;
241        device
242            .write_mem(enable_address, &previous_enable)
243            .map_err(|source| GenicamError::U3v {
244                during: "restore EventEnable",
245                source,
246            })
247    });
248    let reader = match reader {
249        Ok(reader) => reader,
250        Err(error) => {
251            if let Err(restore_error) = disable() {
252                debug!(%restore_error, "restoring EventEnable after reader spawn failed");
253            }
254            return Err(crate::error::network("start the event reader thread")(
255                error,
256            ));
257        }
258    };
259    Ok(U3vEventStream {
260        shared,
261        reader: Some(reader),
262        disable: Some(disable),
263    })
264}
265
266#[cfg(feature = "u3v")]
267impl U3vEventStream {
268    /// Stop and join the event reader on the blocking pool, then restore the
269    /// exact EventEnable control word saved before the reader was opened.
270    ///
271    /// Do not hold the camera or device mutex while awaiting this method.
272    /// A disconnected device is not written; the returned error records that
273    /// its previous EventEnable state could not be restored.
274    pub async fn shutdown(mut self) -> Result<(), GenicamError> {
275        tokio::task::spawn_blocking(move || self.stop_and_restore())
276            .await
277            .map_err(|source| GenicamError::Task {
278                during: "stop the event reader",
279                source,
280            })?
281    }
282
283    fn stop_and_restore(&mut self) -> Result<(), GenicamError> {
284        self.shared
285            .stop
286            .store(true, std::sync::atomic::Ordering::Release);
287        let joined = self.reader.take().map_or(Ok(()), |reader| {
288            reader
289                .join()
290                .map_err(|_| GenicamError::Panicked("the USB event reader"))
291        });
292        let restored = self.disable.take().map_or(Ok(()), |restore| restore());
293        joined.and(restored)
294    }
295
296    /// The next event; an error once the stream has ended, by failing —
297    /// with [`U3vError::Disconnected`](viva_u3v::U3vError::Disconnected) as
298    /// the source when the camera is gone — or by being closed.
299    pub async fn next(&self) -> Result<Event, GenicamError> {
300        let popped = self.shared.queue.pop().await;
301        Self::take(popped)?.ok_or(GenicamError::Panicked("the event stream has ended"))
302    }
303
304    /// Wait up to `timeout` for the next event on the calling thread:
305    /// `Ok(None)` when the stream has ended, [`GenicamError::Timeout`] when
306    /// nothing arrived.
307    pub fn next_blocking(
308        &self,
309        timeout: std::time::Duration,
310    ) -> Result<Option<Event>, GenicamError> {
311        match self.shared.queue.pop_blocking(timeout) {
312            crate::stream::EventPopped::Empty => Err(GenicamError::Timeout(timeout)),
313            popped => Self::take(popped),
314        }
315    }
316
317    fn take(popped: crate::stream::EventPopped) -> Result<Option<Event>, GenicamError> {
318        match popped {
319            crate::stream::EventPopped::Item(event) => Ok(Some(event)),
320            crate::stream::EventPopped::Failed(during, source) => {
321                Err(GenicamError::U3v { during, source })
322            }
323            _ => Ok(None),
324        }
325    }
326}
327
328#[cfg(feature = "u3v")]
329impl Drop for U3vEventStream {
330    fn drop(&mut self) {
331        if let Err(error) = self.stop_and_restore() {
332            debug!(%error, "stopping the USB event reader");
333        }
334    }
335}
336
337/// Attempt to configure the GVCP message channel directly when SFNC nodes are missing.
338pub(crate) fn configure_message_channel_raw<T: crate::genapi::RegisterIo>(
339    transport: &T,
340    ip: Ipv4Addr,
341    port: u16,
342) -> Result<(), GenicamError> {
343    let addr = gvcp_consts::MESSAGE_DESTINATION_ADDRESS;
344    transport
345        .write(addr, &ip.octets())
346        .map_err(GenicamError::from)?;
347    // GevMCP is 32-bit with the port in the low half; a bare `u16` write puts
348    // it in the high half.
349    transport
350        .write(
351            gvcp_consts::MESSAGE_DESTINATION_PORT,
352            &u32::from(port).to_be_bytes(),
353        )
354        .map_err(GenicamError::from)?;
355    info!(%ip, port, "configured message channel via raw registers");
356    Ok(())
357}
358
359// There is deliberately no raw fallback for *enabling* an event.
360//
361// One used to live here, toggling a bit in a "notification mask" at
362// 0x0900_0300 + id/32. No such bootstrap register exists: event delivery is
363// selected through the GenApi `EventSelector` / `EventNotification` features,
364// and the address was invented alongside the equally invented message-channel
365// pair next to it. Writing to it could only corrupt whatever a real device
366// keeps at that address, so a camera without those SFNC nodes now gets an
367// error naming what is missing (ADR-0019).
368
369/// Bind an [`EventSocket`] on the provided interface.
370pub(crate) async fn bind_socket(ip: IpAddr, port: u16) -> Result<EventSocket, GenicamError> {
371    EventSocket::bind(ip, port)
372        .await
373        .map_err(crate::error::network("bind the event socket"))
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379    use std::net::SocketAddr;
380
381    #[test]
382    fn map_packet_without_sync() {
383        let packet = EventPacket {
384            src: SocketAddr::from(([127, 0, 0, 1], 4000)),
385            event_id: 0x1000,
386            timestamp_dev: 42,
387            stream_channel: 3,
388            block_id: 9,
389            payload: Bytes::from_static(b"abcd"),
390            raw: Bytes::from_static(b"0123456789abcdefabcd"),
391        };
392        let event = EventStream::map_packet(packet.clone(), None);
393        assert_eq!(event.id, packet.event_id);
394        assert_eq!(event.ts_dev, packet.timestamp_dev);
395        assert_eq!(event.data, packet.payload);
396        assert_eq!((event.stream_channel, event.block_id), (3, 9));
397        assert_eq!(event.raw, packet.raw);
398    }
399
400    fn packet(timestamp_dev: u64) -> EventPacket {
401        EventPacket {
402            src: SocketAddr::from(([127, 0, 0, 1], 4000)),
403            event_id: 0x9001,
404            timestamp_dev,
405            stream_channel: 0,
406            block_id: 1,
407            payload: Bytes::new(),
408            raw: Bytes::new(),
409        }
410    }
411
412    /// API-20: without a fitted clock an event has no host time. It used to
413    /// get the time it arrived, passed off as the device's.
414    #[test]
415    fn an_event_has_no_host_time_without_a_fitted_clock() {
416        assert_eq!(EventStream::map_packet(packet(42), None).ts_host, None);
417
418        let mut one_sample = TimeSync::new();
419        one_sample.update(10, std::time::Instant::now());
420        assert_eq!(
421            EventStream::map_packet(packet(42), Some(Arc::new(one_sample))).ts_host,
422            None
423        );
424    }
425
426    /// With a fitted clock, the host time is the fit's mapping of the
427    /// event's ticks.
428    #[test]
429    fn an_event_maps_its_ticks_through_a_fitted_clock() {
430        let mut sync = TimeSync::new();
431        let start = std::time::Instant::now();
432        for (ticks, ms) in [(0u64, 0u64), (1_000_000, 1), (2_000_000, 2)] {
433            sync.update(ticks, start + std::time::Duration::from_millis(ms));
434        }
435        sync.fit(Some(1e9));
436        let expected = sync.to_host_time(5_000_000);
437        assert!(expected.is_some());
438        let event = EventStream::map_packet(packet(5_000_000), Some(Arc::new(sync)));
439        assert_eq!(event.ts_host, expected);
440    }
441}