Skip to main content

at_cryptoauth/
error.rs

1//! Error types for ATECC608 communication and operations.
2//!
3//! This module provides error handling for all ATECC608 operations, including:
4//!
5//! - **Device errors** ([`Status`]): Errors returned by the ATECC608 device itself
6//! - **Driver errors** ([`ErrorKind`]): Communication and validation errors
7//!
8//! ## Example
9//!
10//! ```ignore
11//! use at_cryptoauth::error::{Error, ErrorKind};
12//!
13//! fn example() -> Result<(), Error> {
14//!     // Operations return Result<T, Error>
15//!     let info = client.info().await?;
16//!
17//!     // Check specific error kinds
18//!     match some_operation() {
19//!         Err(e) if e.code() == ErrorKind::MutexLocked as u32 => {
20//!             // Handle concurrent access
21//!         }
22//!         Err(e) => return Err(e),
23//!         Ok(v) => { /* ... */ }
24//!     }
25//!     Ok(())
26//! }
27//! ```
28
29use core::convert::TryFrom;
30
31/// An error type representing ATECC608's erroneous conditions.
32#[derive(Copy, Clone, Debug)]
33pub struct Error {
34    repr: Repr,
35}
36
37impl Error {
38    pub fn code(&self) -> u32 {
39        match self.repr {
40            Repr::Device(i) => i as u32,
41            Repr::Simple(i) => i as u32,
42        }
43    }
44}
45
46#[derive(Copy, Clone, Debug)]
47enum Repr {
48    Device(Status),
49    Simple(ErrorKind),
50}
51
52impl From<ErrorKind> for Error {
53    fn from(kind: ErrorKind) -> Error {
54        Error {
55            repr: Repr::Simple(kind),
56        }
57    }
58}
59
60impl From<Status> for Error {
61    fn from(status: Status) -> Error {
62        Error {
63            repr: Repr::Device(status),
64        }
65    }
66}
67
68impl core::fmt::Display for Error {
69    fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
70        match &self.repr {
71            Repr::Device(status) => write!(fmt, "{}", status),
72            Repr::Simple(kind) => write!(fmt, "{}", kind),
73        }
74    }
75}
76
77#[derive(Copy, Clone, Debug)]
78pub enum Status {
79    /// response status byte indicates CheckMac failure (status byte = 0x01)
80    CheckmacVerifyFailed = 0x01,
81    /// chip was in a state where it could not execute the command, response
82    /// status byte indicates command execution error (status byte = 0x0F)
83    Execution = 0x0F,
84    /// response status byte indicates parsing error (status byte = 0x03)
85    Parse = 0x03,
86    /// response status byte indicates Device did not receive data properly
87    /// (status byte = 0xFF)
88    Crc = 0xFF,
89    /// response status byte is unknown
90    Unknown = 0xD5,
91    /// response status byte is Ecc fault (status byte = 0x05)
92    Ecc = 0x05,
93    /// response status byte is Self Test Error, chip in failure mode (status
94    /// byte = 0x07)
95    SelfTest = 0x07,
96    /// random number generator health test error
97    HealthTest = 0x08,
98}
99
100impl TryFrom<u8> for Status {
101    type Error = ();
102
103    fn try_from(value: u8) -> Result<Self, Self::Error> {
104        match value {
105            0x00 => Err(()),
106            0x01 => Ok(Self::CheckmacVerifyFailed),
107            0x0F => Ok(Self::Execution),
108            0x03 => Ok(Self::Parse),
109            0xFF => Ok(Self::Crc),
110            0x05 => Ok(Self::Ecc),
111            0x07 => Ok(Self::SelfTest),
112            0x08 => Ok(Self::HealthTest),
113            _ => Ok(Self::Unknown),
114        }
115    }
116}
117
118impl core::fmt::Display for Status {
119    fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
120        match self {
121            Self::CheckmacVerifyFailed => write!(fmt, "checkmac or verify failed"),
122            Self::Crc => write!(
123                fmt,
124                "bad crc found (command not properly received by device) or other comm error"
125            ),
126            Self::Ecc => write!(
127                fmt,
128                "computation error during ECC processing causing invalid results"
129            ),
130            Self::Execution => write!(fmt, "chip can't execute the command"),
131            Self::HealthTest => write!(fmt, "random number generator health test error"),
132            Self::Parse => write!(
133                fmt,
134                "command received byte length, opcode or parameter was illegal"
135            ),
136            Self::SelfTest => write!(fmt, "chip is in self test failure mode"),
137            Self::Unknown => write!(fmt, "response contains unknown non-zero status byte"),
138        }
139    }
140}
141
142/// A list of specific error causes. Each kind is converted into `Error` type.
143#[derive(Copy, Clone, Debug)]
144pub enum ErrorKind {
145    /// Code failed run-time consistency check
146    AssertFailure = 0xF6,
147    /// opcode is not supported by the device
148    BadOpcode = 0xF2,
149    /// bad argument (out of range, null pointer, etc.)
150    BadParam = 0xE2,
151    /// Communication with device failed. Same as in hardware dependent modules.
152    CommFail = 0xF0,
153    ConfigZoneLocked = 0x01,
154    DataZoneLocked = 0x04,
155    /// Function could not execute due to incorrect condition / state.
156    FuncFail = 0xE0,
157    /// invalid device id, id not set
158    InvalidId = 0xE3,
159    /// Count value is out of range or greater than buffer size.
160    InvalidSize = 0xE4,
161    /// required zone was not locked
162    NotLocked = 0xF8,
163    /// Re-synchronization succeeded, but only after generating a Wake-up
164    ResyncWithWakeup = 0xE8,
165    /// Crc error in data received from device
166    RxCrcError = 0xE5,
167    /// Timed out while waiting for response. Number of bytes received is > 0.
168    RxFail = 0xE6,
169    /// Supplied buffer is too small for data required
170    SmallBuffer = 0xED,
171    /// Timed out while waiting for response. Number of bytes received is 0.
172    Timeout = 0xF1,
173    /// Device did not respond too many times during a transmission. Could
174    /// indicate no device present.
175    TooManyCommRetries = 0xEC,
176    /// Failed to write
177    TxFail = 0xF7,
178    /// Function or some element of it hasn't been implemented yet
179    Unimplemented = 0xF5,
180    /// Use flags on the device indicates its consumed fully
181    UseFlagsConsumed = 0xFC,
182    /// Device did not respond to wake call as expected
183    WakeFailed = 0xD0,
184    /// Mutex is already locked (blocking API contention)
185    MutexLocked = 0xD1,
186}
187
188impl core::fmt::Display for ErrorKind {
189    fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
190        match self {
191            Self::AssertFailure => write!(fmt, "failed run-time consistency check"),
192            Self::BadOpcode => write!(fmt, "opcode is not supported by the device"),
193            Self::BadParam => write!(fmt, "bad argument (out of range, null pointer, etc.)"),
194            Self::CommFail => write!(fmt, "communication with device failed"),
195            Self::ConfigZoneLocked => write!(fmt, "config zone is locked"),
196            Self::DataZoneLocked => write!(fmt, "data zone is locked"),
197            Self::FuncFail => write!(
198                fmt,
199                "function could not execute due to incorrect condition / state"
200            ),
201            Self::InvalidId => write!(fmt, "invalid device id, id not set"),
202            Self::InvalidSize => write!(
203                fmt,
204                "count value is out of range or greater than buffer size"
205            ),
206            Self::NotLocked => write!(fmt, "required zone was not locked"),
207            Self::ResyncWithWakeup => write!(
208                fmt,
209                "re-synchronization succeeded, but only after generating a Wake-up"
210            ),
211            Self::RxCrcError => write!(fmt, "crc error in data received from device"),
212            Self::RxFail => write!(
213                fmt,
214                "timed out while waiting for response. Number of bytes received is > 0"
215            ),
216            Self::SmallBuffer => write!(fmt, "supplied buffer is too small for data required"),
217            Self::Timeout => write!(fmt, "timed out while waiting for response"),
218            Self::TooManyCommRetries => {
219                write!(
220                    fmt,
221                    "device did not respond too many times, indicating no device present"
222                )
223            }
224            Self::TxFail => write!(fmt, "failed to write"),
225            Self::Unimplemented => write!(
226                fmt,
227                "function or some element of it hasn't been implemented yet"
228            ),
229            Self::UseFlagsConsumed => {
230                write!(fmt, "use flags on the device indicates its consumed fully")
231            }
232            Self::WakeFailed => write!(fmt, "device did not respond to wake call as expected"),
233            Self::MutexLocked => write!(fmt, "mutex is already locked (blocking API contention)"),
234        }
235    }
236}