viva_genapi/error.rs
1//! Error types for GenApi operations.
2
3use std::fmt;
4
5use thiserror::Error;
6
7use crate::swissknife::{EvalError, ParseError, Value};
8
9/// The error a transport's failure is carried as: [`RegisterIo`] is
10/// implemented outside this crate, over GVCP, USB or a test's memory map, so
11/// its error type is not part of this crate's API.
12///
13/// [`RegisterIo`]: crate::RegisterIo
14type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
15
16/// Which way an access was refused.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub enum AccessDirection {
19 /// Reading the value.
20 Read,
21 /// Writing the value.
22 Write,
23}
24
25impl fmt::Display for AccessDirection {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 f.write_str(match self {
28 AccessDirection::Read => "read",
29 AccessDirection::Write => "written",
30 })
31 }
32}
33
34/// How a value falls outside what a node accepts.
35#[derive(Debug, Clone, Copy, PartialEq)]
36#[non_exhaustive]
37pub enum RangeViolation {
38 /// Below the minimum in force.
39 BelowMin(Value),
40 /// Above the maximum in force.
41 AboveMax(Value),
42 /// Not the minimum plus a whole number of increments.
43 OffIncrement {
44 /// The minimum the increments count from (zero without one).
45 base: i64,
46 /// The increment.
47 inc: i64,
48 },
49 /// The node's register cannot hold it: too wide for its bytes, beyond an
50 /// IEEE `f32`, not finite, or not a whole raw value at the node's scale.
51 Unrepresentable,
52}
53
54impl fmt::Display for RangeViolation {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 match self {
57 RangeViolation::BelowMin(min) => write!(f, "is below the minimum {min}"),
58 RangeViolation::AboveMax(max) => write!(f, "is above the maximum {max}"),
59 RangeViolation::OffIncrement { base, inc } => {
60 write!(f, "is not {base} plus a multiple of {inc}")
61 }
62 RangeViolation::Unrepresentable => f.write_str("cannot be held by its register"),
63 }
64 }
65}
66
67/// Error type produced by GenApi operations.
68///
69/// Every variant names the node it is about. A transport's failure is the
70/// [`source`](std::error::Error::source) of [`GenApiError::Io`], and a
71/// formula's of [`GenApiError::ExprParse`] and [`GenApiError::ExprEval`]:
72/// carried, never flattened into text (ADR-0030).
73#[derive(Debug, Error)]
74#[non_exhaustive]
75pub enum GenApiError {
76 /// The requested node does not exist in the nodemap.
77 #[error("node not found: {0}")]
78 NodeNotFound(String),
79 /// The node is of another kind than the operation needs.
80 #[error("{name} is a{} {kind}, not {expected}", article(kind))]
81 Type {
82 /// The node.
83 name: String,
84 /// Its kind, as [`crate::Node::kind_name`] names it.
85 kind: &'static str,
86 /// What the operation needs, such as `"an Integer"`.
87 expected: &'static str,
88 },
89 /// The node's access mode forbids the operation: a read of a `WO` node, a
90 /// write of an `RO` one.
91 #[error("{name} cannot be {refused}: its access mode forbids it")]
92 Access {
93 /// The node.
94 name: String,
95 /// The direction refused.
96 refused: AccessDirection,
97 },
98 /// The node declares `pIsLocked` and the device currently reports it
99 /// locked, so the write was refused locally.
100 ///
101 /// Names the locking feature, because that is the actionable part: a
102 /// caller told only "access denied" has nowhere to go, whereas
103 /// "`ExposureTime` is locked by `ExposureTime_Lck`" points at the feature
104 /// to change first. See ADR-0018 and backlog GA-06.
105 #[error("node {name} is locked by {locked_by}")]
106 Locked {
107 /// The node whose write was refused.
108 name: String,
109 /// The feature named by this node's `pIsLocked`.
110 locked_by: String,
111 },
112 /// Text given for a feature does not parse as the feature's type: see
113 /// [`crate::NodeMap::set_text`]. Nothing was written.
114 #[error("invalid value for {name}: expected {expected}, got {text:?}")]
115 InvalidText {
116 /// The feature.
117 name: String,
118 /// What the feature takes, such as `"an integer"`.
119 expected: &'static str,
120 /// The text as given.
121 text: String,
122 },
123 /// The value is outside what the node accepts. Nothing was written.
124 #[error("{name}: {value} {violation}")]
125 Range {
126 /// The node.
127 name: String,
128 /// The value refused.
129 value: Value,
130 /// How it falls outside.
131 violation: RangeViolation,
132 },
133 /// Bytes written to a `<Register>` are not its length. Nothing was
134 /// written.
135 #[error("register {name} is {len} bytes; got {got}")]
136 RegisterLength {
137 /// The register.
138 name: String,
139 /// Its length.
140 len: u32,
141 /// The bytes given.
142 got: usize,
143 },
144 /// The node is currently not available: its `pIsAvailable` reads false.
145 #[error("node unavailable: {0}")]
146 Unavailable(String),
147 /// The node has no value of its own to read or write: no register, no
148 /// `<pValue>` and no `<Value>`.
149 #[error("{name} declares no register, <pValue> or <Value>")]
150 NoValueSource {
151 /// The node.
152 name: String,
153 },
154 /// An indexed `<Integer>` or `<Float>` has no value for the index its
155 /// `<pIndex>` node reads now: no `<ValueIndexed>` or `<pValueIndexed>`
156 /// names it, and there is no `<ValueDefault>` or `<pValueDefault>`
157 /// (GenICam Standard v2.1.1 §2.8.5). Nothing was read or written.
158 #[error("{name} has no value for index {index}, which {index_node} reads, and no default")]
159 NoIndexedValue {
160 /// The indexed node.
161 name: String,
162 /// Its `<pIndex>` node.
163 index_node: String,
164 /// The index read.
165 index: i64,
166 },
167 /// Register I/O failed in the transport. The source is the transport's
168 /// error: a GVCP status, a USB failure, a timeout.
169 #[error("register I/O failed: {0}")]
170 Io(#[source] BoxError),
171 /// A register's bytes cannot be converted to or from the node's value: an
172 /// empty payload, a width its encoding has no form for (an IEEE float of
173 /// three bytes), an unsigned bit field beyond `i64`.
174 ///
175 /// The bytes are the device's, or the width the node declares; the XML
176 /// itself parsed (backlog GA-30).
177 #[error("{name}: cannot convert {width} register bytes: {problem}")]
178 RegisterEncoding {
179 /// The node.
180 name: String,
181 /// The register width in bytes, or the bit-field width in bits for a
182 /// bit field.
183 width: usize,
184 /// What does not convert, such as `"an IEEE float is 4 or 8 bytes"`.
185 problem: &'static str,
186 },
187 /// The node's declaration cannot be evaluated: the XML loaded, but
188 /// declares something a node of its kind cannot have, such as a
189 /// `<Boolean>` over a register with no bit field, or a zero scale.
190 #[error("{name} {problem}")]
191 Declaration {
192 /// The node.
193 name: String,
194 /// What is wrong, such as `"has a zero <Scale> numerator"`.
195 problem: &'static str,
196 },
197 /// A declaration this crate has no builder for.
198 ///
199 /// [`viva_genapi_xml::NodeDecl`] is `#[non_exhaustive]`, so a node type
200 /// added to the XML layer no longer breaks this crate's *build*. It
201 /// surfaces here instead, at nodemap construction, and lands in
202 /// [`crate::NodeMap::skipped`] where the corpus test will see it.
203 #[error("node {name} has declaration kind {kind}, which this nodemap cannot build")]
204 Unsupported {
205 /// The node.
206 name: String,
207 /// The declaration's kind, as [`viva_genapi_xml::NodeDecl::kind`]
208 /// names it.
209 kind: &'static str,
210 },
211 /// Parsing a formula failed.
212 #[error("failed to parse {name}'s formula {formula:?}: {source}")]
213 ExprParse {
214 /// The formula node.
215 name: String,
216 /// The formula, constant or expression as the document writes it.
217 formula: String,
218 /// The parser's error, with the offset into `formula`.
219 #[source]
220 source: ParseError,
221 },
222 /// Evaluating a formula failed.
223 #[error("failed to evaluate {name}: {source}")]
224 ExprEval {
225 /// The formula node, or the node whose value the failure was found
226 /// on.
227 name: String,
228 /// What failed.
229 #[source]
230 source: EvalError,
231 },
232 /// A formula referenced an unknown variable.
233 #[error("unknown variable '{var}' referenced by {name}")]
234 UnknownVariable {
235 /// The formula node.
236 name: String,
237 /// The variable.
238 var: String,
239 },
240 /// A formula qualified a `<pVariable>` with an extension the GenApi
241 /// standard does not define — anything but `.Value`, `.Min`, `.Max`,
242 /// `.Inc` or `.Entry.<Name>`.
243 #[error("{name}: variable '{var}' has unknown extension '.{extension}'")]
244 UnknownVariableExtension {
245 /// The formula node.
246 name: String,
247 /// The qualified identifier as written.
248 var: String,
249 /// The part after the variable name's first `.`.
250 extension: String,
251 },
252 /// Raw register value did not correspond to any enum entry.
253 #[error("enum {node} has no entry for raw value {value}")]
254 EnumValueUnknown {
255 /// The enumeration.
256 node: String,
257 /// The value read.
258 value: i64,
259 },
260 /// The enumeration entry exists but cannot be selected now: its
261 /// `pIsImplemented` or `pIsAvailable` reads false. Nothing was written.
262 #[error("enum {node}'s entry {entry} is not available now")]
263 EnumEntryUnavailable {
264 /// The enumeration.
265 node: String,
266 /// The entry asked for.
267 entry: String,
268 },
269 /// Attempted to select an enum entry that does not exist.
270 #[error("enum {node} has no entry named {entry}")]
271 EnumNoSuchEntry {
272 /// The enumeration.
273 node: String,
274 /// The entry asked for.
275 entry: String,
276 },
277 /// The node reads a chunk or event port, and nothing is attached to it.
278 ///
279 /// A chunk port's registers address one chunk of a stream buffer, an
280 /// event port's one event (GenICam Standard v2.1.1 §2.8.16): there is no
281 /// device memory behind them to fall back on. Attach a frame's chunks or a
282 /// received event first ([`crate::NodeMap::attach_chunks`],
283 /// [`crate::NodeMap::attach_event`]).
284 #[error("{node} reads port {port}, and no chunk or event data is attached to it")]
285 NotAttached {
286 /// The register that was read.
287 node: String,
288 /// Its `<pPort>`.
289 port: String,
290 },
291 /// The node is on a chunk or event port, which holds data the camera sent
292 /// and cannot be written.
293 #[error("{node} is on port {port}, which holds data the camera sent and cannot be written")]
294 PortNotWritable {
295 /// The register that was written.
296 node: String,
297 /// Its `<pPort>`.
298 port: String,
299 },
300 /// The register is on a port the document does not declare, so there is
301 /// nowhere to read it from.
302 #[error("{node} is on port {port}, which the document does not declare")]
303 UnknownPort {
304 /// The register.
305 node: String,
306 /// Its `<pPort>`.
307 port: String,
308 },
309 /// A device address was asked of a register on a chunk or event port,
310 /// whose address counts from the start of a chunk or an event, not from
311 /// device memory: see [`crate::NodeMap::register_address`].
312 #[error("{node} is on port {port}: its address is relative to a chunk or an event")]
313 NotDeviceMemory {
314 /// The register.
315 node: String,
316 /// Its `<pPort>`.
317 port: String,
318 },
319 /// The register lies outside the chunk or event data attached to its port.
320 #[error("{node} reads {len} bytes at offset {offset} of port {port}, which holds {size} bytes")]
321 PortOutOfRange {
322 /// The register that was read.
323 node: String,
324 /// Its `<pPort>`.
325 port: String,
326 /// The resolved offset; negative on a chunk port counts from the end.
327 offset: i64,
328 /// Bytes the register spans.
329 len: u32,
330 /// Bytes attached to the port.
331 size: usize,
332 },
333 /// Indirect addressing resolved to an invalid register.
334 #[error("node {name} resolved invalid indirect address {addr:#X}")]
335 BadIndirectAddress {
336 /// The node.
337 name: String,
338 /// The address its `<pAddress>` or `<pIndex>` resolved to.
339 addr: i64,
340 },
341 /// A `<pLength>` node reads a length no register can have: negative,
342 /// beyond `u32`, or, for device memory, beyond 16 MiB. Nothing was read
343 /// or written.
344 #[error("{name}: its <pLength> {length_node} reads {len}, which is not a register length")]
345 BadLength {
346 /// The register.
347 name: String,
348 /// The node its `<pLength>` names.
349 length_node: String,
350 /// The length it read.
351 len: i64,
352 },
353 /// Bitfield metadata exceeded the backing register width.
354 #[error(
355 "bitfield for node {name} exceeds register length {len} (offset {bit_offset}, length {bit_length})"
356 )]
357 BitfieldOutOfRange {
358 /// The node.
359 name: String,
360 /// The bit field's first bit.
361 bit_offset: u16,
362 /// Its width in bits.
363 bit_length: u16,
364 /// The register's length in bytes.
365 len: usize,
366 },
367 /// Provided value does not fit into the declared bitfield.
368 #[error("value {value} too wide for {bit_length}-bit field on node {name}")]
369 ValueTooWide {
370 /// The node.
371 name: String,
372 /// The value refused.
373 value: i64,
374 /// The bit field's width.
375 bit_length: u16,
376 },
377 /// A bitfield write needs the rest of its register, and the register is
378 /// write-only with nothing cached.
379 ///
380 /// Writing some bits of a register means sending the whole register, so
381 /// the other bits have to come from somewhere. For a `WO` register they
382 /// cannot come from the device — it refuses the read — and inventing them
383 /// would silently overwrite whatever the device holds. Refused locally,
384 /// before anything reaches the wire (backlog GA-31, issue #135).
385 #[error(
386 "cannot write bitfield node {name}: its register at {address:#X} is write-only, so the \
387 other bits it shares cannot be read back, and none are cached"
388 )]
389 MaskedWriteUnreadable {
390 /// The node.
391 name: String,
392 /// Its register's address.
393 address: u64,
394 },
395}
396
397impl GenApiError {
398 /// A transport's failure: `err` becomes the [`GenApiError::Io`] source.
399 ///
400 /// For [`RegisterIo`](crate::RegisterIo) implementations, so the error a
401 /// caller sees can be downcast to the transport's own.
402 pub fn io(err: impl Into<BoxError>) -> Self {
403 GenApiError::Io(err.into())
404 }
405
406 pub(crate) fn access(name: &str, refused: AccessDirection) -> Self {
407 GenApiError::Access {
408 name: name.to_string(),
409 refused,
410 }
411 }
412
413 pub(crate) fn range(name: &str, value: Value, violation: RangeViolation) -> Self {
414 GenApiError::Range {
415 name: name.to_string(),
416 value,
417 violation,
418 }
419 }
420
421 pub(crate) fn encoding(name: &str, width: usize, problem: &'static str) -> Self {
422 GenApiError::RegisterEncoding {
423 name: name.to_string(),
424 width,
425 problem,
426 }
427 }
428
429 pub(crate) fn declaration(name: &str, problem: &'static str) -> Self {
430 GenApiError::Declaration {
431 name: name.to_string(),
432 problem,
433 }
434 }
435
436 pub(crate) fn eval(name: &str, source: EvalError) -> Self {
437 GenApiError::ExprEval {
438 name: name.to_string(),
439 source,
440 }
441 }
442
443 pub(crate) fn no_value_source(name: &str) -> Self {
444 GenApiError::NoValueSource {
445 name: name.to_string(),
446 }
447 }
448
449 pub(crate) fn wrong_kind(name: &str, kind: &'static str, expected: &'static str) -> Self {
450 GenApiError::Type {
451 name: name.to_string(),
452 kind,
453 expected,
454 }
455 }
456}
457
458/// `"n"` before a kind that starts with a vowel, so the message reads
459/// "an Integer", "a Float".
460fn article(kind: &str) -> &'static str {
461 match kind.as_bytes().first() {
462 Some(b'A' | b'E' | b'I' | b'O' | b'U') => "n",
463 _ => "",
464 }
465}
466
467#[cfg(test)]
468mod tests {
469 use super::*;
470
471 #[test]
472 fn a_type_error_reads_as_a_sentence() {
473 let err = GenApiError::wrong_kind("Gain", "Float", "an Integer");
474 assert_eq!(err.to_string(), "Gain is a Float, not an Integer");
475 let err = GenApiError::wrong_kind("Mode", "Enumeration", "a Float");
476 assert_eq!(err.to_string(), "Mode is an Enumeration, not a Float");
477 }
478}