Skip to main content

viva_genicam/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2//! High level GenICam facade that re-exports the workspace crates and provides
3//! convenience wrappers.
4//!
5//! ```rust,no_run
6//! use viva_genicam::{gige, genapi, Camera, GenicamError};
7//! use std::time::Duration;
8//!
9//! # struct DummyTransport;
10//! # impl genapi::RegisterIo for DummyTransport {
11//! #     fn read(&self, _addr: u64, len: usize) -> Result<Vec<u8>, genapi::GenApiError> {
12//! #         Ok(vec![0; len])
13//! #     }
14//! #     fn write(&self, _addr: u64, _data: &[u8]) -> Result<(), genapi::GenApiError> {
15//! #         Ok(())
16//! #     }
17//! # }
18//! # #[allow(dead_code)]
19//! # fn load_nodemap() -> genapi::NodeMap {
20//! #     unimplemented!("replace with GenApi XML parsing")
21//! # }
22//! # #[allow(dead_code)]
23//! # async fn open_transport() -> Result<DummyTransport, GenicamError> {
24//! #     Ok(DummyTransport)
25//! # }
26//! # #[allow(dead_code)]
27//! # async fn run() -> Result<(), GenicamError> {
28//! let timeout = Duration::from_millis(500);
29//! let devices = gige::discover(timeout)
30//!     .await
31//!     .expect("discover cameras");
32//! println!("found {} cameras", devices.len());
33//! let mut camera = Camera::new(open_transport().await?, load_nodemap());
34//! camera.set("ExposureTime", "5000")?;
35//! # Ok(())
36//! # }
37//! ```
38//!
39//! ```rust,no_run
40//! # async fn events_example(
41//! #     mut camera: viva_genicam::Camera<viva_genicam::GigeRegisterIo>,
42//! # ) -> Result<(), viva_genicam::GenicamError> {
43//! use std::net::Ipv4Addr;
44//! let ids = ["FrameStart", "ExposureEnd"];
45//! let iface = Ipv4Addr::new(127, 0, 0, 1);
46//! camera.configure_events(iface, 10020, &ids).await?;
47//! let stream = camera.open_event_stream(iface, 10020).await?;
48//! let event = stream.next().await?;
49//! println!("event id=0x{:04X} payload={} bytes", event.id, event.data.len());
50//! # Ok(())
51//! # }
52//! ```
53//!
54//! ```rust,no_run
55//! # async fn action_example() -> Result<(), std::io::Error> {
56//! use viva_genicam::gige::{send_action, ActionParams};
57//! use std::net::SocketAddr;
58//! let params = ActionParams {
59//!     device_key: 0,
60//!     group_key: 1,
61//!     group_mask: 0xFFFF_FFFF,
62//!     scheduled_time: None,
63//! };
64//! let dest: SocketAddr = "255.255.255.255:3956".parse().unwrap();
65//! let summary = send_action(dest, &params, 200).await?;
66//! println!("acks={}", summary.acks);
67//! Ok(())
68//! # }
69//! ```
70
71pub use viva_genapi as genapi;
72pub use viva_gencp as gencp;
73pub use viva_gige as gige;
74pub use viva_pfnc as pfnc;
75pub use viva_sfnc as sfnc;
76#[cfg(feature = "u3v")]
77#[cfg_attr(docsrs, doc(cfg(feature = "u3v")))]
78pub use viva_u3v as u3v;
79
80pub mod blocking;
81mod chunks;
82mod error;
83mod event_configuration;
84mod events;
85mod evs;
86mod frame;
87#[cfg(feature = "image-io")]
88#[cfg_attr(docsrs, doc(cfg(feature = "image-io")))]
89pub mod image_io;
90mod reopen;
91pub mod report;
92mod standard;
93mod stream;
94
95use std::net::{IpAddr, Ipv4Addr};
96use std::sync::{Arc, Mutex, MutexGuard};
97use std::time::{Duration, Instant, SystemTime};
98
99use crate::events::{
100    bind_socket as bind_event_socket_internal,
101    configure_message_channel_raw as configure_message_channel_fallback,
102};
103use crate::genapi::{GenApiError, Node, NodeMap, PortKind, RegisterIo};
104use gige::GigeDevice;
105use gige::consts as gvcp_consts;
106use tokio::time::sleep;
107use tracing::{debug, info, warn};
108
109pub use chunks::{ChunkData, ChunkError, chunk_data};
110pub use error::{GenicamError, WriteRefused};
111pub use event_configuration::{
112    EventConfiguration, EventRestoreFailure, EventRestoreReport, EventRestoreSkipped,
113    EventSetupError,
114};
115#[cfg(feature = "u3v")]
116#[cfg_attr(docsrs, doc(cfg(feature = "u3v")))]
117pub use events::U3vEventStream;
118pub use events::{Event, EventStream};
119pub use evs::{EvsBlock, EvsFormat};
120pub use frame::{Frame, FrameStatus};
121pub use gige::{AckSummary, ActionParams};
122pub use reopen::{Reopen, Reopened, reopen_gige};
123pub use standard::{ResolvedFeature, Roi, StandardFeature};
124#[cfg(fuzzing)]
125pub use stream::fuzz_assemble;
126pub use stream::{
127    FrameStream, GenericStreamBlock, ResendPolicy, Stream, StreamBlock, StreamBuilder, StreamDest,
128    StreamOptions, StreamStats, StreamStatsAccumulator,
129};
130#[cfg(feature = "u3v")]
131#[cfg_attr(docsrs, doc(cfg(feature = "u3v")))]
132pub use stream::{U3vFrameStream, U3vStreamBuilder};
133pub use viva_gige::TimeSync;
134#[cfg(feature = "u3v")]
135#[cfg_attr(docsrs, doc(cfg(feature = "u3v")))]
136pub use viva_u3v::U3vStreamOptions;
137
138/// How often [`Camera::execute_and_wait`] asks a command whether it has
139/// finished, when the command declares no `<PollingTime>`.
140///
141/// A command's `<PollingTime>` is the camera's own answer (GenICam Standard
142/// v2.1.1 §2.8.8) and is used when present. Without one, ten milliseconds
143/// keeps a self-clearing command's latency low at a cost of one register read
144/// per poll.
145pub const COMMAND_POLL_INTERVAL: Duration = Duration::from_millis(10);
146
147/// How long the helpers that wait for a command — the user-set helpers,
148/// among them — give it to finish, and what consumers of this crate wait by
149/// default.
150pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(5);
151
152/// Camera facade combining a nodemap with a transport implementing [`RegisterIo`].
153#[derive(Debug)]
154pub struct Camera<T: RegisterIo> {
155    transport: T,
156    nodemap: NodeMap,
157    time_sync: TimeSync,
158    event_identity: Arc<()>,
159}
160
161impl<T: RegisterIo> Camera<T> {
162    /// Create a new camera wrapper from a transport and a nodemap.
163    pub fn new(transport: T, nodemap: NodeMap) -> Self {
164        Self {
165            transport,
166            nodemap,
167            time_sync: TimeSync::with_capacity(64),
168            event_identity: Arc::new(()),
169        }
170    }
171
172    #[inline]
173    fn with_map<R>(&mut self, f: impl FnOnce(&mut NodeMap, &T) -> R) -> R {
174        let transport = &self.transport;
175        let nodemap = &mut self.nodemap;
176        f(nodemap, transport)
177    }
178
179    /// Return a reference to the underlying transport.
180    pub fn transport(&self) -> &T {
181        &self.transport
182    }
183
184    /// Return a mutable reference to the underlying transport.
185    pub fn transport_mut(&mut self) -> &mut T {
186        &mut self.transport
187    }
188
189    /// Access the nodemap metadata.
190    pub fn nodemap(&self) -> &NodeMap {
191        &self.nodemap
192    }
193
194    /// Mutable access to the nodemap.
195    pub fn nodemap_mut(&mut self) -> &mut NodeMap {
196        &mut self.nodemap
197    }
198
199    /// Forget `name`'s cached value, and those of the registers it is read
200    /// through and of everything that depends on it, so the next read asks
201    /// the camera: for a value the camera changed in a way its XML does not
202    /// describe. See [`NodeMap::invalidate`].
203    ///
204    /// A value the XML declares `NoCache` needs none of this, and one with a
205    /// `<PollingTime>` is read again once that has passed (ADR-0029).
206    pub fn invalidate(&self, name: &str) {
207        self.nodemap.invalidate(name);
208    }
209
210    /// Forget every cached value, after something that may have changed the
211    /// camera wholesale. [`Camera::load_user_set`] does this itself.
212    pub fn invalidate_all(&self) {
213        self.nodemap.invalidate_all();
214    }
215
216    /// The nodemap's current generation, advanced by every write and every
217    /// invalidation: where a viewer starts [`Camera::changed_since`] from.
218    pub fn generation(&self) -> u64 {
219        self.nodemap.generation()
220    }
221
222    /// The features — and the nodes behind them — that changed after
223    /// generation `since`, in document order, and the generation now. A
224    /// viewer re-reads the ones it shows. See [`NodeMap::changed_since`].
225    pub fn changed_since(&self, since: u64) -> (Vec<String>, u64) {
226        self.nodemap.changed_since(since)
227    }
228
229    /// Invalidate the values whose `<PollingTime>` has passed since they were
230    /// read, and return their names with those of everything read through
231    /// them: what a viewer should read again. Call it as often as the shortest
232    /// polling time a viewer shows. See [`NodeMap::poll`].
233    pub fn poll(&self) -> Vec<String> {
234        self.nodemap.poll()
235    }
236
237    /// List available entries for an enumeration feature.
238    pub fn enum_entries(&self, name: &str) -> Result<Vec<String>, GenicamError> {
239        self.nodemap.enum_entries(name).map_err(Into::into)
240    }
241
242    /// Read everything a viewer needs about a feature at once: its typed
243    /// value, what it permits now, whether it is implemented and available,
244    /// its range, the enumeration entries it accepts, and its unit.
245    ///
246    /// See [`NodeMap::feature_state`](genapi::NodeMap::feature_state).
247    pub fn feature_state(&self, name: &str) -> Result<genapi::FeatureState, GenicamError> {
248        self.nodemap
249            .feature_state(name, &self.transport)
250            .map_err(Into::into)
251    }
252
253    /// Read an integer feature: an `<Integer>`, an `<IntConverter>`, an
254    /// integer `<IntSwissKnife>`, or a `<Converter>` rounded to the nearest
255    /// integer. See [`NodeMap::get_integer`].
256    pub fn get_integer(&self, name: &str) -> Result<i64, GenicamError> {
257        Ok(self.nodemap.get_integer(name, &self.transport)?)
258    }
259
260    /// Write an integer feature, within its bounds and increment.
261    pub fn set_integer(&mut self, name: &str, value: i64) -> Result<(), GenicamError> {
262        Ok(self.nodemap.set_integer(name, value, &self.transport)?)
263    }
264
265    /// Read a float feature: a `<Float>`, a `<Converter>`, a float
266    /// `<SwissKnife>`, or an `<IntConverter>`. An `<Integer>` is not a
267    /// float: read it with [`Camera::get_integer`].
268    pub fn get_float(&self, name: &str) -> Result<f64, GenicamError> {
269        Ok(self.nodemap.get_float(name, &self.transport)?)
270    }
271
272    /// Write a float feature, within its bounds.
273    pub fn set_float(&mut self, name: &str, value: f64) -> Result<(), GenicamError> {
274        Ok(self.nodemap.set_float(name, value, &self.transport)?)
275    }
276
277    /// Read a boolean feature.
278    pub fn get_bool(&self, name: &str) -> Result<bool, GenicamError> {
279        Ok(self.nodemap.get_bool(name, &self.transport)?)
280    }
281
282    /// Write a boolean feature.
283    pub fn set_bool(&mut self, name: &str, value: bool) -> Result<(), GenicamError> {
284        Ok(self.nodemap.set_bool(name, value, &self.transport)?)
285    }
286
287    /// Read an enumeration: the name of its current entry.
288    pub fn get_enum(&self, name: &str) -> Result<String, GenicamError> {
289        Ok(self.nodemap.get_enum(name, &self.transport)?)
290    }
291
292    /// Write an enumeration by entry name.
293    pub fn set_enum(&mut self, name: &str, entry: &str) -> Result<(), GenicamError> {
294        Ok(self.nodemap.set_enum(name, entry, &self.transport)?)
295    }
296
297    /// Read a `<StringReg>`.
298    pub fn get_string(&self, name: &str) -> Result<String, GenicamError> {
299        Ok(self.nodemap.get_string(name, &self.transport)?)
300    }
301
302    /// Write a `<StringReg>`, NUL-padded to its length.
303    pub fn set_string(&mut self, name: &str, value: &str) -> Result<(), GenicamError> {
304        Ok(self.nodemap.set_string(name, value, &self.transport)?)
305    }
306
307    /// Read a `<Register>`'s bytes. See [`NodeMap::get_register`].
308    pub fn get_register(&self, name: &str) -> Result<Vec<u8>, GenicamError> {
309        Ok(self.nodemap.get_register(name, &self.transport)?)
310    }
311
312    /// Write a `<Register>`'s bytes, exactly its length. See
313    /// [`NodeMap::set_register`].
314    pub fn set_register(&mut self, name: &str, data: &[u8]) -> Result<(), GenicamError> {
315        Ok(self.nodemap.set_register(name, data, &self.transport)?)
316    }
317
318    /// Read a feature as text, formatted by its type: for a program that
319    /// does not know the type in advance, such as a command line. The typed
320    /// accessors ([`Camera::get_integer`] and the like) read without the
321    /// round trip. See [`NodeMap::get_text`](genapi::NodeMap::get_text).
322    ///
323    /// A category has no value and a command none to read: both are errors.
324    pub fn get(&self, name: &str) -> Result<String, GenicamError> {
325        if let Some(Node::Command(_)) = self.nodemap.node(name) {
326            return Err(GenApiError::Type {
327                name: name.to_string(),
328                kind: "Command",
329                expected: "a feature with a value (run a command with execute_command or \
330                           execute_and_wait)",
331            }
332            .into());
333        }
334        Ok(self.nodemap.get_text(name, &self.transport)?)
335    }
336
337    /// Write a feature from text, parsed by its type: the counterpart of
338    /// [`Camera::get`]. Text that does not parse as the feature's type is
339    /// [`GenApiError::InvalidText`] (in [`GenicamError::GenApi`]), and nothing
340    /// is written.
341    ///
342    /// A command is not set but executed, with [`Camera::execute_command`] or
343    /// [`Camera::execute_and_wait`]: setting one is an error, and nothing is
344    /// written. So is setting a category.
345    pub fn set(&mut self, name: &str, value: &str) -> Result<(), GenicamError> {
346        if let Some(Node::Command(_)) = self.nodemap.node(name) {
347            return Err(GenApiError::Type {
348                name: name.to_string(),
349                kind: "Command",
350                expected: "a feature that is set (run a command with execute_command or \
351                           execute_and_wait)",
352            }
353            .into());
354        }
355        Ok(self.nodemap.set_text(name, value, &self.transport)?)
356    }
357
358    /// Save the camera's configuration — every feature its XML marks
359    /// `<Streamable>` — to `out`, in the GenApi feature-file layout
360    /// (ADR-0028). A feature behind a selector is saved under each of the
361    /// selector's entries, and the selector is put back; behind a selector
362    /// that cannot be set now — not implemented, not available, locked — it
363    /// has one value, saved once.
364    ///
365    /// Returns what was saved, and in [`Configuration::omitted`] what was
366    /// left out and why; the file carries the same as comments. Save while
367    /// the camera is not acquiring: what `TLParamsLocked` locks is left out
368    /// otherwise.
369    ///
370    /// [`Configuration::omitted`]: genapi::persistence::Configuration::omitted
371    pub fn save_features(
372        &mut self,
373        out: &mut impl std::io::Write,
374    ) -> Result<genapi::Configuration, GenicamError> {
375        let configuration = self.nodemap.save_configuration(&self.transport);
376        out.write_all(configuration.to_text().as_bytes())?;
377        out.flush()?;
378        Ok(configuration)
379    }
380
381    /// Restore a configuration [`Camera::save_features`] wrote, or another
382    /// GenApi-based tool did in the same layout.
383    ///
384    /// Values are written in the order the camera's dependencies require, a
385    /// write that fails is tried once more after the others, and the report
386    /// lists every value that still could not be written, with the reason.
387    /// A file saved from another camera model, or another major version of
388    /// its XML, is loaded too, with a warning in the report. Only a file that
389    /// cannot be read at all is an error.
390    pub fn load_features(
391        &mut self,
392        input: &mut impl std::io::Read,
393    ) -> Result<genapi::LoadReport, GenicamError> {
394        let mut text = String::new();
395        input.read_to_string(&mut text)?;
396        let configuration = genapi::Configuration::parse(&text)?;
397        Ok(self.load_configuration(&configuration))
398    }
399
400    /// Restore a configuration already read, such as the one
401    /// [`Camera::save_features`] returned: [`Camera::load_features`] without
402    /// the file.
403    pub fn load_configuration(
404        &mut self,
405        configuration: &genapi::Configuration,
406    ) -> genapi::LoadReport {
407        self.nodemap
408            .load_configuration(configuration, &self.transport)
409    }
410
411    /// Capture device/host timestamp pairs and fit a mapping model.
412    pub async fn time_calibrate(
413        &mut self,
414        samples: usize,
415        interval_ms: u64,
416    ) -> Result<(), GenicamError> {
417        if samples < 2 {
418            return Err(GenicamError::TimeSync("it takes at least two samples"));
419        }
420
421        let cap = samples.max(self.time_sync.capacity());
422        self.time_sync = TimeSync::with_capacity(cap);
423
424        let latch_cmd = self.find_alias(viva_sfnc::TS_LATCH_CMDS);
425        let value_node = self
426            .find_alias(viva_sfnc::TS_VALUE_NODES)
427            .ok_or_else(|| GenApiError::NodeNotFound("TimestampValue".into()))?;
428
429        let mut freq_hz = if let Some(name) = self.find_alias(viva_sfnc::TS_FREQ_NODES) {
430            match self.nodemap.get_integer(name, &self.transport) {
431                Ok(value) if value > 0 => Some(value as f64),
432                Ok(_) => None,
433                Err(err) => {
434                    debug!(node = name, error = %err, "failed to read timestamp frequency");
435                    None
436                }
437            }
438        } else if let Some(name) = self.find_alias(viva_sfnc::TS_INCREMENT_NODES) {
439            // Nanoseconds a tick (GenCP's Timestamp Increment).
440            match self.nodemap.get_integer(name, &self.transport) {
441                Ok(ns) if ns > 0 => Some(1e9 / ns as f64),
442                Ok(_) => None,
443                Err(err) => {
444                    debug!(node = name, error = %err, "failed to read timestamp increment");
445                    None
446                }
447            }
448        } else {
449            None
450        };
451
452        info!(samples, interval_ms, "starting time calibration");
453        let mut first_sample: Option<(u64, Instant)> = None;
454        let mut last_sample: Option<(u64, Instant)> = None;
455
456        for idx in 0..samples {
457            if let Some(cmd) = latch_cmd {
458                self.nodemap
459                    .exec_command(cmd, &self.transport)
460                    .map_err(GenicamError::from)?;
461            }
462
463            // The latch changed the value behind the cache's back: unless the
464            // XML links the two, the cached first reading came back every
465            // time, no fit was possible, and calibration reported success on
466            // default coefficients (found once a fit had to succeed, Codex
467            // review of #185).
468            self.nodemap.invalidate(value_node);
469            let raw_ticks = self
470                .nodemap
471                .get_integer(value_node, &self.transport)
472                .map_err(GenicamError::from)?;
473            let dev_ticks = u64::try_from(raw_ticks)
474                .map_err(|_| GenicamError::TimeSync("the camera's timestamp reads negative"))?;
475            let host = Instant::now();
476            self.time_sync.update(dev_ticks, host);
477            if idx == 0 {
478                first_sample = Some((dev_ticks, host));
479            }
480            last_sample = Some((dev_ticks, host));
481            if let Some(origin) = self.time_sync.origin_instant() {
482                let ns = host.duration_since(origin).as_nanos();
483                debug!(
484                    sample = idx,
485                    ticks = dev_ticks,
486                    host_ns = ns,
487                    "timestamp sample"
488                );
489            } else {
490                debug!(sample = idx, ticks = dev_ticks, "timestamp sample");
491            }
492
493            if interval_ms > 0 && idx + 1 < samples {
494                sleep(Duration::from_millis(interval_ms)).await;
495            }
496        }
497
498        if freq_hz.is_none()
499            && let (Some((first_ticks, first_host)), Some((last_ticks, last_host))) =
500                (first_sample, last_sample)
501            && last_ticks > first_ticks
502            && let Some(delta) = last_host.checked_duration_since(first_host)
503        {
504            let secs = delta.as_secs_f64();
505            if secs > 0.0 {
506                freq_hz = Some((last_ticks - first_ticks) as f64 / secs);
507            }
508        }
509
510        let (a, b) = self.time_sync.fit(freq_hz).ok_or(GenicamError::TimeSync(
511            "the samples do not fit a clock: too few, or all at one instant",
512        ))?;
513
514        if let Some(freq) = freq_hz {
515            info!(freq_hz = freq, a, b, "time calibration complete");
516        } else {
517            info!(a, b, "time calibration complete");
518        }
519
520        Ok(())
521    }
522
523    /// Map device tick counters to host time using the fitted model; `None`
524    /// before [`time_calibrate`](Self::time_calibrate) has fitted one.
525    pub fn map_dev_ts(&self, dev_ticks: u64) -> Option<SystemTime> {
526        self.time_sync.to_host_time(dev_ticks)
527    }
528
529    /// Inspect the timestamp synchroniser state.
530    pub fn time_sync(&self) -> &TimeSync {
531        &self.time_sync
532    }
533
534    /// Reset the device timestamp counter when supported by the camera.
535    pub fn time_reset(&mut self) -> Result<(), GenicamError> {
536        if let Some(cmd) = self.find_alias(viva_sfnc::TS_RESET_CMDS) {
537            self.nodemap
538                .exec_command(cmd, &self.transport)
539                .map_err(GenicamError::from)?;
540            self.time_sync = TimeSync::with_capacity(self.time_sync.capacity());
541            info!(command = cmd, "timestamp counter reset");
542        }
543        Ok(())
544    }
545
546    /// Execute a command feature by name.
547    ///
548    /// [`Camera::set`] already dispatches to this for `Node::Command`, but
549    /// only from a `&str` value; callers that hold a command name directly
550    /// would otherwise have to reach through [`Camera::nodemap_mut`] and
551    /// [`Camera::transport`] at once, which the borrow checker rejects from
552    /// outside the struct. Splitting the two fields here is the same thing
553    /// [`Camera::acquisition_start`] does.
554    pub fn execute_command(&mut self, name: &str) -> Result<(), GenicamError> {
555        self.nodemap
556            .exec_command(name, &self.transport)
557            .map_err(Into::into)
558    }
559
560    /// Execute a command and wait until the camera reports it finished.
561    ///
562    /// GenICam Standard v2.1.1 §2.8.8: "the state of other nodes can depend on
563    /// the completion of the Command therefore applications ... should always
564    /// wait for the command completion by calling IsDone immediately after the
565    /// Execute". This polls [`NodeMap::is_done`] at the command's
566    /// `<PollingTime>` — every [`COMMAND_POLL_INTERVAL`] when it declares
567    /// none — until it answers `true` or `timeout` passes.
568    ///
569    /// A command whose register path is write-only — most of them — is done
570    /// as soon as the write is acknowledged, so this returns as quickly as
571    /// [`Camera::execute_command`] does. A self-clearing command (its register
572    /// reads back the command value until the device has finished) is waited
573    /// on. Reads made afterwards see the state the command left.
574    ///
575    /// Returns [`GenicamError::CommandNotDone`] when the camera has not
576    /// finished by `timeout`; the command was still executed.
577    pub async fn execute_and_wait(
578        &mut self,
579        name: &str,
580        timeout: Duration,
581    ) -> Result<(), GenicamError> {
582        self.execute_command(name)?;
583        let started = Instant::now();
584        while let Some(pause) = self.poll_done(name, started, timeout)? {
585            sleep(pause).await;
586        }
587        Ok(())
588    }
589
590    /// [`Camera::execute_and_wait`] on the calling thread, for a program
591    /// without an async runtime; it sleeps between polls.
592    pub fn execute_and_wait_blocking(
593        &mut self,
594        name: &str,
595        timeout: Duration,
596    ) -> Result<(), GenicamError> {
597        self.execute_command(name)?;
598        let started = Instant::now();
599        while let Some(pause) = self.poll_done(name, started, timeout)? {
600            std::thread::sleep(pause);
601        }
602        Ok(())
603    }
604
605    /// One poll of a command executed at `started`: `None` once it is done,
606    /// else how long to wait before asking again; `CommandNotDone` once
607    /// `timeout` has passed.
608    fn poll_done(
609        &self,
610        name: &str,
611        started: Instant,
612        timeout: Duration,
613    ) -> Result<Option<Duration>, GenicamError> {
614        if self.nodemap.is_done(name, &self.transport)? {
615            return Ok(None);
616        }
617        let waited = started.elapsed();
618        if waited >= timeout {
619            return Err(GenicamError::CommandNotDone {
620                name: name.to_string(),
621                waited,
622            });
623        }
624        let interval = self
625            .nodemap
626            .polling_time(name)
627            .unwrap_or(COMMAND_POLL_INTERVAL);
628        Ok(Some(interval.min(timeout - waited)))
629    }
630
631    /// Whether the command `name` has finished: GenICam's `IsDone`.
632    ///
633    /// See [`NodeMap::is_done`]; [`Camera::execute_and_wait`] polls it.
634    pub fn is_done(&self, name: &str) -> Result<bool, GenicamError> {
635        self.nodemap
636            .is_done(name, &self.transport)
637            .map_err(Into::into)
638    }
639
640    /// Start acquisition: set `TLParamsLocked`, then execute
641    /// `AcquisitionStart`.
642    ///
643    /// `TLParamsLocked` is how the transport layer tells the camera's XML a
644    /// stream is running, so that features which would change the payload —
645    /// `Width`, `PixelFormat` — are locked until it stops (33 of the 38
646    /// vendor-corpus documents declare it). A camera without it is started
647    /// all the same; one that refuses it is started with a warning. If the
648    /// start fails, the lock is cleared again.
649    pub fn acquisition_start(&mut self) -> Result<(), GenicamError> {
650        self.lock_transport_parameters(true);
651        let started = self
652            .nodemap
653            .exec_command(viva_sfnc::ACQUISITION_START, &self.transport)
654            .map_err(Into::into);
655        if started.is_err() {
656            self.lock_transport_parameters(false);
657        }
658        started
659    }
660
661    /// Stop acquisition: execute `AcquisitionStop`, then clear
662    /// `TLParamsLocked` — cleared even when the stop fails, so the features
663    /// it locked can be written again.
664    pub fn acquisition_stop(&mut self) -> Result<(), GenicamError> {
665        let stopped = self
666            .nodemap
667            .exec_command(viva_sfnc::ACQUISITION_STOP, &self.transport)
668            .map_err(Into::into);
669        self.lock_transport_parameters(false);
670        stopped
671    }
672
673    /// Write `TLParamsLocked`, an `<Integer>` or a `<Boolean>`, if the
674    /// camera has it; a refusal is logged, not returned.
675    fn lock_transport_parameters(&mut self, locked: bool) {
676        let name = viva_sfnc::TL_PARAMS_LOCKED;
677        let written = match self.nodemap.node(name) {
678            None => return,
679            Some(Node::Boolean(_)) => self.nodemap.set_bool(name, locked, &self.transport),
680            Some(_) => self
681                .nodemap
682                .set_integer(name, i64::from(locked), &self.transport),
683        };
684        if let Err(error) = written {
685            warn!(%error, locked, "could not write TLParamsLocked");
686        }
687    }
688
689    /// Configure chunk mode and enable the requested selectors.
690    pub fn configure_chunks(&mut self, cfg: &ChunkConfig) -> Result<(), GenicamError> {
691        self.ensure_chunk_feature(viva_sfnc::CHUNK_MODE_ACTIVE)?;
692        // Only a selector asked for needs them: an Allied Vision Manta G-125B
693        // declares `ChunkModeActive` alone.
694        if !cfg.selectors.is_empty() {
695            self.ensure_chunk_feature(viva_sfnc::CHUNK_SELECTOR)?;
696            self.ensure_chunk_feature(viva_sfnc::CHUNK_ENABLE)?;
697        }
698
699        // SAFE: split-borrow distinct fields of `self`
700        self.with_map(|nm, tr| {
701            nm.set_bool(viva_sfnc::CHUNK_MODE_ACTIVE, cfg.active, tr)?;
702            for s in &cfg.selectors {
703                nm.set_enum(viva_sfnc::CHUNK_SELECTOR, s, tr)?;
704                nm.set_bool(viva_sfnc::CHUNK_ENABLE, cfg.active, tr)?;
705            }
706            Ok(())
707        })
708    }
709
710    /// Read features from a frame's chunks: attach them to the nodemap's
711    /// chunk ports, run `f`, and detach them again.
712    ///
713    /// Inside `f`, `cam.get("ChunkExposureTime")` reads the value this frame
714    /// carried — from the chunk whose ID the camera's XML names, at the offset
715    /// and in the byte order the XML declares (ADR-0026). Nothing is read from
716    /// the device for it. A frame without chunks attaches none, and chunk
717    /// features then fail with [`GenApiError::NotAttached`].
718    ///
719    /// ```rust,no_run
720    /// # fn example(
721    /// #     camera: &mut viva_genicam::Camera<viva_genicam::GigeRegisterIo>,
722    /// #     frame: &viva_genicam::Frame,
723    /// # ) -> Result<(), viva_genicam::GenicamError> {
724    /// let exposure = camera.with_chunks(frame, |cam| cam.get("ChunkExposureTime"))?;
725    /// # Ok(())
726    /// # }
727    /// ```
728    pub fn with_chunks<R>(&mut self, frame: &Frame, f: impl FnOnce(&Self) -> R) -> R {
729        let chunks = frame.chunks.clone().unwrap_or_default();
730        self.nodemap.attach_chunks(&chunks);
731        let result = f(self);
732        self.nodemap.detach_chunks();
733        result
734    }
735
736    /// Every feature `frame`'s chunks feed, with its value or the error that
737    /// kept it from being read, sorted by name.
738    ///
739    /// The features are the ones the camera's XML lists in a category and
740    /// derives from a chunk port whose chunk the frame carries — `ChunkTimestamp`,
741    /// not the `ChunkTimestamp_Val` register behind it. Empty for a frame
742    /// without chunks.
743    pub fn chunk_features(&mut self, frame: &Frame) -> Vec<(String, Result<String, GenicamError>)> {
744        let Some(chunks) = frame.chunks.as_ref() else {
745            return Vec::new();
746        };
747        let ids: Vec<u64> = chunks.ids().collect();
748        let names = self.features_on_ports(
749            |kind| matches!(kind, PortKind::Chunk { chunk_id } if ids.contains(&chunk_id)),
750        );
751        self.with_chunks(frame, |cam| {
752            names
753                .into_iter()
754                .map(|name| {
755                    let value = cam.get(&name);
756                    (name, value)
757                })
758                .collect()
759        })
760    }
761
762    /// Read features from a received event: attach it to the ports whose
763    /// `<EventID>` is the event's, run `f`, and detach events again.
764    ///
765    /// Inside `f`, `cam.get("EventExposureEndTimestamp")` reads the event's
766    /// own bytes at the offset the camera's XML declares — 0x8 for the
767    /// timestamp on every corpus document, which is where the event header has
768    /// it.
769    pub fn with_event<R>(&mut self, event: &Event, f: impl FnOnce(&Self) -> R) -> R {
770        self.nodemap
771            .attach_event(u64::from(event.id), event.raw.clone());
772        let result = f(self);
773        self.nodemap.detach_events();
774        result
775    }
776
777    /// Every feature `event` feeds, with its value or the error that kept it
778    /// from being read, sorted by name: the category features derived from a
779    /// port whose `<EventID>` is the event's. Empty when the XML declares no
780    /// port for it.
781    pub fn event_features(&mut self, event: &Event) -> Vec<(String, Result<String, GenicamError>)> {
782        let id = u64::from(event.id);
783        let names = self.features_on_ports(
784            |kind| matches!(kind, PortKind::Event { event_id } if event_id == id),
785        );
786        self.with_event(event, |cam| {
787            names
788                .into_iter()
789                .map(|name| {
790                    let value = cam.get(&name);
791                    (name, value)
792                })
793                .collect()
794        })
795    }
796
797    /// The `EventSelector` entry an event with `event_id` belongs to, when
798    /// the XML says.
799    ///
800    /// SFNC names an event's data features `Event<Entry>` and
801    /// `Event<Entry>Timestamp`, so an entry with either feature on the port
802    /// whose `<EventID>` is `event_id` names the event. Otherwise an entry
803    /// whose literal `<Value>` is the ID does, as Basler's do. `None` when
804    /// neither matches, or the camera has no `EventSelector`.
805    pub fn event_name(&self, event_id: u16) -> Option<String> {
806        let Some(Node::Enum(selector)) = self.nodemap.node(viva_sfnc::EVENT_SELECTOR) else {
807            return None;
808        };
809        let id = u64::from(event_id);
810        let features = self.features_on_ports(
811            |kind| matches!(kind, PortKind::Event { event_id } if event_id == id),
812        );
813        let named = |entry: &str| {
814            let feature = format!("Event{entry}");
815            features
816                .iter()
817                .any(|name| *name == feature || *name == format!("{feature}Timestamp"))
818        };
819        selector
820            .entries
821            .iter()
822            .find(|entry| named(&entry.name))
823            .or_else(|| {
824                selector.entries.iter().find(|entry| {
825                    matches!(entry.value, genapi::EnumValueSrc::Literal(value) if value == i64::from(event_id))
826                })
827            })
828            .map(|entry| entry.name.clone())
829    }
830
831    /// Turn on notification of each event named, through SFNC's
832    /// `EventSelector` and `EventNotification`.
833    ///
834    /// Which events a device emits is a GenApi decision with no bootstrap
835    /// equivalent: without those features, naming an event is
836    /// [`GenicamError::NoEventSelection`] rather than a write somewhere
837    /// hopeful.
838    pub(crate) fn enable_events(&mut self, enable_ids: &[&str]) -> Result<(), GenicamError> {
839        let sfnc = self.nodemap.node(viva_sfnc::EVENT_SELECTOR).is_some()
840            && self.nodemap.node(viva_sfnc::EVENT_NOTIFICATION).is_some();
841        if !sfnc && !enable_ids.is_empty() {
842            return Err(GenicamError::NoEventSelection {
843                events: enable_ids.iter().map(ToString::to_string).collect(),
844            });
845        }
846        self.with_map(|nodemap, transport| {
847            for &name in enable_ids {
848                nodemap.set_enum(viva_sfnc::EVENT_SELECTOR, name, transport)?;
849                nodemap.set_enum(
850                    viva_sfnc::EVENT_NOTIFICATION,
851                    viva_sfnc::EVENT_NOTIF_ON,
852                    transport,
853                )?;
854            }
855            Ok(())
856        })
857    }
858
859    /// The features fed by the ports `which` selects, sorted, without
860    /// repeats.
861    fn features_on_ports(&self, which: impl Fn(PortKind) -> bool) -> Vec<String> {
862        let mut names: Vec<String> = self
863            .nodemap
864            .ports()
865            .into_iter()
866            .filter(|(_, kind)| which(*kind))
867            .flat_map(|(port, _)| self.nodemap.port_features(port))
868            .map(str::to_string)
869            .collect();
870        names.sort();
871        names.dedup();
872        names
873    }
874
875    fn ensure_chunk_feature(&self, name: &str) -> Result<(), GenicamError> {
876        if self.nodemap.node(name).is_none() {
877            return Err(GenicamError::MissingChunkFeature(name.to_string()));
878        }
879        Ok(())
880    }
881
882    fn find_alias(&self, names: &[&'static str]) -> Option<&'static str> {
883        names
884            .iter()
885            .copied()
886            .find(|name| self.nodemap.node(name).is_some())
887    }
888}
889
890/// What only a GigE Vision camera has: a GVCP message channel for events
891/// and a stream channel that can go to a multicast group. Streams and
892/// control privilege are here too ([`Camera::open_stream`],
893/// [`GigeRegisterIo::control_state`]). A USB3 Vision camera has none of
894/// them, so none of this compiles against one.
895impl Camera<GigeRegisterIo> {
896    /// Configure the GVCP message channel and enable delivery of the requested events.
897    ///
898    /// GigE Vision only:
899    ///
900    /// ```compile_fail
901    /// # async fn f(mut camera: viva_genicam::Camera<viva_genicam::genapi::NullIo>) {
902    /// let _ = camera.configure_events(std::net::Ipv4Addr::LOCALHOST, 10020, &[]).await;
903    /// # }
904    /// ```
905    pub async fn configure_events(
906        &mut self,
907        local_ip: Ipv4Addr,
908        port: u16,
909        enable_ids: &[&str],
910    ) -> Result<(), GenicamError> {
911        info!(%local_ip, port, "configuring GVCP events");
912        // Pre-compute aliases before taking a mutable borrow of the nodemap
913        let msg_sel = self.find_alias(viva_sfnc::MSG_SEL);
914        let msg_ip = self.find_alias(viva_sfnc::MSG_IP);
915        let msg_port = self.find_alias(viva_sfnc::MSG_PORT);
916        let msg_en = self.find_alias(viva_sfnc::MSG_EN);
917
918        let channel_configured = self.with_map(|nodemap, transport| {
919            let mut ok = true;
920
921            if let Some(selector) = msg_sel {
922                match nodemap.enum_entries(selector) {
923                    Ok(entries) => {
924                        if let Some(entry) = entries.into_iter().next() {
925                            if let Err(err) = nodemap.set_enum(selector, &entry, transport) {
926                                warn!(node = selector, error = %err, "failed to set message selector");
927                                ok = false;
928                            }
929                        } else {
930                            warn!(node = selector, "message selector missing entries");
931                            ok = false;
932                        }
933                    }
934                    Err(err) => {
935                        warn!(feature = selector, error = %err, "failed to query message selector");
936                        ok = false;
937                    }
938                }
939            } else {
940                ok = false;
941            }
942
943            if let Some(node) = msg_ip {
944                let value = u32::from(local_ip) as i64;
945                if let Err(err) = nodemap.set_integer(node, value, transport) {
946                    warn!(feature = node, error = %err, "failed to write message IP");
947                    ok = false;
948                }
949            } else {
950                ok = false;
951            }
952
953            if let Some(node) = msg_port {
954                if let Err(err) = nodemap.set_integer(node, port as i64, transport) {
955                    warn!(feature = node, error = %err, "failed to write message port");
956                    ok = false;
957                }
958            } else {
959                ok = false;
960            }
961
962            if let Some(node) = msg_en {
963                if let Err(err) = nodemap.set_bool(node, true, transport) {
964                    warn!(feature = node, error = %err, "failed to enable message channel");
965                    ok = false;
966                }
967            } else {
968                ok = false;
969            }
970
971            ok
972        });
973
974        if !channel_configured {
975            configure_message_channel_fallback(&self.transport, local_ip, port)?;
976        }
977
978        self.enable_events(enable_ids)
979    }
980
981    /// Configure the stream channel for multicast delivery: point `GevSCDA`
982    /// at `group` and `GevSCPHostPort` at `port`.
983    ///
984    /// A multicast destination address is all it takes; SFNC has no
985    /// separate enable. Without the SFNC nodes the bootstrap registers are
986    /// written directly. [`Camera::open_stream`] with
987    /// [`StreamOptions::multicast`] does this and starts receiving too.
988    ///
989    /// GigE Vision only:
990    ///
991    /// ```compile_fail
992    /// # fn f(mut camera: viva_genicam::Camera<viva_genicam::genapi::NullIo>) {
993    /// let _ = camera.configure_stream_multicast(0, std::net::Ipv4Addr::new(239, 0, 0, 1), 5000);
994    /// # }
995    /// ```
996    pub fn configure_stream_multicast(
997        &mut self,
998        stream_idx: u32,
999        group: Ipv4Addr,
1000        port: u16,
1001    ) -> Result<(), GenicamError> {
1002        configure_multicast(self, stream_idx, group, port)
1003    }
1004
1005    /// Open a GVCP event stream bound to the provided local endpoint.
1006    ///
1007    /// GigE Vision only:
1008    ///
1009    /// ```compile_fail
1010    /// # async fn f(camera: viva_genicam::Camera<viva_genicam::genapi::NullIo>) {
1011    /// let _ = camera.open_event_stream(std::net::Ipv4Addr::LOCALHOST, 10020).await;
1012    /// # }
1013    /// ```
1014    pub async fn open_event_stream(
1015        &self,
1016        local_ip: Ipv4Addr,
1017        port: u16,
1018    ) -> Result<EventStream, GenicamError> {
1019        let socket = bind_event_socket_internal(IpAddr::V4(local_ip), port).await?;
1020        let time_sync = if !self.time_sync.is_empty() {
1021            Some(Arc::new(self.time_sync.clone()))
1022        } else {
1023            None
1024        };
1025        Ok(EventStream::new(socket, time_sync))
1026    }
1027}
1028
1029/// [`Camera::configure_stream_multicast`], over any register transport so
1030/// the register writes can be checked in memory.
1031fn configure_multicast<T: RegisterIo>(
1032    camera: &mut Camera<T>,
1033    stream_idx: u32,
1034    group: Ipv4Addr,
1035    port: u16,
1036) -> Result<(), GenicamError> {
1037    if !group.is_multicast() {
1038        return Err(GenicamError::NotMulticast(std::net::SocketAddrV4::new(
1039            group, port,
1040        )));
1041    }
1042    info!(stream_idx, %group, port, "configuring multicast stream");
1043
1044    // Precompute node names before taking &mut camera.nodemap
1045    let dest_addr_node = camera.find_alias(viva_sfnc::SCP_DEST_ADDR);
1046    let host_port_node = camera.find_alias(viva_sfnc::SCP_HOST_PORT);
1047
1048    let mut used_sfnc = true;
1049    camera.with_map(|nm, tr| {
1050        if nm.node(viva_sfnc::STREAM_CH_SELECTOR).is_some() {
1051            if let Err(err) = nm.set_integer(viva_sfnc::STREAM_CH_SELECTOR, stream_idx as i64, tr) {
1052                warn!(
1053                    channel = stream_idx,
1054                    error = %err,
1055                    "failed to select stream channel via SFNC"
1056                );
1057                used_sfnc = false;
1058            }
1059        } else {
1060            used_sfnc = false;
1061        }
1062
1063        if let Some(node) = dest_addr_node {
1064            if let Err(err) = nm.set_integer(node, u32::from(group) as i64, tr) {
1065                warn!(feature = node, error = %err, "failed to write multicast address");
1066                used_sfnc = false;
1067            }
1068        } else {
1069            used_sfnc = false;
1070        }
1071
1072        if let Some(node) = host_port_node {
1073            if let Err(err) = nm.set_integer(node, port as i64, tr) {
1074                warn!(feature = node, error = %err, "failed to write multicast port");
1075                used_sfnc = false;
1076            }
1077        } else {
1078            used_sfnc = false;
1079        }
1080    });
1081
1082    if !used_sfnc {
1083        let base = gvcp_consts::STREAM_CHANNEL_BASE
1084            + stream_idx as u64 * gvcp_consts::STREAM_CHANNEL_STRIDE;
1085        let addr_reg = base + gvcp_consts::STREAM_DESTINATION_ADDRESS;
1086        camera
1087            .transport
1088            .write(addr_reg, &group.octets())
1089            .map_err(GenicamError::from)?;
1090        // GevSCPHostPort is a 32-bit register with the port in its low
1091        // half. The two port bytes alone land in the high half (SR-20),
1092        // the bug already fixed for GevMCP.
1093        let port_reg = base + gvcp_consts::STREAM_DESTINATION_PORT;
1094        camera
1095            .transport
1096            .write(port_reg, &u32::from(port).to_be_bytes())
1097            .map_err(GenicamError::from)?;
1098        info!(
1099            stream_idx,
1100            %group,
1101            port,
1102            "configured multicast destination via raw registers"
1103        );
1104    } else {
1105        info!(
1106            stream_idx,
1107            %group,
1108            port,
1109            "configured multicast destination via SFNC"
1110        );
1111    }
1112
1113    Ok(())
1114}
1115
1116/// Configuration for enabling chunk data via SFNC features.
1117#[derive(Debug, Clone, Default)]
1118pub struct ChunkConfig {
1119    /// Names of chunk selectors that should be enabled on the device.
1120    pub selectors: Vec<String>,
1121    /// Whether chunk mode should be active after configuration.
1122    pub active: bool,
1123}
1124
1125/// Where a GigE session stands with the camera's control channel privilege
1126/// (CCP). Only a session that holds it writes registers: in every other
1127/// state a write is refused before it reaches the camera.
1128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1129#[non_exhaustive]
1130pub enum ControlState {
1131    /// This application holds control privilege and keeps it alive.
1132    Held,
1133    /// Opened read-only ([`GigeRegisterIo::monitor`]): nothing was claimed,
1134    /// nothing is written, no heartbeat is sent.
1135    Monitor,
1136    /// Privilege was lost: CCP reads without control bits — the heartbeat
1137    /// expired — or, on a camera that names its primary application, another
1138    /// application holds it. Checked by the keepalive, and after a write
1139    /// refused with `ACCESS_DENIED`, when a camera that does not name its
1140    /// primary application is also asked by claiming again
1141    /// ([`GigeDevice::holds_control`]). [`GigeRegisterIo::reclaim_control`]
1142    /// asks for it again.
1143    Lost,
1144    /// Given up with [`GigeRegisterIo::release_control`];
1145    /// [`GigeRegisterIo::reclaim_control`] takes it again, and so does
1146    /// [`Camera::open_stream`].
1147    Released,
1148}
1149
1150/// How [`connect_gige_as`] opens a camera.
1151#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1152#[non_exhaustive]
1153pub enum Access {
1154    /// Claim control privilege, keep it alive, release it when the camera is
1155    /// dropped. Fails while another application holds it.
1156    #[default]
1157    Control,
1158    /// Read only: claim nothing, write nothing, send no heartbeat. Works while
1159    /// another application controls the camera; every write is refused.
1160    Monitor,
1161    /// [`Access::Control`], claimed as exclusive access (CCP `0x1`): while it
1162    /// is held, the camera refuses other applications' reads as well as
1163    /// their writes, and a [`Access::Monitor`] cannot open it. An Allied
1164    /// Vision Manta G-125B granted it and answered another application's
1165    /// READREG and READMEM with `ACCESS_DENIED`, while still answering
1166    /// discovery. The session is [`ControlState::Held`], as with control.
1167    Exclusive,
1168}
1169
1170/// Blocking adapter turning an asynchronous [`GigeDevice`] into a [`RegisterIo`]
1171/// implementation.
1172///
1173/// The adapter waits on GVCP register transactions from synchronous code,
1174/// whatever the caller runs on: a plain thread waits on the transport's
1175/// runtime directly; inside a multi-thread runtime the wait goes through
1176/// [`tokio::task::block_in_place`] so the executor keeps making progress;
1177/// on a current-thread runtime's own thread it moves to a short-lived thread,
1178/// since nothing may block that runtime in place.
1179///
1180/// [`connect_gige`] gives a camera opened from a current-thread runtime a
1181/// runtime of its own, as [`blocking::connect`] does for a program with none.
1182/// A camera built with [`GigeRegisterIo::new`] over a current-thread
1183/// runtime's handle can be used from that runtime's blocking pool, but not
1184/// from its own thread, which the socket needs free.
1185///
1186/// An access of exactly one aligned 32-bit register goes out as
1187/// READREG/WRITEREG, anything else as READMEM/WRITEMEM; see
1188/// [`GigeDevice::read_register_or_mem`](gige::GigeDevice::read_register_or_mem)
1189/// for the fallback a device that refuses the register commands gets.
1190///
1191/// # Control channel keepalive
1192///
1193/// Constructing the adapter spawns a background task that keeps the device's
1194/// control channel alive; see [`GigeRegisterIo::new`]. Holding a
1195/// `GigeRegisterIo` is therefore enough to keep control privilege — no caller
1196/// has to run a heartbeat of its own.
1197/// While register I/O holds the device mutex, the GVCP receive loop sends its
1198/// own probes on the same socket. Long ACK waits therefore do not starve the
1199/// idle task's keepalive; ordinary requests remain serialized.
1200pub struct GigeRegisterIo {
1201    handle: tokio::runtime::Handle,
1202    device: Arc<Mutex<GigeDevice>>,
1203    /// Where the session stands with control privilege; the keepalive task
1204    /// reports a loss here.
1205    control: Arc<tokio::sync::watch::Sender<ControlState>>,
1206    keepalive: Mutex<Option<Keepalive>>,
1207    /// The runtime `handle` belongs to, when the transport owns it
1208    /// ([`connect_gige`] from a current-thread runtime, [`blocking::connect`]).
1209    /// Shut down after control is released, when the transport is dropped.
1210    runtime: Option<tokio::runtime::Runtime>,
1211}
1212
1213/// The running keepalive task and the signal that stops it.
1214struct Keepalive {
1215    stop: tokio::sync::watch::Sender<bool>,
1216    task: tokio::task::JoinHandle<()>,
1217}
1218
1219/// How long dropping a controlling adapter waits for the camera to
1220/// acknowledge the release of control privilege. A camera that does not
1221/// answer in time times the privilege out on its own.
1222const RELEASE_TIMEOUT: Duration = Duration::from_millis(500);
1223
1224impl GigeRegisterIo {
1225    /// Create a new adapter using the provided runtime handle and a device
1226    /// that holds control privilege ([`GigeDevice::claim_control`]).
1227    ///
1228    /// This also spawns the control-channel keepalive on `handle`. A GigE Vision
1229    /// device revokes control privilege if it receives no GVCP command within
1230    /// `GevHeartbeatTimeout` (3 000 ms on both `viva-fake-gige` and the aravis
1231    /// fake camera, `arvfakecamera.c:1082`), and GVSP image traffic does not
1232    /// count — so a camera can sit at an interactive prompt, or stream frames for
1233    /// a minute, and then refuse the next write with `ACCESS_DENIED`.
1234    ///
1235    /// Nothing in an application's normal flow refreshes that timer, which is why
1236    /// three consumers of this crate had each grown their own copy of the loop —
1237    /// and why the Python bindings, which had none, hit the failure.
1238    ///
1239    /// The keepalive stops when the adapter is dropped, and control privilege
1240    /// is released then (CCP ← 0), so the next application — or the next run
1241    /// of this one — can claim it at once instead of waiting out the
1242    /// heartbeat timeout. Privilege lost meanwhile is reported through
1243    /// [`control_state`](Self::control_state).
1244    /// Dropping the adapter cancels and drains any in-flight keepalive I/O.
1245    /// The runtime must remain alive until the adapter has been dropped. On a
1246    /// current-thread runtime the async task is aborted, since blocking on its
1247    /// completion would prevent that same runtime from making progress.
1248    pub fn new(handle: tokio::runtime::Handle, mut device: GigeDevice) -> Self {
1249        // A register operation holds the device mutex while waiting for its
1250        // reply. Let the socket owner send heartbeats during that wait; the
1251        // background task below covers idle periods and refines this period.
1252        device.set_inflight_keepalive_period(Some(keepalive_period(None)));
1253        let adapter = Self::with_state(handle, device, ControlState::Held);
1254        adapter.start_keepalive();
1255        adapter
1256    }
1257
1258    /// A read-only adapter: no keepalive, no in-flight probes, and every write
1259    /// refused before it reaches the wire. For a camera another application
1260    /// controls; see [`Access::Monitor`].
1261    pub fn monitor(handle: tokio::runtime::Handle, mut device: GigeDevice) -> Self {
1262        device.set_inflight_keepalive_period(None);
1263        Self::with_state(handle, device, ControlState::Monitor)
1264    }
1265
1266    fn with_state(handle: tokio::runtime::Handle, device: GigeDevice, state: ControlState) -> Self {
1267        Self {
1268            handle,
1269            device: Arc::new(Mutex::new(device)),
1270            control: Arc::new(tokio::sync::watch::channel(state).0),
1271            keepalive: Mutex::new(None),
1272            runtime: None,
1273        }
1274    }
1275
1276    /// Own the runtime this transport's handle belongs to, and shut it down
1277    /// when the transport is dropped.
1278    pub(crate) fn adopt_runtime(&mut self, runtime: tokio::runtime::Runtime) {
1279        self.runtime = Some(runtime);
1280    }
1281
1282    /// Where this session stands with control privilege.
1283    pub fn control_state(&self) -> ControlState {
1284        *self.control.borrow()
1285    }
1286
1287    /// Changes of [`control_state`](Self::control_state) as they happen: losing
1288    /// privilege is reported here, not only logged.
1289    pub fn watch_control(&self) -> tokio::sync::watch::Receiver<ControlState> {
1290        self.control.subscribe()
1291    }
1292
1293    /// Check an owned control session now, using only reads of the control
1294    /// channel and, where supported, the primary application's address.
1295    ///
1296    /// A revoked privilege or `ACCESS_DENIED` while reading that channel marks
1297    /// the session [`ControlState::Lost`], notifies [`Self::watch_control`], and
1298    /// stops its keepalive. Dropping it then sends no control release to another
1299    /// application's camera. A network failure is returned with its cause and
1300    /// does not by itself establish lost ownership.
1301    ///
1302    /// This never claims control. A monitor, released session or already-lost
1303    /// session is returned unchanged, without I/O. On cameras that do not name
1304    /// their primary application, a successful controlled CCP read cannot
1305    /// distinguish the current holder from another controller (TC-38).
1306    pub fn refresh_control_state(&self) -> Result<ControlState, GenicamError> {
1307        let stopped = {
1308            let mut device = self.lock_device()?;
1309            if self.control_state() != ControlState::Held {
1310                return Ok(self.control_state());
1311            }
1312            let held = match self.block_on(device.ping_control_channel())? {
1313                Ok(held) => held,
1314                Err(gige::GigeError::Status(gige::GigeStatus::Common(
1315                    gencp::StatusCode::AccessDenied,
1316                ))) => false,
1317                Err(source) => return Err(error::gige("read the control channel")(source)),
1318            };
1319            if held {
1320                return Ok(self.control_state());
1321            }
1322            self.control.send_replace(ControlState::Lost);
1323            // Take only the old keepalive while its device is still locked.
1324            // A concurrent explicit reclaim may start a new one afterward.
1325            let stopped = self.keepalive.lock().ok().and_then(|mut k| k.take());
1326            if let Some(keepalive) = &stopped {
1327                let _ = keepalive.stop.send(true);
1328            }
1329            stopped
1330        };
1331        if let Some(stopped) = stopped {
1332            self.drain_keepalive(stopped);
1333        }
1334        Ok(self.control_state())
1335    }
1336
1337    /// Ask for control privilege again — after it was lost or released, or
1338    /// to turn a monitor into a controller — and keep it alive.
1339    ///
1340    /// Fails, and changes nothing, while another application holds it.
1341    pub fn reclaim_control(&self) -> Result<(), GenicamError> {
1342        {
1343            let mut guard = self.lock_device()?;
1344            let device: &mut GigeDevice = &mut guard;
1345            let fut = async {
1346                device.claim_control().await?;
1347                if let Err(err) = device.enable_pending_ack().await {
1348                    warn!(error = %err, "could not enable PENDING_ACK");
1349                }
1350                Ok::<_, gige::GigeError>(())
1351            };
1352            self.block_on(fut)?.map_err(error::gige("claim control"))?;
1353            if device.inflight_keepalive_period().is_none() {
1354                device.set_inflight_keepalive_period(Some(keepalive_period(None)));
1355            }
1356        }
1357        self.control.send_replace(ControlState::Held);
1358        self.start_keepalive();
1359        info!("control channel privilege reclaimed");
1360        Ok(())
1361    }
1362
1363    /// Give control privilege up now (CCP ← 0) and stop the keepalive,
1364    /// reporting whether the camera acknowledged. Dropping the adapter does
1365    /// the same, best effort. A release the camera does not take leaves the
1366    /// session as it was, keepalive running.
1367    ///
1368    /// A monitor holds nothing and writes nothing, so for one this does
1369    /// nothing.
1370    pub fn release_control(&self) -> Result<(), GenicamError> {
1371        if self.control_state() == ControlState::Monitor {
1372            return Ok(());
1373        }
1374        self.stop_keepalive();
1375        let result = {
1376            let mut device = self.lock_device()?;
1377            let fut = device.release_control();
1378            self.block_on(fut)
1379                .and_then(|released| released.map_err(error::gige("release control")))
1380        };
1381        match result {
1382            Ok(()) => {
1383                self.control.send_replace(ControlState::Released);
1384            }
1385            // The camera did not take it: whatever the session held, it still
1386            // holds, and the keepalive goes on keeping it — and on finding out
1387            // if it is gone.
1388            Err(_) if self.control_state() == ControlState::Held => self.start_keepalive(),
1389            Err(_) => {}
1390        }
1391        result
1392    }
1393
1394    /// Lock the underlying [`GigeDevice`] for direct async operations.
1395    ///
1396    /// This is intended for callers that need the raw device (e.g. stream
1397    /// channel configuration) while the `Camera` wrapper holds the transport.
1398    pub fn lock_device(&self) -> Result<MutexGuard<'_, GigeDevice>, GenicamError> {
1399        self.device
1400            .lock()
1401            .map_err(|_| GenicamError::Panicked("a thread holding the camera's device lock"))
1402    }
1403
1404    fn lock(&self) -> Result<MutexGuard<'_, GigeDevice>, GenApiError> {
1405        self.device.lock().map_err(|_| {
1406            GenApiError::io(GenicamError::Panicked(
1407                "a thread holding the camera's device lock",
1408            ))
1409        })
1410    }
1411
1412    /// Spawn the keepalive unless one is running.
1413    fn start_keepalive(&self) {
1414        let Ok(mut keepalive) = self.keepalive.lock() else {
1415            return;
1416        };
1417        if keepalive.as_ref().is_some_and(|k| !k.task.is_finished()) {
1418            return;
1419        }
1420        let (stop, stopped) = tokio::sync::watch::channel(false);
1421        let task = spawn_keepalive(
1422            self.handle.clone(),
1423            Arc::downgrade(&self.device),
1424            stopped,
1425            self.control.clone(),
1426        );
1427        *keepalive = Some(Keepalive { stop, task });
1428    }
1429
1430    /// Stop the keepalive and wait for its I/O to drain.
1431    fn stop_keepalive(&self) {
1432        let Some(keepalive) = self.keepalive.lock().ok().and_then(|mut k| k.take()) else {
1433            return;
1434        };
1435        self.drain_keepalive(keepalive);
1436    }
1437
1438    fn drain_keepalive(&self, Keepalive { stop, task }: Keepalive) {
1439        let _ = stop.send(true);
1440        if self.handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::CurrentThread {
1441            // This task cannot progress while its runtime thread is in Drop.
1442            // Abort it and synchronize with the blocking operation instead.
1443            // Queued operations check cancellation before starting any I/O.
1444            task.abort();
1445            drop(self.device.lock());
1446            return;
1447        }
1448        // Aborting the async task would detach its spawn_blocking operation,
1449        // which can still use Tokio timers. Join both before runtime shutdown.
1450        match self.block_on_from_anywhere(task) {
1451            Some(Err(error)) => warn!(%error, "control channel keepalive failed during shutdown"),
1452            Some(Ok(())) => {}
1453            None => warn!("keepalive shutdown thread panicked"),
1454        }
1455    }
1456
1457    /// [`Self::block_on`], for shutdown: `None` where it cannot run.
1458    fn block_on_from_anywhere<F>(&self, fut: F) -> Option<F::Output>
1459    where
1460        F: std::future::Future + Send,
1461        F::Output: Send,
1462    {
1463        self.block_on(fut).ok()
1464    }
1465
1466    /// Release control privilege on the way out, within [`RELEASE_TIMEOUT`].
1467    fn release_on_drop(&self) {
1468        let Ok(mut device) = self.device.lock() else {
1469            return;
1470        };
1471        if self.handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::CurrentThread {
1472            // Nothing can wait for the acknowledgement here: send and go.
1473            if let Err(error) = device.try_send_release() {
1474                debug!(%error, "could not send the control release");
1475            }
1476            return;
1477        }
1478        // Built inside the future: a timer needs the runtime's context.
1479        let device: &mut GigeDevice = &mut device;
1480        let release =
1481            async move { tokio::time::timeout(RELEASE_TIMEOUT, device.release_control()).await };
1482        match self.block_on_from_anywhere(release) {
1483            Some(Ok(Ok(()))) => debug!("control channel privilege released"),
1484            Some(Ok(Err(error))) => debug!(%error, "the camera did not take the control release"),
1485            Some(Err(_)) => debug!("no answer to the control release; the camera will time it out"),
1486            None => debug!("control release thread panicked"),
1487        }
1488    }
1489
1490    /// Control was claimed through the raw device ([`Camera::open_stream`]
1491    /// does): a session that had lost or released it holds it again.
1492    pub(crate) fn note_claimed(&self) {
1493        let reclaimed = self.control.send_if_modified(|state| {
1494            let lapsed = matches!(state, ControlState::Lost | ControlState::Released);
1495            if lapsed {
1496                *state = ControlState::Held;
1497            }
1498            lapsed
1499        });
1500        if reclaimed {
1501            self.start_keepalive();
1502        }
1503    }
1504
1505    /// A write the camera refused with `ACCESS_DENIED`: either the register
1506    /// refuses it, or this session no longer holds control. Ask the device
1507    /// which ([`GigeDevice::holds_control`]), and mark control lost only on
1508    /// its answer.
1509    fn check_refusal(&self, device: &mut GigeDevice, err: &gige::GigeError) {
1510        if !matches!(
1511            err,
1512            gige::GigeError::Status(gige::GigeStatus::Common(gencp::StatusCode::AccessDenied))
1513        ) || self.control_state() != ControlState::Held
1514        {
1515            return;
1516        }
1517        match self
1518            .block_on(device.holds_control())
1519            .and_then(|pinged| pinged.map_err(error::gige("read the control channel")))
1520        {
1521            Ok(false) => {
1522                self.control.send_replace(ControlState::Lost);
1523                warn!(
1524                    "the camera refused a write with ACCESS_DENIED: control privilege is lost \
1525                     (reclaim_control asks for it again)"
1526                );
1527            }
1528            Ok(true) => debug!("ACCESS_DENIED for this register; control is still held"),
1529            Err(error) => debug!(%error, "could not check control privilege after ACCESS_DENIED"),
1530        }
1531    }
1532}
1533
1534impl Drop for GigeRegisterIo {
1535    fn drop(&mut self) {
1536        let held = self.control_state() == ControlState::Held;
1537        self.stop_keepalive();
1538        if held {
1539            self.release_on_drop();
1540        }
1541        // Whatever context this runs in, an async one included: shutting
1542        // down in the background is the only way that never blocks it.
1543        if let Some(runtime) = self.runtime.take() {
1544            runtime.shutdown_background();
1545        }
1546    }
1547}
1548
1549impl GigeRegisterIo {
1550    /// Run `fut` to completion on the adapter's runtime from synchronous
1551    /// code, in any context: on a plain thread directly; inside a
1552    /// multi-thread runtime through `block_in_place`; on a current-thread
1553    /// runtime's thread, which nothing may block in place, on a scoped
1554    /// thread of its own. The rule every register access follows.
1555    ///
1556    /// The one case that cannot work is a transport on a current-thread
1557    /// runtime used from that runtime's own thread: the runtime drives the
1558    /// socket only while that thread is free. From its blocking pool
1559    /// (`spawn_blocking`) the access works; from the thread itself Tokio
1560    /// refuses it with a panic, rather than a hang. [`connect_gige`] never
1561    /// builds such a transport.
1562    pub(crate) fn block_on<F>(&self, fut: F) -> Result<F::Output, GenicamError>
1563    where
1564        F: std::future::Future + Send,
1565        F::Output: Send,
1566    {
1567        use tokio::runtime::RuntimeFlavor::CurrentThread;
1568        match tokio::runtime::Handle::try_current() {
1569            Ok(current)
1570                if current.runtime_flavor() == CurrentThread
1571                    && self.handle.runtime_flavor() != CurrentThread =>
1572            {
1573                std::thread::scope(|scope| scope.spawn(|| self.handle.block_on(fut)).join())
1574                    .map_err(|_| GenicamError::Panicked("the register access thread"))
1575            }
1576            Ok(_) => Ok(tokio::task::block_in_place(|| self.handle.block_on(fut))),
1577            Err(_) => Ok(self.handle.block_on(fut)),
1578        }
1579    }
1580}
1581
1582/// A camera's own runtime, when no runtime the caller has can serve it: one
1583/// worker drives its socket, keepalive and timers.
1584pub(crate) fn camera_runtime() -> Result<tokio::runtime::Runtime, GenicamError> {
1585    tokio::runtime::Builder::new_multi_thread()
1586        .worker_threads(1)
1587        .thread_name("viva-gige")
1588        .enable_all()
1589        .build()
1590        .map_err(error::network("start the camera's runtime"))
1591}
1592
1593impl RegisterIo for GigeRegisterIo {
1594    fn read(&self, addr: u64, len: usize) -> Result<Vec<u8>, GenApiError> {
1595        let mut device = self.lock()?;
1596        let fut = device.read_register_or_mem(addr, len);
1597        self.block_on(fut)
1598            .map_err(GenApiError::io)?
1599            .map_err(GenApiError::io)
1600    }
1601
1602    fn write(&self, addr: u64, data: &[u8]) -> Result<(), GenApiError> {
1603        // Only a session that holds control writes: the camera would refuse
1604        // it anyway, whether another application controls it or nobody does
1605        // (an Allied Vision Manta G-125B answers `ACCESS_DENIED` to both).
1606        match self.control_state() {
1607            ControlState::Held => {}
1608            state => return Err(GenApiError::io(WriteRefused::new(state, addr))),
1609        }
1610        let mut device = self.lock()?;
1611        let fut = device.write_register_or_mem(addr, data);
1612        self.block_on(fut).map_err(GenApiError::io)?.map_err(|err| {
1613            self.check_refusal(&mut device, &err);
1614            GenApiError::io(err)
1615        })
1616    }
1617}
1618
1619// ---------------------------------------------------------------------------
1620// Control channel keepalive
1621// ---------------------------------------------------------------------------
1622
1623/// Heartbeat window assumed when the device does not report a usable one.
1624///
1625/// Both `viva-fake-gige` and the aravis fake camera report 3 000 ms, and it is
1626/// short enough to be a safe assumption for a device that tells us nothing.
1627const ASSUMED_HEARTBEAT_TIMEOUT_MS: u32 = 3_000;
1628
1629/// How many keepalives we aim to fit inside one heartbeat window.
1630///
1631/// Four means three consecutive pings can be lost — to packet loss, to a long
1632/// `lock_device()` hold during stream setup, to a scheduling stall — and the
1633/// fourth still lands inside the window.
1634const KEEPALIVES_PER_WINDOW: u32 = 4;
1635
1636/// Floor on the keepalive period, so a device reporting an implausibly small
1637/// timeout cannot turn the keepalive into a flood.
1638const MIN_KEEPALIVE_PERIOD: Duration = Duration::from_millis(100);
1639
1640/// Ceiling on the keepalive period. A device may report a very long window; the
1641/// keepalive is also our liveness check, so it stays reasonably prompt.
1642const MAX_KEEPALIVE_PERIOD: Duration = Duration::from_secs(2);
1643
1644/// Choose a keepalive period from the device's reported `GevHeartbeatTimeout`.
1645///
1646/// `None` means the register could not be read; `Some(0)` is a device declining
1647/// to say. Both fall back to [`ASSUMED_HEARTBEAT_TIMEOUT_MS`] rather than to a
1648/// period derived from a value we do not trust.
1649///
1650/// aravis instead pings on a fixed 1 s period
1651/// (`ARV_GV_DEVICE_HEARTBEAT_PERIOD_US`), which is fine for the 3 000 ms window
1652/// devices usually report but too slow for one that asks for less. Deriving the
1653/// period costs a single extra register read at connect.
1654fn keepalive_period(reported_timeout_ms: Option<u32>) -> Duration {
1655    let timeout_ms = match reported_timeout_ms {
1656        Some(ms) if ms > 0 => ms,
1657        _ => ASSUMED_HEARTBEAT_TIMEOUT_MS,
1658    };
1659    Duration::from_millis(u64::from(timeout_ms / KEEPALIVES_PER_WINDOW))
1660        .clamp(MIN_KEEPALIVE_PERIOD, MAX_KEEPALIVE_PERIOD)
1661}
1662
1663/// Run one GVCP transaction against the shared device from the blocking pool.
1664///
1665/// Returns `None` once the transport has been dropped — the keepalive's exit
1666/// signal. `spawn_blocking` rather than `block_in_place` because the device
1667/// mutex can be held for the whole of stream negotiation, and waiting for it on
1668/// the blocking pool costs the runtime a pool thread rather than a worker.
1669async fn on_blocking_pool<R, F>(
1670    handle: &tokio::runtime::Handle,
1671    device: &std::sync::Weak<Mutex<GigeDevice>>,
1672    stopped: &mut tokio::sync::watch::Receiver<bool>,
1673    op: F,
1674) -> Option<Result<R, String>>
1675where
1676    F: FnOnce(
1677            &tokio::runtime::Handle,
1678            &mut GigeDevice,
1679            &mut tokio::sync::watch::Receiver<bool>,
1680        ) -> Result<R, String>
1681        + Send
1682        + 'static,
1683    R: Send + 'static,
1684{
1685    if *stopped.borrow() {
1686        return None;
1687    }
1688    let device = device.upgrade()?;
1689    let handle = handle.clone();
1690    let mut blocking_stopped = stopped.clone();
1691    let mut task = tokio::task::spawn_blocking(move || match device.lock() {
1692        Ok(mut guard) => {
1693            if *blocking_stopped.borrow() {
1694                return Err("keepalive stopped".to_string());
1695            }
1696            op(&handle, &mut guard, &mut blocking_stopped)
1697        }
1698        Err(_) => Err("gige device mutex poisoned".to_string()),
1699    });
1700    let joined = tokio::select! {
1701        joined = &mut task => joined,
1702        _ = stopped.changed() => {
1703            // The blocking thread cancels its I/O future; join it so no timer
1704            // registration can race the runtime's shutdown.
1705            let _ = task.await;
1706            return None;
1707        }
1708    };
1709    if *stopped.borrow() {
1710        return None;
1711    }
1712    Some(joined.unwrap_or_else(|err| Err(err.to_string())))
1713}
1714
1715/// Keep the device's control channel alive for as long as the transport exists.
1716///
1717/// The adapter signals cancellation and drains blocking I/O on drop, before
1718/// the owning runtime shuts down.
1719///
1720/// It contends only for the device mutex — never for whatever lock the
1721/// application puts around its [`Camera`] — which is what lets it run without
1722/// the pause/resume dance every app-layer copy of this loop needed.
1723fn spawn_keepalive(
1724    handle: tokio::runtime::Handle,
1725    device: std::sync::Weak<Mutex<GigeDevice>>,
1726    mut stopped: tokio::sync::watch::Receiver<bool>,
1727    control: Arc<tokio::sync::watch::Sender<ControlState>>,
1728) -> tokio::task::JoinHandle<()> {
1729    handle.clone().spawn(async move {
1730        let reported = on_blocking_pool(&handle, &device, &mut stopped, |handle, dev, stopped| {
1731            let reported = handle.block_on(async {
1732                tokio::select! {
1733                    biased;
1734                    _ = stopped.changed() => Err("keepalive stopped".to_string()),
1735                    result = dev.heartbeat_timeout_ms() => result.map_err(|err| err.to_string()),
1736                }
1737            });
1738            // 0 is a device declining to say, read as the assumed window by
1739            // the idle keepalive too: the in-flight probes follow the same
1740            // reading rather than switching off (TC-26).
1741            if let Ok(timeout_ms) = reported {
1742                dev.set_inflight_keepalive_period(Some(keepalive_period(Some(timeout_ms))));
1743            }
1744            reported
1745        })
1746        .await;
1747
1748        let period = match reported {
1749            // Transport already gone; nothing to keep alive.
1750            None => return,
1751            Some(Ok(timeout_ms)) => {
1752                debug!(timeout_ms, "device reported GevHeartbeatTimeout");
1753                keepalive_period(Some(timeout_ms))
1754            }
1755            Some(Err(error)) => {
1756                warn!(
1757                    %error,
1758                    assumed_timeout_ms = ASSUMED_HEARTBEAT_TIMEOUT_MS,
1759                    "could not read GevHeartbeatTimeout; assuming a short window"
1760                );
1761                keepalive_period(None)
1762            }
1763        };
1764        debug!(?period, "control channel keepalive started");
1765
1766        let mut ticker = tokio::time::interval(period);
1767        // After a long device-mutex hold (stream negotiation) one fresh ping is
1768        // enough; do not burst-fire the ticks that elapsed meanwhile.
1769        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
1770        // `interval` fires immediately, and the timeout read above has just
1771        // refreshed the timer.
1772        ticker.tick().await;
1773
1774        let mut consecutive_failures: u32 = 0;
1775        loop {
1776            tokio::select! {
1777                _ = stopped.changed() => return,
1778                _ = ticker.tick() => {}
1779            }
1780            let pinged = on_blocking_pool(&handle, &device, &mut stopped, |handle, dev, stopped| {
1781                handle.block_on(async {
1782                    tokio::select! {
1783                        biased;
1784                        _ = stopped.changed() => Err("keepalive stopped".to_string()),
1785                        result = dev.ping_control_channel() => result.map_err(|err| err.to_string()),
1786                    }
1787                })
1788            })
1789            .await;
1790            match pinged {
1791                None => {
1792                    debug!("control channel keepalive stopped: transport dropped");
1793                    return;
1794                }
1795                Some(Ok(true)) => {
1796                    if consecutive_failures > 0 {
1797                        info!(consecutive_failures, "control channel keepalive recovered");
1798                    }
1799                    consecutive_failures = 0;
1800                }
1801                Some(Ok(false)) => {
1802                    // CCP reads without control bits: the heartbeat expired, or
1803                    // the device released us. Nothing is left to keep alive
1804                    // until the application reclaims it.
1805                    control.send_if_modified(|state| {
1806                        let held = *state == ControlState::Held;
1807                        if held {
1808                            *state = ControlState::Lost;
1809                        }
1810                        held
1811                    });
1812                    warn!(
1813                        "control channel privilege lost: CCP reads without this application's \
1814                         bits, so a heartbeat expired or the camera gave the privilege up; \
1815                         reclaim_control asks for it again"
1816                    );
1817                    return;
1818                }
1819                Some(Err(error)) => {
1820                    consecutive_failures += 1;
1821                    warn!(%error, consecutive_failures, "control channel keepalive failed");
1822                }
1823            }
1824        }
1825    })
1826}
1827
1828/// Connect to a GigE Vision camera with the given [`Access`], returning the
1829/// [`Camera`] and the GenICam XML it was built from.
1830///
1831/// [`Access::Control`] claims control privilege, switches `PENDING_ACK` on
1832/// where GVCP Capability says the camera has it, and keeps the privilege
1833/// alive until the camera is dropped, which releases it. It fails while
1834/// another application holds control. [`Access::Exclusive`] does the same
1835/// with exclusive access, which also keeps other applications from reading.
1836/// [`Access::Monitor`] writes nothing at all, so it works alongside an
1837/// application holding control, though not one holding exclusive access.
1838///
1839/// From a current-thread runtime the camera gets a runtime of its own — one
1840/// worker thread, shut down when the camera is dropped — since a
1841/// current-thread runtime cannot drive the camera's socket while its one
1842/// thread waits in a register read.
1843pub async fn connect_gige_as(
1844    device: &gige::DeviceInfo,
1845    access: Access,
1846) -> Result<(Camera<GigeRegisterIo>, String), GenicamError> {
1847    use tokio::runtime::RuntimeFlavor::CurrentThread;
1848    if tokio::runtime::Handle::current().runtime_flavor() != CurrentThread {
1849        return connect_here(device, access).await;
1850    }
1851    let runtime = BackgroundShutdown(Some(camera_runtime()?));
1852    let device = device.clone();
1853    let opened = match runtime
1854        .handle()
1855        .spawn(async move { connect_here(&device, access).await })
1856        .await
1857    {
1858        Ok(opened) => opened,
1859        Err(err) => Err(error::task("connect")(err)),
1860    };
1861    let (mut camera, xml) = opened?;
1862    camera.transport.adopt_runtime(runtime.into_inner());
1863    Ok((camera, xml))
1864}
1865
1866/// A runtime that, dropped, shuts down in the background: dropping a runtime
1867/// blocks, which an async context forbids. The connect future that holds one
1868/// can be dropped anywhere it awaits — by a timeout, a `select!` — and a
1869/// plain `Runtime` dropped there panics (Codex on #199).
1870struct BackgroundShutdown(Option<tokio::runtime::Runtime>);
1871
1872impl BackgroundShutdown {
1873    fn handle(&self) -> &tokio::runtime::Handle {
1874        self.0
1875            .as_ref()
1876            .expect("the runtime is present until into_inner")
1877            .handle()
1878    }
1879
1880    fn into_inner(mut self) -> tokio::runtime::Runtime {
1881        self.0
1882            .take()
1883            .expect("the runtime is present until into_inner")
1884    }
1885}
1886
1887impl Drop for BackgroundShutdown {
1888    fn drop(&mut self) {
1889        if let Some(runtime) = self.0.take() {
1890            runtime.shutdown_background();
1891        }
1892    }
1893}
1894
1895/// A claimed control socket while XML is being fetched. A cancelled connect
1896/// must release it too, before a `GigeRegisterIo` exists to do that on drop.
1897struct OpeningGigeDevice {
1898    device: Option<tokio::sync::Mutex<GigeDevice>>,
1899    claimed: bool,
1900}
1901
1902impl Drop for OpeningGigeDevice {
1903    fn drop(&mut self) {
1904        if self.claimed
1905            && let Some(device) = self.device.as_mut()
1906            && let Err(error) = device.get_mut().try_send_release()
1907        {
1908            debug!(%error, "could not send the cancelled connection's control release");
1909        }
1910    }
1911}
1912
1913/// [`connect_gige_as`] on the runtime it is called from, which must be a
1914/// multi-thread one or one other threads drive.
1915pub(crate) async fn connect_here(
1916    device: &gige::DeviceInfo,
1917    access: Access,
1918) -> Result<(Camera<GigeRegisterIo>, String), GenicamError> {
1919    use std::net::{IpAddr, SocketAddr};
1920    use tokio::sync::Mutex as AsyncMutex;
1921
1922    let control_addr = SocketAddr::new(IpAddr::V4(device.ip), gige::GVCP_PORT);
1923    info!(%control_addr, ?access, "connecting to GigE Vision camera");
1924
1925    let device = gige::GigeDevice::open(control_addr)
1926        .await
1927        .map_err(error::gige("open the control channel"))?;
1928
1929    let mut opening = OpeningGigeDevice {
1930        device: Some(AsyncMutex::new(device)),
1931        claimed: false,
1932    };
1933    if access != Access::Monitor {
1934        let mut device = opening
1935            .device
1936            .as_ref()
1937            .expect("opening device")
1938            .lock()
1939            .await;
1940        // Claim control privilege (required before configuration and
1941        // streaming); every later claim, after a loss, asks for the same.
1942        device.set_exclusive_access(access == Access::Exclusive);
1943        // The camera can apply the claim before its ACK arrives. Arm the
1944        // release first so cancellation in that gap does not leave it held.
1945        opening.claimed = true;
1946        if let Err(source) = device.claim_control().await {
1947            // A device refusal acquired nothing; a missing/malformed ACK
1948            // may hide a successful claim and still needs a release.
1949            opening.claimed = !matches!(source, gige::GigeError::Status(_));
1950            return Err(error::gige("claim control")(source));
1951        }
1952        match device.enable_pending_ack().await {
1953            Ok(enabled) => debug!(enabled, "PENDING_ACK"),
1954            Err(err) => {
1955                warn!(error = %err, "could not enable PENDING_ACK; slow commands will be retried")
1956            }
1957        }
1958    }
1959
1960    let control = opening.device.as_ref().expect("opening device");
1961
1962    // Fetch and parse the GenApi XML.
1963    let fetched = viva_genapi_xml::fetch_and_load_xml(|address, length| {
1964        let control = &control;
1965        async move {
1966            let mut dev = control.lock().await;
1967            dev.read_mem(address, length)
1968                .await
1969                .map_err(viva_genapi_xml::XmlError::transport)
1970        }
1971    })
1972    .await;
1973
1974    // Extract the device and create the blocking adapter. It owns the release
1975    // of control from here, so a failure below still gives control back.
1976    let handle = tokio::runtime::Handle::current();
1977    let control_device = opening.device.take().expect("opening device").into_inner();
1978    opening.claimed = false;
1979    let transport = match access {
1980        Access::Control | Access::Exclusive => GigeRegisterIo::new(handle, control_device),
1981        Access::Monitor => GigeRegisterIo::monitor(handle, control_device),
1982    };
1983    let xml = fetched?;
1984    let nodemap = build_nodemap(&xml)?;
1985
1986    info!("GigE camera connected successfully");
1987    Ok((Camera::new(transport, nodemap), xml))
1988}
1989
1990/// Connect to a GigE Vision camera and return a fully configured [`Camera`].
1991///
1992/// This convenience function handles all connection boilerplate:
1993/// 1. Opens a GVCP control connection to the device and claims control
1994/// 2. Fetches and parses the GenApi XML from the camera
1995/// 3. Builds the nodemap
1996/// 4. Creates the transport adapter, which releases control when dropped
1997///
1998/// [`connect_gige_as`] opens a read-only monitor instead.
1999///
2000/// # Example
2001///
2002/// ```rust,ignore
2003/// use std::time::Duration;
2004/// use viva_genicam::{gige, connect_gige};
2005///
2006/// let devices = gige::discover(Duration::from_millis(500)).await?;
2007/// let device = devices.into_iter().next().expect("no camera found");
2008/// let mut camera = connect_gige(&device).await?;
2009/// camera.set("ExposureTime", "5000")?;
2010/// ```
2011pub async fn connect_gige(
2012    device: &gige::DeviceInfo,
2013) -> Result<Camera<GigeRegisterIo>, GenicamError> {
2014    let (camera, _xml) = connect_gige_with_xml(device).await?;
2015    Ok(camera)
2016}
2017
2018/// Connect to a GigE Vision camera and return both a [`Camera`] and the raw
2019/// GenICam XML string fetched from the device.
2020///
2021/// This is useful when the caller needs the XML for purposes beyond node
2022/// evaluation (e.g. forwarding it over a network API). The same as
2023/// [`connect_gige_as`] with [`Access::Control`].
2024pub async fn connect_gige_with_xml(
2025    device: &gige::DeviceInfo,
2026) -> Result<(Camera<GigeRegisterIo>, String), GenicamError> {
2027    connect_gige_as(device, Access::Control).await
2028}
2029
2030// ---------------------------------------------------------------------------
2031// USB3 Vision transport (behind `u3v` feature)
2032// ---------------------------------------------------------------------------
2033
2034/// Blocking [`RegisterIo`] adapter wrapping a [`U3vDevice`](u3v::U3vDevice).
2035///
2036/// Generic over `T: UsbTransfer` so that real hardware (`NusbTransfer`) and
2037/// test doubles (`MockUsbTransfer`, `FakeU3vTransport`) all work through the
2038/// same code path. USB operations are inherently synchronous, so this adapter
2039/// simply forwards calls through a `Mutex` for thread safety.
2040#[cfg(feature = "u3v")]
2041#[cfg_attr(docsrs, doc(cfg(feature = "u3v")))]
2042pub struct U3vRegisterIo<T: u3v::UsbTransfer + 'static> {
2043    /// Shared with a [`U3vFrameStream`](crate::U3vFrameStream), which clears
2044    /// StreamEnable through it when it stops.
2045    device: Arc<Mutex<u3v::U3vDevice<T>>>,
2046    /// Set once a transfer — a register access, a stream's, an event's —
2047    /// found the device disconnected.
2048    lost: Arc<std::sync::atomic::AtomicBool>,
2049}
2050
2051/// Whether a USB3 Vision camera is gone, readable apart from its
2052/// transport ([`U3vRegisterIo::connection`]).
2053#[cfg(feature = "u3v")]
2054#[cfg_attr(docsrs, doc(cfg(feature = "u3v")))]
2055#[derive(Debug, Clone)]
2056pub struct U3vConnection(Arc<std::sync::atomic::AtomicBool>);
2057
2058#[cfg(feature = "u3v")]
2059impl U3vConnection {
2060    /// [`U3vRegisterIo::is_lost`].
2061    pub fn is_lost(&self) -> bool {
2062        self.0.load(std::sync::atomic::Ordering::Acquire)
2063    }
2064}
2065
2066#[cfg(feature = "u3v")]
2067impl<T: u3v::UsbTransfer + 'static> U3vRegisterIo<T> {
2068    /// Create a new adapter wrapping a [`U3vDevice`](u3v::U3vDevice).
2069    pub fn new(device: u3v::U3vDevice<T>) -> Self {
2070        Self {
2071            device: Arc::new(Mutex::new(device)),
2072            lost: Arc::new(std::sync::atomic::AtomicBool::new(false)),
2073        }
2074    }
2075
2076    /// Whether the camera is gone: a register access, a stream or an event
2077    /// stream on it failed with
2078    /// [`U3vError::Disconnected`](u3v::U3vError::Disconnected) — unplugged,
2079    /// or reset (backlog UV-03). It does not come back; open the camera
2080    /// again once it is.
2081    pub fn is_lost(&self) -> bool {
2082        self.lost.load(std::sync::atomic::Ordering::Acquire)
2083    }
2084
2085    /// A handle that answers [`is_lost`](Self::is_lost) without the
2086    /// transport: for a service watching a camera another task uses.
2087    pub fn connection(&self) -> U3vConnection {
2088        U3vConnection(Arc::clone(&self.lost))
2089    }
2090
2091    /// Record the camera as gone.
2092    pub(crate) fn mark_lost(&self) {
2093        self.lost.store(true, std::sync::atomic::Ordering::Release);
2094    }
2095
2096    /// The flag [`is_lost`](Self::is_lost) reads, for a stream to set.
2097    pub(crate) fn lost_flag(&self) -> Arc<std::sync::atomic::AtomicBool> {
2098        Arc::clone(&self.lost)
2099    }
2100
2101    /// Note a disconnect in `error`, and hand it on.
2102    fn noting_loss(&self, error: u3v::U3vError) -> u3v::U3vError {
2103        if matches!(error, u3v::U3vError::Disconnected) {
2104            self.mark_lost();
2105        }
2106        error
2107    }
2108
2109    /// Lock the underlying device for direct access (e.g. stream configuration).
2110    pub fn lock_device(&self) -> Result<MutexGuard<'_, u3v::U3vDevice<T>>, GenicamError> {
2111        self.device
2112            .lock()
2113            .map_err(|_| GenicamError::Panicked("a thread holding the camera's device lock"))
2114    }
2115
2116    /// The device, shared: a frame stream holds it to stop the stream.
2117    pub(crate) fn shared_device(&self) -> Arc<Mutex<u3v::U3vDevice<T>>> {
2118        Arc::clone(&self.device)
2119    }
2120
2121    fn lock(&self) -> Result<MutexGuard<'_, u3v::U3vDevice<T>>, GenApiError> {
2122        self.device.lock().map_err(|_| {
2123            GenApiError::io(GenicamError::Panicked(
2124                "a thread holding the camera's device lock",
2125            ))
2126        })
2127    }
2128}
2129
2130#[cfg(feature = "u3v")]
2131impl<T: u3v::UsbTransfer + 'static> RegisterIo for U3vRegisterIo<T> {
2132    fn read(&self, addr: u64, len: usize) -> Result<Vec<u8>, GenApiError> {
2133        let mut device = self.lock()?;
2134        device
2135            .read_mem(addr, len)
2136            .map_err(|e| GenApiError::io(self.noting_loss(e)))
2137    }
2138
2139    fn write(&self, addr: u64, data: &[u8]) -> Result<(), GenApiError> {
2140        let mut device = self.lock()?;
2141        device
2142            .write_mem(addr, data)
2143            .map_err(|e| GenApiError::io(self.noting_loss(e)))
2144    }
2145}
2146
2147/// What only a USB3 Vision camera has: an event interface, whose events
2148/// arrive on a USB endpoint rather than a GVCP message channel (backlog
2149/// TC-27 (4)). Its stream is
2150/// [`Camera::open_stream`](crate::Camera::open_stream) too.
2151#[cfg(feature = "u3v")]
2152#[cfg_attr(docsrs, doc(cfg(feature = "u3v")))]
2153impl<T: u3v::UsbTransfer + 'static> Camera<U3vRegisterIo<T>> {
2154    /// Turn on notification of the events named — `"ExposureEnd"`, say —
2155    /// through SFNC's `EventSelector` and `EventNotification`. They arrive on
2156    /// a stream from [`open_event_stream`](Self::open_event_stream).
2157    pub fn configure_events(&mut self, enable_ids: &[&str]) -> Result<(), GenicamError> {
2158        self.enable_events(enable_ids)
2159    }
2160
2161    /// Set the event interface's EventEnable and read its endpoint on a
2162    /// thread of its own. Events carry their device time in ns, mapped to
2163    /// host time once [`time_calibrate`](Camera::time_calibrate) has fitted
2164    /// a clock; dropping the stream restores the previous EventEnable word.
2165    pub fn open_event_stream(&self) -> Result<U3vEventStream, GenicamError> {
2166        let time_sync = (!self.time_sync.is_empty()).then(|| self.time_sync.clone());
2167        events::open_u3v_event_stream(&self.transport, time_sync)
2168    }
2169}
2170
2171/// Connect to a USB3 Vision camera and return a fully configured [`Camera`].
2172///
2173/// This convenience function handles all connection boilerplate:
2174/// 1. Opens the USB device and claims U3V interfaces
2175/// 2. Reads ABRM/SBRM bootstrap registers
2176/// 3. Fetches and parses the GenApi XML from the manifest table
2177/// 4. Builds the nodemap and creates the transport adapter
2178///
2179/// # Example
2180///
2181/// ```rust,ignore
2182/// use viva_genicam::{u3v, connect_u3v};
2183///
2184/// let devices = u3v::discover()?;
2185/// let device = devices.into_iter().next().expect("no U3V camera found");
2186/// let mut camera = connect_u3v(&device)?;
2187/// camera.set("ExposureTime", "5000")?;
2188/// ```
2189#[cfg(feature = "u3v-usb")]
2190#[cfg_attr(docsrs, doc(cfg(feature = "u3v-usb")))]
2191pub fn connect_u3v(
2192    device: &u3v::U3vDeviceInfo,
2193) -> Result<Camera<U3vRegisterIo<u3v::NusbTransfer>>, GenicamError> {
2194    let (camera, _xml) = connect_u3v_with_xml(device)?;
2195    Ok(camera)
2196}
2197
2198/// Connect to a USB3 Vision camera and return both a [`Camera`] and the raw
2199/// GenICam XML string fetched from the device.
2200#[cfg(feature = "u3v-usb")]
2201#[cfg_attr(docsrs, doc(cfg(feature = "u3v-usb")))]
2202pub fn connect_u3v_with_xml(
2203    device_info: &u3v::U3vDeviceInfo,
2204) -> Result<(Camera<U3vRegisterIo<u3v::NusbTransfer>>, String), GenicamError> {
2205    info!(
2206        vendor_id = device_info.vendor_id,
2207        product_id = device_info.product_id,
2208        "connecting to USB3 Vision camera"
2209    );
2210
2211    let mut device =
2212        u3v::U3vDevice::open_device(device_info).map_err(error::u3v("open the device"))?;
2213
2214    let xml = device.fetch_xml().map_err(error::u3v("fetch the XML"))?;
2215
2216    let nodemap = build_nodemap(&xml)?;
2217    let transport = U3vRegisterIo::new(device);
2218
2219    info!("USB3 Vision camera connected successfully");
2220    Ok((Camera::new(transport, nodemap), xml))
2221}
2222
2223/// Create a [`Camera`] from an already-opened [`U3vDevice`](u3v::U3vDevice)
2224/// with any [`UsbTransfer`](u3v::UsbTransfer) backend.
2225///
2226/// This is the generic entry point for testing with fake or mock transports.
2227/// The device must have been opened and bootstrapped (ABRM/SBRM read)
2228/// before calling this function.
2229#[cfg(feature = "u3v")]
2230#[cfg_attr(docsrs, doc(cfg(feature = "u3v")))]
2231pub fn open_u3v_device<T: u3v::UsbTransfer + 'static>(
2232    mut device: u3v::U3vDevice<T>,
2233) -> Result<(Camera<U3vRegisterIo<T>>, String), GenicamError> {
2234    let xml = device.fetch_xml().map_err(error::u3v("fetch the XML"))?;
2235    let nodemap = build_nodemap(&xml)?;
2236    let transport = U3vRegisterIo::new(device);
2237    Ok((Camera::new(transport, nodemap), xml))
2238}
2239
2240/// Parse a camera's GenApi XML and build its nodemap, reporting what we could
2241/// not represent.
2242///
2243/// Both layers isolate per-node failures, so a camera opens with a missing
2244/// feature rather than not at all. That only helps if the loss is visible:
2245/// every dropped node is logged here, and a summary line goes out at `warn`
2246/// so a user hitting an unsupported construct has something to report.
2247fn build_nodemap(xml: &str) -> Result<NodeMap, GenicamError> {
2248    let model = viva_genapi_xml::parse(xml)?;
2249    // The nodemap absorbs the XML layer's losses, so one list covers both.
2250    let nodemap = NodeMap::try_from_xml(model)?;
2251    for skipped in nodemap.skipped() {
2252        debug!(
2253            kind = %skipped.tag,
2254            node = skipped.name.as_deref().unwrap_or("<unnamed>"),
2255            error = %skipped.error,
2256            "GenApi node unavailable"
2257        );
2258    }
2259
2260    if !nodemap.skipped().is_empty() {
2261        warn!(
2262            unavailable = nodemap.skipped().len(),
2263            features = nodemap.node_names().count(),
2264            "some camera features are unavailable; run `viva-camctl report` for the list \
2265             and please report them at https://github.com/VitalyVorobyev/viva-genicam/issues"
2266        );
2267    }
2268    Ok(nodemap)
2269}
2270
2271#[cfg(test)]
2272mod tests {
2273    use super::*;
2274
2275    /// Registers in memory, for driving `Camera` without a transport.
2276    #[derive(Default)]
2277    struct MemoryIo(Mutex<std::collections::HashMap<u64, Vec<u8>>>);
2278
2279    impl RegisterIo for MemoryIo {
2280        fn read(&self, addr: u64, len: usize) -> Result<Vec<u8>, GenApiError> {
2281            let regs = self.0.lock().unwrap();
2282            let data = regs.get(&addr).cloned().unwrap_or_else(|| vec![0; len]);
2283            Ok(data)
2284        }
2285
2286        fn write(&self, addr: u64, data: &[u8]) -> Result<(), GenApiError> {
2287            self.0.lock().unwrap().insert(addr, data.to_vec());
2288            Ok(())
2289        }
2290    }
2291
2292    /// API-18 and SR-20: SFNC has no multicast "enable" — a multicast address
2293    /// in `GevSCDA` is what makes a stream multicast — and
2294    /// `GevSCPSDoNotFragment`, which the alias list used to name first, is
2295    /// the don't-fragment bit of `GevSCPSPacketSize`. The destination goes
2296    /// through the SFNC nodes, whose real name is `GevSCDA` (25 corpus
2297    /// documents; `GevSCPDA` is in none), and the port keeps the register's
2298    /// other half.
2299    #[test]
2300    fn multicast_goes_through_gevscda_and_leaves_do_not_fragment_alone() {
2301        const XML: &str = r#"
2302            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2303                <Integer Name="GevStreamChannelSelector"><pValue>SelectorReg</pValue></Integer>
2304                <IntReg Name="SelectorReg"><Address>0x2000</Address><Length>4</Length><AccessMode>RW</AccessMode><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
2305                <Integer Name="GevSCDA"><pValue>ScdaReg</pValue></Integer>
2306                <IntReg Name="ScdaReg"><Address>0x0D18</Address><Length>4</Length><AccessMode>RW</AccessMode><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
2307                <Integer Name="GevSCPHostPort"><pValue>ScpReg</pValue></Integer>
2308                <MaskedIntReg Name="ScpReg"><Address>0x0D00</Address><Length>4</Length><AccessMode>RW</AccessMode><LSB>31</LSB><MSB>16</MSB><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></MaskedIntReg>
2309                <Boolean Name="GevSCPSDoNotFragment"><pValue>DfReg</pValue></Boolean>
2310                <MaskedIntReg Name="DfReg"><Address>0x0D04</Address><Length>4</Length><AccessMode>RW</AccessMode><LSB>1</LSB><MSB>1</MSB><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></MaskedIntReg>
2311            </RegisterDescription>
2312        "#;
2313        let model = viva_genapi_xml::parse(XML).expect("parse");
2314        let nodemap = NodeMap::try_from_xml(model).expect("build nodemap");
2315        let io = MemoryIo::default();
2316        io.write(0x0D00, &0xABCD_0000u32.to_be_bytes()).unwrap();
2317        io.write(0x0D04, &1500u32.to_be_bytes()).unwrap();
2318        let mut camera = Camera::new(io, nodemap);
2319
2320        let group = Ipv4Addr::new(239, 192, 1, 30);
2321        configure_multicast(&mut camera, 0, group, 50030).expect("configure");
2322
2323        let read = |addr| camera.transport().read(addr, 4).unwrap();
2324        assert_eq!(read(0x0D18), group.octets());
2325        assert_eq!(
2326            read(0x0D00),
2327            0xABCD_C36Eu32.to_be_bytes(),
2328            "the port, written through GevSCPHostPort, keeps the other half"
2329        );
2330        assert_eq!(
2331            read(0x0D04),
2332            1500u32.to_be_bytes(),
2333            "the don't-fragment bit is untouched"
2334        );
2335    }
2336
2337    /// An Allied Vision Manta G-125B declares `ChunkModeActive` — the
2338    /// stream channel's chunk bit, `0x0D24` bit 31 — and no `ChunkSelector`
2339    /// or `ChunkEnable`. Chunk mode alone is turned on and off; a selector
2340    /// asked for is what needs those features.
2341    #[test]
2342    fn chunk_mode_alone_needs_no_chunk_selector() {
2343        const XML: &str = r#"
2344            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2345                <Boolean Name="ChunkModeActive" NameSpace="Standard">
2346                    <Streamable>Yes</Streamable>
2347                    <pValue>RegSCCFGChunk</pValue>
2348                    <OnValue>1</OnValue>
2349                    <OffValue>0</OffValue>
2350                </Boolean>
2351                <MaskedIntReg Name="RegSCCFGChunk" NameSpace="Custom">
2352                    <Address>0xD24</Address>
2353                    <Length>4</Length>
2354                    <AccessMode>RW</AccessMode>
2355                    <pPort>Device</pPort>
2356                    <Bit>31</Bit>
2357                    <Endianess>BigEndian</Endianess>
2358                </MaskedIntReg>
2359                <Port Name="Device" NameSpace="Standard"/>
2360            </RegisterDescription>
2361        "#;
2362        let model = viva_genapi_xml::parse(XML).expect("parse");
2363        let nodemap = NodeMap::try_from_xml(model).expect("build nodemap");
2364        let mut camera = Camera::new(MemoryIo::default(), nodemap);
2365        let mode = |active| ChunkConfig {
2366            selectors: Vec::new(),
2367            active,
2368        };
2369
2370        camera.configure_chunks(&mode(true)).expect("chunk mode on");
2371        assert_eq!(camera.transport().read(0xD24, 4).unwrap(), [0, 0, 0, 1]);
2372        camera
2373            .configure_chunks(&mode(false))
2374            .expect("chunk mode off");
2375        assert_eq!(camera.transport().read(0xD24, 4).unwrap(), [0, 0, 0, 0]);
2376
2377        let timestamp = ChunkConfig {
2378            selectors: vec!["Timestamp".into()],
2379            active: true,
2380        };
2381        assert!(matches!(
2382            camera.configure_chunks(&timestamp),
2383            Err(GenicamError::MissingChunkFeature(name)) if name == "ChunkSelector"
2384        ));
2385    }
2386
2387    /// `Camera::set` on a feature that is itself a `<Converter>` writes through
2388    /// its `<FormulaTo>`, as `NodeMap::set_float` already does.
2389    #[test]
2390    fn set_writes_a_converter_through_its_formula() {
2391        const XML: &str = r#"
2392            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2393                <IntReg Name="FrameRateRaw">
2394                    <Address>0x1000</Address>
2395                    <Length>4</Length>
2396                    <AccessMode>RW</AccessMode>
2397                    <Endianess>BigEndian</Endianess>
2398                </IntReg>
2399                <Converter Name="AcquisitionFrameRateAbs">
2400                    <FormulaTo>FROM * 100</FormulaTo>
2401                    <FormulaFrom>TO / 100</FormulaFrom>
2402                    <pValue>FrameRateRaw</pValue>
2403                </Converter>
2404            </RegisterDescription>
2405        "#;
2406        let model = viva_genapi_xml::parse(XML).expect("parse");
2407        let nodemap = NodeMap::try_from_xml(model).expect("build nodemap");
2408        let mut camera = Camera::new(MemoryIo::default(), nodemap);
2409
2410        camera
2411            .set("AcquisitionFrameRateAbs", "12.5")
2412            .expect("write the converter");
2413
2414        assert_eq!(camera.get("FrameRateRaw").expect("read raw"), "1250");
2415        assert_eq!(
2416            camera.get("AcquisitionFrameRateAbs").expect("read back"),
2417            "12.5"
2418        );
2419    }
2420
2421    /// A command register the device clears once it has finished: the first
2422    /// `busy_reads` reads after a write still return the command value.
2423    struct SelfClearingIo {
2424        addr: u64,
2425        busy_reads: usize,
2426        state: Mutex<(Vec<u8>, usize, usize)>,
2427    }
2428
2429    impl SelfClearingIo {
2430        fn new(addr: u64, busy_reads: usize) -> Self {
2431            Self {
2432                addr,
2433                busy_reads,
2434                state: Mutex::new((vec![0; 4], 0, 0)),
2435            }
2436        }
2437
2438        /// `(writes, reads)` seen at the command register.
2439        fn counts(&self) -> (usize, usize) {
2440            let state = self.state.lock().unwrap();
2441            (state.1, state.2)
2442        }
2443    }
2444
2445    impl RegisterIo for SelfClearingIo {
2446        fn read(&self, addr: u64, len: usize) -> Result<Vec<u8>, GenApiError> {
2447            assert_eq!(addr, self.addr, "only the command register is read");
2448            let mut state = self.state.lock().unwrap();
2449            state.2 += 1;
2450            if state.2 > self.busy_reads {
2451                state.0 = vec![0; len];
2452            }
2453            Ok(state.0.clone())
2454        }
2455
2456        fn write(&self, addr: u64, data: &[u8]) -> Result<(), GenApiError> {
2457            assert_eq!(addr, self.addr);
2458            let mut state = self.state.lock().unwrap();
2459            state.0 = data.to_vec();
2460            state.1 += 1;
2461            Ok(())
2462        }
2463    }
2464
2465    const COMMAND_XML: &str = r#"
2466        <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">
2467            <Command Name="UserSetLoad">
2468                <pValue>UserSetLoadReg</pValue>
2469                <CommandValue>1</CommandValue>
2470            </Command>
2471            <IntReg Name="UserSetLoadReg">
2472                <Address>0x4000</Address><Length>4</Length><AccessMode>RW</AccessMode>
2473                <Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2474            </IntReg>
2475            <Command Name="TriggerSoftware">
2476                <pValue>TriggerSoftwareReg</pValue>
2477                <CommandValue>1</CommandValue>
2478            </Command>
2479            <IntReg Name="TriggerSoftwareReg">
2480                <Address>0x4000</Address><Length>4</Length><AccessMode>WO</AccessMode>
2481                <Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2482            </IntReg>
2483        </RegisterDescription>
2484    "#;
2485
2486    fn command_camera(io: SelfClearingIo) -> Camera<SelfClearingIo> {
2487        let model = viva_genapi_xml::parse(COMMAND_XML).expect("parse");
2488        Camera::new(io, NodeMap::try_from_xml(model).expect("build nodemap"))
2489    }
2490
2491    /// GA-36: executing waits until the register no longer reads back the
2492    /// command value (GenICam Standard v2.1.1 §2.8.8, `IsDone`).
2493    #[tokio::test]
2494    async fn execute_and_wait_polls_until_the_command_clears() {
2495        let mut camera = command_camera(SelfClearingIo::new(0x4000, 3));
2496        camera
2497            .execute_and_wait("UserSetLoad", Duration::from_secs(5))
2498            .await
2499            .expect("finishes after three busy reads");
2500        assert_eq!(camera.transport().counts(), (1, 4));
2501    }
2502
2503    /// GA-36: a command that never finishes is reported, not waited on
2504    /// forever and not reported as done.
2505    #[tokio::test]
2506    async fn execute_and_wait_gives_up_at_the_timeout() {
2507        let mut camera = command_camera(SelfClearingIo::new(0x4000, usize::MAX));
2508        let err = camera
2509            .execute_and_wait("UserSetLoad", Duration::from_millis(50))
2510            .await
2511            .expect_err("never clears");
2512        assert!(
2513            matches!(err, GenicamError::CommandNotDone { ref name, .. } if name == "UserSetLoad"),
2514            "{err:?}"
2515        );
2516        assert_eq!(camera.transport().counts().0, 1, "written once");
2517    }
2518
2519    /// GA-36: a write-only command is done once written; its register is
2520    /// never read, which a device would refuse.
2521    #[tokio::test]
2522    async fn execute_and_wait_does_not_read_a_write_only_command() {
2523        let mut camera = command_camera(SelfClearingIo::new(0x4000, usize::MAX));
2524        camera
2525            .execute_and_wait("TriggerSoftware", Duration::from_secs(5))
2526            .await
2527            .expect("done at once");
2528        assert_eq!(camera.transport().counts(), (1, 0));
2529    }
2530
2531    /// GA-05: a command that declares a `<PollingTime>` is asked whether it
2532    /// has finished at that interval, not every `COMMAND_POLL_INTERVAL`
2533    /// (GenICam Standard v2.1.1 §2.8.8). Over 500 ms at 200 ms that is at
2534    /// most four reads; at 10 ms it would be fifty.
2535    #[tokio::test]
2536    async fn execute_and_wait_polls_at_the_commands_polling_time() {
2537        const XML: &str = r#"
2538            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">
2539                <Command Name="UserSetLoad">
2540                    <pValue>UserSetLoadReg</pValue>
2541                    <CommandValue>1</CommandValue>
2542                    <PollingTime>200</PollingTime>
2543                </Command>
2544                <IntReg Name="UserSetLoadReg">
2545                    <Address>0x4000</Address><Length>4</Length><AccessMode>RW</AccessMode>
2546                    <Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2547                </IntReg>
2548            </RegisterDescription>
2549        "#;
2550        let model = viva_genapi_xml::parse(XML).expect("parse");
2551        let nodemap = NodeMap::try_from_xml(model).expect("build nodemap");
2552        let mut camera = Camera::new(SelfClearingIo::new(0x4000, usize::MAX), nodemap);
2553        let err = camera
2554            .execute_and_wait("UserSetLoad", Duration::from_millis(500))
2555            .await
2556            .expect_err("never clears");
2557        assert!(
2558            matches!(err, GenicamError::CommandNotDone { .. }),
2559            "{err:?}"
2560        );
2561        let (_, reads) = camera.transport().counts();
2562        assert!(
2563            reads <= 5,
2564            "{reads} reads in 500 ms at a 200 ms polling time"
2565        );
2566        assert!(reads >= 3, "{reads} reads: it did poll");
2567    }
2568
2569    #[test]
2570    fn keepalive_period_fits_four_pings_in_the_reported_window() {
2571        assert_eq!(keepalive_period(Some(3_000)), Duration::from_millis(750));
2572        assert_eq!(keepalive_period(Some(1_000)), Duration::from_millis(250));
2573    }
2574
2575    #[test]
2576    fn an_unusable_heartbeat_timeout_falls_back_to_a_short_window() {
2577        // A device that declines to report, and a register we could not read,
2578        // must not be believed as "0 ms" or "no timeout at all".
2579        let assumed = keepalive_period(Some(ASSUMED_HEARTBEAT_TIMEOUT_MS));
2580        assert_eq!(keepalive_period(None), assumed);
2581        assert_eq!(keepalive_period(Some(0)), assumed);
2582    }
2583
2584    #[test]
2585    fn the_period_is_clamped_at_both_ends() {
2586        // 40 ms / 4 = 10 ms would be a flood; a 10-minute window would make the
2587        // keepalive useless as a liveness check.
2588        assert_eq!(keepalive_period(Some(40)), MIN_KEEPALIVE_PERIOD);
2589        assert_eq!(keepalive_period(Some(600_000)), MAX_KEEPALIVE_PERIOD);
2590    }
2591
2592    /// Every kind of feature the typed accessors reach, over registers in
2593    /// memory.
2594    const TYPED_XML: &str = r#"
2595        <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">
2596            <Category Name="Root"><pFeature>Width</pFeature></Category>
2597            <Integer Name="Width">
2598                <Address>0x10</Address><Length>4</Length><AccessMode>RW</AccessMode>
2599                <Min>1</Min><Max>4096</Max><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2600            </Integer>
2601            <Float Name="Gain"><pValue>GainReg</pValue><Min>0</Min><Max>48</Max></Float>
2602            <FloatReg Name="GainReg">
2603                <Address>0x20</Address><Length>8</Length><AccessMode>RW</AccessMode><Endianess>BigEndian</Endianess>
2604            </FloatReg>
2605            <Boolean Name="ReverseX"><pValue>ReverseXReg</pValue></Boolean>
2606            <IntReg Name="ReverseXReg">
2607                <Address>0x30</Address><Length>4</Length><AccessMode>RW</AccessMode><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2608            </IntReg>
2609            <Enumeration Name="Mode">
2610                <EnumEntry Name="Off"><Value>0</Value></EnumEntry>
2611                <EnumEntry Name="On"><Value>1</Value></EnumEntry>
2612                <pValue>ModeReg</pValue>
2613            </Enumeration>
2614            <IntReg Name="ModeReg">
2615                <Address>0x40</Address><Length>4</Length><AccessMode>RW</AccessMode><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2616            </IntReg>
2617            <StringReg Name="DeviceUserID">
2618                <Address>0x100</Address><Length>16</Length><AccessMode>RW</AccessMode>
2619            </StringReg>
2620            <Converter Name="FrameRate">
2621                <FormulaTo>FROM * 10</FormulaTo>
2622                <FormulaFrom>TO / 10</FormulaFrom>
2623                <pValue>FrameRateRaw</pValue>
2624                <Slope>Increasing</Slope>
2625            </Converter>
2626            <IntReg Name="FrameRateRaw">
2627                <Address>0x50</Address><Length>4</Length><AccessMode>RW</AccessMode><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2628            </IntReg>
2629            <Command Name="AcquisitionStart">
2630                <pValue>AcquisitionStartReg</pValue>
2631                <CommandValue>1</CommandValue>
2632            </Command>
2633            <IntReg Name="AcquisitionStartReg">
2634                <Address>0x60</Address><Length>4</Length><AccessMode>WO</AccessMode><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2635            </IntReg>
2636        </RegisterDescription>
2637    "#;
2638
2639    fn memory_camera(xml: &str) -> Camera<MemoryIo> {
2640        let model = viva_genapi_xml::parse(xml).expect("parse");
2641        Camera::new(
2642            MemoryIo::default(),
2643            NodeMap::try_from_xml(model).expect("build nodemap"),
2644        )
2645    }
2646
2647    /// API-05: each kind is read and written as its own type, as `NodeMap`
2648    /// does — a converter read as an integer is rounded, not refused because
2649    /// its text has a decimal point, and an integer is not a float.
2650    #[test]
2651    fn typed_accessors_reach_each_kind_as_its_own_type() {
2652        let mut camera = memory_camera(TYPED_XML);
2653        camera.set_integer("Width", 1024).expect("set Width");
2654        assert_eq!(camera.get_integer("Width").expect("Width"), 1024);
2655        camera.set_float("Gain", 1.0 / 3.0).expect("set Gain");
2656        assert_eq!(camera.get_float("Gain").expect("Gain"), 1.0 / 3.0);
2657        camera.set_bool("ReverseX", true).expect("set ReverseX");
2658        assert!(camera.get_bool("ReverseX").expect("ReverseX"));
2659        camera.set_enum("Mode", "On").expect("set Mode");
2660        assert_eq!(camera.get_enum("Mode").expect("Mode"), "On");
2661        camera
2662            .set_string("DeviceUserID", "left")
2663            .expect("set DeviceUserID");
2664        assert_eq!(camera.get_string("DeviceUserID").expect("id"), "left");
2665
2666        camera
2667            .transport()
2668            .write(0x50, &123u32.to_be_bytes())
2669            .expect("raw frame rate");
2670        assert_eq!(camera.get_float("FrameRate").expect("float"), 12.3);
2671        assert_eq!(camera.get_integer("FrameRate").expect("integer"), 12);
2672        assert!(
2673            matches!(
2674                camera.get_float("Width"),
2675                Err(GenicamError::GenApi(GenApiError::Type { .. }))
2676            ),
2677            "an Integer is not read as a float"
2678        );
2679    }
2680
2681    /// API-08: a category has no value to read, and a command is executed,
2682    /// not set — the value a `set` would have carried was ignored.
2683    #[test]
2684    fn get_on_a_category_and_set_on_a_command_are_errors() {
2685        let mut camera = memory_camera(TYPED_XML);
2686        assert!(camera.get("Root").is_err(), "a category has no value");
2687        let err = camera
2688            .set("AcquisitionStart", "1")
2689            .expect_err("a command is executed, not set");
2690        assert!(err.to_string().contains("execute_command"), "{err}");
2691        assert!(
2692            !camera.transport().0.lock().unwrap().contains_key(&0x60),
2693            "nothing was written"
2694        );
2695    }
2696
2697    /// The names a camera without an SFNC 2 exposure or gain has instead:
2698    /// raw integers, and a category named `Gain` that is not the feature.
2699    const RAW_XML: &str = r#"
2700        <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">
2701            <Category Name="Gain"><pFeature>GainRaw</pFeature></Category>
2702            <Integer Name="ExposureTimeRaw">
2703                <Address>0x10</Address><Length>4</Length><AccessMode>RW</AccessMode>
2704                <Min>1</Min><Max>100000</Max><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2705            </Integer>
2706            <Integer Name="GainRaw">
2707                <Address>0x20</Address><Length>4</Length><AccessMode>RW</AccessMode>
2708                <Min>0</Min><Max>1023</Max><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2709            </Integer>
2710        </RegisterDescription>
2711    "#;
2712
2713    /// API-14: exposure and gain fall back to the raw integer features, a
2714    /// value rounded to the integer it must be, and say which they wrote;
2715    /// a category that shares the name `Gain` is passed over.
2716    #[test]
2717    fn exposure_and_gain_fall_back_to_raw_integers() {
2718        let mut camera = memory_camera(RAW_XML);
2719        let exposure = camera.set_exposure_time(250.4).expect("exposure");
2720        assert_eq!(
2721            (exposure.name, exposure.kind),
2722            ("ExposureTimeRaw", "Integer")
2723        );
2724        assert_eq!(
2725            camera.transport().read(0x10, 4).unwrap(),
2726            250u32.to_be_bytes()
2727        );
2728        assert_eq!(camera.exposure_time().expect("read back"), 250.0);
2729
2730        let gain = camera.set_gain(3.0).expect("gain");
2731        assert_eq!((gain.name, gain.kind), ("GainRaw", "Integer"));
2732        assert_eq!(
2733            camera.transport().read(0x20, 4).unwrap(),
2734            3u32.to_be_bytes()
2735        );
2736    }
2737
2738    /// API-14: a feature the camera has under none of its names is an error
2739    /// that lists every name tried.
2740    #[test]
2741    fn a_feature_the_camera_lacks_names_every_candidate() {
2742        let mut camera = memory_camera(TYPED_XML);
2743        let err = camera.set_exposure_time(1.0).expect_err("no exposure");
2744        assert!(
2745            err.to_string()
2746                .contains("ExposureTime, ExposureTimeAbs, ExposureTimeRaw"),
2747            "{err}"
2748        );
2749    }
2750
2751    /// Binning as the Hikrobot MV-CS050-10GC declares it: an enumeration
2752    /// whose entry names end in the factor (vertically an integer here).
2753    const BINNING_XML: &str = r#"
2754        <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">
2755            <Enumeration Name="BinningHorizontal">
2756                <EnumEntry Name="BinningHorizontal1"><Value>1</Value></EnumEntry>
2757                <EnumEntry Name="BinningHorizontal2"><Value>2</Value></EnumEntry>
2758                <EnumEntry Name="BinningHorizontal4"><Value>4</Value></EnumEntry>
2759                <pValue>BinningHorizontalReg</pValue>
2760            </Enumeration>
2761            <IntReg Name="BinningHorizontalReg">
2762                <Address>0x10</Address><Length>4</Length><AccessMode>RW</AccessMode><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2763            </IntReg>
2764            <Integer Name="BinningVertical">
2765                <Address>0x20</Address><Length>4</Length><AccessMode>RW</AccessMode>
2766                <Min>1</Min><Max>4</Max><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
2767            </Integer>
2768        </RegisterDescription>
2769    "#;
2770
2771    /// API-14: an enumerated binning is written by the entry whose name ends
2772    /// in the factor.
2773    #[test]
2774    fn binning_by_enumeration_writes_the_entry_naming_the_factor() {
2775        let mut camera = memory_camera(BINNING_XML);
2776        camera.set_binning(2, 2).expect("binning");
2777        assert_eq!(
2778            camera.transport().read(0x10, 4).unwrap(),
2779            2u32.to_be_bytes()
2780        );
2781        assert_eq!(
2782            camera.transport().read(0x20, 4).unwrap(),
2783            2u32.to_be_bytes()
2784        );
2785        assert_eq!(camera.binning().expect("read back"), (2, 2));
2786    }
2787
2788    /// API-14: SVS's evo4050 declares `BinningHorizontal` as `Off`/`On`,
2789    /// which names no factor: refused, with the entries listed, and nothing
2790    /// written.
2791    #[test]
2792    fn binning_by_enumeration_without_factors_is_refused() {
2793        let xml = BINNING_XML
2794            .replace(
2795                r#"<EnumEntry Name="BinningHorizontal1"><Value>1</Value></EnumEntry>"#,
2796                r#"<EnumEntry Name="Off"><Value>0</Value></EnumEntry>"#,
2797            )
2798            .replace(
2799                r#"<EnumEntry Name="BinningHorizontal2"><Value>2</Value></EnumEntry>"#,
2800                r#"<EnumEntry Name="On"><Value>1</Value></EnumEntry>"#,
2801            )
2802            .replace(
2803                r#"<EnumEntry Name="BinningHorizontal4"><Value>4</Value></EnumEntry>"#,
2804                "",
2805            );
2806        let mut camera = memory_camera(&xml);
2807        let err = camera
2808            .set_binning(2, 2)
2809            .expect_err("Off/On names no factor");
2810        assert!(err.to_string().contains("Off, On"), "{err}");
2811        assert!(
2812            camera.transport().0.lock().unwrap().is_empty(),
2813            "nothing was written"
2814        );
2815    }
2816}