Skip to main content

viva_genapi/
state.rs

1//! A feature's live state: what it holds and what it permits, read at once.
2//!
3//! A viewer needs more than a value to draw a control. It needs to know
4//! whether the feature exists on this device, whether it is available in the
5//! current selector state, whether it can be written now, its current range
6//! and the enumeration entries the device will accept. [`NodeMap::feature_state`]
7//! gathers all of it in one call, so every consumer — the camera services and
8//! Viva Studio among them — computes it the same way ([ADR-0010], backlog
9//! ST-26).
10//!
11//! [ADR-0010]: https://github.com/VitalyVorobyev/viva-genicam/blob/main/docs/adrs/adr0010-feature-state-contract.md
12
13use std::collections::HashSet;
14
15use tracing::{debug, warn};
16use viva_genapi_xml::{AccessMode, CachingMode};
17
18use crate::nodemap::Limit;
19use crate::nodes::Node;
20use crate::{GenApiError, NodeMap, RegisterIo, SkOutput};
21
22/// The live state of one feature, read from the device in a single call.
23///
24/// See [`NodeMap::feature_state`].
25#[derive(Debug, Clone, PartialEq)]
26#[non_exhaustive]
27pub struct FeatureState {
28    /// GenICam node type, as [`Node::kind_name`] spells it.
29    pub kind: &'static str,
30    /// The current value, or [`FeatureValue::None`] for a feature that has
31    /// none to read.
32    pub value: FeatureValue,
33    /// What the feature permits now: the declared mode along its `<pValue>`
34    /// chain, made `RO` by a lock or by being unavailable.
35    ///
36    /// `None` means neither reading nor writing is possible, or the node has
37    /// no access mode at all, as a category does.
38    pub access: Option<AccessMode>,
39    /// `pIsImplemented`: whether the device has this feature at all.
40    pub is_implemented: bool,
41    /// `pIsAvailable` and selector gating: whether the feature can be used in
42    /// the device's current state.
43    pub is_available: bool,
44    /// Current bounds of an Integer, Float or converter feature; `None` when
45    /// either bound is unknown — not declared, or declared through a `<pMin>`
46    /// or `<pMax>` that could not be read. A converter's are its `<pValue>`'s
47    /// mapped through `<FormulaFrom>` and `<Slope>`.
48    pub range: Option<ValueRange>,
49    /// The entries an Enumeration accepts now, after their own
50    /// `pIsImplemented`/`pIsAvailable`.
51    pub enum_entries: Option<Vec<String>>,
52    /// Engineering unit, such as `"us"`.
53    pub unit: Option<String>,
54    /// How long a viewer may show this value before reading it again: the
55    /// `<PollingTime>` of the feature or of a register its value is read
56    /// through ([`NodeMap::polling_time`]). `None` when nothing polls it.
57    pub polling_time: Option<std::time::Duration>,
58    /// Whether, and how, its value may be answered from a cache
59    /// ([`NodeMap::caching_mode`]). A `NoCache` feature without a polling
60    /// time changes on the device with nothing to say when.
61    pub caching: CachingMode,
62}
63
64/// A feature's current value, typed by the node that holds it.
65#[derive(Debug, Clone, PartialEq)]
66#[non_exhaustive]
67pub enum FeatureValue {
68    /// Nothing to read: a category, a command, a write-only feature, a node a
69    /// command writes through, or a feature not implemented or not available
70    /// now.
71    None,
72    /// An Integer, IntConverter or integer SwissKnife.
73    Integer(i64),
74    /// A Float, Converter or float SwissKnife.
75    Float(f64),
76    /// A Boolean.
77    Boolean(bool),
78    /// The symbolic name of an Enumeration's current entry.
79    Enum(String),
80    /// A StringReg.
81    String(String),
82    /// A raw `<Register>`, reported by size rather than content.
83    ///
84    /// A register can be very large — the Micro-Epsilon scanCONTROL declares
85    /// a 100 000-byte `FileAccessBuffer` — and viewers poll feature state, so
86    /// copying the payload into every snapshot would be a poor trade for a
87    /// value nothing renders. Read it with [`NodeMap::get_register`].
88    Register {
89        /// Length in bytes: its `<Length>`, or what its `<pLength>` node
90        /// reads now.
91        len: u32,
92    },
93}
94
95/// The current bounds of a numeric feature.
96#[derive(Debug, Clone, Copy, PartialEq)]
97pub struct ValueRange {
98    /// Smallest accepted value.
99    pub min: f64,
100    /// Largest accepted value.
101    pub max: f64,
102    /// Step between accepted values, when the feature declares one.
103    pub inc: Option<f64>,
104}
105
106impl NodeMap {
107    /// Read everything a viewer needs about `name` from the device: its value,
108    /// what it permits now, whether it is implemented and available, its
109    /// range, the enumeration entries it accepts, and its unit.
110    ///
111    /// Only a node that has a value is read. A write-only node refuses the
112    /// read — locally, or with the device's `ACCESS_DENIED` — and a node a
113    /// command writes through holds a trigger, not a value; some devices even
114    /// treat reading one as significant (issues #112, #135). Both are reported
115    /// with [`FeatureValue::None`] and their access mode, so a viewer still
116    /// offers the write or the execute.
117    ///
118    /// A feature that is not implemented, or not available now, is not read
119    /// either — not its value, its `<pMin>`/`<pMax>` or its entries'
120    /// predicates. GenApi forbids value access on such a node, and cameras
121    /// commonly refuse to read the register behind it. It is reported with
122    /// [`FeatureValue::None`], its static range and its declared entries.
123    ///
124    /// A predicate that cannot be evaluated — its register refused, its link
125    /// down — is not satisfied, and is logged: an unread `pIsImplemented`
126    /// reports the feature not implemented, an unread `pIsAvailable` not
127    /// available, an unread `pIsLocked` locked (backlog GA-58: an Allied Vision
128    /// Manta G-125B refuses the inquiry register of the lens control it does
129    /// not have). A failed value read is an error.
130    pub fn feature_state(
131        &self,
132        name: &str,
133        io: &dyn RegisterIo,
134    ) -> Result<FeatureState, GenApiError> {
135        let node = self
136            .node(name)
137            .ok_or_else(|| GenApiError::NodeNotFound(name.to_string()))?;
138
139        // A predicate the device will not let us read has no value to satisfy
140        // it (GA-58). Each failure is logged once, with what it was taken
141        // for: the same path carries a register the camera does not have
142        // and a link that dropped mid-read, and only the log tells them apart.
143        let is_implemented = self.is_implemented(name, io).unwrap_or_else(|e| {
144            warn!(%name, error = %e, "pIsImplemented could not be read: not implemented");
145            false
146        });
147        let is_available = is_implemented
148            && self.own_availability(name, io).unwrap_or_else(|e| {
149                warn!(%name, error = %e, "pIsAvailable could not be read: not available");
150                false
151            });
152        let declared = self.declared_access_mode(name);
153        let access = match declared {
154            // A node with no access at all, as a category, stays without one.
155            None => None,
156            // Unavailable: nothing can be written now.
157            Some(_) if !is_available => Some(AccessMode::RO),
158            Some(_) => {
159                let base = match self.access_now(name, io) {
160                    Ok(mode) => mode.unwrap_or(AccessMode::RO),
161                    Err(e) => {
162                        warn!(%name, error = %e, "the access of the selected value could not be read");
163                        declared.unwrap_or(AccessMode::RO)
164                    }
165                };
166                let locked = self.locked_by(name, io).map_or_else(
167                    |e| {
168                        warn!(%name, error = %e, "pIsLocked could not be read: locked");
169                        true
170                    },
171                    |provider| provider.is_some(),
172                );
173                Some(match base {
174                    AccessMode::RW if locked => AccessMode::RO,
175                    other => other,
176                })
177            }
178        };
179
180        let usable = is_implemented && is_available;
181        // `access` covers the node an indexed value selects now, which the
182        // static `is_write_only` cannot see.
183        let has_value = usable
184            && access != Some(AccessMode::WO)
185            && !self.is_write_only(name)
186            && !self.command_targets().contains(name);
187        // A chunk or event feature with nothing attached has no value now and
188        // cannot be used: the port it reads is "not present" (GenICam
189        // Standard v2.1.1 §2.8.16), as it is between frames.
190        let mut detached = false;
191        let value = if has_value {
192            match self.read_value(node, io) {
193                Err(GenApiError::NotAttached { .. }) => {
194                    detached = true;
195                    FeatureValue::None
196                }
197                other => other?,
198            }
199        } else {
200            FeatureValue::None
201        };
202        let is_available = is_available && !detached;
203        let usable = usable && !detached;
204        let access = if detached { None } else { access };
205
206        // A bound is reported only when something declares it: a `<Min>`,
207        // a `<pMin>`, or one of those on the node `<pValue>` delegates to. A
208        // feature that cannot be used now is not read, so only its own
209        // constants are; a pointer that cannot be read leaves them too.
210        let (range, unit) = match node {
211            Node::Integer(n) => {
212                let bound = |which: Limit, declared: Option<i64>| -> Option<i64> {
213                    if !usable {
214                        return declared;
215                    }
216                    match self.limit(name, which, io, &mut HashSet::new()) {
217                        Ok(value) => value.map(|v| v.as_i64()),
218                        Err(e) => {
219                            warn!(%name, error = %e, ?which, "reading a bound failed");
220                            declared
221                        }
222                    }
223                };
224                let (min, max, inc) = (
225                    bound(Limit::Min, n.min),
226                    bound(Limit::Max, n.max),
227                    bound(Limit::Inc, n.inc),
228                );
229                let range = match (min, max) {
230                    (Some(min), Some(max)) => Some(ValueRange {
231                        min: min as f64,
232                        max: max as f64,
233                        inc: inc.map(|i| i as f64),
234                    }),
235                    _ => None,
236                };
237                (range, n.unit.clone())
238            }
239            Node::Float(_) | Node::Converter(_) | Node::IntConverter(_) => {
240                let (declared_min, declared_max, unit) = match node {
241                    Node::Float(n) => (n.min, n.max, n.unit.clone()),
242                    _ => (None, None, None),
243                };
244                let is_converter = !matches!(node, Node::Float(_));
245                let bound = |which: Limit, declared: Option<f64>| -> Option<f64> {
246                    if !usable {
247                        return declared;
248                    }
249                    match self.limit(name, which, io, &mut HashSet::new()) {
250                        Ok(value) => value.map(|v| v.as_f64()),
251                        // A converter's formula need not be defined at its
252                        // raw bounds (`1 / TO` at 0); that is no fault.
253                        Err(e) if is_converter => {
254                            debug!(%name, error = %e, ?which, "converter bound undefined");
255                            declared
256                        }
257                        Err(e) => {
258                            warn!(%name, error = %e, ?which, "reading a bound failed");
259                            declared
260                        }
261                    }
262                };
263                let range = match (
264                    bound(Limit::Min, declared_min),
265                    bound(Limit::Max, declared_max),
266                ) {
267                    (Some(min), Some(max)) => Some(ValueRange {
268                        min,
269                        max,
270                        inc: None,
271                    }),
272                    _ => None,
273                };
274                (range, unit)
275            }
276            _ => (None, None),
277        };
278
279        let enum_entries = match node {
280            Node::Enum(_) if !usable => self.enum_entries(name).ok(),
281            Node::Enum(_) => self
282                .available_enum_entries(name, io)
283                .or_else(|e| {
284                    warn!(%name, error = %e, "available_enum_entries eval failed");
285                    self.enum_entries(name)
286                })
287                .ok(),
288            _ => None,
289        };
290
291        Ok(FeatureState {
292            kind: node.kind_name(),
293            value,
294            access,
295            is_implemented,
296            is_available,
297            range,
298            enum_entries,
299            unit,
300            polling_time: self.polling_time(name),
301            caching: self.caching_mode(name).unwrap_or(CachingMode::WriteThrough),
302        })
303    }
304
305    fn read_value(&self, node: &Node, io: &dyn RegisterIo) -> Result<FeatureValue, GenApiError> {
306        let name = node.name();
307        Ok(match node {
308            Node::Integer(_) => FeatureValue::Integer(self.get_integer(name, io)?),
309            Node::Float(_) => FeatureValue::Float(self.get_float(name, io)?),
310            Node::Enum(_) => FeatureValue::Enum(self.get_enum(name, io)?),
311            Node::Boolean(_) => FeatureValue::Boolean(self.get_bool(name, io)?),
312            Node::String(_) => FeatureValue::String(self.get_string(name, io)?),
313            Node::Register(reg) => FeatureValue::Register {
314                len: self.register_length(name, &reg.addressing, io)?,
315            },
316            Node::SwissKnife(sk) => match sk.output {
317                SkOutput::Float => FeatureValue::Float(self.get_float(name, io)?),
318                SkOutput::Integer => FeatureValue::Integer(self.get_integer(name, io)?),
319            },
320            Node::Converter(_) => FeatureValue::Float(self.get_converter(name, io)?),
321            Node::IntConverter(_) => FeatureValue::Integer(self.get_int_converter(name, io)?),
322            Node::Command(_) | Node::Category(_) => FeatureValue::None,
323        })
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use std::cell::RefCell;
330    use std::collections::HashMap;
331
332    use super::{FeatureValue, ValueRange};
333    use crate::{AccessMode, GenApiError, NodeMap, RegisterIo};
334
335    /// Register memory; a write lands where a later read finds it. Reads of
336    /// a `denied` address fail, as a camera refuses to read a register its
337    /// feature has gated off.
338    #[derive(Default)]
339    struct MemIo {
340        regs: RefCell<HashMap<u64, Vec<u8>>>,
341        denied: Vec<u64>,
342    }
343
344    impl MemIo {
345        fn with(regs: &[(u64, u32)]) -> Self {
346            let io = Self::default();
347            for &(addr, value) in regs {
348                io.regs
349                    .borrow_mut()
350                    .insert(addr, value.to_be_bytes().to_vec());
351            }
352            io
353        }
354
355        fn denying(mut self, addrs: &[u64]) -> Self {
356            self.denied = addrs.to_vec();
357            self
358        }
359    }
360
361    impl RegisterIo for MemIo {
362        fn read(&self, addr: u64, len: usize) -> Result<Vec<u8>, GenApiError> {
363            if self.denied.contains(&addr) {
364                return Err(GenApiError::io(format!("read of {addr:#x} denied")));
365            }
366            Ok(self
367                .regs
368                .borrow()
369                .get(&addr)
370                .cloned()
371                .unwrap_or_else(|| vec![0; len]))
372        }
373
374        fn write(&self, addr: u64, data: &[u8]) -> Result<(), GenApiError> {
375            self.regs.borrow_mut().insert(addr, data.to_vec());
376            Ok(())
377        }
378    }
379
380    /// A write-only integer, an integer delegating to a write-only register
381    /// (the `ActionDeviceKey` shape from #112), a command reaching an `RW`
382    /// register through `<pValue>`, an integer over a read-only register,
383    /// an enumeration whose second entry is unavailable, an integer whose
384    /// maximum is read from the device, and one ordinary feature.
385    const XML: &str = r#"
386        <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
387            <Integer Name="Width">
388                <Address>0x100</Address>
389                <Length>4</Length>
390                <AccessMode>RW</AccessMode>
391                <Min>16</Min>
392                <pMax>WidthMax</pMax>
393                <Inc>4</Inc>
394            </Integer>
395            <IntReg Name="WidthMax">
396                <Address>0x104</Address>
397                <Length>4</Length>
398                <AccessMode>RO</AccessMode>
399                <Sign>Unsigned</Sign>
400                <Endianess>BigEndian</Endianess>
401            </IntReg>
402            <Integer Name="DeviceKey">
403                <Address>0x200</Address>
404                <Length>4</Length>
405                <AccessMode>WO</AccessMode>
406            </Integer>
407            <Integer Name="ActionDeviceKey">
408                <pValue>ActionDeviceKeyReg</pValue>
409            </Integer>
410            <IntReg Name="ActionDeviceKeyReg">
411                <Address>0x300</Address>
412                <Length>4</Length>
413                <AccessMode>WO</AccessMode>
414                <Sign>Unsigned</Sign>
415                <Endianess>BigEndian</Endianess>
416            </IntReg>
417            <Command Name="TriggerSoftware">
418                <pValue>TriggerSoftwareReg</pValue>
419                <CommandValue>1</CommandValue>
420            </Command>
421            <IntReg Name="TriggerSoftwareReg">
422                <Address>0x400</Address>
423                <Length>4</Length>
424                <AccessMode>RW</AccessMode>
425                <Sign>Unsigned</Sign>
426                <Endianess>BigEndian</Endianess>
427            </IntReg>
428            <Integer Name="SensorWidth">
429                <pValue>SensorWidthReg</pValue>
430            </Integer>
431            <IntReg Name="SensorWidthReg">
432                <Address>0x500</Address>
433                <Length>4</Length>
434                <AccessMode>RO</AccessMode>
435                <Sign>Unsigned</Sign>
436                <Endianess>BigEndian</Endianess>
437            </IntReg>
438            <Enumeration Name="PixelFormat">
439                <EnumEntry Name="Mono8"><Value>1</Value></EnumEntry>
440                <EnumEntry Name="Mono16">
441                    <pIsAvailable>Mono16Available</pIsAvailable>
442                    <Value>2</Value>
443                </EnumEntry>
444                <pValue>PixelFormatReg</pValue>
445            </Enumeration>
446            <IntReg Name="PixelFormatReg">
447                <Address>0x600</Address>
448                <Length>4</Length>
449                <AccessMode>RW</AccessMode>
450                <Sign>Unsigned</Sign>
451                <Endianess>BigEndian</Endianess>
452            </IntReg>
453            <Float Name="FrameRate">
454                <Address>0x900</Address>
455                <Length>4</Length>
456                <AccessMode>RW</AccessMode>
457            </Float>
458            <Integer Name="Gain">
459                <pIsAvailable>GainAvailable</pIsAvailable>
460                <Address>0x800</Address>
461                <Length>4</Length>
462                <AccessMode>RW</AccessMode>
463                <Min>0</Min>
464                <pMax>GainMax</pMax>
465            </Integer>
466            <IntReg Name="GainMax">
467                <Address>0x804</Address>
468                <Length>4</Length>
469                <AccessMode>RO</AccessMode>
470                <Sign>Unsigned</Sign>
471                <Endianess>BigEndian</Endianess>
472            </IntReg>
473            <IntReg Name="GainAvailable">
474                <Address>0x700</Address>
475                <Length>4</Length>
476                <AccessMode>RO</AccessMode>
477                <Sign>Unsigned</Sign>
478                <Endianess>BigEndian</Endianess>
479            </IntReg>
480            <IntReg Name="Mono16Available">
481                <Address>0x604</Address>
482                <Length>4</Length>
483                <AccessMode>RO</AccessMode>
484                <Sign>Unsigned</Sign>
485                <Endianess>BigEndian</Endianess>
486            </IntReg>
487        </RegisterDescription>
488    "#;
489
490    fn nodemap() -> NodeMap {
491        let model = viva_genapi_xml::parse(XML).expect("parse");
492        let nodemap = NodeMap::try_from_xml(model).expect("build nodemap");
493        assert!(nodemap.skipped().is_empty(), "{:?}", nodemap.skipped());
494        nodemap
495    }
496
497    fn io() -> MemIo {
498        MemIo::with(&[(0x100, 640), (0x104, 1280), (0x500, 1920), (0x600, 1)])
499    }
500
501    #[test]
502    fn an_ordinary_feature_reports_its_value_range_and_access() {
503        let state = nodemap().feature_state("Width", &io()).expect("state");
504        assert_eq!(state.kind, "Integer");
505        assert_eq!(state.value, FeatureValue::Integer(640));
506        assert_eq!(state.access, Some(AccessMode::RW));
507        assert!(state.is_implemented && state.is_available);
508        // `<pMax>` is read from the device, not left as the `i64` sentinel.
509        assert_eq!(
510            state.range,
511            Some(ValueRange {
512                min: 16.0,
513                max: 1280.0,
514                inc: Some(4.0)
515            })
516        );
517    }
518
519    /// Write-only nodes are reported without being read, so one of them no
520    /// longer fails a whole snapshot (#135). `MemIo` would answer the read,
521    /// so a value other than `None` here means the read was attempted.
522    #[test]
523    fn a_write_only_feature_is_reported_but_not_read() {
524        let nodemap = nodemap();
525        let io = io();
526        for name in ["DeviceKey", "ActionDeviceKey"] {
527            let state = nodemap.feature_state(name, &io).expect(name);
528            assert_eq!(state.value, FeatureValue::None, "{name}");
529            assert_eq!(state.access, Some(AccessMode::WO), "{name}");
530        }
531    }
532
533    /// A command's backing register holds a trigger, not a value (#112).
534    #[test]
535    fn a_command_target_is_reported_but_not_read() {
536        let state = nodemap()
537            .feature_state("TriggerSoftwareReg", &io())
538            .expect("state");
539        assert_eq!(state.value, FeatureValue::None);
540        assert_eq!(state.access, Some(AccessMode::RW));
541    }
542
543    /// An integer that declares no access of its own is as writable as the
544    /// register it delegates to — here, not at all.
545    #[test]
546    fn a_feature_over_a_read_only_register_reports_ro() {
547        let state = nodemap()
548            .feature_state("SensorWidth", &io())
549            .expect("state");
550        assert_eq!(state.value, FeatureValue::Integer(1920));
551        assert_eq!(state.access, Some(AccessMode::RO));
552    }
553
554    /// The entries offered are the ones the device accepts now (backlog
555    /// ST-18): `Mono16` is gated by a register that reads 0.
556    #[test]
557    fn an_enumeration_offers_only_its_available_entries() {
558        let nodemap = nodemap();
559        let state = nodemap.feature_state("PixelFormat", &io()).expect("state");
560        assert_eq!(state.value, FeatureValue::Enum("Mono8".into()));
561        assert_eq!(state.enum_entries, Some(vec!["Mono8".to_string()]));
562
563        // Negative control: once the gate opens, the entry is offered. A fresh
564        // map, because the first one has cached the closed gate.
565        let open = MemIo::with(&[(0x600, 1), (0x604, 1)]);
566        let state = self::nodemap()
567            .feature_state("PixelFormat", &open)
568            .expect("state");
569        assert_eq!(
570            state.enum_entries,
571            Some(vec!["Mono8".to_string(), "Mono16".to_string()]),
572            "in the XML's order"
573        );
574    }
575
576    /// A feature its `pIsAvailable` gates off is reported, not read: cameras
577    /// commonly refuse to read such a register, and a failed read used to fail
578    /// the whole snapshot, so the feature went missing from a bulk read
579    /// instead of showing as unavailable (Codex review of #169).
580    #[test]
581    fn an_unavailable_feature_is_reported_but_not_read() {
582        let gated_off = io().denying(&[0x800, 0x804]);
583        let state = nodemap()
584            .feature_state("Gain", &gated_off)
585            .expect("an unavailable feature still has a state");
586        assert!(!state.is_available);
587        assert_eq!(state.value, FeatureValue::None);
588        assert_eq!(state.access, Some(AccessMode::RO));
589        // `<pMax>` went unread, so there is no maximum to report, and a range
590        // made of the parser's `i64::MAX` placeholder would be a lie (Codex
591        // review of #170).
592        assert_eq!(state.range, None);
593
594        // Negative control: with the gate open the value and `<pMax>` are read.
595        let open = MemIo::with(&[(0x700, 1), (0x800, 6), (0x804, 24)]);
596        let state = nodemap().feature_state("Gain", &open).expect("state");
597        assert!(state.is_available);
598        assert_eq!(state.value, FeatureValue::Integer(6));
599        assert_eq!(state.range.map(|r| r.max), Some(24.0));
600    }
601
602    /// GA-58: an Allied Vision Manta G-125B (firmware 00.01.44.28514) gates
603    /// its `LensVoltage` on an inquiry bit at `0x23000`, a register that
604    /// camera, which has no lens control, answers with `INVALID_ADDRESS`. A
605    /// predicate that cannot be read gives no value to satisfy it: the
606    /// feature is reported as not implemented, and nothing behind it is read.
607    /// The same holds for `pIsAvailable` (not available) and `pIsLocked`
608    /// (locked, so not writable).
609    #[test]
610    fn a_predicate_the_camera_refuses_to_read_is_not_satisfied() {
611        const LENS: &str = r#"
612            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
613                <Integer Name="LensVoltage" NameSpace="Custom">
614                    <pIsImplemented>RegLensControlInqVoltage</pIsImplemented>
615                    <Streamable>Yes</Streamable>
616                    <pValue>RegLensVoltage</pValue>
617                    <Min>0</Min>
618                    <pMax>RegLensVoltageMax</pMax>
619                </Integer>
620                <Integer Name="LensVoltageControl" NameSpace="Custom">
621                    <pIsAvailable>RegLensControlInqVoltage</pIsAvailable>
622                    <pValue>RegLensVoltageControl</pValue>
623                </Integer>
624                <Integer Name="LensDriveDuration" NameSpace="Custom">
625                    <pIsLocked>RegLensControlInqVoltage</pIsLocked>
626                    <pValue>RegLensVoltageControl</pValue>
627                </Integer>
628                <MaskedIntReg Name="RegLensControlInqVoltage" NameSpace="Custom">
629                    <Address>0x23000</Address>
630                    <Length>4</Length>
631                    <AccessMode>RO</AccessMode>
632                    <pPort>Device</pPort>
633                    <Bit>31</Bit>
634                    <Endianess>BigEndian</Endianess>
635                </MaskedIntReg>
636                <IntReg Name="RegLensVoltageMax" NameSpace="Custom">
637                    <Address>0x23100</Address>
638                    <Length>4</Length>
639                    <AccessMode>RO</AccessMode>
640                    <pPort>Device</pPort>
641                    <Sign>Unsigned</Sign>
642                    <Endianess>BigEndian</Endianess>
643                </IntReg>
644                <IntReg Name="RegLensVoltage" NameSpace="Custom">
645                    <Address>0x23104</Address>
646                    <Length>4</Length>
647                    <AccessMode>RO</AccessMode>
648                    <pPort>Device</pPort>
649                    <Sign>Unsigned</Sign>
650                    <Endianess>BigEndian</Endianess>
651                </IntReg>
652                <IntReg Name="RegLensVoltageControl" NameSpace="Custom">
653                    <Address>0x23108</Address>
654                    <Length>4</Length>
655                    <AccessMode>RW</AccessMode>
656                    <pPort>Device</pPort>
657                    <Cachable>WriteAround</Cachable>
658                    <Sign>Unsigned</Sign>
659                    <Endianess>BigEndian</Endianess>
660                </IntReg>
661            </RegisterDescription>
662        "#;
663        let nodemap = || {
664            let model = viva_genapi_xml::parse(LENS).expect("parse");
665            NodeMap::try_from_xml(model).expect("build nodemap")
666        };
667        // The inquiry register is refused; the registers behind it answer, so
668        // a value here would mean the feature was read after all.
669        let refused =
670            MemIo::with(&[(0x23100, 24000), (0x23104, 12000), (0x23108, 5)]).denying(&[0x23000]);
671        let map = nodemap();
672
673        let state = map.feature_state("LensVoltage", &refused).expect("state");
674        assert!(!state.is_implemented, "not implemented");
675        assert!(!state.is_available, "nor available");
676        assert_eq!(state.value, FeatureValue::None, "and not read");
677        assert_eq!(state.range, None, "nor its <pMax>");
678
679        let state = map
680            .feature_state("LensVoltageControl", &refused)
681            .expect("state");
682        assert!(state.is_implemented);
683        assert!(!state.is_available, "pIsAvailable unread: not available");
684        assert_eq!(state.value, FeatureValue::None);
685
686        let state = map
687            .feature_state("LensDriveDuration", &refused)
688            .expect("state");
689        assert!(state.is_implemented && state.is_available);
690        assert_eq!(state.value, FeatureValue::Integer(5));
691        assert_eq!(
692            state.access,
693            Some(AccessMode::RO),
694            "pIsLocked unread: locked"
695        );
696
697        // Negative control: with the inquiry bit set, each predicate is
698        // satisfied and the features read.
699        let lens = MemIo::with(&[
700            (0x23000, 0xFFFF_FFFF),
701            (0x23100, 24000),
702            (0x23104, 12000),
703            (0x23108, 5),
704        ]);
705        let map = nodemap();
706        let state = map.feature_state("LensVoltage", &lens).expect("state");
707        assert!(state.is_implemented && state.is_available);
708        assert_eq!(state.value, FeatureValue::Integer(12000));
709        assert_eq!(state.range.map(|r| r.max), Some(24000.0));
710        let state = map
711            .feature_state("LensVoltageControl", &lens)
712            .expect("state");
713        assert!(state.is_available);
714        assert_eq!(state.access, Some(AccessMode::RW));
715        let state = map
716            .feature_state("LensDriveDuration", &lens)
717            .expect("state");
718        assert_eq!(state.access, Some(AccessMode::RO), "locked: the bit is set");
719    }
720
721    /// A Float that declares no bounds has none to report: the parser's
722    /// `f64::MIN`/`f64::MAX` placeholders are not a range.
723    #[test]
724    fn a_feature_without_bounds_reports_no_range() {
725        let state = nodemap().feature_state("FrameRate", &io()).expect("state");
726        assert_eq!(state.value, FeatureValue::Float(0.0));
727        assert_eq!(state.range, None);
728    }
729
730    #[test]
731    fn an_unknown_name_is_an_error() {
732        assert!(matches!(
733            nodemap().feature_state("Nope", &io()),
734            Err(GenApiError::NodeNotFound(_))
735        ));
736    }
737}