Skip to main content

viva_zenoh_api/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2//! The message payloads and topic names the viva GenICam camera services
3//! publish, and their clients subscribe to.
4//!
5//! This is the *contract*, not the transport. Despite the crate name, nothing
6//! here depends on the `zenoh` crate: these are plain serde types, so a client
7//! can agree with the service on the message format without linking a message
8//! broker — and the crate compiles everywhere, including `wasm32`.
9
10use serde::{Deserialize, Serialize};
11
12pub mod camera_event;
13pub mod camera_tools;
14pub mod evs_header;
15pub mod frame_header;
16pub mod frame_metadata;
17pub use camera_event::{
18    CameraEvent, EventCommand, EventControlRequest, EventFeature, EventMonitorStatus,
19};
20#[cfg(feature = "genicam")]
21#[cfg_attr(docsrs, doc(cfg(feature = "genicam")))]
22pub use camera_event::{restore_warnings, setup_error_message};
23pub use camera_tools::{
24    ConfigurationLoadRequest, ConfigurationLoaded, ConfigurationOmission, ConfigurationSaved,
25    RegisterData, RegisterWriteRequest,
26};
27pub use evs_header::{EVS_HEADER_SIZE, EVS_MAGIC, EvsFormat, EvsHeader, EvsHeaderError};
28pub use frame_header::{FRAME_MAGIC, FrameHeader, FrameHeaderError, HEADER_SIZE};
29pub use frame_metadata::{
30    FrameChunk, FrameFeature, FrameMetadata, MAX_FRAME_METADATA_BYTES, MAX_FRAME_METADATA_ITEMS,
31    MAX_FRAME_METADATA_TEXT,
32};
33
34// ── Discovery ────────────────────────────────────────────────────────────────
35
36/// Current GenICam Zenoh API version.
37///
38/// Increment this constant when making breaking changes to the Zenoh wire
39/// protocol.  The service publishes this value; clients check it on discovery
40/// and emit warnings when versions differ.
41///
42/// ## Version history
43/// - `1` — initial `NodeValueUpdate` contract with optional `min`/`max`/`inc`.
44/// - `2` — adds [`FeatureState`] / [`NumericRange`] / [`CommandResult`] for
45///   live introspection. `NodeValueUpdate` stays wire-compatible; readers that
46///   understand the new types can consume the new queryables and payloads.
47/// - `3` — [`DeviceAnnounce`] carries the device's own identity (`ip`, `mac`,
48///   `user_name`, `manufacturer`), and `serial` is the serial the device
49///   reports rather than the service's device id
50///   ([#137](https://github.com/VitalyVorobyev/viva-genicam/issues/137)). The
51///   new fields are optional, so a version 2 announce still deserialises.
52/// - `4` — event-vision blocks move off [`keys::image`] onto their own key,
53///   [`keys::evs`], framed by an [`EvsHeader`]
54///   ([#138](https://github.com/VitalyVorobyev/viva-genicam/issues/138)).
55///   Nothing else changes, but a version 3 client subscribed only to `image`
56///   no longer receives anything from an event camera, and the version is
57///   what tells it why.
58/// - `5` — a pixel format is `viva-pfnc`'s: [`ImageMeta`] names any PFNC
59///   format by its PFNC name (`RGB8Packed` where version 4 said `RGB8`,
60///   `Coord3D_ABC32f` where it said `Unknown`), and a USB3 Vision camera's
61///   device id names its vendor, product and serial ([`u3v_device_id`]).
62///   The frame header's one-byte codes are unchanged.
63/// - `6` — [`AcquisitionStatus`] carries the stream's counters,
64///   [`StreamCounters`], in `stats`, where version 5 had one `dropped` count;
65///   it is sent every second while acquiring, frames or not, and a final
66///   [`AcquisitionStatus::stopped`] snapshot follows the stream's end.
67/// - `7` — [`FrameHeader`] version 2 carries the row stride, so padded images
68///   retain their row layout in remote consumers. The header is 20 bytes;
69///   version-1 image headers are rejected.
70/// - `8` — version-3 image headers carry bounded per-frame metadata inline,
71///   preserving exact identifiers, timestamps and chunk values with the pixels.
72/// - `9` — GenICam device events: [`keys::events_control`] starts and stops
73///   monitoring ([`EventControlRequest`]), each event is a [`CameraEvent`] on
74///   [`keys::events`], and [`EventMonitorStatus`] on [`keys::events_status`]
75///   says when monitoring stops and what could not be restored.
76/// - `10` — a camera's configuration is saved on
77///   [`keys::configuration_save`] ([`ConfigurationSaved`]) and restored on
78///   [`keys::configuration_load`] ([`ConfigurationLoaded`]), and a
79///   `<Register>` node is read on [`keys::node_register`] ([`RegisterData`])
80///   and written on [`keys::node_register_set`] ([`RegisterWriteRequest`]).
81pub const API_VERSION: u32 = 10;
82
83/// Periodic announcement published by the camera service.
84///
85/// Carries enough of the device's identity for a client to tell two cameras of
86/// the same model apart: the user-defined name, the serial and the address.
87///
88/// `#[non_exhaustive]`: build one with [`DeviceAnnounce::new`] and assign the
89/// optional fields, so that adding the next field is not a breaking change.
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
91#[non_exhaustive]
92pub struct DeviceAnnounce {
93    /// Service-assigned device id, also the `{id}` segment of every key
94    /// expression in [`keys`]. For GigE Vision it is [`gige_device_id`].
95    pub id: String,
96    /// Human-readable name: the user-defined name, else the model.
97    pub name: String,
98    /// The camera's model name.
99    pub model: String,
100    /// Serial number as the device reports it; empty when it reports none.
101    ///
102    /// Services before API version 3 put the device id here instead.
103    pub serial: String,
104    /// Zenoh API version supported by this service.
105    ///
106    /// `None` when deserializing from older services that do not include the
107    /// field — handled gracefully by the app (warns but still discovers).
108    #[serde(default)]
109    pub api_version: Option<u32>,
110    /// Current IPv4 address in dotted-quad form. `None` for transports without
111    /// one (USB3 Vision) and from services before API version 3.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub ip: Option<String>,
114    /// MAC address as `AA:BB:CC:DD:EE:FF`. `None` for transports without one.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub mac: Option<String>,
117    /// User-defined device name (the GigE Vision Discovery ACK's user-defined
118    /// name field), when one is set.
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    pub user_name: Option<String>,
121    /// Manufacturer name, when the device reports one.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub manufacturer: Option<String>,
124}
125
126impl DeviceAnnounce {
127    /// An announce carrying the required fields and the current
128    /// [`API_VERSION`], with every optional identity field unset.
129    pub fn new(
130        id: impl Into<String>,
131        name: impl Into<String>,
132        model: impl Into<String>,
133        serial: impl Into<String>,
134    ) -> Self {
135        Self {
136            id: id.into(),
137            name: name.into(),
138            model: model.into(),
139            serial: serial.into(),
140            api_version: Some(API_VERSION),
141            ip: None,
142            mac: None,
143            user_name: None,
144            manufacturer: None,
145        }
146    }
147
148    /// The announce for a GigE Vision camera, from the fields of its Discovery
149    /// ACK.
150    ///
151    /// The one place the GigE identity rule lives, so the service and Studio's
152    /// embedded backend announce the same camera identically: `id` is
153    /// [`gige_device_id`], `name` is the user-defined name, else the model,
154    /// else the address, and `serial` is the device's own (empty when absent).
155    pub fn for_gige(
156        mac: &[u8; 6],
157        ip: std::net::Ipv4Addr,
158        model: Option<&str>,
159        serial: Option<&str>,
160        user_name: Option<&str>,
161        manufacturer: Option<&str>,
162    ) -> Self {
163        let name = user_name
164            .or(model)
165            .map_or_else(|| ip.to_string(), str::to_string);
166        let mut announce = Self::new(
167            gige_device_id(mac),
168            name,
169            model.unwrap_or_default(),
170            serial.unwrap_or_default(),
171        );
172        announce.ip = Some(ip.to_string());
173        announce.mac = Some(
174            mac.iter()
175                .map(|b| format!("{b:02X}"))
176                .collect::<Vec<_>>()
177                .join(":"),
178        );
179        announce.user_name = user_name.map(str::to_string);
180        announce.manufacturer = manufacturer.map(str::to_string);
181        announce
182    }
183}
184
185/// Device id for a GigE Vision camera: `cam-` followed by its MAC address as
186/// twelve lowercase hex digits.
187///
188/// The MAC is the one identifier every GigE Vision device reports, that is
189/// unique on the wire, and that survives an address change — DHCP, `FORCEIP`,
190/// or a persistent IP written from Studio itself. The IP is none of those, and
191/// the serial is optional in the Discovery ACK. The service and Studio's
192/// embedded backend both derive the id here, so a camera keeps one identity in
193/// either mode.
194pub fn gige_device_id(mac: &[u8; 6]) -> String {
195    let hex: String = mac.iter().map(|b| format!("{b:02x}")).collect();
196    format!("cam-{hex}")
197}
198
199/// Device id for a USB3 Vision camera: `cam-u3v-`, its vendor and product
200/// ids as eight hex digits, then its serial number.
201///
202/// The serial is the USB serial string the operating system caches, which a
203/// rescan reads without opening the device — so it does not change while the
204/// camera is in use — and which stays the same when the camera is plugged in
205/// again, wherever (backlog UV-03). On the one camera this has met, a MATRIX
206/// VISION mvBlueFOX3-2004G, it is the serial its bootstrap registers report
207/// too. A camera without one is named by its `bus` and `address`, and may get
208/// a new id when plugged in again.
209///
210/// Letters, digits, `-` and `.` are kept; every other byte of the serial's
211/// UTF-8, `_` included, becomes `_` and two lowercase hex digits (`/` is
212/// `_2f`, `_` is `_5f`). The escape is reversible, so two serials never share
213/// an id: replacing each by a bare `_` made `a/b` and `a*b` one camera
214/// (Codex review of #205).
215pub fn u3v_device_id(
216    vendor_id: u16,
217    product_id: u16,
218    serial: Option<&str>,
219    bus: &str,
220    address: u8,
221) -> String {
222    let instance = match serial.map(str::trim).filter(|s| !s.is_empty()) {
223        Some(serial) => serial.to_string(),
224        None => format!("{bus}-{address}"),
225    };
226    let mut escaped = String::with_capacity(instance.len());
227    for byte in instance.bytes() {
228        match byte {
229            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' => escaped.push(char::from(byte)),
230            _ => escaped.push_str(&format!("_{byte:02x}")),
231        }
232    }
233    format!("cam-u3v-{vendor_id:04x}{product_id:04x}-{escaped}")
234}
235
236// ── Connection Lifecycle ─────────────────────────────────────────────────────
237
238// Every payload below is `#[non_exhaustive]` and built with its constructor,
239// so a field added later is not a breaking change for the services and
240// clients that build them (API-13). Deserialization is unaffected.
241
242/// Device connection status pushed by the service on change.
243#[derive(Debug, Clone, Serialize, Deserialize)]
244#[non_exhaustive]
245pub struct DeviceStatus {
246    /// Whether the service holds the camera.
247    pub connected: bool,
248    /// Why it does not, when it does not.
249    pub error: Option<String>,
250}
251
252impl DeviceStatus {
253    /// The device is connected.
254    pub fn connected() -> Self {
255        Self {
256            connected: true,
257            error: None,
258        }
259    }
260
261    /// The device is not connected, and why, if known.
262    pub fn disconnected(error: Option<String>) -> Self {
263        Self {
264            connected: false,
265            error,
266        }
267    }
268}
269
270/// Response to `genicam/devices/{id}/xml` queryable.
271#[derive(Debug, Clone, Serialize, Deserialize)]
272#[non_exhaustive]
273pub struct DeviceXmlResponse {
274    /// The camera's GenICam XML.
275    pub xml: String,
276}
277
278impl DeviceXmlResponse {
279    /// The device's GenApi XML.
280    pub fn new(xml: impl Into<String>) -> Self {
281        Self { xml: xml.into() }
282    }
283}
284
285/// Request payload for the `genicam/devices/{id}/report` queryable.
286#[derive(Debug, Clone, Serialize, Deserialize)]
287#[non_exhaustive]
288pub struct DeviceReportRequest {
289    /// Include the device's GenApi XML; on unless the client asks otherwise.
290    #[serde(default = "default_true")]
291    pub include_xml: bool,
292}
293
294impl DeviceReportRequest {
295    /// A report request, with or without the GenApi XML.
296    pub fn new(include_xml: bool) -> Self {
297        Self { include_xml }
298    }
299}
300
301/// Response to the `report` queryable: the diagnostic report the service
302/// wrote for its device, as plain text, the same report `viva-camctl report`
303/// writes.
304#[derive(Debug, Clone, Serialize, Deserialize)]
305#[non_exhaustive]
306pub struct DeviceReportResponse {
307    /// The report, as `viva-camctl report` writes it.
308    pub report: String,
309}
310
311impl DeviceReportResponse {
312    /// The report text.
313    pub fn new(report: impl Into<String>) -> Self {
314        Self {
315            report: report.into(),
316        }
317    }
318}
319
320// ── Node Values ──────────────────────────────────────────────────────────────
321
322/// Live node value update published by the service on change.
323///
324/// `min`, `max`, and `inc` are optional runtime constraint hints.
325/// When present, the UI can tighten slider ranges without re-parsing XML.
326/// Services that do not implement constraint propagation may omit them.
327///
328/// **Legacy payload.** New code should publish [`FeatureState`] instead — it
329/// carries the same information plus runtime introspection (access mode, kind,
330/// implementation/availability, available enum entries). `NodeValueUpdate`
331/// stays in the wire contract so older services/clients keep working.
332#[derive(Debug, Clone, Serialize, Deserialize)]
333#[non_exhaustive]
334pub struct NodeValueUpdate {
335    /// The value, typed as JSON (`null` for one that cannot be read).
336    pub value: serde_json::Value,
337    /// Access mode: `RO`, `RW`, `WO` or `NA`.
338    pub access_mode: String,
339    /// Optional minimum allowed value for this node at the current camera state.
340    #[serde(skip_serializing_if = "Option::is_none")]
341    pub min: Option<f64>,
342    /// Optional maximum allowed value for this node at the current camera state.
343    #[serde(skip_serializing_if = "Option::is_none")]
344    pub max: Option<f64>,
345    /// Optional increment (step) for this node's value.
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub inc: Option<f64>,
348}
349
350impl NodeValueUpdate {
351    /// A value and its access mode, with no constraint hints.
352    pub fn new(value: serde_json::Value, access_mode: impl Into<String>) -> Self {
353        Self {
354            value,
355            access_mode: access_mode.into(),
356            min: None,
357            max: None,
358            inc: None,
359        }
360    }
361}
362
363// ── FeatureState (live introspection) ────────────────────────────────────────
364
365/// Numeric range for an Integer or Float feature at the current camera state.
366///
367/// `min`/`max` are resolved from the XML's static declaration, from `pMin`/`pMax`
368/// references when present, or from selector-dependent rules. Services that
369/// cannot resolve the range must omit [`FeatureState::numeric`] entirely rather
370/// than invent defaults like `i64::MIN..=i64::MAX` (the UI renders "range
371/// unknown" in that case).
372#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
373#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
374#[cfg_attr(feature = "ts", ts(optional_fields))]
375#[non_exhaustive]
376pub struct NumericRange {
377    /// Minimum.
378    pub min: f64,
379    /// Maximum.
380    pub max: f64,
381    /// Optional increment (step). Omitted when the feature has no grid.
382    #[serde(default, skip_serializing_if = "Option::is_none")]
383    pub inc: Option<f64>,
384}
385
386impl NumericRange {
387    /// A range, with an increment when the feature has a grid.
388    pub fn new(min: f64, max: f64, inc: Option<f64>) -> Self {
389        Self { min, max, inc }
390    }
391}
392
393/// Live state of a GenICam feature at a single point in time.
394///
395/// Replaces [`NodeValueUpdate`] as the authoritative snapshot consumed by the
396/// UI. Every field reflects what the device reports *now*, not what the XML
397/// declares statically.
398///
399/// # Design notes
400///
401/// - `kind` is a plain string matching `viva_genapi::Node::kind_name` values
402///   ("Integer", "Float", "Enumeration", "Boolean", "Command", "Category",
403///   "SwissKnife", "Converter", "IntConverter", "StringReg", "Register").
404///   Clients should
405///   tolerate unknown kinds.
406/// - `access_mode` uses GenICam spelling: `"RO"`, `"RW"`, `"WO"`, `"NA"`.
407/// - `is_implemented` and `is_available` default to `true` for deserialization
408///   from services that do not evaluate these predicates yet.
409/// - `numeric` is `Some` only for Integer/Float nodes with a resolvable range.
410/// - `enum_available` is `Some` only for Enumeration nodes. When the service
411///   cannot filter by IsAvailable it SHOULD still populate this with the full
412///   entry list so the UI stops falling back to static XML.
413#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
414#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
415#[cfg_attr(feature = "ts", ts(optional_fields))]
416#[non_exhaustive]
417pub struct FeatureState {
418    /// Current feature value, typed according to `kind`.
419    ///
420    /// `null` when the feature has no value to read: a Category, a Command, a
421    /// node declared `WO`, or the register a command writes through. Such a
422    /// feature is still reported, with its access mode, so a client can offer
423    /// the write or the execute without a value to show.
424    pub value: serde_json::Value,
425    /// Live access mode.
426    pub access_mode: String,
427    /// GenICam node kind.
428    pub kind: String,
429    /// Whether the node is implemented by the device.
430    #[serde(default = "default_true")]
431    pub is_implemented: bool,
432    /// Whether the node is currently accessible (selector gating etc).
433    #[serde(default = "default_true")]
434    pub is_available: bool,
435    /// Range for Integer/Float nodes, when resolvable.
436    #[serde(default, skip_serializing_if = "Option::is_none")]
437    pub numeric: Option<NumericRange>,
438    /// Available enum entries for Enumeration nodes.
439    #[serde(default, skip_serializing_if = "Option::is_none")]
440    pub enum_available: Option<Vec<String>>,
441    /// Engineering unit copied from node metadata (e.g. `"us"`).
442    #[serde(default, skip_serializing_if = "Option::is_none")]
443    pub unit: Option<String>,
444    /// How long, in milliseconds, the value may be shown before it is read
445    /// again: the `<PollingTime>` of the feature or of a register its value
446    /// is read through. Absent when nothing polls it.
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    pub polling_ms: Option<u64>,
449    /// The feature's caching mode in GenICam spelling — `"NoCache"`,
450    /// `"WriteThrough"`, `"WriteAround"` — its own combined with that of the
451    /// registers it is read through. A `NoCache` feature changes on the
452    /// device with nothing to announce it. Absent from services that predate
453    /// it.
454    #[serde(default, skip_serializing_if = "Option::is_none")]
455    pub caching: Option<String>,
456}
457
458fn default_true() -> bool {
459    true
460}
461
462impl FeatureState {
463    /// An implemented, available feature with a value, an access mode and a
464    /// kind, and no range, entries or unit.
465    pub fn new(
466        value: serde_json::Value,
467        access_mode: impl Into<String>,
468        kind: impl Into<String>,
469    ) -> Self {
470        Self {
471            value,
472            access_mode: access_mode.into(),
473            kind: kind.into(),
474            is_implemented: true,
475            is_available: true,
476            numeric: None,
477            enum_available: None,
478            unit: None,
479            polling_ms: None,
480            caching: None,
481        }
482    }
483
484    /// Project this state into the legacy [`NodeValueUpdate`] shape so callers
485    /// that still speak the old contract keep working during migration.
486    pub fn to_node_value_update(&self) -> NodeValueUpdate {
487        let (min, max, inc) = match &self.numeric {
488            Some(r) => (Some(r.min), Some(r.max), r.inc),
489            None => (None, None, None),
490        };
491        let mut update = NodeValueUpdate::new(self.value.clone(), self.access_mode.clone());
492        update.min = min;
493        update.max = max;
494        update.inc = inc;
495        update
496    }
497}
498
499impl From<&FeatureState> for NodeValueUpdate {
500    fn from(s: &FeatureState) -> Self {
501        s.to_node_value_update()
502    }
503}
504
505/// The wire form of a state read through `viva-genapi`.
506///
507/// Every service that holds a nodemap builds its [`FeatureState`] this way,
508/// so the access-mode spelling, the register summary and the unreadable-value
509/// rules cannot drift between them (backlog ST-26).
510#[cfg(feature = "genapi")]
511#[cfg_attr(docsrs, doc(cfg(feature = "genapi")))]
512impl From<viva_genapi::FeatureState> for FeatureState {
513    fn from(state: viva_genapi::FeatureState) -> Self {
514        use viva_genapi::{AccessMode, FeatureValue};
515
516        let value = match state.value {
517            FeatureValue::None => serde_json::Value::Null,
518            FeatureValue::Integer(v) => serde_json::Value::Number(v.into()),
519            FeatureValue::Float(v) => f64_to_json(v),
520            FeatureValue::Boolean(v) => serde_json::Value::Bool(v),
521            FeatureValue::Enum(v) | FeatureValue::String(v) => serde_json::Value::String(v),
522            FeatureValue::Register { len } => {
523                serde_json::json!({ "kind": "register", "length": len })
524            }
525            // `FeatureValue` is `#[non_exhaustive]`: name what we cannot show
526            // rather than emitting a bare null.
527            _ => serde_json::json!({ "kind": state.kind, "unsupported": true }),
528        };
529        let access_mode = match state.access {
530            Some(AccessMode::RO) => "RO",
531            Some(AccessMode::RW) => "RW",
532            Some(AccessMode::WO) => "WO",
533            None => "NA",
534        };
535        FeatureState {
536            value,
537            access_mode: access_mode.to_string(),
538            kind: state.kind.to_string(),
539            is_implemented: state.is_implemented,
540            is_available: state.is_available,
541            numeric: state.range.map(|r| NumericRange {
542                min: r.min,
543                max: r.max,
544                inc: r.inc,
545            }),
546            enum_available: state.enum_entries,
547            unit: state.unit,
548            polling_ms: state
549                .polling_time
550                .map(|t| u64::try_from(t.as_millis()).unwrap_or(u64::MAX)),
551            caching: Some(caching_text(state.caching).to_string()),
552        }
553    }
554}
555
556/// GenICam's spelling of a caching mode.
557#[cfg(feature = "genapi")]
558fn caching_text(mode: viva_genapi::CachingMode) -> &'static str {
559    match mode {
560        viva_genapi::CachingMode::NoCache => "NoCache",
561        viva_genapi::CachingMode::WriteThrough => "WriteThrough",
562        viva_genapi::CachingMode::WriteAround => "WriteAround",
563    }
564}
565
566/// A JSON number, or the value's text for NaN and infinities, which JSON
567/// cannot carry.
568#[cfg(feature = "genapi")]
569fn f64_to_json(v: f64) -> serde_json::Value {
570    serde_json::Number::from_f64(v)
571        .map(serde_json::Value::Number)
572        .unwrap_or_else(|| serde_json::Value::String(v.to_string()))
573}
574
575// ── CommandResult ────────────────────────────────────────────────────────────
576
577/// Response from an `execute` queryable.
578///
579/// Like [`NodeOpResponse`] but also returns the post-execution state of any
580/// nodes whose value is likely to have changed. For example, executing
581/// `AcquisitionStart` populates `affected_states` with the refreshed state of
582/// `AcquisitionStatus`, etc. The UI uses these to update badges / form inputs
583/// without a second round-trip.
584#[derive(Debug, Clone, Serialize, Deserialize)]
585#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
586#[cfg_attr(feature = "ts", ts(optional_fields))]
587#[non_exhaustive]
588pub struct CommandResult {
589    /// Whether the command was executed.
590    pub ok: bool,
591    #[serde(default, skip_serializing_if = "Option::is_none")]
592    /// Why not, when it was not.
593    pub error: Option<String>,
594    /// Map of node name -> refreshed state for nodes affected by this command.
595    /// Empty when the service cannot determine side effects.
596    #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
597    // Omitted when empty; `nullable` adds the `?` without unwrapping a type
598    // that is not an `Option`.
599    #[cfg_attr(feature = "ts", ts(optional = nullable))]
600    pub affected_states: std::collections::HashMap<String, FeatureState>,
601}
602
603impl CommandResult {
604    /// Success, with no affected states.
605    pub fn ok() -> Self {
606        Self {
607            ok: true,
608            error: None,
609            affected_states: std::collections::HashMap::new(),
610        }
611    }
612
613    /// Failure, with its reason.
614    pub fn err(error: impl Into<String>) -> Self {
615        Self {
616            ok: false,
617            error: Some(error.into()),
618            affected_states: std::collections::HashMap::new(),
619        }
620    }
621}
622
623/// Request payload for the `nodes/{name}/set` queryable.
624#[derive(Debug, Clone, Serialize, Deserialize)]
625#[non_exhaustive]
626pub struct NodeSetRequest {
627    /// The value to write, typed as JSON.
628    pub value: serde_json::Value,
629}
630
631impl NodeSetRequest {
632    /// Write `value`.
633    pub fn new(value: serde_json::Value) -> Self {
634        Self { value }
635    }
636}
637
638/// Generic response for node write, execute, and acquisition control.
639#[derive(Debug, Clone, Serialize, Deserialize)]
640#[non_exhaustive]
641pub struct NodeOpResponse {
642    /// Whether the operation succeeded.
643    pub ok: bool,
644    /// Why not, when it did not.
645    pub error: Option<String>,
646    /// After a successful write or execute: the features whose value or
647    /// state the operation may have changed, from
648    /// `viva_genapi::NodeMap::invalidated_by`. A client re-reads the ones it
649    /// shows. It can be hundreds of names, so the service names them rather
650    /// than publishing their state. Empty for acquisition control, and from a
651    /// service that predates the field.
652    #[serde(default, skip_serializing_if = "Vec::is_empty")]
653    pub invalidated: Vec<String>,
654}
655
656impl NodeOpResponse {
657    /// Success, with nothing invalidated.
658    pub fn ok() -> Self {
659        Self {
660            ok: true,
661            error: None,
662            invalidated: Vec::new(),
663        }
664    }
665
666    /// Failure, with its reason.
667    pub fn err(error: impl Into<String>) -> Self {
668        Self {
669            ok: false,
670            error: Some(error.into()),
671            invalidated: Vec::new(),
672        }
673    }
674
675    /// The same response, naming the features the operation invalidated.
676    pub fn with_invalidated(mut self, invalidated: Vec<String>) -> Self {
677        self.invalidated = invalidated;
678        self
679    }
680}
681
682// ── Bulk Node Read ────────────────────────────────────────────────────────────
683
684/// Request payload for the `nodes/bulk/read` queryable.
685///
686/// An empty `names` list is valid and returns an empty map.
687#[derive(Debug, Clone, Serialize, Deserialize)]
688#[non_exhaustive]
689pub struct BulkReadRequest {
690    /// The features to read.
691    pub names: Vec<String>,
692}
693
694impl BulkReadRequest {
695    /// Read these features.
696    pub fn new(names: Vec<String>) -> Self {
697        Self { names }
698    }
699}
700
701/// Response to a `nodes/bulk/read` query.
702///
703/// `values` maps each requested node name to its current value + access_mode.
704/// Node names not found in the store are omitted (not an error).
705#[derive(Debug, Clone, Serialize, Deserialize)]
706#[non_exhaustive]
707pub struct BulkReadResponse {
708    /// Their values, by name.
709    pub values: std::collections::HashMap<String, NodeValueUpdate>,
710}
711
712impl BulkReadResponse {
713    /// The values read, by feature name.
714    pub fn new(values: std::collections::HashMap<String, NodeValueUpdate>) -> Self {
715        Self { values }
716    }
717}
718
719// ── Acquisition ──────────────────────────────────────────────────────────────
720
721/// Request payload for the `acquisition/control` queryable.
722#[derive(Debug, Clone, Serialize, Deserialize)]
723#[non_exhaustive]
724pub struct AcquisitionControlRequest {
725    /// Start or stop.
726    pub command: AcquisitionCommand,
727    /// For `Start`: the GVSP packet size to use, as a ceiling the service's
728    /// path probe stays under. Absent, the service negotiates one from the
729    /// NIC's MTU. A size the user measured for their link is how they get
730    /// past a link the negotiation misjudges (issue #112).
731    #[serde(default, skip_serializing_if = "Option::is_none")]
732    pub packet_size: Option<u32>,
733}
734
735impl AcquisitionControlRequest {
736    /// `command` with the service's own choice of packet size.
737    pub fn new(command: AcquisitionCommand) -> Self {
738        Self {
739            command,
740            packet_size: None,
741        }
742    }
743}
744
745#[derive(Debug, Clone, Serialize, Deserialize)]
746#[serde(rename_all = "lowercase")]
747/// What an acquisition control request asks for.
748pub enum AcquisitionCommand {
749    /// Start acquisition and stream.
750    Start,
751    /// Stop streaming and acquisition.
752    Stop,
753}
754
755/// Acquisition status pushed by the service: once when acquisition starts,
756/// once a second while it runs, whether or not frames arrive, a final
757/// [`stopped`](Self::stopped) snapshot when the stream ends, and
758/// [`inactive`](Self::inactive) once the camera has stopped.
759#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
760#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
761#[non_exhaustive]
762pub struct AcquisitionStatus {
763    /// Whether the camera is acquiring.
764    pub active: bool,
765    /// Frames a second delivered by the stream over the last status
766    /// interval, when known. It counts every frame the stream hands over,
767    /// not the ones a viewer draws.
768    pub fps: Option<f32>,
769    /// The stream's counters since it started; `null` on the wire when
770    /// there are none: in the status sent on start, before the first count,
771    /// and in the one that says acquisition is off.
772    pub stats: Option<StreamCounters>,
773}
774
775impl AcquisitionStatus {
776    /// Acquiring at `fps`, with the stream's counters so far.
777    pub fn active(fps: Option<f32>, stats: Option<StreamCounters>) -> Self {
778        Self {
779            active: true,
780            fps,
781            stats,
782        }
783    }
784
785    /// Not acquiring, and nothing to count.
786    pub fn inactive() -> Self {
787        Self {
788            active: false,
789            fps: None,
790            stats: None,
791        }
792    }
793
794    /// The stream has ended; `stats` are its final counters.
795    pub fn stopped(stats: StreamCounters) -> Self {
796        Self {
797            active: false,
798            fps: None,
799            stats: Some(stats),
800        }
801    }
802}
803
804/// One stream's counters on the wire: `viva_genicam::StreamStats`, with the
805/// six reasons a packet was ignored summed into one.
806///
807/// **USB3 Vision** streams fill the frame counters the same way. Of the packet
808/// counters, `packets_received` counts bulk transfers and `packets_ignored`
809/// the transfers that were not the leader, payload or trailer due;
810/// `transfer_errors` counts failed transfers the stream recovered from. The
811/// other packet and resend counters stay 0.
812///
813/// Every block the camera sends is counted once, when its fate is decided:
814/// complete, incomplete, missed, dropped to backpressure or unsupported. A
815/// frame still waiting in the delivery queue is in none of them yet.
816#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
817#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
818#[non_exhaustive]
819pub struct StreamCounters {
820    /// Frames handed to the application with every packet present.
821    pub frames_complete: u64,
822    /// Frames closed without that: packets missing, no trailer, or an error
823    /// status from the device. Counted whether or not the stream delivers
824    /// incomplete frames.
825    pub frames_incomplete: u64,
826    /// Blocks never seen at all: gaps in the block-id sequence.
827    pub frames_missed: u64,
828    /// Frames assembled and then discarded because the application did not
829    /// take them before the delivery queue filled.
830    pub frames_backpressure: u64,
831    /// Blocks whose payload type the engine does not assemble.
832    pub frames_unsupported: u64,
833    /// Datagrams read from the socket. USB3 Vision: bulk transfers.
834    pub packets_received: u64,
835    /// Packets never received, of frames closed incomplete. A lower bound when
836    /// a trailer is missing, since the trailer is what says how many there were.
837    pub packets_missing: u64,
838    /// Packets received more than once.
839    pub packets_duplicate: u64,
840    /// Packets received and not used, for any reason: not GVSP, a format the
841    /// engine does not assemble, beyond the end of the frame, late, an error
842    /// status, or from an address other than the camera's.
843    pub packets_ignored: u64,
844    /// Packets asked for again, each counted once however often it was asked.
845    pub resend_requested: u64,
846    /// Packets asked for again that then arrived.
847    pub resend_recovered: u64,
848    /// Packets asked for again that the camera answered it no longer has.
849    pub resend_unavailable: u64,
850    /// USB3 Vision: transfers that failed — a stall, a fault — and that the
851    /// stream recovered from by resetting its endpoint, at the cost of the
852    /// block in progress. 0 on GigE Vision.
853    pub transfer_errors: u64,
854    /// Payload bytes of complete frames handed to the application.
855    pub bytes: u64,
856    /// Smoothed payload throughput of complete frames, in megabits a second.
857    pub avg_mbps: f64,
858    /// Smoothed delay from the device timestamp to delivery, in milliseconds,
859    /// when the stream can map device time to host time.
860    pub avg_latency_ms: Option<f64>,
861    /// Time since the stream started, in milliseconds.
862    pub elapsed_ms: u64,
863}
864
865impl StreamCounters {
866    /// Frames the application did not receive complete: incomplete, missed
867    /// and dropped to backpressure.
868    pub fn frames_lost(&self) -> u64 {
869        self.frames_incomplete + self.frames_missed + self.frames_backpressure
870    }
871}
872
873#[cfg(feature = "genicam")]
874#[cfg_attr(docsrs, doc(cfg(feature = "genicam")))]
875impl From<&viva_genicam::StreamStats> for StreamCounters {
876    fn from(stats: &viva_genicam::StreamStats) -> Self {
877        Self {
878            frames_complete: stats.frames_complete,
879            frames_incomplete: stats.frames_incomplete,
880            frames_missed: stats.frames_missed,
881            frames_backpressure: stats.frames_backpressure,
882            frames_unsupported: stats.frames_unsupported,
883            packets_received: stats.packets_received,
884            packets_missing: stats.packets_missing,
885            packets_duplicate: stats.packets_duplicate,
886            packets_ignored: stats.packets_ignored(),
887            resend_requested: stats.resend_requested,
888            resend_recovered: stats.resend_recovered,
889            resend_unavailable: stats.resend_unavailable,
890            transfer_errors: stats.transfer_errors,
891            bytes: stats.bytes,
892            avg_mbps: stats.avg_mbps,
893            avg_latency_ms: stats.avg_latency_ms,
894            elapsed_ms: u64::try_from(stats.elapsed.as_millis()).unwrap_or(u64::MAX),
895        }
896    }
897}
898
899// ── Image ────────────────────────────────────────────────────────────────────
900
901/// [`ImageMeta::pixel_format`] on the wire: the format's PFNC name
902/// (`"Mono8"`, `"RGB8Packed"`), or `"Unknown"` for a code PFNC does not name.
903/// Reading accepts the older spellings cameras report (`"RGB8"`), as
904/// [`viva_pfnc::PixelFormat::from_name`] does.
905mod pfnc_name {
906    use serde::{Deserialize, Deserializer, Serializer};
907    use viva_pfnc::PixelFormat;
908
909    pub(crate) fn serialize<S: Serializer>(
910        format: &PixelFormat,
911        serializer: S,
912    ) -> Result<S::Ok, S::Error> {
913        serializer.serialize_str(format.name().unwrap_or("Unknown"))
914    }
915
916    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
917        deserializer: D,
918    ) -> Result<PixelFormat, D::Error> {
919        let name = String::deserialize(deserializer)?;
920        Ok(PixelFormat::from_name(&name))
921    }
922}
923
924/// Image stream metadata published at acquisition start and on format change.
925#[derive(Debug, Clone, Serialize, Deserialize)]
926#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
927#[non_exhaustive]
928pub struct ImageMeta {
929    /// The camera's pixel format; on the wire, its PFNC name. `viva-pfnc` is
930    /// the one authority on formats (ADR-0030).
931    #[serde(with = "pfnc_name")]
932    #[cfg_attr(feature = "ts", ts(type = "string"))]
933    pub pixel_format: viva_pfnc::PixelFormat,
934    /// Image width in pixels.
935    pub width: u32,
936    /// Image height in pixels.
937    pub height: u32,
938    /// Bytes a frame's payload carries: the camera's `PayloadSize`, padding
939    /// and chunk data included.
940    pub payload_size: u64,
941}
942
943impl ImageMeta {
944    /// Image geometry and the bytes a frame carries.
945    pub fn new(
946        pixel_format: viva_pfnc::PixelFormat,
947        width: u32,
948        height: u32,
949        payload_size: u64,
950    ) -> Self {
951        Self {
952            pixel_format,
953            width,
954            height,
955            payload_size,
956        }
957    }
958}
959
960// ── Announce cadence ─────────────────────────────────────────────────────────
961
962/// How often a service re-announces each camera it serves.
963///
964/// Independent of how often the service *discovers* cameras: the GigE service
965/// announced from inside its discovery loop, every discovery timeout plus
966/// discovery interval (2 s + 5 s), which outlived [`ANNOUNCE_EXPIRY`] and made
967/// cameras flicker in Viva Studio (backlog SVC-01).
968pub const ANNOUNCE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(2);
969
970/// How long a client keeps a camera whose announces have stopped: three
971/// missed [`ANNOUNCE_INTERVAL`]s.
972pub const ANNOUNCE_EXPIRY: std::time::Duration = std::time::Duration::from_secs(6);
973
974// ── Key Expressions ──────────────────────────────────────────────────────────
975
976/// Key expression constants and helpers for the GenICam Zenoh API.
977pub mod keys {
978    /// Wildcard subscription for all device announcements.
979    pub const ANNOUNCE_ALL: &str = "genicam/devices/*/announce";
980
981    /// Where a camera is announced.
982    pub fn announce(device_id: &str) -> String {
983        format!("genicam/devices/{device_id}/announce")
984    }
985
986    /// Where its XML is asked for.
987    pub fn xml(device_id: &str) -> String {
988        format!("genicam/devices/{device_id}/xml")
989    }
990
991    /// Key expression for the diagnostic report queryable.
992    /// Direction: App -> Service (queryable GET).
993    pub fn report(device_id: &str) -> String {
994        format!("genicam/devices/{device_id}/report")
995    }
996
997    /// Where its connection status is published.
998    pub fn status(device_id: &str) -> String {
999        format!("genicam/devices/{device_id}/status")
1000    }
1001
1002    /// Where a feature's value is published.
1003    pub fn node_value(device_id: &str, node_name: &str) -> String {
1004        format!("genicam/devices/{device_id}/nodes/{node_name}/value")
1005    }
1006
1007    /// Every feature value of a camera, for a subscriber.
1008    pub fn node_value_wildcard(device_id: &str) -> String {
1009        format!("genicam/devices/{device_id}/nodes/*/value")
1010    }
1011
1012    /// Where a feature is written.
1013    pub fn node_set(device_id: &str, node_name: &str) -> String {
1014        format!("genicam/devices/{device_id}/nodes/{node_name}/set")
1015    }
1016
1017    /// Where a command is executed.
1018    pub fn node_execute(device_id: &str, node_name: &str) -> String {
1019        format!("genicam/devices/{device_id}/nodes/{node_name}/execute")
1020    }
1021
1022    /// Key expression for a single-node [`super::FeatureState`] queryable.
1023    /// Direction: App -> Service (queryable GET). Reply payload is a
1024    /// [`super::FeatureState`] JSON object.
1025    pub fn node_introspect(device_id: &str, node_name: &str) -> String {
1026        format!("genicam/devices/{device_id}/nodes/{node_name}/state")
1027    }
1028
1029    /// Wildcard subscription for every node's [`super::FeatureState`]
1030    /// publication. Direction: Service -> App.
1031    pub fn node_state_wildcard(device_id: &str) -> String {
1032        format!("genicam/devices/{device_id}/nodes/*/state")
1033    }
1034
1035    /// Key expression for the bulk node read queryable.
1036    /// Direction: App -> Service (queryable GET).
1037    pub fn nodes_bulk_read(device_id: &str) -> String {
1038        format!("genicam/devices/{device_id}/nodes/bulk/read")
1039    }
1040
1041    /// Key expression for the bulk [`super::FeatureState`] queryable.
1042    /// Direction: App -> Service (queryable GET). Reply payload is a
1043    /// `HashMap<String, FeatureState>` JSON object.
1044    pub fn nodes_bulk_state(device_id: &str) -> String {
1045        format!("genicam/devices/{device_id}/nodes/bulk/state")
1046    }
1047
1048    /// Where acquisition is started and stopped.
1049    pub fn acquisition_control(device_id: &str) -> String {
1050        format!("genicam/devices/{device_id}/acquisition/control")
1051    }
1052
1053    /// Where acquisition status is published.
1054    pub fn acquisition_status(device_id: &str) -> String {
1055        format!("genicam/devices/{device_id}/acquisition/status")
1056    }
1057
1058    /// Where image frames are published.
1059    pub fn image(device_id: &str) -> String {
1060        format!("genicam/devices/{device_id}/image")
1061    }
1062
1063    /// Where image metadata is published.
1064    pub fn image_meta(device_id: &str) -> String {
1065        format!("genicam/devices/{device_id}/image/meta")
1066    }
1067
1068    /// Key expression for event-vision blocks.
1069    /// Direction: Service -> subscribers (`put` per block). Payload is a
1070    /// [`super::EvsHeader`] followed by the encoded events.
1071    ///
1072    /// Event data never goes on [`image`]: it has no image geometry, and
1073    /// before API version 4 an event block was published there as a
1074    /// 1 × N "image" in a format clients decode as `Unknown`. Named `evs`,
1075    /// not `events`, so it cannot be mistaken for GenICam device events
1076    /// (GVCP `EVENT` messages such as `EventExposureEnd`).
1077    pub fn evs(device_id: &str) -> String {
1078        format!("genicam/devices/{device_id}/evs")
1079    }
1080
1081    /// Where a `<Register>` node's bytes are read.
1082    /// Direction: App -> Service (queryable GET, no payload). The reply is a
1083    /// [`super::RegisterData`], or an error reply when the read failed.
1084    pub fn node_register(device_id: &str, node_name: &str) -> String {
1085        format!("genicam/devices/{device_id}/nodes/{node_name}/register")
1086    }
1087
1088    /// Where a `<Register>` node's bytes are written.
1089    /// Direction: App -> Service (queryable GET). Payload is a
1090    /// [`super::RegisterWriteRequest`]; the reply a [`super::NodeOpResponse`]
1091    /// naming the features the write invalidated.
1092    pub fn node_register_set(device_id: &str, node_name: &str) -> String {
1093        format!("genicam/devices/{device_id}/nodes/{node_name}/register_set")
1094    }
1095
1096    /// Where the camera's configuration is saved: every feature its XML
1097    /// marks `<Streamable>`, as a GenApi feature file (ADR-0028).
1098    /// Direction: App -> Service (queryable GET, no payload). The reply is a
1099    /// [`super::ConfigurationSaved`].
1100    pub fn configuration_save(device_id: &str) -> String {
1101        format!("genicam/devices/{device_id}/configuration/save")
1102    }
1103
1104    /// Where a saved configuration is restored to the camera.
1105    /// Direction: App -> Service (queryable GET). Payload is a
1106    /// [`super::ConfigurationLoadRequest`]; the reply a
1107    /// [`super::ConfigurationLoaded`], or an error reply for a file that
1108    /// cannot be read.
1109    pub fn configuration_load(device_id: &str) -> String {
1110        format!("genicam/devices/{device_id}/configuration/load")
1111    }
1112
1113    /// Where GenICam device events are started and stopped.
1114    /// Direction: App -> Service (queryable GET). Payload is a
1115    /// [`super::EventControlRequest`]; the reply is a
1116    /// [`super::EventMonitorStatus`], or an error reply when starting failed.
1117    pub fn events_control(device_id: &str) -> String {
1118        format!("genicam/devices/{device_id}/events/control")
1119    }
1120
1121    /// Where each GenICam device event is published while monitoring is on.
1122    /// Direction: Service -> App (`put` per event). Payload is a
1123    /// [`super::CameraEvent`]. Not [`evs`], which carries event-vision
1124    /// pixels.
1125    pub fn events(device_id: &str) -> String {
1126        format!("genicam/devices/{device_id}/events")
1127    }
1128
1129    /// Where event monitoring status is published: on every start and stop,
1130    /// and when monitoring ends by itself. Direction: Service -> App.
1131    /// Payload is a [`super::EventMonitorStatus`].
1132    pub fn events_status(device_id: &str) -> String {
1133        format!("genicam/devices/{device_id}/events/status")
1134    }
1135
1136    /// Extract node name from `genicam/devices/{id}/nodes/{name}/{suffix}`
1137    /// where suffix is `"value"`, `"set"`, `"execute"`, `"state"`,
1138    /// `"register"` or `"register_set"`.
1139    pub fn extract_node_name(key: &str) -> Option<&str> {
1140        let parts: Vec<&str> = key.split('/').collect();
1141        if parts.len() >= 6 && parts[parts.len() - 3] == "nodes" {
1142            Some(parts[parts.len() - 2])
1143        } else {
1144            None
1145        }
1146    }
1147}
1148
1149#[cfg(test)]
1150mod tests {
1151    use super::*;
1152
1153    /// A USB3 Vision camera is keyed by what it is — vendor, product,
1154    /// serial — not where it is plugged in, so moving it to another port
1155    /// keeps its id (UV-03); only a camera without a serial falls back to
1156    /// its bus position. Whatever the serial holds, the id is one key
1157    /// expression chunk.
1158    #[test]
1159    fn a_u3v_device_id_is_keyed_by_serial() {
1160        assert_eq!(
1161            u3v_device_id(0x164c, 0x5533, Some("FF003089"), "1", 3),
1162            "cam-u3v-164c5533-FF003089"
1163        );
1164        assert_eq!(
1165            u3v_device_id(0x164c, 0x5533, Some("FF003089"), "20", 9),
1166            u3v_device_id(0x164c, 0x5533, Some("FF003089"), "1", 3),
1167        );
1168        assert_eq!(
1169            u3v_device_id(0x2676, 0xba02, None, "2", 7),
1170            "cam-u3v-2676ba02-2-7"
1171        );
1172        assert_eq!(
1173            u3v_device_id(0x2676, 0xba02, Some("  "), "2", 7),
1174            "cam-u3v-2676ba02-2-7"
1175        );
1176        assert_eq!(
1177            u3v_device_id(0x2676, 0xba02, Some("a/b*c$#?"), "2", 7),
1178            "cam-u3v-2676ba02-a_2fb_2ac_24_23_3f"
1179        );
1180    }
1181
1182    /// Codex review of #205: replacing each character a key cannot carry by
1183    /// `_` made `a/b` and `a*b` one id, and discovery skipped the second
1184    /// camera. The escape is reversible, so distinct serials stay distinct.
1185    #[test]
1186    fn serials_that_differ_only_where_a_key_cannot_carry_them_stay_distinct() {
1187        let id = |serial| u3v_device_id(0x2676, 0xba02, Some(serial), "2", 7);
1188        assert_ne!(id("a/b"), id("a*b"));
1189        assert_ne!(id("a_b"), id("a/b"));
1190        assert_ne!(id("a_2fb"), id("a/b"));
1191    }
1192
1193    #[test]
1194    fn test_device_announce_deserializes_without_api_version() {
1195        let legacy = r#"{"id":"cam0","name":"Test Cam","model":"M1","serial":"S1"}"#;
1196        let a: DeviceAnnounce = serde_json::from_str(legacy).expect("should deserialize");
1197        assert!(
1198            a.api_version.is_none(),
1199            "api_version should be None for legacy JSON"
1200        );
1201    }
1202
1203    #[test]
1204    fn test_device_announce_deserializes_with_api_version() {
1205        let json = r#"{"id":"cam0","name":"Test","model":"M","serial":"S","api_version":1}"#;
1206        let a: DeviceAnnounce = serde_json::from_str(json).expect("should deserialize");
1207        assert_eq!(a.api_version, Some(1));
1208    }
1209
1210    #[test]
1211    fn device_announce_round_trips_every_identity_field() {
1212        let mut a = DeviceAnnounce::new("cam-deadbeefcafe", "Left", "FakeGigE", "FAKE-001");
1213        a.ip = Some("192.168.1.10".into());
1214        a.mac = Some("DE:AD:BE:EF:CA:FE".into());
1215        a.user_name = Some("Left".into());
1216        a.manufacturer = Some("viva-genicam".into());
1217        let json = serde_json::to_string(&a).expect("serialize");
1218        let back: DeviceAnnounce = serde_json::from_str(&json).expect("deserialize");
1219        assert_eq!(back, a);
1220        assert_eq!(back.api_version, Some(API_VERSION));
1221    }
1222
1223    #[test]
1224    fn device_announce_omits_unset_identity_fields() {
1225        let a = DeviceAnnounce::new("cam-u3v-00010002", "U3V", "U3V", "");
1226        let json = serde_json::to_string(&a).expect("serialize");
1227        for field in ["ip", "mac", "user_name", "manufacturer"] {
1228            assert!(!json.contains(&format!("\"{field}\"")), "{field} in {json}");
1229        }
1230        let back: DeviceAnnounce = serde_json::from_str(&json).expect("deserialize");
1231        assert_eq!(back, a);
1232    }
1233
1234    /// What a version 2 service publishes: the device id in `serial` and none
1235    /// of the identity fields. It must still deserialise, or upgrading the app
1236    /// would make every older service's cameras disappear.
1237    #[test]
1238    fn device_announce_deserializes_a_version_2_payload() {
1239        let v2 = r#"{"id":"cam-deadbeefcafe","name":"FakeGigE","model":"FakeGigE","serial":"cam-deadbeefcafe","api_version":2}"#;
1240        let a: DeviceAnnounce = serde_json::from_str(v2).expect("should deserialize");
1241        assert_eq!(a.api_version, Some(2));
1242        assert_eq!(a.serial, "cam-deadbeefcafe");
1243        assert_eq!(a.ip, None);
1244        assert_eq!(a.mac, None);
1245        assert_eq!(a.user_name, None);
1246        assert_eq!(a.manufacturer, None);
1247    }
1248
1249    #[test]
1250    fn for_gige_carries_the_device_identity() {
1251        let a = DeviceAnnounce::for_gige(
1252            &[0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE],
1253            std::net::Ipv4Addr::new(192, 168, 1, 10),
1254            Some("FakeGigE"),
1255            Some("FAKE-001"),
1256            Some("Left"),
1257            Some("viva-genicam"),
1258        );
1259        assert_eq!(a.id, "cam-deadbeefcafe");
1260        assert_eq!(a.name, "Left");
1261        assert_eq!(a.model, "FakeGigE");
1262        assert_eq!(a.serial, "FAKE-001");
1263        assert_eq!(a.ip.as_deref(), Some("192.168.1.10"));
1264        assert_eq!(a.mac.as_deref(), Some("DE:AD:BE:EF:CA:FE"));
1265        assert_eq!(a.user_name.as_deref(), Some("Left"));
1266        assert_eq!(a.manufacturer.as_deref(), Some("viva-genicam"));
1267        assert_eq!(a.api_version, Some(API_VERSION));
1268    }
1269
1270    #[test]
1271    fn for_gige_names_by_user_name_then_model_then_address() {
1272        let mac = [0, 1, 2, 3, 4, 5];
1273        let ip = std::net::Ipv4Addr::new(10, 0, 0, 7);
1274        let name = |model, user_name| {
1275            DeviceAnnounce::for_gige(&mac, ip, model, None, user_name, None).name
1276        };
1277        assert_eq!(name(Some("M"), Some("U")), "U");
1278        assert_eq!(name(Some("M"), None), "M");
1279        assert_eq!(name(None, None), "10.0.0.7");
1280    }
1281
1282    /// An absent serial stays empty: services before version 3 filled it with
1283    /// the device id, which is not a serial and read as one.
1284    #[test]
1285    fn for_gige_does_not_invent_a_serial() {
1286        let a = DeviceAnnounce::for_gige(
1287            &[0, 1, 2, 3, 4, 5],
1288            std::net::Ipv4Addr::new(10, 0, 0, 7),
1289            Some("M"),
1290            None,
1291            None,
1292            None,
1293        );
1294        assert_eq!(a.serial, "");
1295        assert_eq!(a.user_name, None);
1296        assert_eq!(a.manufacturer, None);
1297    }
1298
1299    #[test]
1300    fn gige_device_id_is_lowercase_mac_hex() {
1301        assert_eq!(
1302            gige_device_id(&[0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE]),
1303            "cam-deadbeefcafe"
1304        );
1305        assert_eq!(
1306            gige_device_id(&[0x00, 0x0C, 0xDF, 0x06, 0x5B, 0x2F]),
1307            "cam-000cdf065b2f"
1308        );
1309    }
1310
1311    #[test]
1312    fn test_node_value_update_without_constraints() {
1313        let u = NodeValueUpdate {
1314            value: serde_json::json!(42),
1315            access_mode: "RW".to_string(),
1316            min: None,
1317            max: None,
1318            inc: None,
1319        };
1320        let s = serde_json::to_string(&u).expect("serialization failed");
1321        assert!(!s.contains("\"min\""), "min should be absent: {s}");
1322        assert!(!s.contains("\"max\""), "max should be absent: {s}");
1323        assert!(!s.contains("\"inc\""), "inc should be absent: {s}");
1324        assert!(s.contains("\"value\""));
1325        assert!(s.contains("\"access_mode\""));
1326    }
1327
1328    #[test]
1329    fn test_node_value_update_with_constraints() {
1330        let u = NodeValueUpdate {
1331            value: serde_json::json!(1024),
1332            access_mode: "RW".to_string(),
1333            min: Some(1.0),
1334            max: Some(4096.0),
1335            inc: Some(1.0),
1336        };
1337        let s = serde_json::to_string(&u).expect("serialization failed");
1338        let d: NodeValueUpdate = serde_json::from_str(&s).expect("deserialization failed");
1339        assert_eq!(d.min, Some(1.0));
1340        assert_eq!(d.max, Some(4096.0));
1341        assert_eq!(d.inc, Some(1.0));
1342        assert_eq!(d.access_mode, "RW");
1343    }
1344
1345    #[test]
1346    fn test_extract_node_name_value_key() {
1347        assert_eq!(
1348            keys::extract_node_name("genicam/devices/cam0/nodes/Width/value"),
1349            Some("Width")
1350        );
1351    }
1352
1353    #[test]
1354    fn test_extract_node_name_set_key() {
1355        assert_eq!(
1356            keys::extract_node_name("genicam/devices/cam0/nodes/Width/set"),
1357            Some("Width")
1358        );
1359    }
1360
1361    #[test]
1362    fn test_extract_node_name_execute_key() {
1363        assert_eq!(
1364            keys::extract_node_name("genicam/devices/cam0/nodes/AcquisitionStart/execute"),
1365            Some("AcquisitionStart")
1366        );
1367    }
1368
1369    #[test]
1370    fn test_extract_node_name_register_keys() {
1371        for key in [
1372            keys::node_register("cam0", "DeviceUserBuffer"),
1373            keys::node_register_set("cam0", "DeviceUserBuffer"),
1374        ] {
1375            assert_eq!(
1376                keys::extract_node_name(&key),
1377                Some("DeviceUserBuffer"),
1378                "{key}"
1379            );
1380        }
1381    }
1382
1383    #[test]
1384    fn test_extract_node_name_too_short() {
1385        assert_eq!(keys::extract_node_name("genicam/devices/cam0"), None);
1386    }
1387
1388    #[test]
1389    fn test_extract_node_name_non_node_key() {
1390        assert_eq!(
1391            keys::extract_node_name("genicam/devices/cam0/acquisition/control/something"),
1392            None
1393        );
1394    }
1395
1396    #[test]
1397    fn test_node_value_update_deserializes_legacy() {
1398        let legacy = r#"{"value": 1024, "access_mode": "RW"}"#;
1399        let d: NodeValueUpdate = serde_json::from_str(legacy).expect("deserialization failed");
1400        assert!(d.min.is_none());
1401        assert!(d.max.is_none());
1402        assert!(d.inc.is_none());
1403        assert_eq!(d.access_mode, "RW");
1404    }
1405
1406    // ── FeatureState ────────────────────────────────────────────────────────
1407
1408    /// GA-05: the wire state says how to refresh a feature — its polling time
1409    /// and its caching mode, both resolved along its value path — so a remote
1410    /// viewer polls what a local one does.
1411    #[cfg(feature = "genapi")]
1412    #[test]
1413    fn a_genapi_state_carries_its_polling_time_and_caching_mode() {
1414        let xml = r#"<RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">
1415            <Float Name="DeviceTemperature"><pValue>DeviceTemperatureReg</pValue></Float>
1416            <FloatReg Name="DeviceTemperatureReg"><Address>0x0</Address><Length>4</Length><AccessMode>RO</AccessMode><Cachable>NoCache</Cachable><PollingTime>500</PollingTime></FloatReg>
1417            <Integer Name="Width"><Address>0x4</Address><Length>4</Length><AccessMode>RW</AccessMode></Integer>
1418        </RegisterDescription>"#;
1419        let model = viva_genapi_xml::parse(xml).expect("parse");
1420        let map = viva_genapi::NodeMap::try_from_xml(model).expect("build");
1421        let io = viva_genapi::NullIo;
1422        let wire = FeatureState::from(map.feature_state("DeviceTemperature", &io).unwrap());
1423        assert_eq!(wire.polling_ms, Some(500));
1424        assert_eq!(wire.caching.as_deref(), Some("NoCache"));
1425        let json = serde_json::to_string(&wire).unwrap();
1426        assert!(json.contains(r#""polling_ms":500"#), "{json}");
1427        let wire = FeatureState::from(map.feature_state("Width", &io).unwrap());
1428        assert_eq!(wire.polling_ms, None);
1429        assert_eq!(wire.caching.as_deref(), Some("WriteThrough"));
1430    }
1431
1432    // ── AcquisitionStatus ───────────────────────────────────────────────────
1433
1434    /// The status carries the stream's counters, and a stopped stream's final
1435    /// ones, so a client can show more than one lost-frame count.
1436    #[test]
1437    fn an_acquisition_status_round_trips_its_counters() {
1438        let stats = StreamCounters {
1439            frames_complete: 2_410,
1440            frames_incomplete: 2,
1441            frames_missed: 1,
1442            packets_received: 1_000_000,
1443            transfer_errors: 3,
1444            avg_mbps: 812.5,
1445            avg_latency_ms: Some(1.25),
1446            elapsed_ms: 10_000,
1447            ..Default::default()
1448        };
1449
1450        for status in [
1451            AcquisitionStatus::active(Some(241.0), Some(stats)),
1452            AcquisitionStatus::stopped(stats),
1453        ] {
1454            let json = serde_json::to_string(&status).unwrap();
1455            let back: AcquisitionStatus = serde_json::from_str(&json).unwrap();
1456            assert_eq!(back, status, "{json}");
1457        }
1458        assert_eq!(stats.frames_lost(), 3);
1459        let stopped = AcquisitionStatus::stopped(stats);
1460        assert!(!stopped.active);
1461        assert_eq!(stopped.fps, None);
1462
1463        // Nothing to count says so, rather than a row of zeros.
1464        let json = serde_json::to_value(AcquisitionStatus::inactive()).unwrap();
1465        assert_eq!(
1466            json,
1467            serde_json::json!({ "active": false, "fps": null, "stats": null })
1468        );
1469    }
1470
1471    /// The six reasons a packet goes unused are one count on the wire, and
1472    /// the elapsed time is whole milliseconds.
1473    #[cfg(feature = "genicam")]
1474    #[test]
1475    fn stream_counters_carry_the_librarys_stream_stats() {
1476        let mut stats = viva_genicam::StreamStats::default();
1477        stats.frames_complete = 10;
1478        stats.frames_incomplete = 1;
1479        stats.frames_missed = 2;
1480        stats.frames_backpressure = 3;
1481        stats.frames_unsupported = 4;
1482        stats.packets_received = 500;
1483        stats.packets_missing = 5;
1484        stats.packets_duplicate = 6;
1485        stats.packets_ignored_malformed = 1;
1486        stats.packets_ignored_unsupported = 2;
1487        stats.packets_ignored_out_of_range = 3;
1488        stats.packets_ignored_late = 4;
1489        stats.packets_ignored_error_status = 5;
1490        stats.packets_ignored_foreign = 6;
1491        stats.resend_requested = 7;
1492        stats.resend_recovered = 8;
1493        stats.resend_unavailable = 9;
1494        stats.transfer_errors = 11;
1495        stats.bytes = 12_345;
1496        stats.avg_mbps = 98.5;
1497        stats.avg_latency_ms = Some(0.5);
1498        stats.elapsed = std::time::Duration::from_micros(2_500_900);
1499
1500        let wire = StreamCounters::from(&stats);
1501        assert_eq!(wire.packets_ignored, 21);
1502        assert_eq!(wire.packets_ignored, stats.packets_ignored());
1503        assert_eq!(wire.elapsed_ms, 2_500);
1504        assert_eq!(wire.frames_lost(), stats.frames_lost());
1505        assert_eq!(
1506            (
1507                wire.frames_complete,
1508                wire.frames_incomplete,
1509                wire.frames_missed,
1510                wire.frames_backpressure,
1511                wire.frames_unsupported,
1512            ),
1513            (10, 1, 2, 3, 4)
1514        );
1515        assert_eq!(
1516            (
1517                wire.packets_received,
1518                wire.packets_missing,
1519                wire.packets_duplicate,
1520            ),
1521            (500, 5, 6)
1522        );
1523        assert_eq!(
1524            (
1525                wire.resend_requested,
1526                wire.resend_recovered,
1527                wire.resend_unavailable,
1528                wire.transfer_errors,
1529            ),
1530            (7, 8, 9, 11)
1531        );
1532        assert_eq!(wire.bytes, 12_345);
1533        assert_eq!(wire.avg_mbps, 98.5);
1534        assert_eq!(wire.avg_latency_ms, Some(0.5));
1535    }
1536
1537    #[test]
1538    fn test_feature_state_minimal_roundtrip() {
1539        let s = FeatureState {
1540            value: serde_json::json!(1920),
1541            access_mode: "RW".to_string(),
1542            kind: "Integer".to_string(),
1543            is_implemented: true,
1544            is_available: true,
1545            numeric: None,
1546            enum_available: None,
1547            unit: None,
1548            polling_ms: None,
1549            caching: None,
1550        };
1551        let j = serde_json::to_string(&s).expect("serialize");
1552        // Optional fields should be skipped.
1553        assert!(!j.contains("\"numeric\""), "numeric should be absent: {j}");
1554        assert!(
1555            !j.contains("\"enum_available\""),
1556            "enum_available absent: {j}"
1557        );
1558        assert!(!j.contains("\"unit\""), "unit absent: {j}");
1559        let d: FeatureState = serde_json::from_str(&j).expect("deserialize");
1560        assert_eq!(d, s);
1561    }
1562
1563    #[test]
1564    fn test_feature_state_defaults_when_fields_missing() {
1565        // A service that does not yet populate is_implemented/is_available
1566        // must still deserialize into a usable state.
1567        let legacy = r#"{"value":1920,"access_mode":"RW","kind":"Integer"}"#;
1568        let d: FeatureState = serde_json::from_str(legacy).expect("deserialize");
1569        assert!(d.is_implemented, "is_implemented defaults to true");
1570        assert!(d.is_available, "is_available defaults to true");
1571    }
1572
1573    #[test]
1574    fn test_feature_state_integer_with_range() {
1575        let s = FeatureState {
1576            value: serde_json::json!(512),
1577            access_mode: "RW".to_string(),
1578            kind: "Integer".to_string(),
1579            is_implemented: true,
1580            is_available: true,
1581            numeric: Some(NumericRange {
1582                min: 16.0,
1583                max: 4096.0,
1584                inc: Some(8.0),
1585            }),
1586            enum_available: None,
1587            unit: Some("px".to_string()),
1588            polling_ms: None,
1589            caching: None,
1590        };
1591        let j = serde_json::to_string(&s).expect("serialize");
1592        let d: FeatureState = serde_json::from_str(&j).expect("deserialize");
1593        assert_eq!(d, s);
1594    }
1595
1596    #[test]
1597    fn test_feature_state_to_node_value_update() {
1598        let s = FeatureState {
1599            value: serde_json::json!(512),
1600            access_mode: "RW".to_string(),
1601            kind: "Integer".to_string(),
1602            is_implemented: true,
1603            is_available: true,
1604            numeric: Some(NumericRange {
1605                min: 16.0,
1606                max: 4096.0,
1607                inc: Some(8.0),
1608            }),
1609            enum_available: None,
1610            unit: None,
1611            polling_ms: None,
1612            caching: None,
1613        };
1614        let u: NodeValueUpdate = (&s).into();
1615        assert_eq!(u.value, serde_json::json!(512));
1616        assert_eq!(u.access_mode, "RW");
1617        assert_eq!(u.min, Some(16.0));
1618        assert_eq!(u.max, Some(4096.0));
1619        assert_eq!(u.inc, Some(8.0));
1620    }
1621
1622    #[test]
1623    fn test_feature_state_enumeration() {
1624        let s = FeatureState {
1625            value: serde_json::json!("Once"),
1626            access_mode: "RW".to_string(),
1627            kind: "Enumeration".to_string(),
1628            is_implemented: true,
1629            is_available: true,
1630            numeric: None,
1631            enum_available: Some(vec!["Off".to_string(), "Once".to_string()]),
1632            unit: None,
1633            polling_ms: None,
1634            caching: None,
1635        };
1636        let j = serde_json::to_string(&s).expect("serialize");
1637        assert!(j.contains("\"enum_available\""));
1638        let d: FeatureState = serde_json::from_str(&j).expect("deserialize");
1639        assert_eq!(
1640            d.enum_available.as_deref(),
1641            Some(&["Off".to_string(), "Once".to_string()][..])
1642        );
1643    }
1644
1645    #[test]
1646    fn test_command_result_ok_empty() {
1647        let r = CommandResult {
1648            ok: true,
1649            error: None,
1650            affected_states: std::collections::HashMap::new(),
1651        };
1652        let j = serde_json::to_string(&r).expect("serialize");
1653        assert!(
1654            !j.contains("\"affected_states\""),
1655            "empty affected_states should be skipped: {j}"
1656        );
1657        assert!(
1658            !j.contains("\"error\""),
1659            "none error should be skipped: {j}"
1660        );
1661    }
1662
1663    #[test]
1664    fn test_command_result_with_affected_states() {
1665        let mut affected = std::collections::HashMap::new();
1666        affected.insert(
1667            "AcquisitionStatus".to_string(),
1668            FeatureState {
1669                value: serde_json::json!(true),
1670                access_mode: "RO".to_string(),
1671                kind: "Boolean".to_string(),
1672                is_implemented: true,
1673                is_available: true,
1674                numeric: None,
1675                enum_available: None,
1676                unit: None,
1677                polling_ms: None,
1678                caching: None,
1679            },
1680        );
1681        let r = CommandResult {
1682            ok: true,
1683            error: None,
1684            affected_states: affected,
1685        };
1686        let j = serde_json::to_string(&r).expect("serialize");
1687        let d: CommandResult = serde_json::from_str(&j).expect("deserialize");
1688        assert!(d.ok);
1689        assert_eq!(d.affected_states.len(), 1);
1690        assert!(d.affected_states.contains_key("AcquisitionStatus"));
1691    }
1692
1693    /// `ImageMeta` names the camera's format as PFNC does, every format PFNC
1694    /// names: the wire's own enum named 54 and sent the rest as `"Unknown"`
1695    /// (backlog API-10).
1696    #[test]
1697    fn image_meta_names_the_format_as_pfnc_does() {
1698        for (format, name) in [
1699            (viva_pfnc::PixelFormat::Mono8, "Mono8"),
1700            (viva_pfnc::PixelFormat::RGB8Packed, "RGB8Packed"),
1701            (viva_pfnc::PixelFormat::Coord3DC16, "Coord3D_C16"),
1702            (viva_pfnc::PixelFormat::Coord3DABC32f, "Coord3D_ABC32f"),
1703            (viva_pfnc::PixelFormat::from_code(0x0123_4567), "Unknown"),
1704        ] {
1705            let meta = ImageMeta::new(format, 4, 2, 8);
1706            let json = serde_json::to_value(&meta).expect("serialize");
1707            assert_eq!(json["pixel_format"], name, "{format}");
1708        }
1709    }
1710
1711    /// A client reads the name back, the older spellings cameras use too.
1712    #[test]
1713    fn image_meta_reads_the_pfnc_name_and_its_older_spellings() {
1714        for (name, format) in [
1715            ("Mono12Packed", viva_pfnc::PixelFormat::Mono12Packed),
1716            ("RGB8", viva_pfnc::PixelFormat::RGB8Packed),
1717            ("YUV422Packed", viva_pfnc::PixelFormat::YUV422_8_UYVY),
1718            ("Fancy42", viva_pfnc::PixelFormat::Unknown(0)),
1719        ] {
1720            let json =
1721                format!(r#"{{"pixel_format":"{name}","width":1,"height":1,"payload_size":1}}"#);
1722            let meta: ImageMeta = serde_json::from_str(&json).expect("deserialize");
1723            assert_eq!(meta.pixel_format, format, "{name}");
1724        }
1725    }
1726}