Skip to main content

viva_zenoh_api/
camera_event.rs

1//! GenICam device events — GigE Vision `EVENT`/`EVENTDATA` messages and USB3
2//! Vision `EVENT_CMD`s — and the control that turns their delivery on and
3//! off.
4//!
5//! Not event-vision blocks: those are [`crate::EvsHeader`] on
6//! [`crate::keys::evs`].
7
8use serde::{Deserialize, Serialize};
9
10/// One event a camera sent, with the features its XML reads from it.
11///
12/// Published on [`crate::keys::events`] while event monitoring is on.
13/// 64-bit counters are decimal strings, so a JavaScript client keeps every
14/// digit.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
17#[non_exhaustive]
18pub struct CameraEvent {
19    /// The event identifier the device sent, as `0x` and four hex digits.
20    pub event_id: String,
21    /// The `EventSelector` entry the identifier belongs to, when the XML says
22    /// (`viva_genicam::Camera::event_name`).
23    pub name: Option<String>,
24    /// Device timestamp in ticks, decimal.
25    pub ts_dev: String,
26    /// Calibrated Unix nanoseconds; absent without a fitted device clock.
27    /// Never the time the event arrived. Negative values precede the epoch.
28    pub ts_host_ns: Option<String>,
29    /// GigE Vision: the stream channel the event concerns. Absent for USB3
30    /// Vision, whose events carry none.
31    pub stream_channel: Option<u16>,
32    /// GigE Vision: the block the event concerns, decimal. Absent for USB3
33    /// Vision.
34    pub block_id: Option<String>,
35    /// The features the event's port feeds, each with its value or the
36    /// error that kept it from being read, sorted by name.
37    pub features: Vec<EventFeature>,
38}
39
40/// A feature read from one event, or why it could not be.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
43pub struct EventFeature {
44    /// Feature name from the camera XML.
45    pub name: String,
46    /// GenApi's textual value.
47    pub value: Option<String>,
48    /// The read error, when there is no value.
49    pub error: Option<String>,
50}
51
52impl CameraEvent {
53    /// Attach the features read from this event, as
54    /// `viva_genicam::Camera::event_features` returns them.
55    pub fn with_features<E: std::fmt::Display>(
56        mut self,
57        features: impl IntoIterator<Item = (String, Result<String, E>)>,
58    ) -> Self {
59        self.features = features
60            .into_iter()
61            .map(|(name, value)| match value {
62                Ok(value) => EventFeature {
63                    name,
64                    value: Some(value),
65                    error: None,
66                },
67                Err(error) => EventFeature {
68                    name,
69                    value: None,
70                    error: Some(error.to_string()),
71                },
72            })
73            .collect();
74        self
75    }
76
77    /// Set the resolved `EventSelector` entry.
78    pub fn with_name(mut self, name: Option<String>) -> Self {
79        self.name = name;
80        self
81    }
82}
83
84#[cfg(feature = "genicam")]
85#[cfg_attr(docsrs, doc(cfg(feature = "genicam")))]
86impl CameraEvent {
87    /// The wire form of `event`, without a name or features yet. A USB3
88    /// Vision event (`usb`) has no stream channel or block of its own: both
89    /// are left absent rather than reporting the zeros the library fills in.
90    pub fn new(event: &viva_genicam::Event, usb: bool) -> Self {
91        let ts_host_ns = event
92            .ts_host
93            .map(|t| match t.duration_since(std::time::UNIX_EPOCH) {
94                Ok(d) => d.as_nanos().to_string(),
95                Err(e) => format!("-{}", e.duration().as_nanos()),
96            });
97        Self {
98            event_id: format!("0x{:04X}", event.id),
99            name: None,
100            ts_dev: event.ts_dev.to_string(),
101            ts_host_ns,
102            stream_channel: (!usb).then_some(event.stream_channel),
103            block_id: (!usb).then(|| event.block_id.to_string()),
104            features: Vec::new(),
105        }
106    }
107}
108
109/// Request payload for the [`crate::keys::events_control`] queryable.
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111#[non_exhaustive]
112pub struct EventControlRequest {
113    /// Start or stop monitoring.
114    pub command: EventCommand,
115    /// For `Start`: the `EventSelector` entries to turn notification on for.
116    #[serde(default, skip_serializing_if = "Vec::is_empty")]
117    pub events: Vec<String>,
118}
119
120impl EventControlRequest {
121    /// Start monitoring `events`, replacing any monitoring already on.
122    pub fn start(events: Vec<String>) -> Self {
123        Self {
124            command: EventCommand::Start,
125            events,
126        }
127    }
128
129    /// Stop monitoring and restore the settings starting it changed.
130    pub fn stop() -> Self {
131        Self {
132            command: EventCommand::Stop,
133            events: Vec::new(),
134        }
135    }
136}
137
138/// What an event control request asks for.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "lowercase")]
141pub enum EventCommand {
142    /// Configure the camera's event delivery and start forwarding events.
143    Start,
144    /// Stop forwarding and restore the camera's previous event settings.
145    Stop,
146}
147
148/// Whether events are being monitored, and what went wrong putting the
149/// camera's event settings back.
150///
151/// The reply to every [`EventControlRequest`], and published on
152/// [`crate::keys::events_status`] whenever monitoring starts or stops —
153/// including when it stops by itself, because the camera was lost or its
154/// event channel failed.
155#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
156#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
157#[non_exhaustive]
158pub struct EventMonitorStatus {
159    /// Whether events are being forwarded.
160    pub active: bool,
161    /// The `EventSelector` entries monitored; empty when inactive.
162    pub events: Vec<String>,
163    /// Why monitoring stopped by itself, and each setting that could not be
164    /// restored when it stopped. Empty when stopping restored everything.
165    pub warnings: Vec<String>,
166}
167
168impl EventMonitorStatus {
169    /// Monitoring `events`.
170    pub fn active(events: Vec<String>) -> Self {
171        Self {
172            active: true,
173            events,
174            warnings: Vec::new(),
175        }
176    }
177
178    /// Not monitoring, with what stopping could not undo.
179    pub fn inactive(warnings: Vec<String>) -> Self {
180        Self {
181            active: false,
182            events: Vec::new(),
183            warnings,
184        }
185    }
186}
187
188/// What an incomplete restoration leaves to tell the user, one line per
189/// setting: never an empty list for a report that is not complete.
190#[cfg(feature = "genicam")]
191#[cfg_attr(docsrs, doc(cfg(feature = "genicam")))]
192pub fn restore_warnings(report: &viva_genicam::EventRestoreReport) -> Vec<String> {
193    let mut warnings: Vec<String> = report
194        .failures
195        .iter()
196        .map(|failure| format!("{} was not restored: {}", failure.setting, failure.error))
197        .collect();
198    if let Some(skipped) = report.skipped {
199        use viva_genicam::EventRestoreSkipped;
200        warnings.push(match skipped {
201            EventRestoreSkipped::DifferentCamera => {
202                "Event settings were not restored: the camera session was replaced".into()
203            }
204            EventRestoreSkipped::NotInControl(state) => {
205                format!("Event settings were not restored: camera control is {state:?}")
206            }
207            EventRestoreSkipped::Disconnected => {
208                "Event settings were not restored: the camera is disconnected".into()
209            }
210            _ => "Event settings were not restored".into(),
211        });
212    }
213    warnings
214}
215
216/// A failed event setup as one message: the error, and each setting its
217/// rollback could not restore.
218#[cfg(feature = "genicam")]
219#[cfg_attr(docsrs, doc(cfg(feature = "genicam")))]
220pub fn setup_error_message(error: &viva_genicam::EventSetupError) -> String {
221    let mut message = format!("Starting events failed: {}", error.source);
222    for warning in restore_warnings(&error.restoration) {
223        message.push_str("; ");
224        message.push_str(&warning);
225    }
226    message
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    /// The control request and the status round-trip in the shape the
234    /// service and Studio agree on.
235    #[test]
236    fn control_and_status_have_a_stable_wire_shape() {
237        let start = EventControlRequest::start(vec!["ExposureEnd".into()]);
238        let json = serde_json::to_value(&start).unwrap();
239        assert_eq!(
240            json,
241            serde_json::json!({"command": "start", "events": ["ExposureEnd"]})
242        );
243        assert_eq!(
244            serde_json::from_value::<EventControlRequest>(serde_json::json!({"command": "stop"}))
245                .unwrap(),
246            EventControlRequest::stop()
247        );
248        let status = EventMonitorStatus::inactive(vec!["EventNotification[First] failed".into()]);
249        let back: EventMonitorStatus =
250            serde_json::from_slice(&serde_json::to_vec(&status).unwrap()).unwrap();
251        assert_eq!(back, status);
252    }
253
254    #[test]
255    fn features_keep_their_value_or_error() {
256        let event = CameraEvent {
257            event_id: "0x9001".into(),
258            name: None,
259            ts_dev: "18446744073709551615".into(),
260            ts_host_ns: None,
261            stream_channel: None,
262            block_id: None,
263            features: Vec::new(),
264        }
265        .with_features([
266            ("A".to_string(), Ok::<_, String>("1".to_string())),
267            ("B".to_string(), Err("unreadable".to_string())),
268        ]);
269        assert_eq!(event.features[0].value.as_deref(), Some("1"));
270        assert_eq!(event.features[1].error.as_deref(), Some("unreadable"));
271        assert_eq!(event.ts_dev, u64::MAX.to_string());
272    }
273
274    #[cfg(feature = "genicam")]
275    #[test]
276    fn a_usb_event_has_no_stream_channel_or_block() {
277        let event = viva_genicam::Event {
278            id: 0x9001,
279            stream_channel: 0,
280            block_id: 0,
281            ts_dev: 42,
282            ts_host: None,
283            data: Default::default(),
284            raw: Default::default(),
285        };
286        let usb = CameraEvent::new(&event, true);
287        assert_eq!(usb.event_id, "0x9001");
288        assert_eq!((usb.stream_channel, usb.block_id), (None, None));
289        let gige = CameraEvent::new(&event, false);
290        assert_eq!(gige.stream_channel, Some(0));
291        assert_eq!(gige.block_id.as_deref(), Some("0"));
292    }
293}