Skip to main content

viva_genapi/nodemap/
refresh.rs

1//! `<Cachable>`, `<PollingTime>` and what changed when (GA-05, GA-40,
2//! [ADR-0029]).
3//!
4//! GenICam Standard v2.1.1 §2.8.3 gives a register one of three caching
5//! modes: "WriteThrough means that a value written to the camera is written to
6//! the cache as well. WriteAround means that only read values are written to
7//! the cache", and `NoCache` keeps nothing. Absent, a `<FloatReg>`'s mode is
8//! `WriteAround` and every other register's `WriteThrough` (§3.2).
9//! `<PollingTime>` is "a recommended time interval [in ms] after which a node
10//! should be invalidated".
11//!
12//! The standard says nothing about the node in front of a register — the
13//! `<Float>` whose `<pValue>` is a `NoCache` `<IntReg>`, the `<Converter>`
14//! reading it. Here such a node is cached only as far as every register it is
15//! read through allows, the combination GenApi's reference implementation
16//! computes with `Combine`, and it keeps no cache of its own when one of them
17//! polls: the register's own cache then decides when the value is read again.
18//! That is the reading that never answers with a stale value.
19//!
20//! A `NodeMap` is not `Sync` — its caches are `RefCell`s — so there are no
21//! callbacks. Every write and every invalidation advances a generation and
22//! records it against the nodes it touched; [`NodeMap::changed_since`] answers
23//! what changed after a generation a viewer saw, and [`NodeMap::poll`] turns
24//! elapsed polling times into such changes, as `INodeMap::Poll` does.
25//!
26//! [ADR-0029]: https://github.com/VitalyVorobyev/viva-genicam/blob/main/docs/adrs/adr0029-caching-polling-and-refresh.md
27
28use std::cell::{Cell, RefCell};
29use std::collections::{HashMap, HashSet};
30use std::sync::Arc;
31use std::time::Duration;
32
33use viva_genapi_xml::CachingMode;
34
35use super::NodeMap;
36use crate::clock::{Clock, default_clock};
37use crate::nodes::{Node, node_addressing};
38
39/// What a `<PollingTime>` polls, by the kind of node declaring it.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41enum PollKind {
42    /// A value: its reading is the device's for the polling time, then read
43    /// again (§2.8.3).
44    Value,
45    /// A command: polled from its execution until `is_done` finds it
46    /// finished; "If the command is write only no polling takes place"
47    /// (§2.8.8).
48    Command,
49    /// An enumeration: polled — and read past every cache — while its value
50    /// is an entry with `<IsSelfClearing>Yes` (§2.8.10).
51    SelfClearing,
52}
53
54/// A node with a `<PollingTime>` of its own.
55#[derive(Debug)]
56pub(crate) struct Polled {
57    kind: PollKind,
58    period: Duration,
59    /// When polling last started: the value read from the device (or written
60    /// through to the cache), the command executed, the self-clearing entry
61    /// seen. `None` while there is nothing to poll.
62    since: Cell<Option<Duration>>,
63}
64
65/// The caching and polling each node is subject to, resolved once from the
66/// XML, and the change history.
67#[derive(Debug)]
68pub(crate) struct Refresh {
69    /// The mode of every node whose mode is not `WriteThrough`: its own, and
70    /// that of every node its value is read through.
71    modes: HashMap<String, CachingMode>,
72    /// Nodes whose value is read through a polled node. They keep no cache
73    /// of their own, so the polled node's expiry is what decides.
74    via_polled: HashSet<String>,
75    /// The shortest polling time on each node's value path, its own
76    /// included.
77    polling: HashMap<String, Duration>,
78    /// Nodes with a polling time of their own.
79    polled: HashMap<String, Polled>,
80    clock: Arc<dyn Clock>,
81    /// The generation each node last changed in.
82    changed: RefCell<HashMap<String, u64>>,
83    /// The generation every node last changed in at once.
84    all_changed: Cell<u64>,
85}
86
87impl Default for Refresh {
88    fn default() -> Self {
89        Self {
90            modes: HashMap::new(),
91            via_polled: HashSet::new(),
92            polling: HashMap::new(),
93            polled: HashMap::new(),
94            clock: default_clock(),
95            changed: RefCell::new(HashMap::new()),
96            all_changed: Cell::new(0),
97        }
98    }
99}
100
101/// A node's own caching mode: its `<Cachable>`, or a register's default.
102fn own_mode(node: &Node) -> Option<CachingMode> {
103    let declared = node.meta().cachable;
104    if node_addressing(node).is_none() {
105        return declared;
106    }
107    Some(declared.unwrap_or(match node {
108        // Only a `<FloatReg>` is a float with a register of its own in a
109        // standard document (a `<Float>` has none, §2.8.9).
110        Node::Float(_) => CachingMode::WriteAround,
111        _ => CachingMode::WriteThrough,
112    }))
113}
114
115/// The nodes `node`'s value is read from: its `<pValue>`, an indexed value's
116/// index and every node it can select, a formula's variables, a converter's
117/// `<pValue>` and the variables of its `<FormulaFrom>`.
118fn value_sources(node: &Node) -> Vec<&str> {
119    match node {
120        Node::Integer(n) => n
121            .pvalue
122            .iter()
123            .map(String::as_str)
124            .chain(n.indexed.iter().flat_map(|i| i.table.referenced_nodes()))
125            .collect(),
126        Node::Float(n) => n
127            .pvalue
128            .iter()
129            .map(String::as_str)
130            .chain(n.indexed.iter().flat_map(|i| i.table.referenced_nodes()))
131            .collect(),
132        Node::Enum(n) => n.pvalue.iter().map(String::as_str).collect(),
133        Node::Boolean(n) => n.pvalue.iter().map(String::as_str).collect(),
134        Node::Command(n) => n.pvalue.iter().map(String::as_str).collect(),
135        Node::Converter(n) => std::iter::once(n.p_value.as_str())
136            .chain(n.vars_from.iter().map(|var| var.provider.as_str()))
137            .collect(),
138        Node::IntConverter(n) => std::iter::once(n.p_value.as_str())
139            .chain(n.vars_from.iter().map(|var| var.provider.as_str()))
140            .collect(),
141        Node::SwissKnife(n) => n.vars.iter().map(|var| var.provider.as_str()).collect(),
142        _ => Vec::new(),
143    }
144}
145
146/// What a node is subject to along its value path.
147#[derive(Debug, Clone, Copy)]
148struct Resolved {
149    mode: CachingMode,
150    polling: Option<Duration>,
151    via_polled: bool,
152}
153
154const NEUTRAL: Resolved = Resolved {
155    mode: CachingMode::WriteThrough,
156    polling: None,
157    via_polled: false,
158};
159
160impl NodeMap {
161    /// Resolve every node's caching mode and polling time, once the map is
162    /// built.
163    pub(crate) fn build_refresh(&mut self) {
164        let polled: HashMap<String, Polled> = self
165            .nodes
166            .iter()
167            .filter_map(|(name, node)| {
168                let ms = node.meta().polling_time_ms?;
169                let kind = match node {
170                    Node::Command(_) => PollKind::Command,
171                    Node::Enum(_) => PollKind::SelfClearing,
172                    _ => PollKind::Value,
173                };
174                Some((
175                    name.clone(),
176                    Polled {
177                        kind,
178                        period: Duration::from_millis(ms),
179                        since: Cell::new(None),
180                    },
181                ))
182            })
183            .collect();
184        let mut memo: HashMap<&str, Resolved> = HashMap::new();
185        let mut stack: Vec<&str> = Vec::new();
186        for name in &self.order {
187            self.resolve(name, &polled, &mut memo, &mut stack);
188        }
189        let mut modes = HashMap::new();
190        let mut polling = HashMap::new();
191        let mut via_polled = HashSet::new();
192        for (name, resolved) in memo {
193            if resolved.mode != CachingMode::WriteThrough {
194                modes.insert(name.to_string(), resolved.mode);
195            }
196            if let Some(period) = resolved.polling {
197                polling.insert(name.to_string(), period);
198            }
199            if resolved.via_polled {
200                via_polled.insert(name.to_string());
201            }
202        }
203        self.refresh.modes = modes;
204        self.refresh.polling = polling;
205        self.refresh.via_polled = via_polled;
206        self.refresh.polled = polled;
207    }
208
209    fn resolve<'a>(
210        &'a self,
211        name: &'a str,
212        polled: &HashMap<String, Polled>,
213        memo: &mut HashMap<&'a str, Resolved>,
214        stack: &mut Vec<&'a str>,
215    ) -> Resolved {
216        if let Some(resolved) = memo.get(name) {
217            return *resolved;
218        }
219        let Some(node) = self.nodes.get(name) else {
220            return NEUTRAL;
221        };
222        // A `<pValue>` cycle is reported elsewhere; here it ends the path.
223        if stack.contains(&name) {
224            return NEUTRAL;
225        }
226        stack.push(name);
227        let mut resolved = Resolved {
228            mode: own_mode(node).unwrap_or(CachingMode::WriteThrough),
229            polling: node.meta().polling_time_ms.map(Duration::from_millis),
230            via_polled: false,
231        };
232        for source in value_sources(node) {
233            let from = self.resolve(source, polled, memo, stack);
234            resolved.mode = resolved.mode.combine(from.mode);
235            resolved.polling = match (resolved.polling, from.polling) {
236                (Some(a), Some(b)) => Some(a.min(b)),
237                (a, b) => a.or(b),
238            };
239            resolved.via_polled |= from.via_polled || polled.contains_key(source);
240        }
241        stack.pop();
242        memo.insert(name, resolved);
243        resolved
244    }
245
246    /// How `name`'s value may be cached: its own `<Cachable>` — or, for a
247    /// register that declares none, the standard's default — combined with
248    /// that of every node its value is read through. `None` for an unknown
249    /// name.
250    ///
251    /// FLIR's `DeviceTemperature` is a `<Float>` over a `<Converter>` over an
252    /// `<IntReg>` declared `NoCache`, so all three are `NoCache`.
253    pub fn caching_mode(&self, name: &str) -> Option<CachingMode> {
254        self.nodes.contains_key(name).then(|| {
255            self.refresh
256                .modes
257                .get(name)
258                .copied()
259                .unwrap_or(CachingMode::WriteThrough)
260        })
261    }
262
263    /// How long `name`'s value may be shown before it is read again: the
264    /// shortest `<PollingTime>` among the node and those its value is read
265    /// through. `None` when nothing on the path polls, and for an unknown
266    /// name.
267    ///
268    /// A viewer re-reads the features it shows at this interval. A command's
269    /// is how often to ask whether it has finished.
270    pub fn polling_time(&self, name: &str) -> Option<Duration> {
271        self.refresh.polling.get(name).copied()
272    }
273
274    /// Measure polling times against `clock` rather than the system clock —
275    /// a [`ManualClock`](crate::ManualClock) in a test, or the host's clock
276    /// where there is no `std::time::Instant` (`wasm32-unknown-unknown`).
277    ///
278    /// A polled value read before is treated as read at an unknown time, so
279    /// it is read again. A command still running, and an enumeration whose
280    /// entry is self-clearing, stay active: their polling starts again now,
281    /// on the new clock.
282    pub fn set_clock(&mut self, clock: Arc<dyn Clock>) {
283        let now = clock.now();
284        for polled in self.refresh.polled.values() {
285            polled.since.set(match polled.kind {
286                PollKind::Value => None,
287                PollKind::Command | PollKind::SelfClearing => polled.since.get().map(|_| now),
288            });
289        }
290        self.refresh.clock = clock;
291    }
292
293    /// The current generation: advanced by every write and every
294    /// invalidation, never by a read.
295    pub fn generation(&self) -> u64 {
296        self.generation.get()
297    }
298
299    /// The nodes that changed after generation `since` — written, or
300    /// invalidated because something they depend on was — in document order,
301    /// and the generation now, to pass next time.
302    ///
303    /// A viewer keeps the generation of what it shows and re-reads the
304    /// features this names. A value the camera changes on its own appears
305    /// here once [`NodeMap::poll`] finds its polling time over, or once
306    /// something invalidates it; nothing else can know.
307    pub fn changed_since(&self, since: u64) -> (Vec<String>, u64) {
308        let now = self.generation.get();
309        if self.refresh.all_changed.get() > since {
310            return (self.order.clone(), now);
311        }
312        let changed = self.refresh.changed.borrow();
313        let names = self
314            .order
315            .iter()
316            .filter(|name| {
317                changed
318                    .get(name.as_str())
319                    .is_some_and(|generation| *generation > since)
320            })
321            .cloned()
322            .collect();
323        (names, now)
324    }
325
326    /// Invalidate every polled node whose polling time has passed, and
327    /// return their names with those of every node read through them, in
328    /// document order: what a viewer should read again. GenApi's
329    /// `INodeMap::Poll`, measured against the node map's clock.
330    ///
331    /// A value is polled from when it was last read from the device and
332    /// reported once until it is read again; one never read is not reported.
333    /// A command is polled from its execution until [`NodeMap::is_done`]
334    /// finds it finished, an enumeration while its value is a self-clearing
335    /// entry; both are reported each time their polling time passes. The
336    /// invalidations count as changes for [`NodeMap::changed_since`].
337    pub fn poll(&self) -> Vec<String> {
338        let refresh = &self.refresh;
339        if refresh.polled.is_empty() {
340            return Vec::new();
341        }
342        let now = refresh.clock.now();
343        let mut due: Vec<&str> = Vec::new();
344        for (name, polled) in &refresh.polled {
345            let Some(since) = polled.since.get() else {
346                continue;
347            };
348            if now.saturating_sub(since) < polled.period {
349                continue;
350            }
351            polled.since.set(match polled.kind {
352                PollKind::Value => None,
353                PollKind::Command | PollKind::SelfClearing => Some(now),
354            });
355            due.push(name);
356        }
357        if due.is_empty() {
358            return Vec::new();
359        }
360        self.bump_generation();
361        let mut touched: HashSet<String> = HashSet::new();
362        for name in due {
363            self.invalidate_recursive(name, &mut touched);
364        }
365        self.order
366            .iter()
367            .filter(|name| touched.contains(name.as_str()))
368            .cloned()
369            .collect()
370    }
371
372    /// Whether a read of `name` may be answered from its own cache now.
373    pub(crate) fn may_serve(&self, name: &str) -> bool {
374        let refresh = &self.refresh;
375        if refresh.modes.get(name) == Some(&CachingMode::NoCache)
376            || refresh.via_polled.contains(name)
377        {
378            return false;
379        }
380        let Some(polled) = refresh.polled.get(name) else {
381            return true;
382        };
383        match polled.kind {
384            PollKind::Value => polled
385                .since
386                .get()
387                .is_some_and(|since| refresh.clock.now().saturating_sub(since) < polled.period),
388            PollKind::SelfClearing => polled.since.get().is_none(),
389            PollKind::Command => true,
390        }
391    }
392
393    /// Whether a value of `name` just read from the device may be kept.
394    pub(crate) fn may_cache(&self, name: &str) -> bool {
395        self.refresh.modes.get(name) != Some(&CachingMode::NoCache)
396            && !self.refresh.via_polled.contains(name)
397    }
398
399    /// Whether a write to `name` may leave the written value in its cache:
400    /// `WriteThrough` only.
401    pub(crate) fn keeps_written(&self, name: &str) -> bool {
402        !self.refresh.modes.contains_key(name) && !self.refresh.via_polled.contains(name)
403    }
404
405    /// `name`'s value was just read from the device, or written through to
406    /// its cache: a polled value's polling time starts now.
407    pub(crate) fn note_read(&self, name: &str) {
408        let refresh = &self.refresh;
409        if refresh.polled.is_empty() {
410            return;
411        }
412        if let Some(polled) = refresh.polled.get(name)
413            && polled.kind == PollKind::Value
414        {
415            polled.since.set(Some(refresh.clock.now()));
416        }
417    }
418
419    /// `name`, an enumeration, now holds an entry that is, or is not,
420    /// self-clearing: polling starts or stops.
421    pub(crate) fn note_entry(&self, name: &str, self_clearing: bool) {
422        let refresh = &self.refresh;
423        if let Some(polled) = refresh.polled.get(name)
424            && polled.kind == PollKind::SelfClearing
425        {
426            polled.since.set(self_clearing.then(|| refresh.clock.now()));
427        }
428    }
429
430    /// Whether `name` is an enumeration polled while self-clearing that is
431    /// active now: read past every cache.
432    pub(crate) fn self_clearing_active(&self, name: &str) -> bool {
433        self.refresh.polled.get(name).is_some_and(|polled| {
434            polled.kind == PollKind::SelfClearing && polled.since.get().is_some()
435        })
436    }
437
438    /// `name`, a command, was executed (`true`) or found finished: polling
439    /// starts or stops.
440    pub(crate) fn note_command(&self, name: &str, running: bool) {
441        let refresh = &self.refresh;
442        if let Some(polled) = refresh.polled.get(name)
443            && polled.kind == PollKind::Command
444        {
445            polled.since.set(running.then(|| refresh.clock.now()));
446        }
447    }
448
449    /// Record that `name` changed in the current generation.
450    pub(crate) fn note_changed(&self, name: &str) {
451        let generation = self.generation.get();
452        let mut changed = self.refresh.changed.borrow_mut();
453        match changed.get_mut(name) {
454            Some(at) => *at = generation,
455            None => {
456                changed.insert(name.to_string(), generation);
457            }
458        }
459    }
460
461    /// Record that every node changed in the current generation.
462    pub(crate) fn note_all_changed(&self) {
463        self.refresh.all_changed.set(self.generation.get());
464    }
465}