Skip to main content

viva_zenoh_api/
camera_tools.rs

1//! A camera's configuration, saved and restored, and its raw `<Register>`
2//! nodes: the queries behind Viva Studio's configuration and register tools
3//! (backlog ST-50, ST-53).
4//!
5//! A configuration travels as the text of a GenApi feature file (ADR-0028):
6//! the service saves and restores it on its camera, and the client reads and
7//! writes the file where it runs.
8
9use serde::{Deserialize, Serialize};
10
11// ── Configuration ────────────────────────────────────────────────────────────
12
13/// A feature a save left out, and why.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
16#[non_exhaustive]
17pub struct ConfigurationOmission {
18    /// The feature, with the selector entries it was read under when only
19    /// some of its values were left out: `Gain[GainSelector=DigitalAll]`.
20    pub feature: String,
21    /// Why: "not available", "locked by ExposureAuto", ...
22    pub reason: String,
23}
24
25impl ConfigurationOmission {
26    /// `feature` was left out for `reason`.
27    pub fn new(feature: impl Into<String>, reason: impl Into<String>) -> Self {
28        Self {
29            feature: feature.into(),
30            reason: reason.into(),
31        }
32    }
33}
34
35/// Reply of the [`crate::keys::configuration_save`] queryable: the camera's
36/// configuration as a GenApi feature file, and what the save left out.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[non_exhaustive]
39pub struct ConfigurationSaved {
40    /// The file, in the layout `viva_genicam::Camera::save_features` writes.
41    pub text: String,
42    /// How many values the file holds.
43    pub values: usize,
44    /// What was left out, and why; the file carries the same as comments.
45    pub omitted: Vec<ConfigurationOmission>,
46}
47
48impl ConfigurationSaved {
49    /// A saved configuration of `values` values, with nothing left out.
50    pub fn new(text: impl Into<String>, values: usize) -> Self {
51        Self {
52            text: text.into(),
53            values,
54            omitted: Vec::new(),
55        }
56    }
57}
58
59/// Request payload for the [`crate::keys::configuration_load`] queryable.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61#[non_exhaustive]
62pub struct ConfigurationLoadRequest {
63    /// The file to restore, as [`ConfigurationSaved::text`] holds one.
64    pub text: String,
65}
66
67impl ConfigurationLoadRequest {
68    /// Restore the configuration `text`.
69    pub fn new(text: impl Into<String>) -> Self {
70        Self { text: text.into() }
71    }
72}
73
74/// What restoring a configuration did: the reply of the
75/// [`crate::keys::configuration_load`] queryable. A file that cannot be read
76/// at all is an error reply instead.
77#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
78#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
79#[non_exhaustive]
80pub struct ConfigurationLoaded {
81    /// Values written.
82    pub written: usize,
83    /// Of `written`, those written only on the second pass, once the values
84    /// they depend on were in place.
85    pub written_on_retry: usize,
86    /// Each value that could not be written, with the reason:
87    /// `Gain[GainSelector=DigitalAll] = 9: <why>`.
88    pub failures: Vec<String>,
89    /// Doubts about the file as a whole: saved from another camera model, or
90    /// from another version of its XML.
91    pub warnings: Vec<String>,
92}
93
94#[cfg(feature = "genapi")]
95#[cfg_attr(docsrs, doc(cfg(feature = "genapi")))]
96impl From<&viva_genapi::persistence::Omission> for ConfigurationOmission {
97    fn from(omission: &viva_genapi::persistence::Omission) -> Self {
98        let mut feature = omission.feature.clone();
99        if !omission.selectors.is_empty() {
100            let selectors: Vec<String> = omission
101                .selectors
102                .iter()
103                .map(|(selector, entry)| format!("{selector}={entry}"))
104                .collect();
105            feature = format!("{feature}[{}]", selectors.join(", "));
106        }
107        Self::new(feature, omission.reason.clone())
108    }
109}
110
111#[cfg(feature = "genapi")]
112#[cfg_attr(docsrs, doc(cfg(feature = "genapi")))]
113impl From<&viva_genapi::Configuration> for ConfigurationSaved {
114    fn from(configuration: &viva_genapi::Configuration) -> Self {
115        Self {
116            text: configuration.to_text(),
117            values: configuration.values.len(),
118            omitted: configuration.omitted.iter().map(Into::into).collect(),
119        }
120    }
121}
122
123#[cfg(feature = "genapi")]
124#[cfg_attr(docsrs, doc(cfg(feature = "genapi")))]
125impl From<&viva_genapi::LoadReport> for ConfigurationLoaded {
126    fn from(report: &viva_genapi::LoadReport) -> Self {
127        Self {
128            written: report.written,
129            written_on_retry: report.written_on_retry,
130            failures: report.failures.iter().map(ToString::to_string).collect(),
131            warnings: report.warnings.clone(),
132        }
133    }
134}
135
136// ── Registers ────────────────────────────────────────────────────────────────
137
138/// Reply of the [`crate::keys::node_register`] queryable: a `<Register>`
139/// node's bytes, in the order the device holds them. A register that cannot
140/// be read is an error reply instead.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[non_exhaustive]
143pub struct RegisterData {
144    /// The bytes.
145    pub data: Vec<u8>,
146}
147
148impl RegisterData {
149    /// A register holding `data`.
150    pub fn new(data: Vec<u8>) -> Self {
151        Self { data }
152    }
153}
154
155/// Request payload for the [`crate::keys::node_register_set`] queryable. The
156/// reply is a [`crate::NodeOpResponse`] naming what the write invalidated.
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158#[non_exhaustive]
159pub struct RegisterWriteRequest {
160    /// The bytes to write: exactly the register's length, or the write is
161    /// refused.
162    pub data: Vec<u8>,
163}
164
165impl RegisterWriteRequest {
166    /// Write `data`.
167    pub fn new(data: Vec<u8>) -> Self {
168        Self { data }
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    /// The payloads round-trip through JSON, as they travel.
177    #[test]
178    fn the_payloads_round_trip() {
179        let mut saved = ConfigurationSaved::new("# file\nWidth\t640\n", 1);
180        saved
181            .omitted
182            .push(ConfigurationOmission::new("ExposureTime", "locked"));
183        let back: ConfigurationSaved =
184            serde_json::from_str(&serde_json::to_string(&saved).unwrap()).unwrap();
185        assert_eq!(back, saved);
186
187        let loaded = ConfigurationLoaded {
188            written: 3,
189            written_on_retry: 1,
190            failures: vec!["Gain = 9: refused".into()],
191            warnings: vec!["saved from another model".into()],
192        };
193        let back: ConfigurationLoaded =
194            serde_json::from_str(&serde_json::to_string(&loaded).unwrap()).unwrap();
195        assert_eq!(back, loaded);
196
197        let write = RegisterWriteRequest::new(vec![0, 1, 0xFF]);
198        let json = serde_json::to_string(&write).unwrap();
199        assert_eq!(json, r#"{"data":[0,1,255]}"#);
200        let back: RegisterWriteRequest = serde_json::from_str(&json).unwrap();
201        assert_eq!(back, write);
202    }
203
204    /// A save's omissions and a load's failures keep the selector entries
205    /// they concern, as a reader of the file sees them.
206    #[cfg(feature = "genapi")]
207    #[test]
208    fn genapi_results_name_their_selector_entries() {
209        let omission = viva_genapi::persistence::Omission {
210            feature: "Gain".into(),
211            selectors: vec![("GainSelector".into(), "DigitalAll".into())],
212            reason: "not available".into(),
213        };
214        assert_eq!(
215            ConfigurationOmission::from(&omission),
216            ConfigurationOmission::new("Gain[GainSelector=DigitalAll]", "not available")
217        );
218
219        let configuration = viva_genapi::Configuration {
220            omitted: vec![omission],
221            ..Default::default()
222        };
223        let saved = ConfigurationSaved::from(&configuration);
224        assert_eq!(saved.values, 0);
225        assert_eq!(saved.omitted.len(), 1);
226        assert!(
227            saved.text.contains("viva-genicam configuration"),
228            "{}",
229            saved.text
230        );
231    }
232}