Skip to main content

viva_genicam/
reopen.rs

1//! Opening a GigE Vision camera again after it went away (backlog API-21).
2//!
3//! A camera that loses its link, or its power, comes back as a new session:
4//! the old one's control privilege may have expired with its heartbeat, its
5//! stream channel may have closed, and volatile settings may have reset.
6//! [`reopen_gige`] finds it again by its MAC address, waits for it to answer
7//! and to be free, connects afresh, and puts a saved configuration back.
8
9use std::time::{Duration, Instant};
10
11use tracing::{debug, info, warn};
12
13use crate::genapi::{Configuration, LoadReport};
14use crate::gige::{self, DeviceInfo, DiscoveryOptions};
15use crate::{Access, Camera, GenicamError, GigeRegisterIo, connect_gige_as};
16
17/// How [`reopen_gige`] looks for a camera that went away, and what it puts
18/// back.
19#[derive(Debug, Clone)]
20#[non_exhaustive]
21pub struct Reopen {
22    /// How the camera is opened again; [`Access::Control`] by default.
23    pub access: Access,
24    /// How long to keep trying before giving up; 30 s by default, enough for
25    /// a camera's heartbeat to expire and for one to boot.
26    pub patience: Duration,
27    /// How long each discovery waits for an answer; 500 ms by default.
28    pub discovery_timeout: Duration,
29    /// The host interface to look on when the camera no longer answers at
30    /// its old address, by OS name; every interface when `None`.
31    pub interface: Option<String>,
32    /// A configuration to restore once the camera is open, such as one
33    /// [`Camera::save_features`] saved before it went away.
34    pub configuration: Option<Configuration>,
35}
36
37impl Default for Reopen {
38    fn default() -> Self {
39        Self {
40            access: Access::Control,
41            patience: Duration::from_secs(30),
42            discovery_timeout: Duration::from_millis(500),
43            interface: None,
44            configuration: None,
45        }
46    }
47}
48
49impl Reopen {
50    /// Reopen with control, for 30 s, restoring nothing.
51    pub fn new() -> Self {
52        Self::default()
53    }
54
55    /// Open the camera again with `access`.
56    pub fn access(mut self, access: Access) -> Self {
57        self.access = access;
58        self
59    }
60
61    /// Keep trying for `patience`.
62    pub fn patience(mut self, patience: Duration) -> Self {
63        self.patience = patience;
64        self
65    }
66
67    /// Wait `timeout` for each discovery answer.
68    pub fn discovery_timeout(mut self, timeout: Duration) -> Self {
69        self.discovery_timeout = timeout;
70        self
71    }
72
73    /// Look on the host interface named `name` (`en0`, `eth0`).
74    pub fn interface(mut self, name: impl Into<String>) -> Self {
75        self.interface = Some(name.into());
76        self
77    }
78
79    /// Restore `configuration` once the camera is open.
80    pub fn configuration(mut self, configuration: Configuration) -> Self {
81        self.configuration = Some(configuration);
82        self
83    }
84}
85
86/// A camera [`reopen_gige`] opened again.
87#[non_exhaustive]
88pub struct Reopened {
89    /// The camera, in a new session.
90    pub camera: Camera<GigeRegisterIo>,
91    /// The GenApi XML it serves now, fetched again: a firmware update while
92    /// it was away may have changed it.
93    pub xml: String,
94    /// Its Discovery ACK now: the address may differ from the one it had.
95    pub device: DeviceInfo,
96    /// What restoring [`Reopen::configuration`] did, when one was given.
97    pub restored: Option<LoadReport>,
98    /// How many connection attempts it took, the successful one included.
99    pub attempts: u32,
100}
101
102/// Open again a GigE Vision camera that went away: unplugged, power-cycled,
103/// or with its heartbeat expired.
104///
105/// `previous` is the camera's Discovery ACK from before. The camera is
106/// looked for by its MAC address — at its old address first, then by
107/// broadcast on [`Reopen::interface`] (or every interface) in case it came
108/// back with another — and then opened afresh with [`connect_gige_as`],
109/// which fetches its XML again. Every failure is retried, with a growing
110/// pause, until [`Reopen::patience`] runs out: a camera that is still
111/// booting does not answer, and one whose old session's heartbeat has not
112/// yet expired refuses the claim. Once open, [`Reopen::configuration`] is
113/// restored, if given; a value that could not be written is in
114/// [`Reopened::restored`], not an error.
115///
116/// A record without a MAC address ([`DeviceInfo::from_ip`]) matches whatever
117/// camera answers at its address.
118///
119/// The old [`Camera`] should be dropped first, or the claim waits for its
120/// session, still being kept alive, to give control up.
121///
122/// The patience bounds discovery, connection attempts and their retry pauses.
123/// Configuration restoration follows a successful open and uses the camera's
124/// ordinary register timeouts; its failures are reported, never retried as a
125/// new connection. Cancelling an open sends a best-effort release for any control
126/// it already claimed; a lost release datagram leaves the camera to expire it.
127///
128/// Returns the last error when no further attempt fits, or [`GenicamError::Timeout`]
129/// if an in-flight attempt consumes the remaining patience.
130pub async fn reopen_gige(
131    previous: &DeviceInfo,
132    options: &Reopen,
133) -> Result<Reopened, GenicamError> {
134    let started = Instant::now();
135    let mut attempts = 0u32;
136    let mut pause = Duration::from_millis(250);
137    loop {
138        let Some(remaining) = options.patience.checked_sub(started.elapsed()) else {
139            return Err(GenicamError::Timeout(options.patience));
140        };
141        if remaining.is_zero() {
142            return Err(GenicamError::Timeout(options.patience));
143        }
144        attempts = attempts.saturating_add(1);
145        let attempt = async {
146            let device = find(previous, options)
147                .await?
148                .ok_or(GenicamError::Timeout(options.discovery_timeout))?;
149            let (camera, xml) = connect_gige_as(&device, options.access).await?;
150            Ok::<_, GenicamError>((device, camera, xml))
151        };
152        let error = match tokio::time::timeout(remaining, attempt).await {
153            Ok(Ok((device, mut camera, xml))) => {
154                let restored = options
155                    .configuration
156                    .as_ref()
157                    .map(|configuration| camera.load_configuration(configuration));
158                info!(
159                    ip = %device.ip,
160                    attempts,
161                    waited = ?started.elapsed(),
162                    "camera reopened"
163                );
164                return Ok(Reopened {
165                    camera,
166                    xml,
167                    device,
168                    restored,
169                    attempts,
170                });
171            }
172            Ok(Err(error)) => error,
173            Err(_) => return Err(GenicamError::Timeout(options.patience)),
174        };
175        let waited = started.elapsed();
176        if waited + pause >= options.patience {
177            warn!(attempts, ?waited, %error, "the camera did not come back");
178            return Err(error);
179        }
180        debug!(attempts, %error, ?pause, "camera not back yet; trying again");
181        tokio::time::sleep(pause).await;
182        pause = (pause * 2).min(Duration::from_secs(2));
183    }
184}
185
186/// The camera `previous` describes, as it answers now, or `None`.
187async fn find(previous: &DeviceInfo, options: &Reopen) -> Result<Option<DeviceInfo>, GenicamError> {
188    let unknown_mac = previous.mac == [0; 6];
189    let same = |found: &DeviceInfo| unknown_mac || found.mac == previous.mac;
190    let discovery = |source| GenicamError::Gige {
191        during: "look for the camera again",
192        source,
193    };
194    match gige::discover_ip(previous.ip, options.discovery_timeout).await {
195        Ok(Some(found)) if same(&found) => return Ok(Some(found)),
196        Err(error) if unknown_mac => return Err(discovery(error)),
197        Err(error) => debug!(%error, "old address unreachable; looking for the camera by MAC"),
198        Ok(_) => {}
199    }
200    if unknown_mac {
201        return Ok(None);
202    }
203    let mut broadcast = DiscoveryOptions::new().allow_broadcast_ack(true);
204    if let Some(name) = &options.interface {
205        broadcast = broadcast.interface(name);
206    }
207    let found = gige::discover_with(options.discovery_timeout, &broadcast)
208        .await
209        .map_err(discovery)?;
210    Ok(found.into_iter().find(|found| found.mac == previous.mac))
211}