Skip to main content

viva_genicam/
error.rs

1//! The facade's error type.
2
3use std::net::{Ipv4Addr, SocketAddrV4};
4use std::time::Duration;
5
6use thiserror::Error;
7
8use crate::ControlState;
9use crate::genapi::GenApiError;
10use crate::genapi::persistence::ParseConfigurationError;
11use crate::gige::GigeError;
12use viva_genapi_xml::XmlError;
13use viva_pfnc::convert::ConvertError;
14
15/// Error type produced by the high level GenICam facade.
16///
17/// Every variant either carries what caused it as its
18/// [`source`](std::error::Error::source) — a GVCP status, a USB failure, a
19/// socket's error — or names what it refused with typed fields; nothing is
20/// flattened into text (ADR-0030). The `during` of a transport variant says
21/// what the facade was doing, such as `"claim control"`.
22#[derive(Debug, Error)]
23#[non_exhaustive]
24pub enum GenicamError {
25    /// A feature's read, write or evaluation failed in the node map.
26    #[error(transparent)]
27    GenApi(#[from] GenApiError),
28    /// The camera's GenApi XML could not be fetched or parsed.
29    #[error("GenApi XML: {0}")]
30    Xml(#[from] XmlError),
31    /// A GigE Vision control transaction failed.
32    #[error("{during}: {source}")]
33    Gige {
34        /// What the facade was doing.
35        during: &'static str,
36        /// The GVCP error: a status, a timeout, a socket's failure.
37        #[source]
38        source: GigeError,
39    },
40    /// A USB3 Vision transaction failed.
41    #[cfg(feature = "u3v")]
42    #[cfg_attr(docsrs, doc(cfg(feature = "u3v")))]
43    #[error("{during}: {source}")]
44    U3v {
45        /// What the facade was doing.
46        during: &'static str,
47        /// The USB3 Vision error.
48        #[source]
49        source: crate::u3v::U3vError,
50    },
51    /// A socket operation failed: binding a stream or event socket, joining
52    /// a multicast group, receiving.
53    #[error("{during}: {source}")]
54    Network {
55        /// What the facade was doing.
56        during: &'static str,
57        /// The socket's error.
58        #[source]
59        source: std::io::Error,
60    },
61    /// Reading or writing a file or stream failed.
62    #[error("i/o: {0}")]
63    Io(#[from] std::io::Error),
64    /// A configuration file does not parse (see
65    /// [`Camera::load_features`](crate::Camera::load_features)).
66    #[error("configuration file: {0}")]
67    Configuration(#[from] ParseConfigurationError),
68    /// A frame's pixels could not be converted.
69    #[error("cannot convert the frame: {0}")]
70    Convert(#[source] ConvertError),
71    /// Required chunk feature missing from the nodemap.
72    #[error("chunk feature '{0}' not found; verify camera supports chunk data")]
73    MissingChunkFeature(String),
74    /// The camera reported a pixel format without a conversion path.
75    #[error("unsupported pixel format: {0}")]
76    UnsupportedPixelFormat(viva_pfnc::PixelFormat),
77    /// A command was written but the camera did not report it finished
78    /// (GenICam `IsDone`) within the time allowed.
79    ///
80    /// The write itself was acknowledged: the camera may still be acting on
81    /// it, or its command register may never clear.
82    #[error("command {name} was executed but did not report completion within {waited:?}")]
83    CommandNotDone {
84        /// The command node.
85        name: String,
86        /// How long [`Camera::execute_and_wait`](crate::Camera::execute_and_wait)
87        /// polled.
88        waited: Duration,
89    },
90    /// Nothing arrived within the time a blocking call was given.
91    #[error("timed out after {0:?}")]
92    Timeout(Duration),
93    /// The camera declares none of the names a standard feature goes by.
94    #[error("the camera has no {what}: it declares none of {}", tried.join(", "))]
95    MissingFeature {
96        /// What was looked for, such as `"exposure time"`.
97        what: &'static str,
98        /// Every name tried, in the order tried.
99        tried: &'static [&'static str],
100    },
101    /// Events were asked for on a camera whose XML has no
102    /// `EventSelector`/`EventNotification`; event selection has no bootstrap
103    /// register to fall back on.
104    #[error(
105        "cannot enable events {events:?}: the camera declares neither EventSelector nor \
106         EventNotification, and event selection has no bootstrap register"
107    )]
108    NoEventSelection {
109        /// The events asked for.
110        events: Vec<String>,
111    },
112    /// The session does not hold control of the camera, so it neither
113    /// writes nor configures a stream: it was opened as a monitor, or
114    /// control was released or lost.
115    #[error("{}", not_in_control(*.0))]
116    NotInControl(ControlState),
117    /// A GVSP packet size below the smallest a stream accepts.
118    #[error(
119        "GVSP packet size {size} is below the {min}-byte minimum; raise the camera's \
120         GevSCPSPacketSize, or pass auto_packet_size() or packet_size(n)"
121    )]
122    PacketTooSmall {
123        /// The packet size, as asked for or as the camera set it.
124        size: u32,
125        /// The smallest accepted.
126        min: u32,
127    },
128    /// A GVSP packet size above the largest an IPv4 datagram carries.
129    #[error("GVSP packet size {size} exceeds the {max}-byte maximum an IPv4 datagram carries")]
130    PacketTooLarge {
131        /// The packet size asked for.
132        size: u32,
133        /// The largest accepted.
134        max: u32,
135    },
136    /// A stream channel the camera does not have; `count` is its
137    /// `GevNumberOfStreamChannels`, when it says.
138    #[error("{}", stream_channel(*channel, *count))]
139    StreamChannel {
140        /// The channel asked for.
141        channel: u32,
142        /// The channels the camera has.
143        count: Option<u32>,
144    },
145    /// An inter-packet delay that cannot be expressed in `GevSCPD`'s unit.
146    #[error("cannot set a packet delay of {delay:?}: {problem}")]
147    PacketDelay {
148        /// The delay asked for.
149        delay: Duration,
150        /// Why, such as `"the camera reports a tick frequency of 0"`.
151        problem: &'static str,
152    },
153    /// A stream needs a host interface to receive on, and none was given.
154    #[error("a stream needs a network interface to receive on; none was given")]
155    NoInterface,
156    /// The interface given has no IPv4 address.
157    #[error("interface {0} has no IPv4 address")]
158    InterfaceWithoutIpv4(String),
159    /// No host interface routes to the camera; pass one explicitly.
160    #[error("no local interface routes to {camera}: {source}")]
161    NoRoute {
162        /// The camera's address.
163        camera: Ipv4Addr,
164        /// The route probe's error.
165        #[source]
166        source: std::io::Error,
167    },
168    /// An address that is not a multicast group where one is needed: the
169    /// group asked for, or where the camera streams to for a monitor.
170    #[error("{0} is not a multicast group (224.0.0.0/4)")]
171    NotMulticast(SocketAddrV4),
172    /// Time calibration could not fit the camera's clock.
173    #[error("time calibration: {0}")]
174    TimeSync(&'static str),
175    /// A binning enumeration entry names no factor (SVS's `On`).
176    #[error("{feature}: entry {entry} names no binning factor")]
177    NoBinningFactor {
178        /// The binning feature.
179        feature: &'static str,
180        /// The entry it holds.
181        entry: String,
182    },
183    /// No binning enumeration entry names the factor asked for.
184    #[error("{feature}: no entry names a binning factor of {factor}; its entries are {}", entries.join(", "))]
185    NoBinningEntry {
186        /// The binning feature.
187        feature: &'static str,
188        /// The factor asked for.
189        factor: i64,
190        /// The entries it has.
191        entries: Vec<String>,
192    },
193    /// A frame cannot be sized: the camera has no `PayloadSize`, and the
194    /// pixel format declares no size.
195    #[error(
196        "cannot size a {pixel_format} frame: the camera has no PayloadSize and the format \
197         declares no size; give the payload size explicitly"
198    )]
199    UnsizedFrame {
200        /// The pixel format, as the camera names it.
201        pixel_format: String,
202    },
203    /// A thread panicked: one holding the device's lock, which a panic
204    /// poisons, or one the call ran on.
205    #[error("{0} panicked")]
206    Panicked(&'static str),
207    /// A background task the call waited on panicked or was cancelled.
208    #[error("{during}: {source}")]
209    Task {
210        /// What the task was doing.
211        during: &'static str,
212        /// Its join error.
213        #[source]
214        source: tokio::task::JoinError,
215    },
216    /// A blocking call was made inside an async runtime, which it would
217    /// stall; use the async API there.
218    #[error(
219        "blocking::{0} was called inside an async runtime, which it would stall; use the async API there"
220    )]
221    InsideRuntime(&'static str),
222}
223
224/// The message for [`GenicamError::NotInControl`], with what to do about it.
225fn not_in_control(state: ControlState) -> &'static str {
226    match state {
227        ControlState::Monitor => {
228            "the camera was opened as a read-only monitor, so nothing is written; open it \
229             with Access::Control, or reclaim_control, to write"
230        }
231        ControlState::Released => {
232            "control of the camera was released, so nothing is written; reclaim_control \
233             takes it again"
234        }
235        _ => {
236            "control of the camera was lost, so nothing is written; reclaim_control takes it again"
237        }
238    }
239}
240
241fn stream_channel(channel: u32, count: Option<u32>) -> String {
242    match count {
243        Some(count) => format!(
244            "the camera has {count} stream channel(s) (GevNumberOfStreamChannels); stream \
245             channel {channel} does not exist"
246        ),
247        None => format!(
248            "the camera does not say how many stream channels it has; only stream channel 0 \
249             can be configured, not {channel}"
250        ),
251    }
252}
253
254impl From<GigeError> for GenicamError {
255    fn from(source: GigeError) -> Self {
256        GenicamError::Gige {
257            during: "GigE Vision control",
258            source,
259        }
260    }
261}
262
263#[cfg(feature = "u3v")]
264impl From<crate::u3v::U3vError> for GenicamError {
265    fn from(source: crate::u3v::U3vError) -> Self {
266        GenicamError::U3v {
267            during: "USB3 Vision control",
268            source,
269        }
270    }
271}
272
273impl From<ConvertError> for GenicamError {
274    fn from(err: ConvertError) -> Self {
275        match err {
276            ConvertError::Unsupported(format) => GenicamError::UnsupportedPixelFormat(format),
277            other => GenicamError::Convert(other),
278        }
279    }
280}
281
282/// `map_err` for a GVCP call: the error, with what was being done.
283pub(crate) fn gige(during: &'static str) -> impl FnOnce(GigeError) -> GenicamError {
284    move |source| GenicamError::Gige { during, source }
285}
286
287/// `map_err` for a USB3 Vision call: the error, with what was being done.
288#[cfg(feature = "u3v")]
289pub(crate) fn u3v(during: &'static str) -> impl FnOnce(crate::u3v::U3vError) -> GenicamError {
290    move |source| GenicamError::U3v { during, source }
291}
292
293/// `map_err` for a socket call: the error, with what was being done.
294pub(crate) fn network(during: &'static str) -> impl FnOnce(std::io::Error) -> GenicamError {
295    move |source| GenicamError::Network { during, source }
296}
297
298/// `map_err` for a task join: the error, with what the task was doing.
299pub(crate) fn task(during: &'static str) -> impl FnOnce(tokio::task::JoinError) -> GenicamError {
300    move |source| GenicamError::Task { during, source }
301}
302
303/// Why a [`GigeRegisterIo`](crate::GigeRegisterIo) refused a write before it
304/// reached the camera: the session does not hold control. The
305/// [`source`](std::error::Error::source) of the [`GenApiError::Io`] a
306/// refused feature write returns, so a caller can tell it from a camera's
307/// refusal by downcasting.
308#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
309#[error("{} (register {address:#010x})", not_in_control(*state))]
310#[non_exhaustive]
311pub struct WriteRefused {
312    /// Where the session stands.
313    pub state: ControlState,
314    /// The register the write was for.
315    pub address: u64,
316}
317
318impl WriteRefused {
319    pub(crate) fn new(state: ControlState, address: u64) -> Self {
320        Self { state, address }
321    }
322}