1use serde::{Deserialize, Serialize};
9
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
17#[non_exhaustive]
18pub struct CameraEvent {
19 pub event_id: String,
21 pub name: Option<String>,
24 pub ts_dev: String,
26 pub ts_host_ns: Option<String>,
29 pub stream_channel: Option<u16>,
32 pub block_id: Option<String>,
35 pub features: Vec<EventFeature>,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
43pub struct EventFeature {
44 pub name: String,
46 pub value: Option<String>,
48 pub error: Option<String>,
50}
51
52impl CameraEvent {
53 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111#[non_exhaustive]
112pub struct EventControlRequest {
113 pub command: EventCommand,
115 #[serde(default, skip_serializing_if = "Vec::is_empty")]
117 pub events: Vec<String>,
118}
119
120impl EventControlRequest {
121 pub fn start(events: Vec<String>) -> Self {
123 Self {
124 command: EventCommand::Start,
125 events,
126 }
127 }
128
129 pub fn stop() -> Self {
131 Self {
132 command: EventCommand::Stop,
133 events: Vec::new(),
134 }
135 }
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "lowercase")]
141pub enum EventCommand {
142 Start,
144 Stop,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
156#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
157#[non_exhaustive]
158pub struct EventMonitorStatus {
159 pub active: bool,
161 pub events: Vec<String>,
163 pub warnings: Vec<String>,
166}
167
168impl EventMonitorStatus {
169 pub fn active(events: Vec<String>) -> Self {
171 Self {
172 active: true,
173 events,
174 warnings: Vec::new(),
175 }
176 }
177
178 pub fn inactive(warnings: Vec<String>) -> Self {
180 Self {
181 active: false,
182 events: Vec::new(),
183 warnings,
184 }
185 }
186}
187
188#[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#[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 #[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}