Skip to main content

rtlsdr_nusb/
errors.rs

1//! Errors returned by the RTL-SDR driver.
2
3use core::fmt;
4
5/// Error returned by a RTL-SDR operation.
6///
7/// The variants preserve structured driver errors and the original `nusb` error values. Use
8/// [`Error::kind`] when only a broad, backend-independent category is needed.
9#[derive(Debug)]
10#[non_exhaustive]
11pub enum Error {
12    /// A receiver configuration value failed validation.
13    InvalidConfig {
14        /// Name of the invalid configuration field.
15        field: &'static str,
16        /// Reason the value is invalid.
17        reason: &'static str,
18    },
19    /// No matching RTL-SDR device was found.
20    DeviceNotFound,
21    /// The connected tuner is not an R820T/R828D-family device.
22    UnsupportedTuner,
23    /// The tuner PLL failed to lock after a retry.
24    PllUnlocked,
25    /// Configuration failed or was canceled; reapply a complete configuration.
26    ConfigurationUnknown,
27    /// The logical device session has been shut down.
28    DeviceClosed,
29    /// The device or USB resource is already in use.
30    Busy,
31    /// The requested operation is not supported by the backend or device.
32    Unsupported,
33    /// The stream is not running or is otherwise closed.
34    StreamClosed {
35        /// Reason the stream is no longer usable.
36        reason: &'static str,
37    },
38    /// The USB backend returned an error outside an individual transfer.
39    Usb(nusb::Error),
40    /// An individual USB transfer failed.
41    Transfer(nusb::transfer::TransferError),
42    /// A RTL-SDR operation failed with a more specific source error.
43    Operation {
44        /// Operation being performed when the error occurred.
45        operation: &'static str,
46        /// More specific driver or USB error.
47        source: Box<Error>,
48    },
49    /// The device or driver violated the expected RTL-SDR protocol.
50    Protocol {
51        /// Operation that failed.
52        operation: &'static str,
53        /// Protocol violation or unexpected response.
54        reason: &'static str,
55    },
56}
57
58/// Stable error category.
59#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60#[non_exhaustive]
61pub enum ErrorKind {
62    /// A provided configuration value failed validation.
63    InvalidConfig,
64    /// No matching RTL-SDR device was found.
65    NotFound,
66    /// The logical device session has been shut down.
67    DeviceClosed,
68    /// The physical device was disconnected from USB.
69    DeviceDisconnected,
70    /// The device or USB resource is already in use.
71    Busy,
72    /// The requested operation is not supported by the backend or device.
73    Unsupported,
74    /// The USB backend returned an error.
75    Usb,
76    /// The stream is not running or is otherwise closed.
77    StreamClosed,
78    /// Any other driver or backend error.
79    Other,
80}
81
82impl Error {
83    /// Build a receiver configuration validation error.
84    pub(crate) const fn invalid_config(field: &'static str, reason: &'static str) -> Self {
85        Self::InvalidConfig { field, reason }
86    }
87
88    /// Build a stream lifecycle error.
89    pub(crate) const fn stream_closed(reason: &'static str) -> Self {
90        Self::StreamClosed { reason }
91    }
92
93    /// Build a RTL-SDR protocol error.
94    pub(crate) const fn protocol(operation: &'static str, reason: &'static str) -> Self {
95        Self::Protocol { operation, reason }
96    }
97
98    /// Attach driver-operation context while preserving the source error.
99    pub(crate) fn at(self, operation: &'static str) -> Self {
100        Self::Operation {
101            operation,
102            source: Box::new(self),
103        }
104    }
105
106    /// Return a broad, backend-independent error category.
107    pub fn kind(&self) -> ErrorKind {
108        match self {
109            Self::InvalidConfig { .. } => ErrorKind::InvalidConfig,
110            Self::DeviceNotFound => ErrorKind::NotFound,
111            Self::UnsupportedTuner => ErrorKind::Unsupported,
112            Self::PllUnlocked | Self::ConfigurationUnknown => ErrorKind::Other,
113            Self::DeviceClosed => ErrorKind::DeviceClosed,
114            Self::Busy => ErrorKind::Busy,
115            Self::Unsupported => ErrorKind::Unsupported,
116            Self::StreamClosed { .. } => ErrorKind::StreamClosed,
117            Self::Usb(err) => match err.kind() {
118                nusb::ErrorKind::Disconnected => ErrorKind::DeviceDisconnected,
119                nusb::ErrorKind::Busy => ErrorKind::Busy,
120                nusb::ErrorKind::NotFound => ErrorKind::NotFound,
121                nusb::ErrorKind::Unsupported => ErrorKind::Unsupported,
122                _ => ErrorKind::Usb,
123            },
124            Self::Transfer(nusb::transfer::TransferError::Disconnected) => {
125                ErrorKind::DeviceDisconnected
126            }
127            Self::Transfer(_) => ErrorKind::Usb,
128            Self::Operation { source, .. } => source.kind(),
129            Self::Protocol { .. } => ErrorKind::Other,
130        }
131    }
132}
133
134impl fmt::Display for Error {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        match self {
137            Self::InvalidConfig { field, reason } => {
138                write!(f, "invalid configuration for {field}: {reason}")
139            }
140            Self::DeviceNotFound => f.write_str("no matching RTL-SDR device found"),
141            Self::UnsupportedTuner => f.write_str("unsupported tuner (R820T/R828D required)"),
142            Self::PllUnlocked => f.write_str("tuner PLL did not lock"),
143            Self::ConfigurationUnknown => {
144                f.write_str("configuration is unknown; reapply a complete configuration or reopen")
145            }
146            Self::DeviceClosed => f.write_str("RTL-SDR device is closed"),
147            Self::Busy => f.write_str("RTL-SDR device or USB resource is busy"),
148            Self::Unsupported => f.write_str("operation is unsupported"),
149            Self::StreamClosed { reason } => write!(f, "stream closed: {reason}"),
150            Self::Usb(err) => write!(f, "USB error: {err}"),
151            Self::Transfer(err) => write!(f, "USB transfer error: {err}"),
152            Self::Operation { operation, source } => write!(f, "{operation}: {source}"),
153            Self::Protocol { operation, reason } => write!(f, "{operation}: {reason}"),
154        }
155    }
156}
157
158impl std::error::Error for Error {
159    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
160        match self {
161            Self::Usb(err) => Some(err),
162            Self::Transfer(err) => Some(err),
163            Self::Operation { source, .. } => Some(source),
164            _ => None,
165        }
166    }
167}
168
169impl From<nusb::Error> for Error {
170    fn from(value: nusb::Error) -> Self {
171        Self::Usb(value)
172    }
173}
174
175impl From<nusb::transfer::TransferError> for Error {
176    fn from(value: nusb::transfer::TransferError) -> Self {
177        Self::Transfer(value)
178    }
179}
180
181/// Crate result alias using [`Error`].
182pub type Result<T> = core::result::Result<T, Error>;
183
184#[cfg(test)]
185mod tests {
186    use std::error::Error as _;
187
188    use super::{Error, ErrorKind};
189
190    #[test]
191    fn transfer_errors_preserve_their_source_and_are_not_configuration_errors() {
192        let err = Error::from(nusb::transfer::TransferError::InvalidArgument);
193
194        assert!(matches!(
195            &err,
196            Error::Transfer(nusb::transfer::TransferError::InvalidArgument)
197        ));
198        assert_eq!(err.kind(), ErrorKind::Usb);
199        assert!(err.source().is_some());
200    }
201
202    #[test]
203    fn transfer_disconnects_have_their_own_error_category() {
204        let err = Error::from(nusb::transfer::TransferError::Disconnected);
205
206        assert_eq!(err.kind(), ErrorKind::DeviceDisconnected);
207        assert!(err.source().is_some());
208    }
209
210    #[test]
211    fn configuration_errors_expose_the_field_and_reason() {
212        let err = Error::invalid_config("frequency_hz", "must be nonzero");
213
214        assert!(matches!(
215            &err,
216            Error::InvalidConfig {
217                field: "frequency_hz",
218                reason: "must be nonzero"
219            }
220        ));
221        assert_eq!(err.kind(), ErrorKind::InvalidConfig);
222    }
223
224    #[test]
225    fn operation_context_preserves_source_category() {
226        let err =
227            Error::from(nusb::transfer::TransferError::Fault).at("applying receiver configuration");
228
229        assert_eq!(err.kind(), ErrorKind::Usb);
230        assert!(
231            err.to_string()
232                .starts_with("applying receiver configuration: USB transfer error:")
233        );
234        assert!(err.source().is_some());
235    }
236
237    #[test]
238    fn operation_context_preserves_disconnect_category() {
239        let err =
240            Error::from(nusb::transfer::TransferError::Disconnected).at("reading receiver samples");
241
242        assert_eq!(err.kind(), ErrorKind::DeviceDisconnected);
243        assert!(err.source().is_some());
244    }
245
246    #[test]
247    fn closed_device_has_its_own_error_category() {
248        assert_eq!(Error::DeviceClosed.kind(), ErrorKind::DeviceClosed);
249        assert_eq!(Error::DeviceClosed.to_string(), "RTL-SDR device is closed");
250    }
251}