#![deny(missing_docs)]
mod args;
pub use args::Args;
mod async_compat;
mod async_device;
mod async_registry;
mod backend_macros;
mod capabilities;
mod device;
pub use async_compat::AsyncFutureExt;
pub use async_compat::BoxedFuture;
pub use async_compat::MaybeSend;
pub use async_compat::MaybeSync;
pub use async_device::AsyncAgc;
pub use async_device::AsyncAgcControl;
pub use async_device::AsyncAntenna;
pub use async_device::AsyncAntennaControl;
pub use async_device::AsyncBandwidth;
pub use async_device::AsyncBandwidthControl;
pub use async_device::AsyncDcOffset;
pub use async_device::AsyncDcOffsetControl;
pub use async_device::AsyncDevice;
pub use async_device::AsyncDeviceInfo;
pub use async_device::AsyncFrequency;
pub use async_device::AsyncFrequencyControl;
pub use async_device::AsyncGain;
pub use async_device::AsyncGainControl;
pub use async_device::AsyncRxChannel;
pub use async_device::AsyncRxDevice;
pub use async_device::AsyncSampleRate;
pub use async_device::AsyncSampleRateControl;
pub use async_device::AsyncTxChannel;
pub use async_device::AsyncTxDevice;
pub use async_device::DynAsyncDevice;
pub use async_device::DynAsyncRxStreamer;
pub use async_device::DynAsyncTxStreamer;
pub use async_registry::AsyncRegistry;
pub use capabilities::ChannelCapabilities;
pub use capabilities::ChannelControls;
pub use capabilities::DeviceCapabilities;
pub use device::Agc;
pub use device::AgcControl;
pub use device::Antenna;
pub use device::AntennaControl;
pub use device::Bandwidth;
pub use device::BandwidthControl;
pub use device::DcOffset;
pub use device::DcOffsetControl;
pub use device::Device;
pub use device::DeviceInfo;
pub use device::DynDevice;
pub use device::DynRxStreamer;
pub use device::DynTxStreamer;
pub use device::Frequency;
pub use device::FrequencyComponent;
pub use device::FrequencyControl;
pub use device::Gain;
pub use device::GainControl;
pub use device::GainElement;
pub use device::RxChannel;
pub use device::RxDevice;
pub use device::SampleRate;
pub use device::SampleRateControl;
pub use device::TxChannel;
pub use device::TxDevice;
pub mod impls;
mod registry;
pub use registry::DeviceDescriptor;
pub use registry::Registry;
mod range;
pub use range::Range;
pub use range::RangeItem;
mod async_streamer;
mod streamer;
pub use async_streamer::AsyncRxStreamer;
pub use async_streamer::AsyncTxStreamer;
pub use streamer::RxStreamer;
pub use streamer::TxStreamer;
pub mod dev {
#[cfg(any(target_arch = "wasm32", feature = "smol", feature = "tokio"))]
pub use crate::async_compat::timeout_from_micros;
#[cfg(any(target_arch = "wasm32", feature = "smol", feature = "tokio"))]
pub use crate::async_compat::with_timeout;
#[cfg(any(target_arch = "wasm32", feature = "smol", feature = "tokio"))]
pub use crate::async_compat::TimeoutResult;
pub use crate::async_device::DynAsyncAgcControl;
pub use crate::async_device::DynAsyncAntennaControl;
pub use crate::async_device::DynAsyncBandwidthControl;
pub use crate::async_device::DynAsyncDcOffsetControl;
pub use crate::async_device::DynAsyncDeviceBackend;
pub use crate::async_device::DynAsyncDeviceInfo;
pub use crate::async_device::DynAsyncFrequencyControl;
pub use crate::async_device::DynAsyncGainControl;
pub use crate::async_device::DynAsyncRxDevice;
pub use crate::async_device::DynAsyncSampleRateControl;
pub use crate::async_device::DynAsyncTxDevice;
pub use crate::async_registry::AsyncTypedDeviceBackend;
#[cfg(target_arch = "wasm32")]
pub use crate::async_registry::WebUsbDeviceFilter;
pub use crate::async_streamer::DynAsyncRxStreamerBackend;
pub use crate::async_streamer::DynAsyncTxStreamerBackend;
pub use crate::device::DynDeviceBackend;
pub use crate::device::DynRxDevice;
pub use crate::device::DynTxDevice;
pub use crate::impl_dyn_async_device_backend;
pub use crate::impl_dyn_device_backend;
pub use crate::registry::TypedDeviceBackend;
}
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Capability {
RxStreaming,
TxStreaming,
Antenna,
Agc,
Gain,
Frequency,
SampleRate,
Bandwidth,
DcOffset,
DeviceId,
TimedActivation,
TimedDeactivation,
DriverOperation,
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DriverError {
#[cfg(all(feature = "soapy", not(target_arch = "wasm32")))]
#[error("Soapy ({0})")]
Soapy(soapysdr::Error),
#[cfg(all(feature = "aaronia_http", not(target_arch = "wasm32")))]
#[error("Ureq ({0})")]
Ureq(Box<ureq::Error>),
#[cfg(feature = "rtlsdr")]
#[error("RtlSdr ({0})")]
RtlSdr(rtlsdr_nusb::Error),
#[cfg(feature = "hackrf")]
#[error("Hackrf ({0})")]
HackRf(hackrf_nusb::Error),
#[cfg(feature = "pluto")]
#[error("Pluto ({0})")]
Pluto(plutosdr::Error),
#[cfg(feature = "hydrasdr")]
#[error("HydraSdr ({0})")]
HydraSdr(hydrasdr_rs::Error),
#[cfg(feature = "uhd")]
#[error("Uhd ({0})")]
Uhd(uhd_rs::Error),
#[error("{0}")]
Other(String),
}
#[derive(Debug, Error)]
pub enum Error {
#[error("unsupported capability {capability:?}{detail}", detail = .reason.as_ref().map(|reason| format!(": {reason}")).unwrap_or_default())]
Unsupported {
capability: Capability,
reason: Option<String>,
},
#[error("invalid {direction:?} channel {channel}; available channels: {available}")]
InvalidChannel {
direction: Direction,
channel: usize,
available: usize,
},
#[error("invalid argument {name}: {reason}")]
InvalidArgument {
name: String,
reason: String,
},
#[error("missing argument {name}")]
MissingArgument {
name: String,
},
#[error("device not found")]
DeviceNotFound,
#[error("driver feature not enabled for {driver:?}")]
DriverFeatureNotEnabled {
driver: Driver,
},
#[error("driver mismatch: expected {expected:?}, requested {requested:?}")]
DriverMismatch {
expected: Driver,
requested: Driver,
},
#[error("value {value} for {name} out of range ({range:?})")]
OutOfRange {
name: String,
range: Range,
value: f64,
},
#[error("busy")]
Busy,
#[error("device disconnected")]
DeviceDisconnected,
#[error("timeout")]
Timeout,
#[error("stream inactive")]
StreamInactive,
#[error("stream closed")]
StreamClosed,
#[error("overrun")]
Overrun,
#[error("underrun")]
Underrun,
#[error("Json ({0})")]
Json(#[from] serde_json::Error),
#[error("Io ({0})")]
Io(#[from] std::io::Error),
#[error("driver error ({0})")]
Driver(#[from] DriverError),
}
impl Error {
pub fn unsupported(capability: Capability) -> Self {
Self::Unsupported {
capability,
reason: None,
}
}
pub fn unsupported_reason(capability: Capability, reason: impl Into<String>) -> Self {
Self::Unsupported {
capability,
reason: Some(reason.into()),
}
}
pub fn invalid_argument(name: impl Into<String>, reason: impl Into<String>) -> Self {
Self::InvalidArgument {
name: name.into(),
reason: reason.into(),
}
}
pub fn missing_argument(name: impl Into<String>) -> Self {
Self::MissingArgument { name: name.into() }
}
pub fn invalid_channel(direction: Direction, channel: usize, available: usize) -> Self {
Self::InvalidChannel {
direction,
channel,
available,
}
}
pub fn out_of_range(name: impl Into<String>, range: Range, value: f64) -> Self {
Self::OutOfRange {
name: name.into(),
range,
value,
}
}
pub fn is_unsupported(&self) -> bool {
matches!(self, Self::Unsupported { .. })
}
pub fn is_device_not_found(&self) -> bool {
matches!(self, Self::DeviceNotFound)
}
pub fn is_missing_argument(&self) -> bool {
matches!(self, Self::MissingArgument { .. })
}
}
#[cfg(all(feature = "aaronia_http", not(target_arch = "wasm32")))]
impl From<ureq::Error> for Error {
fn from(value: ureq::Error) -> Self {
Error::Driver(DriverError::Ureq(Box::new(value)))
}
}
#[cfg(feature = "rtlsdr")]
impl From<rtlsdr_nusb::Error> for Error {
fn from(value: rtlsdr_nusb::Error) -> Self {
Error::Driver(DriverError::RtlSdr(value))
}
}
#[cfg(feature = "hackrf")]
impl From<hackrf_nusb::Error> for Error {
fn from(value: hackrf_nusb::Error) -> Self {
Error::Driver(DriverError::HackRf(value))
}
}
#[cfg(feature = "hydrasdr")]
impl From<hydrasdr_rs::Error> for Error {
fn from(value: hydrasdr_rs::Error) -> Self {
Error::Driver(DriverError::HydraSdr(value))
}
}
#[cfg(feature = "pluto")]
impl From<plutosdr::Error> for Error {
fn from(value: plutosdr::Error) -> Self {
Error::Driver(DriverError::Pluto(value))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Driver {
AaroniaHttp,
BladeRf,
Dummy,
HackRf,
HydraSdr,
Pluto,
RtlSdr,
Soapy,
Uhd,
}
impl FromStr for Driver {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.to_lowercase();
if s == "aaronia_http" || s == "aaronia-http" || s == "aaroniahttp" {
return Ok(Driver::AaroniaHttp);
}
if s == "bladerf" || s == "bladerf1" || s == "BladeRf" {
return Ok(Driver::BladeRf);
}
if s == "rtlsdr" || s == "rtl-sdr" || s == "rtl" {
return Ok(Driver::RtlSdr);
}
if s == "soapy" || s == "soapysdr" {
return Ok(Driver::Soapy);
}
if s == "hackrf" || s == "hackrfone" {
return Ok(Driver::HackRf);
}
if s == "hydrasdr" || s == "hydra-sdr" || s == "hydra" {
return Ok(Driver::HydraSdr);
}
if s == "pluto" || s == "plutosdr" || s == "adalm-pluto" {
return Ok(Driver::Pluto);
}
if s == "uhd" || s == "usrp" {
return Ok(Driver::Uhd);
}
if s == "dummy" || s == "Dummy" {
return Ok(Driver::Dummy);
}
Err(Error::invalid_argument("driver", "unknown driver"))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Direction {
Rx,
Tx,
}
pub fn enumerate() -> Result<Vec<Args>, Error> {
enumerate_with_args(Args::new())
}
pub fn enumerate_with_args<A: TryInto<Args>>(a: A) -> Result<Vec<Args>, Error> {
Ok(Registry::default()
.probe(a)?
.into_iter()
.map(DeviceDescriptor::into_args)
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unsupported_error_displays_backend_reason() {
assert_eq!(
Error::unsupported_reason(
Capability::DriverOperation,
"WebUSB requires a browser window"
)
.to_string(),
"unsupported capability DriverOperation: WebUSB requires a browser window"
);
assert_eq!(
Error::unsupported(Capability::DriverOperation).to_string(),
"unsupported capability DriverOperation"
);
}
#[test]
fn hackrf_driver_aliases_parse() {
for alias in ["hackrf", "hackrfone"] {
assert_eq!(alias.parse::<Driver>().unwrap(), Driver::HackRf);
}
}
#[test]
fn hydrasdr_driver_aliases_parse() {
for alias in ["hydrasdr", "hydra-sdr", "hydra"] {
assert_eq!(alias.parse::<Driver>().unwrap(), Driver::HydraSdr);
}
}
#[test]
fn native_aaronia_driver_is_not_parseable() {
assert!(matches!(
"aaronia".parse::<Driver>(),
Err(Error::InvalidArgument { name, .. }) if name == "driver"
));
}
#[test]
fn aaronia_http_driver_aliases_parse() {
for alias in ["aaronia_http", "aaronia-http", "aaroniahttp"] {
assert_eq!(alias.parse::<Driver>().unwrap(), Driver::AaroniaHttp);
}
}
#[test]
#[cfg(not(all(feature = "hackrf", not(target_arch = "wasm32"))))]
fn hackrf_enumeration_reports_disabled_feature_when_not_enabled() {
assert!(matches!(
enumerate_with_args("driver=hackrf"),
Err(Error::DriverFeatureNotEnabled {
driver: Driver::HackRf
})
));
}
#[test]
#[cfg(not(all(feature = "hackrf", not(target_arch = "wasm32"))))]
fn hackrf_from_args_reports_disabled_feature_when_not_enabled() {
let result = DynDevice::from_args("driver=hackrf");
assert!(matches!(
result,
Err(Error::DriverFeatureNotEnabled {
driver: Driver::HackRf
})
));
}
#[test]
#[cfg(not(all(feature = "hydrasdr", not(target_arch = "wasm32"))))]
fn hydrasdr_enumeration_reports_disabled_feature_when_not_enabled() {
assert!(matches!(
enumerate_with_args("driver=hydrasdr"),
Err(Error::DriverFeatureNotEnabled {
driver: Driver::HydraSdr
})
));
}
#[test]
#[cfg(not(all(feature = "hydrasdr", not(target_arch = "wasm32"))))]
fn hydrasdr_from_args_reports_disabled_feature_when_not_enabled() {
let result = DynDevice::from_args("driver=hydrasdr");
assert!(matches!(
result,
Err(Error::DriverFeatureNotEnabled {
driver: Driver::HydraSdr
})
));
}
}