Skip to main content

rtlsdr_nusb/
device.rs

1//! Device discovery, configuration and shared hardware ownership.
2use crate::{
3    DeviceDescriptor, DirectSampling, GainConfig, Result, TunerKind,
4    config::{Config, ConfigBuilder, F32Iq, RawIq, SampleMode},
5    discovery::Selector,
6    maybe_future::{MaybeFutureExt, ready},
7    rtl2832u::Applied,
8    rx::RxStream,
9    session::{RxStreamClaim, Session},
10    usb::NusbTransport,
11};
12use nusb::MaybeFuture;
13use std::sync::Arc;
14
15/// Immutable identity captured during device initialization.
16#[derive(Clone, Debug, Eq, PartialEq)]
17pub struct DeviceInfo {
18    /// USB identity.
19    pub descriptor: DeviceDescriptor,
20    /// Detected tuner family.
21    pub tuner: TunerKind,
22    /// Whether USB branding identifies an RTL-SDR Blog V4.
23    pub rtl_sdr_blog_v4: bool,
24}
25
26/// Owned device handle with a separately owned receive stream.
27/// Dropping the handle does not interrupt an outstanding stream, even if stopped.
28#[derive(Debug)]
29pub struct Device<M: SampleMode = F32Iq> {
30    session: Arc<Session>,
31    config: Config<M>,
32    applied: Applied,
33}
34impl Device<F32Iq> {
35    /// List visible receivers with the standard Realtek USB IDs, without opening them.
36    pub fn list() -> impl MaybeFuture<Output = Result<Vec<DeviceDescriptor>>> {
37        crate::discovery::list()
38    }
39    /// Start a device builder with default configuration.
40    pub fn builder() -> DeviceBuilder {
41        DeviceBuilder::default()
42    }
43    /// Open the first visible receiver with default configuration.
44    pub fn open() -> impl MaybeFuture<Output = Result<Self>> {
45        Self::builder().open()
46    }
47    /// Open a device by its exact USB serial string.
48    pub fn open_serial(serial: impl Into<String>) -> impl MaybeFuture<Output = Result<Self>> {
49        Self::builder().serial(serial).open()
50    }
51    /// Ask for browser WebUSB permission from a user gesture, without opening the receiver.
52    #[cfg(target_arch = "wasm32")]
53    pub async fn request_permission() -> Result<()> {
54        Self::builder().request_permission().await
55    }
56}
57impl<M: SampleMode> Device<M> {
58    /// Immutable device metadata.
59    pub fn info(&self) -> &DeviceInfo {
60        self.session.info.get().expect("initialized metadata")
61    }
62    /// Last successfully applied configuration. A failed/canceled configuration
63    /// leaves this snapshot unchanged and requires a complete `configure` retry.
64    pub fn config(&self) -> &Config<M> {
65        &self.config
66    }
67    /// Last successfully programmed center frequency after divider quantization.
68    pub fn actual_frequency_hz(&self) -> u64 {
69        self.applied.frequency_hz
70    }
71    /// Last successfully programmed complex sample rate after divider quantization.
72    pub fn actual_sample_rate_hz(&self) -> u32 {
73        self.applied.sample_rate_hz
74    }
75    /// Apply a complete configuration. This also recovers from a failed or canceled
76    /// control operation. Controls are serialized; overlapping operations from a
77    /// stream return [`crate::Error::Busy`] and can be retried.
78    ///
79    /// Queued samples may predate a live configuration change. Stop and restart
80    /// the stream when the caller needs previously queued samples discarded.
81    pub fn configure(&mut self, config: &Config<M>) -> impl MaybeFuture<Output = Result<()>> + '_ {
82        self.update(config.clone())
83    }
84    fn update(&mut self, proposed: Config<M>) -> impl MaybeFuture<Output = Result<()>> + '_ {
85        ready(proposed.settings.validate()).and_then(move |_| {
86            self.session
87                .configure(proposed.settings.clone())
88                .map(move |result| {
89                    self.applied = result?;
90                    self.config = proposed;
91                    Ok(())
92                })
93        })
94    }
95    /// Tune the center frequency in Hz, preserving other settings.
96    pub fn set_frequency_hz(&mut self, hz: u64) -> impl MaybeFuture<Output = Result<()>> + '_ {
97        let mut config = self.config.clone();
98        config.settings.frequency_hz = hz;
99        self.update(config)
100    }
101    /// Set complex sample rate, preserving other settings.
102    pub fn set_sample_rate_hz(&mut self, hz: u32) -> impl MaybeFuture<Output = Result<()>> + '_ {
103        let mut config = self.config.clone();
104        config.settings.sample_rate_hz = hz;
105        self.update(config)
106    }
107    /// Change tuner gain policy, preserving other settings.
108    pub fn set_gain(&mut self, gain: GainConfig) -> impl MaybeFuture<Output = Result<()>> + '_ {
109        let mut config = self.config.clone();
110        config.settings.gain = gain;
111        self.update(config)
112    }
113    /// Correct the sampling clock and reapply tuning with the corrected crystal frequency.
114    pub fn set_correction_ppm(&mut self, ppm: i32) -> impl MaybeFuture<Output = Result<()>> + '_ {
115        let mut config = self.config.clone();
116        config.settings.correction_ppm = ppm;
117        self.update(config)
118    }
119    /// Enable or disable GPIO 0 bias power, preserving other settings.
120    pub fn set_bias_tee(&mut self, enabled: bool) -> impl MaybeFuture<Output = Result<()>> + '_ {
121        let mut config = self.config.clone();
122        config.settings.bias_tee = enabled;
123        self.update(config)
124    }
125    /// Set low-frequency direct sampling policy, preserving other settings.
126    pub fn set_direct_sampling(
127        &mut self,
128        mode: DirectSampling,
129    ) -> impl MaybeFuture<Output = Result<()>> + '_ {
130        let mut config = self.config.clone();
131        config.settings.direct_sampling = mode;
132        self.update(config)
133    }
134    /// Claim the single receive stream. The stream starts only when `start` is
135    /// waited/awaited. Dormant and stopped streams retain the claim until close/drop.
136    pub fn rx_stream(&self) -> Result<RxStream<M>> {
137        self.session.ensure_configured()?;
138        Ok(RxStream::new(RxStreamClaim::acquire(&self.session)?))
139    }
140    /// Stop the hardware and disable RF bias power.
141    ///
142    /// Returns Busy without changing lifecycle while a stream claim is held.
143    /// Close/drop the stream first. Unpolled shutdown has no effects; once begun,
144    /// shutdown is terminal, idempotent after success, and retryable on failure or
145    /// cancellation. All independent cleanup steps are attempted on error.
146    ///
147    /// Final-owner Drop performs the same cleanup best-effort, blocking on native
148    /// targets and scheduling a background task on WebUSB. Explicit shutdown is
149    /// required to observe cleanup errors/completion.
150    pub fn shutdown(&mut self) -> impl MaybeFuture<Output = Result<()>> + '_ {
151        self.session.shutdown()
152    }
153}
154
155/// Select and configure a receiver. Standard IDs are `0bda:2832` and `0bda:2838`.
156#[derive(Clone, Debug)]
157pub struct DeviceBuilder<M: SampleMode = F32Iq> {
158    selector: Selector,
159    config: ConfigBuilder<M>,
160}
161impl Default for DeviceBuilder<F32Iq> {
162    fn default() -> Self {
163        Self {
164            selector: Selector::default(),
165            config: ConfigBuilder::default(),
166        }
167    }
168}
169impl<M: SampleMode> DeviceBuilder<M> {
170    /// Select by exact serial; this replaces a previously chosen index.
171    pub fn serial(mut self, serial: impl Into<String>) -> Self {
172        self.selector.serial = Some(serial.into());
173        self.selector.index = None;
174        self
175    }
176    /// Select by enumeration index; this replaces a previously chosen serial.
177    pub fn index(mut self, index: usize) -> Self {
178        self.selector.index = Some(index);
179        self.selector.serial = None;
180        self
181    }
182    /// Match a custom USB VID/PID instead of the standard Realtek IDs.
183    pub fn usb_id(mut self, vid: u16, pid: u16) -> Self {
184        self.selector.usb_id = Some((vid, pid));
185        self
186    }
187    /// Set center frequency in Hz.
188    pub fn frequency_hz(mut self, value: u64) -> Self {
189        self.config = self.config.frequency_hz(value);
190        self
191    }
192    /// Set complex sample rate in samples/s.
193    pub fn sample_rate_hz(mut self, value: u32) -> Self {
194        self.config = self.config.sample_rate_hz(value);
195        self
196    }
197    /// Set gain policy.
198    pub fn gain(mut self, value: GainConfig) -> Self {
199        self.config = self.config.gain(value);
200        self
201    }
202    /// Set crystal correction in ppm.
203    pub fn correction_ppm(mut self, value: i32) -> Self {
204        self.config = self.config.correction_ppm(value);
205        self
206    }
207    /// Enable or disable RF bias power.
208    pub fn bias_tee(mut self, value: bool) -> Self {
209        self.config = self.config.bias_tee(value);
210        self
211    }
212    /// Select low-frequency direct sampling behavior.
213    pub fn direct_sampling(mut self, value: DirectSampling) -> Self {
214        self.config = self.config.direct_sampling(value);
215        self
216    }
217    /// Validate the configuration without opening hardware.
218    pub fn config(self) -> Result<Config<M>> {
219        self.config.build()
220    }
221    /// Validate, open, probe, and configure the selected receiver.
222    /// After interface claim, failure/cancellation arms final-owner cleanup.
223    pub fn open(self) -> impl MaybeFuture<Output = Result<Device<M>>> {
224        ready(self.config.build()).and_then(move |config| {
225            NusbTransport::open(self.selector).and_then(move |(control, descriptor)| {
226                Session::initialize(control, descriptor, config.settings.clone()).map_ok(
227                    move |(session, applied)| Device {
228                        session,
229                        config,
230                        applied,
231                    },
232                )
233            })
234        })
235    }
236    /// Request WebUSB permission from a browser user gesture. Opening afterwards
237    /// can take place in either a Window or a Worker and never prompts.
238    #[cfg(target_arch = "wasm32")]
239    pub async fn request_permission(&self) -> Result<()> {
240        crate::discovery::request_permission(&self.selector).await
241    }
242}
243impl DeviceBuilder<F32Iq> {
244    /// Select raw unsigned eight-bit I/Q blocks instead of converted floats.
245    pub fn raw_iq(self) -> DeviceBuilder<RawIq> {
246        DeviceBuilder {
247            selector: self.selector,
248            config: self.config.raw_iq(),
249        }
250    }
251}