seify 0.26.2

Shiny Samples from your Rusty SDR
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use super::{
    common::{
        buffer_samples, check_channel, map_error, named, numeric, probe_args, range, Metadata,
        Selector,
    },
    IioContext,
};
use crate::{
    async_compat::Shared, dev::AsyncTypedDeviceBackend, Args, AsyncDeviceInfo, Direction, Driver,
    Error,
};
use crate::{Capability, Range};
use futures::lock::Mutex;
use num_complex::Complex32;
use plutosdr::Device as PlutoDevice;
use plutosdr::RxAttribute;

/// Asynchronous PlutoSDR RX backend, including browser WebUSB.
/// Clones share one USB session and its shutdown state.
#[derive(Clone)]
pub struct AsyncPluto {
    session: Shared<Mutex<Option<PlutoDevice>>>,
    metadata: Shared<Metadata>,
}

impl AsyncPluto {
    /// Probe standard Pluto USB devices already authorized on browser targets.
    pub async fn probe(args: &Args) -> Result<Vec<Args>, Error> {
        let selector = Selector::from_args(args)?;
        let devices = PlutoDevice::list().await.map_err(map_error)?;
        Ok(selector
            .select(devices)
            .map(|(i, d)| probe_args(i, &d))
            .collect())
    }

    /// Open an IIO session and enable hardware DC tracking when supported.
    /// On WebUSB, obtain permission through AsyncRegistry before opening.
    pub async fn open<A: TryInto<Args>>(args: A) -> Result<Self, Error> {
        let args = args
            .try_into()
            .map_err(|_| Error::invalid_argument("args", "failed to convert args"))?;
        let selector = Selector::from_args(&args)?;
        let devices = PlutoDevice::list().await.map_err(map_error)?;
        let (index, descriptor) = selector
            .select(devices)
            .next()
            .ok_or(Error::DeviceNotFound)?;
        let mut device = PlutoDevice::builder()
            .descriptor(descriptor)
            .open()
            .await
            .map_err(map_error)?;
        if device.dc_offset_available() {
            device
                .set_dc_offset_enabled(true)
                .await
                .map_err(map_error)?;
        }
        let metadata = Shared::new(Metadata::from_device(&device, index)?);
        Ok(Self {
            session: Shared::new(Mutex::new(Some(device))),
            metadata,
        })
    }

    /// Cached context; inspecting it performs no USB I/O.
    pub fn context(&self) -> &IioContext {
        &self.metadata.context
    }

    /// Close the session shared by all clones; repeat/retry safely.
    /// Drop all RX stream handles first, including stopped streams, or this returns Busy.
    /// The metadata snapshot remains readable after shutdown.
    pub async fn shutdown(&self) -> Result<(), Error> {
        let mut session = self.session.lock().await;
        if let Some(device) = session.as_mut() {
            device.shutdown().await.map_err(map_error)?;
        }
        *session = None;
        Ok(())
    }
}

impl AsyncDeviceInfo for AsyncPluto {
    fn driver(&self) -> Driver {
        Driver::Pluto
    }
    async fn async_id(&self) -> Result<String, Error> {
        self.metadata.id()
    }
    async fn async_info(&self) -> Result<Args, Error> {
        Ok(self.metadata.args.clone())
    }
    async fn async_num_channels(&self, direction: Direction) -> Result<usize, Error> {
        Ok(usize::from(direction == Direction::Rx))
    }
    async fn async_full_duplex(&self) -> Result<bool, Error> {
        Ok(false)
    }
}

crate::impl_dyn_async_device_backend!(AsyncPluto => [rx, antenna, agc, gain, frequency, sample_rate, bandwidth, dc_offset]);

impl AsyncTypedDeviceBackend for AsyncPluto {
    fn driver() -> Driver {
        Driver::Pluto
    }
    async fn async_probe(args: &Args) -> Result<Vec<Args>, Error> {
        Self::probe(args).await
    }
    async fn async_open(args: &Args) -> Result<Self, Error> {
        Self::open(args.clone()).await
    }

    #[cfg(target_arch = "wasm32")]
    fn webusb_filters(args: &Args) -> Result<Vec<crate::dev::WebUsbDeviceFilter>, Error> {
        use plutosdr::usb::discovery::{PLUTO_PID, PLUTO_VID};
        let mut filter =
            crate::dev::WebUsbDeviceFilter::new().with_vendor_product(PLUTO_VID, PLUTO_PID);
        if let Selector::Serial(serial) = Selector::from_args(args)? {
            filter = filter.with_serial_number(serial);
        }
        Ok(vec![filter])
    }
}

impl AsyncPluto {
    async fn read_setting(
        &self,
        direction: Direction,
        channel: usize,
        attr: RxAttribute,
        available: bool,
    ) -> Result<String, Error> {
        check_channel(direction, channel)?;
        let mut session = self.session.lock().await;
        session
            .as_mut()
            .ok_or(Error::DeviceDisconnected)?
            .read_rx_attribute(attr, available)
            .await
            .map_err(map_error)
    }
    async fn setting_range(
        &self,
        direction: Direction,
        channel: usize,
        attr: RxAttribute,
    ) -> Result<Range, Error> {
        check_channel(direction, channel)?;
        let mut session = self.session.lock().await;
        range(
            session
                .as_mut()
                .ok_or(Error::DeviceDisconnected)?
                .rx_range(attr)
                .await
                .map_err(map_error)?,
        )
    }
    async fn write_setting(
        &self,
        direction: Direction,
        channel: usize,
        attr: RxAttribute,
        value: &str,
    ) -> Result<(), Error> {
        check_channel(direction, channel)?;
        let mut session = self.session.lock().await;
        session
            .as_mut()
            .ok_or(Error::DeviceDisconnected)?
            .set_rx_attribute(attr, value)
            .await
            .map_err(map_error)
    }
}

impl crate::AsyncAntennaControl for AsyncPluto {
    async fn async_antennas(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<String>, Error> {
        Ok(self
            .read_setting(direction, channel, RxAttribute::Port, true)
            .await?
            .split_whitespace()
            .map(str::to_owned)
            .collect())
    }
    async fn async_antenna(&self, direction: Direction, channel: usize) -> Result<String, Error> {
        self.read_setting(direction, channel, RxAttribute::Port, false)
            .await
    }
    async fn async_set_antenna<'a>(
        &'a self,
        direction: Direction,
        channel: usize,
        name: &'a str,
    ) -> Result<(), Error> {
        self.write_setting(direction, channel, RxAttribute::Port, name)
            .await
    }
}

impl crate::AsyncAgcControl for AsyncPluto {
    async fn async_agc_available(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<bool, Error> {
        check_channel(direction, channel)?;
        Ok(true)
    }
    async fn async_agc_enabled(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
        Ok(self
            .read_setting(direction, channel, RxAttribute::GainMode, false)
            .await?
            != "manual")
    }
    async fn async_set_agc_enabled(
        &self,
        direction: Direction,
        channel: usize,
        enabled: bool,
    ) -> Result<(), Error> {
        self.write_setting(
            direction,
            channel,
            RxAttribute::GainMode,
            if enabled { "slow_attack" } else { "manual" },
        )
        .await
    }
}

impl crate::AsyncDcOffsetControl for AsyncPluto {
    async fn async_dc_offset_available(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<bool, Error> {
        check_channel(direction, channel)?;
        let mut session = self.session.lock().await;
        Ok(session
            .as_mut()
            .ok_or(Error::DeviceDisconnected)?
            .dc_offset_available())
    }
    async fn async_dc_offset_enabled(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<bool, Error> {
        check_channel(direction, channel)?;
        let mut session = self.session.lock().await;
        session
            .as_mut()
            .ok_or(Error::DeviceDisconnected)?
            .dc_offset_enabled()
            .await
            .map_err(map_error)
    }
    async fn async_set_dc_offset_enabled(
        &self,
        direction: Direction,
        channel: usize,
        enabled: bool,
    ) -> Result<(), Error> {
        check_channel(direction, channel)?;
        let mut session = self.session.lock().await;
        session
            .as_mut()
            .ok_or(Error::DeviceDisconnected)?
            .set_dc_offset_enabled(enabled)
            .await
            .map_err(map_error)
    }
}

impl crate::AsyncGainControl for AsyncPluto {
    async fn async_gain_elements(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<String>, Error> {
        check_channel(direction, channel)?;
        Ok(vec!["RX".into()])
    }
    async fn async_set_gain(
        &self,
        direction: Direction,
        channel: usize,
        gain: f64,
    ) -> Result<(), Error> {
        self.write_setting(direction, channel, RxAttribute::Gain, &gain.to_string())
            .await
    }
    async fn async_gain(&self, direction: Direction, channel: usize) -> Result<Option<f64>, Error> {
        numeric(
            self.read_setting(direction, channel, RxAttribute::Gain, false)
                .await?,
        )
        .map(Some)
    }
    async fn async_gain_range(&self, direction: Direction, channel: usize) -> Result<Range, Error> {
        self.setting_range(direction, channel, RxAttribute::Gain)
            .await
    }
    async fn async_set_gain_element<'a>(
        &'a self,
        direction: Direction,
        channel: usize,
        name: &'a str,
        gain: f64,
    ) -> Result<(), Error> {
        check_channel(direction, channel)?;
        named(name, "RX")?;
        self.write_setting(direction, channel, RxAttribute::Gain, &gain.to_string())
            .await
    }
    async fn async_gain_element<'a>(
        &'a self,
        direction: Direction,
        channel: usize,
        name: &'a str,
    ) -> Result<Option<f64>, Error> {
        check_channel(direction, channel)?;
        named(name, "RX")?;
        numeric(
            self.read_setting(direction, channel, RxAttribute::Gain, false)
                .await?,
        )
        .map(Some)
    }
    async fn async_gain_element_range<'a>(
        &'a self,
        direction: Direction,
        channel: usize,
        name: &'a str,
    ) -> Result<Range, Error> {
        check_channel(direction, channel)?;
        named(name, "RX")?;
        self.setting_range(direction, channel, RxAttribute::Gain)
            .await
    }
}

impl crate::AsyncFrequencyControl for AsyncPluto {
    async fn async_frequency_range(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Range, Error> {
        self.setting_range(direction, channel, RxAttribute::Frequency)
            .await
    }
    async fn async_frequency(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        numeric(
            self.read_setting(direction, channel, RxAttribute::Frequency, false)
                .await?,
        )
    }
    async fn async_set_frequency(
        &self,
        direction: Direction,
        channel: usize,
        frequency: f64,
        args: Args,
    ) -> Result<(), Error> {
        check_channel(direction, channel)?;
        if !args.map().is_empty() {
            return Err(Error::invalid_argument(
                "args",
                "Pluto tuning arguments are unsupported",
            ));
        }
        self.write_setting(
            direction,
            channel,
            RxAttribute::Frequency,
            &frequency.to_string(),
        )
        .await
    }
    async fn async_frequency_components(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<String>, Error> {
        check_channel(direction, channel)?;
        Ok(vec!["RF".into()])
    }
    async fn async_component_frequency_range<'a>(
        &'a self,
        direction: Direction,
        channel: usize,
        name: &'a str,
    ) -> Result<Range, Error> {
        check_channel(direction, channel)?;
        named(name, "RF")?;
        self.setting_range(direction, channel, RxAttribute::Frequency)
            .await
    }
    async fn async_component_frequency<'a>(
        &'a self,
        direction: Direction,
        channel: usize,
        name: &'a str,
    ) -> Result<f64, Error> {
        check_channel(direction, channel)?;
        named(name, "RF")?;
        numeric(
            self.read_setting(direction, channel, RxAttribute::Frequency, false)
                .await?,
        )
    }
    async fn async_set_component_frequency<'a>(
        &'a self,
        direction: Direction,
        channel: usize,
        name: &'a str,
        frequency: f64,
    ) -> Result<(), Error> {
        check_channel(direction, channel)?;
        named(name, "RF")?;
        self.write_setting(
            direction,
            channel,
            RxAttribute::Frequency,
            &frequency.to_string(),
        )
        .await
    }
}

impl crate::AsyncSampleRateControl for AsyncPluto {
    async fn async_sample_rate(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        numeric(
            self.read_setting(direction, channel, RxAttribute::SampleRate, false)
                .await?,
        )
    }
    async fn async_set_sample_rate(
        &self,
        direction: Direction,
        channel: usize,
        rate: f64,
    ) -> Result<(), Error> {
        self.write_setting(
            direction,
            channel,
            RxAttribute::SampleRate,
            &rate.to_string(),
        )
        .await
    }
    async fn async_get_sample_rate_range(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Range, Error> {
        self.setting_range(direction, channel, RxAttribute::SampleRate)
            .await
    }
}

impl crate::AsyncBandwidthControl for AsyncPluto {
    async fn async_bandwidth(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        numeric(
            self.read_setting(direction, channel, RxAttribute::Bandwidth, false)
                .await?,
        )
    }
    async fn async_set_bandwidth(
        &self,
        direction: Direction,
        channel: usize,
        bandwidth: f64,
    ) -> Result<(), Error> {
        self.write_setting(
            direction,
            channel,
            RxAttribute::Bandwidth,
            &bandwidth.to_string(),
        )
        .await
    }
    async fn async_get_bandwidth_range(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Range, Error> {
        self.setting_range(direction, channel, RxAttribute::Bandwidth)
            .await
    }
}

/// A single-channel Pluto RX stream owning its independent USB pipe.
pub struct AsyncPlutoRxStreamer {
    inner: plutosdr::RxStream,
}
impl crate::AsyncRxDevice for AsyncPluto {
    type RxStreamer = AsyncPlutoRxStreamer;
    async fn async_rx_streamer(
        &self,
        channels: &[usize],
        args: Args,
    ) -> Result<Self::RxStreamer, Error> {
        let samples = buffer_samples(channels, &args)?;
        let mut session = self.session.lock().await;
        let inner = session
            .as_mut()
            .ok_or(Error::DeviceDisconnected)?
            .rx_stream_with_buffer(samples)
            .map_err(map_error)?;
        Ok(AsyncPlutoRxStreamer { inner })
    }
}
impl crate::AsyncRxStreamer for AsyncPlutoRxStreamer {
    async fn mtu(&self) -> Result<usize, Error> {
        Ok(self.inner.mtu())
    }
    async fn activate_at(&mut self, time_ns: Option<i64>) -> Result<(), Error> {
        if time_ns.is_some() {
            return Err(Error::unsupported(Capability::TimedActivation));
        }
        self.inner.start().await.map_err(map_error)
    }
    async fn deactivate_at(&mut self, time_ns: Option<i64>) -> Result<(), Error> {
        if time_ns.is_some() {
            return Err(Error::unsupported(Capability::TimedDeactivation));
        }
        self.inner.stop().await.map_err(map_error)
    }
    async fn read<'a>(
        &'a mut self,
        buffers: &'a mut [&'a mut [Complex32]],
        timeout_us: i64,
    ) -> Result<usize, Error> {
        crate::streamer::expect_buffer_count(buffers.len(), 1)?;
        let timeout = if timeout_us < 0 {
            None
        } else {
            Some(std::time::Duration::from_micros(timeout_us as u64))
        };
        self.inner
            .read(buffers[0], timeout)
            .await
            .map_err(map_error)
    }
}