Skip to main content

rtlsdr_nusb/
discovery.rs

1//! Device enumeration, selection, and USB identity completion.
2use crate::maybe_future::{Either, MaybeFutureExt, NonWasmSend, ready};
3use crate::{Error, Result};
4use nusb::MaybeFuture;
5use std::num::NonZeroU8;
6
7/// USB identity collected during enumeration and completed during open.
8#[derive(Clone, Debug, Eq, PartialEq)]
9pub struct DeviceDescriptor {
10    /// Index among currently visible devices with the selected USB IDs.
11    pub index: usize,
12    /// USB vendor ID.
13    pub vid: u16,
14    /// USB product ID.
15    pub pid: u16,
16    /// Device serial string, when the OS/browser supplies it.
17    pub serial: Option<String>,
18    /// Manufacturer string, when available.
19    pub manufacturer: Option<String>,
20    /// Product string, when available.
21    pub product: Option<String>,
22}
23impl DeviceDescriptor {
24    pub(crate) fn from_nusb(index: usize, info: &nusb::DeviceInfo) -> Self {
25        Self {
26            index,
27            vid: info.vendor_id(),
28            pid: info.product_id(),
29            serial: info.serial_number().map(str::to_owned),
30            manufacturer: info.manufacturer_string().map(str::to_owned),
31            product: info.product_string().map(str::to_owned),
32        }
33    }
34    pub(crate) fn blog_v4(&self) -> bool {
35        self.manufacturer.as_deref() == Some("RTLSDRBlog")
36            && self.product.as_deref() == Some("Blog V4")
37    }
38    pub(crate) fn read_missing_strings<F, M>(
39        mut self,
40        manufacturer_index: Option<NonZeroU8>,
41        product_index: Option<NonZeroU8>,
42        mut read: F,
43    ) -> impl MaybeFuture<Output = Self>
44    where
45        F: FnMut(NonZeroU8) -> M + NonWasmSend,
46        M: MaybeFuture<Output = Option<String>>,
47    {
48        ready(()).continue_with(move |()| {
49            let manufacturer = match manufacturer_index.filter(|_| self.manufacturer.is_none()) {
50                Some(index) => Either::left(read(index)),
51                None => Either::right(ready(None)),
52            };
53            manufacturer.continue_with(move |value| {
54                self.manufacturer = self.manufacturer.or(value);
55                let product = match product_index.filter(|_| self.product.is_none()) {
56                    Some(index) => Either::left(read(index)),
57                    None => Either::right(ready(None)),
58                };
59                product.map(move |value| {
60                    self.product = self.product.or(value);
61                    self
62                })
63            })
64        })
65    }
66}
67
68#[derive(Clone, Debug, Default)]
69pub(crate) struct Selector {
70    pub index: Option<usize>,
71    pub serial: Option<String>,
72    pub usb_id: Option<(u16, u16)>,
73}
74impl Selector {
75    pub(crate) fn matches_id(&self, vid: u16, pid: u16) -> bool {
76        self.usb_id
77            .map_or(vid == 0x0bda && matches!(pid, 0x2832 | 0x2838), |pair| {
78                pair == (vid, pid)
79            })
80    }
81    fn matches(&self, index: usize, info: &nusb::DeviceInfo) -> bool {
82        self.index.is_none_or(|i| i == index)
83            && self
84                .serial
85                .as_deref()
86                .is_none_or(|s| info.serial_number() == Some(s))
87    }
88}
89pub(crate) fn list() -> impl MaybeFuture<Output = Result<Vec<DeviceDescriptor>>> {
90    nusb::list_devices().map(|devices| {
91        Ok(devices?
92            .filter(|d| Selector::default().matches_id(d.vendor_id(), d.product_id()))
93            .enumerate()
94            .map(|(i, d)| DeviceDescriptor::from_nusb(i, &d))
95            .collect())
96    })
97}
98pub(crate) fn select(
99    selector: Selector,
100) -> impl MaybeFuture<Output = Result<(DeviceDescriptor, nusb::DeviceInfo)>> {
101    nusb::list_devices().map(move |devices| {
102        devices?
103            .filter(|d| selector.matches_id(d.vendor_id(), d.product_id()))
104            .enumerate()
105            .find(|(i, d)| selector.matches(*i, d))
106            .map(|(i, d)| (DeviceDescriptor::from_nusb(i, &d), d))
107            .ok_or(Error::DeviceNotFound)
108    })
109}
110#[cfg(target_arch = "wasm32")]
111pub(crate) async fn request_permission(selector: &Selector) -> Result<()> {
112    let pairs = selector
113        .usb_id
114        .map_or_else(|| vec![(0x0bda, 0x2832), (0x0bda, 0x2838)], |p| vec![p]);
115    let selectors: Vec<_> = pairs
116        .into_iter()
117        .map(|(vid, pid)| {
118            let mut filter = nusb::DeviceSelector::all().with_vid_pid(vid, pid);
119            if let Some(serial) = &selector.serial {
120                filter = filter.with_serial_number(serial.clone());
121            }
122            filter
123        })
124        .collect();
125    nusb::request_device(&selectors)
126        .await?
127        .ok_or(Error::DeviceNotFound)?;
128    Ok(())
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use std::{
135        future::IntoFuture,
136        sync::{Arc, Mutex},
137    };
138
139    fn descriptor(manufacturer: Option<&str>, product: Option<&str>) -> DeviceDescriptor {
140        DeviceDescriptor {
141            index: 0,
142            vid: 0x0bda,
143            pid: 0x2838,
144            serial: Some("00000001".into()),
145            manufacturer: manufacturer.map(str::to_owned),
146            product: product.map(str::to_owned),
147        }
148    }
149
150    #[test]
151    fn missing_windows_manufacturer_is_read_lazily_and_enables_v4() {
152        let reads = Arc::new(Mutex::new(Vec::new()));
153        let observed = reads.clone();
154        let operation = descriptor(None, Some("Blog V4")).read_missing_strings(
155            NonZeroU8::new(1),
156            NonZeroU8::new(2),
157            move |index| {
158                observed.lock().unwrap().push(index.get());
159                ready(Some("RTLSDRBlog".into()))
160            },
161        );
162        assert!(reads.lock().unwrap().is_empty());
163        let result = operation.wait();
164        assert!(result.blog_v4());
165        assert_eq!(result.serial.as_deref(), Some("00000001"));
166        assert_eq!(*reads.lock().unwrap(), [1]);
167    }
168
169    #[test]
170    fn async_open_recovers_both_branding_strings() {
171        let result = futures_lite::future::block_on(
172            descriptor(None, None)
173                .read_missing_strings(NonZeroU8::new(1), NonZeroU8::new(2), |index| {
174                    ready(Some(
175                        match index.get() {
176                            1 => "RTLSDRBlog",
177                            2 => "Blog V4",
178                            _ => unreachable!(),
179                        }
180                        .into(),
181                    ))
182                })
183                .into_future(),
184        );
185        assert!(result.blog_v4());
186    }
187
188    #[test]
189    fn cached_absent_and_unreadable_strings_do_not_fabricate_v4_branding() {
190        let cached = descriptor(Some("Other"), Some("Blog V4"));
191        let mut reads = 0;
192        let result = cached
193            .clone()
194            .read_missing_strings(NonZeroU8::new(1), NonZeroU8::new(2), |_| {
195                reads += 1;
196                ready(None)
197            })
198            .wait();
199        assert_eq!(result, cached);
200        assert_eq!(reads, 0);
201        let result = descriptor(None, None)
202            .read_missing_strings(None, NonZeroU8::new(2), |index| {
203                assert_eq!(index.get(), 2);
204                ready(None)
205            })
206            .wait();
207        assert!(!result.blog_v4());
208        assert_eq!(result.manufacturer, None);
209        assert_eq!(result.product, None);
210    }
211}