Skip to main content

knx_pico/
error.rs

1//! Error types for KNX operations following M-ERRORS-CANONICAL-STRUCTS guideline.
2//!
3//! This module provides structured error types with backtraces (when std is enabled)
4//! and helper methods for error information.
5
6use core::fmt;
7
8#[cfg(feature = "std")]
9use std::backtrace::Backtrace;
10
11/// Result type alias for KNX operations.
12pub type Result<T> = core::result::Result<T, KnxError>;
13
14// =============================================================================
15// Error Kind Enums (Internal)
16// =============================================================================
17
18/// Protocol error variants (internal)
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20#[cfg_attr(feature = "defmt", derive(defmt::Format))]
21pub(crate) enum ProtocolErrorKind {
22    InvalidFrame,
23    InvalidChecksum,
24    UnsupportedVersion,
25    UnsupportedServiceType,
26    PayloadTooLarge,
27    InvalidMessageCode,
28    InvalidControlField,
29}
30
31/// Connection error variants (internal)
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33#[cfg_attr(feature = "defmt", derive(defmt::Format))]
34pub(crate) enum ConnectionErrorKind {
35    Refused,
36    Timeout,
37    Failed,
38    Lost,
39    ChannelNotFound,
40    NoFreeChannels,
41    NotConnected,
42    AlreadyConnected,
43}
44
45/// Tunneling error variants (internal)
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47#[cfg_attr(feature = "defmt", derive(defmt::Format))]
48pub(crate) enum TunnelingErrorKind {
49    SequenceMismatch,
50    AckFailed,
51}
52
53/// Transport error variants (internal)
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55#[cfg_attr(feature = "defmt", derive(defmt::Format))]
56pub(crate) enum TransportErrorKind {
57    SendFailed,
58    ReceiveFailed,
59    BufferTooSmall,
60    NotBound,
61    SocketError,
62}
63
64/// Addressing error variants (internal)
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66#[cfg_attr(feature = "defmt", derive(defmt::Format))]
67pub(crate) enum AddressingErrorKind {
68    InvalidIndividualAddress,
69    InvalidGroupAddress,
70    OutOfRange,
71}
72
73/// DPT error variants (internal)
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75#[cfg_attr(feature = "defmt", derive(defmt::Format))]
76pub(crate) enum DptErrorKind {
77    InvalidData,
78    ValueOutOfRange,
79    UnsupportedType,
80}
81
82// =============================================================================
83// Main Error Type
84// =============================================================================
85
86/// KNX protocol error types.
87///
88/// This is the main error type returned by all KNX operations.
89/// It contains a backtrace (when std feature is enabled) and detailed
90/// error information through helper methods.
91#[derive(Debug)]
92#[cfg_attr(feature = "defmt", derive(defmt::Format))]
93pub enum KnxError {
94    /// Protocol-related errors (frame parsing, version, etc.)
95    Protocol(ProtocolError),
96    /// Connection-related errors (connect, disconnect, etc.)
97    Connection(ConnectionError),
98    /// Tunneling-related errors (sequence, ACK, etc.)
99    Tunneling(TunnelingError),
100    /// Transport-related errors (socket, send, receive, etc.)
101    Transport(TransportError),
102    /// Addressing errors (invalid address format, etc.)
103    Addressing(AddressingError),
104    /// Datapoint Type errors (encoding, decoding, etc.)
105    Dpt(DptError),
106    /// Operation attempted in invalid state
107    InvalidState,
108    /// Operation not supported in current context
109    UnsupportedOperation,
110    /// Operation timed out
111    Timeout,
112}
113
114// =============================================================================
115// Structured Error Types
116// =============================================================================
117
118/// Protocol error with optional backtrace
119#[derive(Debug)]
120#[cfg_attr(feature = "defmt", derive(defmt::Format))]
121pub struct ProtocolError {
122    kind: ProtocolErrorKind,
123    #[cfg(feature = "std")]
124    backtrace: Backtrace,
125}
126
127impl ProtocolError {
128    pub(crate) fn new(kind: ProtocolErrorKind) -> Self {
129        Self {
130            kind,
131            #[cfg(feature = "std")]
132            backtrace: Backtrace::capture(),
133        }
134    }
135
136    /// Check if this is an invalid frame error
137    pub fn is_invalid_frame(&self) -> bool {
138        matches!(self.kind, ProtocolErrorKind::InvalidFrame)
139    }
140
141    /// Check if this is an unsupported version error
142    pub fn is_unsupported_version(&self) -> bool {
143        matches!(self.kind, ProtocolErrorKind::UnsupportedVersion)
144    }
145}
146
147/// Connection error with optional backtrace
148#[derive(Debug)]
149#[cfg_attr(feature = "defmt", derive(defmt::Format))]
150pub struct ConnectionError {
151    kind: ConnectionErrorKind,
152    #[cfg(feature = "std")]
153    backtrace: Backtrace,
154}
155
156impl ConnectionError {
157    pub(crate) fn new(kind: ConnectionErrorKind) -> Self {
158        Self {
159            kind,
160            #[cfg(feature = "std")]
161            backtrace: Backtrace::capture(),
162        }
163    }
164
165    /// Check if this is a timeout error
166    pub fn is_timeout(&self) -> bool {
167        matches!(self.kind, ConnectionErrorKind::Timeout)
168    }
169
170    /// Check if connection was refused
171    pub fn is_refused(&self) -> bool {
172        matches!(self.kind, ConnectionErrorKind::Refused)
173    }
174
175    /// Check if connection was lost
176    pub fn is_lost(&self) -> bool {
177        matches!(self.kind, ConnectionErrorKind::Lost)
178    }
179}
180
181/// Tunneling error with optional backtrace
182#[derive(Debug)]
183#[cfg_attr(feature = "defmt", derive(defmt::Format))]
184pub struct TunnelingError {
185    kind: TunnelingErrorKind,
186    #[cfg(feature = "std")]
187    backtrace: Backtrace,
188}
189
190impl TunnelingError {
191    pub(crate) fn new(kind: TunnelingErrorKind) -> Self {
192        Self {
193            kind,
194            #[cfg(feature = "std")]
195            backtrace: Backtrace::capture(),
196        }
197    }
198
199    /// Check if this is a sequence mismatch error
200    pub fn is_sequence_mismatch(&self) -> bool {
201        matches!(self.kind, TunnelingErrorKind::SequenceMismatch)
202    }
203}
204
205/// Transport error with optional backtrace
206#[derive(Debug)]
207#[cfg_attr(feature = "defmt", derive(defmt::Format))]
208pub struct TransportError {
209    kind: TransportErrorKind,
210    #[cfg(feature = "std")]
211    backtrace: Backtrace,
212}
213
214impl TransportError {
215    pub(crate) fn new(kind: TransportErrorKind) -> Self {
216        Self {
217            kind,
218            #[cfg(feature = "std")]
219            backtrace: Backtrace::capture(),
220        }
221    }
222
223    /// Check if buffer is too small
224    pub fn is_buffer_too_small(&self) -> bool {
225        matches!(self.kind, TransportErrorKind::BufferTooSmall)
226    }
227
228    /// Check if this is a socket error
229    pub fn is_socket_error(&self) -> bool {
230        matches!(self.kind, TransportErrorKind::SocketError)
231    }
232}
233
234/// Addressing error with optional backtrace
235#[derive(Debug)]
236#[cfg_attr(feature = "defmt", derive(defmt::Format))]
237pub struct AddressingError {
238    kind: AddressingErrorKind,
239    #[cfg(feature = "std")]
240    backtrace: Backtrace,
241}
242
243impl AddressingError {
244    pub(crate) fn new(kind: AddressingErrorKind) -> Self {
245        Self {
246            kind,
247            #[cfg(feature = "std")]
248            backtrace: Backtrace::capture(),
249        }
250    }
251
252    /// Check if address is out of range
253    pub fn is_out_of_range(&self) -> bool {
254        matches!(self.kind, AddressingErrorKind::OutOfRange)
255    }
256}
257
258/// DPT error with optional backtrace
259#[derive(Debug)]
260#[cfg_attr(feature = "defmt", derive(defmt::Format))]
261pub struct DptError {
262    kind: DptErrorKind,
263    #[cfg(feature = "std")]
264    backtrace: Backtrace,
265}
266
267impl DptError {
268    pub(crate) fn new(kind: DptErrorKind) -> Self {
269        Self {
270            kind,
271            #[cfg(feature = "std")]
272            backtrace: Backtrace::capture(),
273        }
274    }
275
276    /// Check if value is out of range
277    pub fn is_out_of_range(&self) -> bool {
278        matches!(self.kind, DptErrorKind::ValueOutOfRange)
279    }
280}
281
282// =============================================================================
283// Convenience Constructors for KnxError
284// =============================================================================
285
286impl KnxError {
287    // Protocol errors
288    #[inline]
289    pub(crate) const fn invalid_frame() -> Self {
290        Self::Protocol(ProtocolError {
291            kind: ProtocolErrorKind::InvalidFrame,
292            #[cfg(feature = "std")]
293            backtrace: Backtrace::disabled(),
294        })
295    }
296
297    #[inline]
298    pub(crate) const fn invalid_checksum() -> Self {
299        Self::Protocol(ProtocolError {
300            kind: ProtocolErrorKind::InvalidChecksum,
301            #[cfg(feature = "std")]
302            backtrace: Backtrace::disabled(),
303        })
304    }
305
306    #[inline]
307    pub(crate) const fn unsupported_version() -> Self {
308        Self::Protocol(ProtocolError {
309            kind: ProtocolErrorKind::UnsupportedVersion,
310            #[cfg(feature = "std")]
311            backtrace: Backtrace::disabled(),
312        })
313    }
314
315    #[inline]
316    pub(crate) const fn unsupported_service_type() -> Self {
317        Self::Protocol(ProtocolError {
318            kind: ProtocolErrorKind::UnsupportedServiceType,
319            #[cfg(feature = "std")]
320            backtrace: Backtrace::disabled(),
321        })
322    }
323
324    #[inline]
325    pub(crate) const fn payload_too_large() -> Self {
326        Self::Protocol(ProtocolError {
327            kind: ProtocolErrorKind::PayloadTooLarge,
328            #[cfg(feature = "std")]
329            backtrace: Backtrace::disabled(),
330        })
331    }
332
333    // Connection errors
334    pub(crate) fn connection_refused() -> Self {
335        Self::Connection(ConnectionError::new(ConnectionErrorKind::Refused))
336    }
337
338    pub(crate) fn connection_timeout() -> Self {
339        Self::Connection(ConnectionError::new(ConnectionErrorKind::Timeout))
340    }
341
342    pub(crate) fn connection_failed() -> Self {
343        Self::Connection(ConnectionError::new(ConnectionErrorKind::Failed))
344    }
345
346    pub(crate) fn connection_lost() -> Self {
347        Self::Connection(ConnectionError::new(ConnectionErrorKind::Lost))
348    }
349
350    pub(crate) fn not_connected() -> Self {
351        Self::Connection(ConnectionError::new(ConnectionErrorKind::NotConnected))
352    }
353
354    pub(crate) fn channel_not_found() -> Self {
355        Self::Connection(ConnectionError::new(ConnectionErrorKind::ChannelNotFound))
356    }
357
358    pub(crate) fn no_free_channels() -> Self {
359        Self::Connection(ConnectionError::new(ConnectionErrorKind::NoFreeChannels))
360    }
361
362    pub(crate) fn already_connected() -> Self {
363        Self::Connection(ConnectionError::new(ConnectionErrorKind::AlreadyConnected))
364    }
365
366    // Tunneling errors
367    pub(crate) fn sequence_mismatch() -> Self {
368        Self::Tunneling(TunnelingError::new(TunnelingErrorKind::SequenceMismatch))
369    }
370
371    pub(crate) fn tunneling_ack_failed() -> Self {
372        Self::Tunneling(TunnelingError::new(TunnelingErrorKind::AckFailed))
373    }
374
375    // Transport errors
376    pub(crate) fn buffer_too_small() -> Self {
377        Self::Transport(TransportError::new(TransportErrorKind::BufferTooSmall))
378    }
379
380    pub(crate) fn socket_error() -> Self {
381        Self::Transport(TransportError::new(TransportErrorKind::SocketError))
382    }
383
384    pub(crate) fn send_failed() -> Self {
385        Self::Transport(TransportError::new(TransportErrorKind::SendFailed))
386    }
387
388    pub(crate) fn receive_failed() -> Self {
389        Self::Transport(TransportError::new(TransportErrorKind::ReceiveFailed))
390    }
391
392    pub(crate) fn not_bound() -> Self {
393        Self::Transport(TransportError::new(TransportErrorKind::NotBound))
394    }
395
396    // Addressing errors
397    pub(crate) fn invalid_group_address() -> Self {
398        Self::Addressing(AddressingError::new(
399            AddressingErrorKind::InvalidGroupAddress,
400        ))
401    }
402
403    pub(crate) fn invalid_address() -> Self {
404        Self::Addressing(AddressingError::new(
405            AddressingErrorKind::InvalidGroupAddress,
406        ))
407    }
408
409    pub(crate) fn invalid_individual_address() -> Self {
410        Self::Addressing(AddressingError::new(
411            AddressingErrorKind::InvalidIndividualAddress,
412        ))
413    }
414
415    pub(crate) fn address_out_of_range() -> Self {
416        Self::Addressing(AddressingError::new(AddressingErrorKind::OutOfRange))
417    }
418
419    // DPT errors
420    pub(crate) fn invalid_dpt_data() -> Self {
421        Self::Dpt(DptError::new(DptErrorKind::InvalidData))
422    }
423
424    pub(crate) fn dpt_value_out_of_range() -> Self {
425        Self::Dpt(DptError::new(DptErrorKind::ValueOutOfRange))
426    }
427
428    pub(crate) fn unsupported_dpt() -> Self {
429        Self::Dpt(DptError::new(DptErrorKind::UnsupportedType))
430    }
431
432    // cEMI errors (Protocol category)
433    pub(crate) fn invalid_message_code() -> Self {
434        Self::Protocol(ProtocolError::new(ProtocolErrorKind::InvalidMessageCode))
435    }
436
437    pub(crate) fn invalid_control_field() -> Self {
438        Self::Protocol(ProtocolError::new(ProtocolErrorKind::InvalidControlField))
439    }
440}
441
442// =============================================================================
443// Display Implementation
444// =============================================================================
445
446impl fmt::Display for KnxError {
447    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448        match self {
449            KnxError::Protocol(e) => write!(f, "Protocol error: {:?}", e.kind),
450            KnxError::Connection(e) => write!(f, "Connection error: {:?}", e.kind),
451            KnxError::Tunneling(e) => write!(f, "Tunneling error: {:?}", e.kind),
452            KnxError::Transport(e) => write!(f, "Transport error: {:?}", e.kind),
453            KnxError::Addressing(e) => write!(f, "Addressing error: {:?}", e.kind),
454            KnxError::Dpt(e) => write!(f, "DPT error: {:?}", e.kind),
455            KnxError::InvalidState => write!(f, "Invalid state"),
456            KnxError::UnsupportedOperation => write!(f, "Unsupported operation"),
457            KnxError::Timeout => write!(f, "Operation timeout"),
458        }
459
460        // Note: Backtrace will be printed when std::error::Error::source() is called
461    }
462}
463
464// Implement std::error::Error for std-based applications
465#[cfg(feature = "std")]
466impl std::error::Error for KnxError {}