rustradio 0.16.4

Software defined radio library
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
//! SoapySDR source.
use std::collections::{HashMap, HashSet};
use std::sync::LazyLock;

use log::{debug, trace};

use crate::block::{Block, BlockRet};
use crate::stream::{ReadStream, Tag, TagValue, WriteStream};
use crate::{Complex, Error, Float, Result};

// Sensors and time_ns are re-read this often.
const TIME_TAG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);

enum SensorType {
    Float,
    U64,
    Bool,
}

// Allowlist of sensors that don't accidentally reveal secrets.
static ALLOWED_SENSORS: LazyLock<HashSet<&str>> = LazyLock::new(|| {
    ["gps_time", "gps_locked", "ref_locked", "lo_locked"]
        .into_iter()
        .collect()
});

// If GPS tags are enabled, these are the sensor names.
//
// Should not be enabled by default, since they can be sensitive.
static POSITION_SENSORS: LazyLock<HashSet<&str>> = LazyLock::new(|| {
    ["gps_gpgga", "gps_gprmc", "gps_servo"]
        .into_iter()
        .collect()
});

// If tag is not listed, or fails to parse, then it defaults to String.
static SENSOR_TYPE: LazyLock<HashMap<&str, SensorType>> = LazyLock::new(|| {
    [
        ("temp", SensorType::Float),
        ("rssi", SensorType::Float),
        ("gps_time", SensorType::U64),
        ("ref_locked", SensorType::Bool),
        ("gps_locked", SensorType::Bool),
        ("lo_locked", SensorType::Bool),
    ]
    .into_iter()
    .collect()
});

// Turn a tag value into a typed TagValue. Defaults to String if unknown or
// failing to parse.
fn make_sensor_tag(tag: &str, val: &str) -> TagValue {
    match SENSOR_TYPE.get(tag) {
        Some(SensorType::Float) => val
            .parse::<Float>()
            .map(TagValue::Float)
            .unwrap_or_else(|e| {
                trace!("Failed to parse sensor tag {tag} value {val} as float: {e}");
                TagValue::String(val.to_string())
            }),
        Some(SensorType::U64) => val.parse::<u64>().map(TagValue::U64).unwrap_or_else(|e| {
            trace!("Failed to parse sensor tag {tag} value {val} as u64: {e}");
            TagValue::String(val.to_string())
        }),
        Some(SensorType::Bool) => val.parse::<bool>().map(TagValue::Bool).unwrap_or_else(|e| {
            trace!("Failed to parse sensor tag {tag} value {val} as bool: {e}");
            TagValue::String(val.to_string())
        }),
        None => TagValue::String(val.to_string()),
    }
}

impl From<soapysdr::Error> for Error {
    fn from(e: soapysdr::Error) -> Self {
        Error::device(e, "soapysdr")
    }
}

/// SoapySDR source builder.
#[must_use]
pub struct SoapySdrSourceBuilder<'a> {
    dev: &'a soapysdr::Device,
    antenna: Option<String>,
    channel: usize,
    igain: f64,
    samp_rate: f64,
    freq: f64,
    gps_coords: bool,
}

macro_rules! log_and_tag {
    ($tags:ident, $expr:expr, $tag_key:expr) => {
        match $expr {
            Ok(s) => {
                debug!("SoapySDR RX {}: {s}", $tag_key);
                $tags.push(Tag::new(
                    0,
                    concat!("SoapySdrSource::", $tag_key),
                    TagValue::String(s),
                ));
            }
            Err(e) => debug!("SoapySDR RX {} error: {e}", $tag_key),
        }
    };
}

impl SoapySdrSourceBuilder<'_> {
    /// Set channel number.
    pub fn channel(mut self, channel: usize) -> Self {
        self.channel = channel;
        self
    }
    /// Set input gain.
    ///
    /// Normalized to 0.0 to 1.0.
    pub fn igain(mut self, igain: f64) -> Self {
        self.igain = igain;
        self
    }
    /// Set antenna.
    pub fn antenna<T: Into<String>>(mut self, a: T) -> Self {
        self.antenna = Some(a.into());
        self
    }
    /// Set whether to generate GPS coordinate tags.
    pub fn gps_coordinates(mut self, v: bool) -> Self {
        self.gps_coords = v;
        self
    }
    /// Build the source object.
    pub fn build(self) -> Result<(SoapySdrSource, ReadStream<Complex>)> {
        let mut tags = vec![
            Tag::new(
                0,
                "SoapySdrSource::channel",
                TagValue::U64(self.channel as u64),
            ),
            Tag::new(
                0,
                "SoapySdrSource::input_gain",
                TagValue::Float(self.igain as Float),
            ),
            Tag::new(
                0,
                "SoapySdrSource::frequency",
                TagValue::Float(self.freq as Float),
            ),
            Tag::new(
                0,
                "SoapySdrSource::sample_rate",
                TagValue::Float(self.samp_rate as Float),
            ),
        ];
        log_and_tag!(tags, self.dev.driver_key(), "driver");
        log_and_tag!(tags, self.dev.hardware_key(), "hardware");
        // Hardware info has serial numbers.
        debug!("SoapySDR RX hardware info: {}", self.dev.hardware_info()?);
        log_and_tag!(
            tags,
            self.dev.frontend_mapping(soapysdr::Direction::Rx),
            "frontend_mapping"
        );
        log_and_tag!(tags, self.dev.get_clock_source(), "clock_source");
        log_and_tag!(tags, self.dev.get_time_source(), "time_source");
        let allowed_sensors = {
            let mut a = ALLOWED_SENSORS.clone();
            if self.gps_coords {
                a.extend(&*POSITION_SENSORS);
            }
            a
        };
        for sensor in self.dev.list_sensors()? {
            debug!(
                "SoapySDR RX sensor {sensor}: {:?}",
                self.dev.get_sensor_info(&sensor)?
            );
            let read = self.dev.read_sensor(&sensor)?.to_string();
            debug!("SoapySDR RX sensor {sensor}: {read:?}");
        }
        debug!(
            "SoapySDR RX clock sources: {:?}",
            self.dev.list_clock_sources()?
        );
        debug!(
            "SoapySDR RX time sources: {:?}",
            self.dev.list_time_sources()?
        );
        if let Ok(t) = self.dev.get_hardware_time(None) {
            tags.push(Tag::new(
                0,
                "SoapySdrSource::hardware_time",
                TagValue::I64(t),
            ));
        }
        let chans = self.dev.num_channels(soapysdr::Direction::Rx)?;
        debug!("SoapySDR RX channels : {chans}");
        for channel in 0..chans {
            for sensor in self
                .dev
                .list_channel_sensors(soapysdr::Direction::Rx, channel)?
            {
                match self
                    .dev
                    .read_channel_sensor(soapysdr::Direction::Rx, channel, &sensor)
                {
                    Ok(s) => debug!("SoapySDR RX channel {channel} sensor {sensor}: {s}"),
                    Err(e) => debug!("SoapySDR RX channel {channel} sensor {sensor} error: {e}"),
                }
            }
            debug!(
                "SoapySDR RX channel {channel} antennas: {:?}",
                self.dev.antennas(soapysdr::Direction::Rx, channel)?
            );
            debug!(
                "SoapySDR RX channel {channel} gains: {:?}",
                self.dev.list_gains(soapysdr::Direction::Rx, channel)?
            );
            debug!(
                "SoapySDR RX channel {channel} gain range: {:?}",
                self.dev.gain_range(soapysdr::Direction::Rx, channel)?
            );
            debug!(
                "SoapySDR RX channel {channel} frequency range: {:?}",
                self.dev.frequency_range(soapysdr::Direction::Rx, channel)?
            );
            for ai in self
                .dev
                .stream_args_info(soapysdr::Direction::Rx, channel)?
            {
                debug!("SoapySDR RX channel {channel} arg info: {}", ai_string(&ai));
            }
            debug!(
                "SoapySDR RX channel {channel} stream formats: {:?}",
                self.dev.stream_formats(soapysdr::Direction::Rx, channel)?
            );
            debug!(
                "SoapySDR RX channel {channel} info: {}",
                self.dev.channel_info(soapysdr::Direction::Rx, channel)?
            );
        }
        self.dev.set_frequency(
            soapysdr::Direction::Rx,
            self.channel,
            self.freq,
            soapysdr::Args::new(),
        )?;
        self.dev
            .set_sample_rate(soapysdr::Direction::Rx, self.channel, self.samp_rate)?;
        let gr = self.dev.gain_range(soapysdr::Direction::Rx, self.channel)?;
        let gain = gr.minimum + self.igain * (gr.maximum - gr.minimum);
        debug!(
            "SoapySdrSource: input gain {} in range {}-{} became {gain}",
            self.igain, gr.minimum, gr.maximum
        );
        self.dev
            .set_gain(soapysdr::Direction::Rx, self.channel, gain)?;
        if let Some(a) = self.antenna {
            // TODO: set antenna even if not specified.
            tags.push(Tag::new(
                0,
                "SoapySdrSource::antenna",
                TagValue::String(a.clone()),
            ));
            self.dev
                .set_antenna(soapysdr::Direction::Rx, self.channel, a)?;
        }
        let mut stream = self.dev.rx_stream(&[self.channel])?;
        stream.activate(None)?;
        let (dst, dr) = crate::stream::new_stream();
        Ok((
            SoapySdrSource {
                dev: self.dev.clone(),
                channel: self.channel,
                allowed_sensors,
                stream,
                dst,
                tags,
                last_time_tag: None,
            },
            dr,
        ))
    }
}

/// SoapySDR source.
#[derive(rustradio_macros::Block)]
#[rustradio(crate)]
pub struct SoapySdrSource {
    dev: soapysdr::Device,
    channel: usize,
    allowed_sensors: HashSet<&'static str>,
    stream: soapysdr::RxStream<Complex>,
    #[rustradio(out)]
    dst: WriteStream<Complex>,
    #[rustradio(default)]
    tags: Vec<Tag>,

    #[rustradio(default)]
    last_time_tag: Option<std::time::Instant>,
}

impl SoapySdrSource {
    /// Create new SoapySdrSource builder.
    pub fn builder(dev: &soapysdr::Device, freq: f64, samp_rate: f64) -> SoapySdrSourceBuilder<'_> {
        SoapySdrSourceBuilder {
            dev,
            freq,
            samp_rate,
            channel: 0,
            igain: 0.5,
            antenna: None,
            gps_coords: false,
        }
    }
    fn add_sensor_tags(&mut self) -> Result<()> {
        self.dev
            .list_sensors()?
            .into_iter()
            .filter(|sensor| {
                let s: &str = sensor;
                self.allowed_sensors.contains(s)
            })
            .map(|sensor| {
                self.dev.read_sensor(&sensor).map(|s| {
                    self.tags.push(Tag::new(
                        0,
                        format!("SoapySdrSource::sensor_{sensor}"),
                        make_sensor_tag(&sensor, &s),
                    ));
                })
            })
            .for_each(|r| {
                if let Err(e) = r {
                    debug!("SoapySdrSource failed to attach sensor tags: {e}");
                }
            });
        Ok(())
    }
    fn add_channel_sensor_tags(&mut self) -> Result<()> {
        self.dev
            .list_channel_sensors(soapysdr::Direction::Rx, self.channel)?
            .into_iter()
            .filter(|sensor| {
                let s: &str = sensor;
                self.allowed_sensors.contains(s)
            })
            .map(|sensor| {
                (
                    sensor.clone(),
                    self.dev
                        .read_channel_sensor(soapysdr::Direction::Rx, self.channel, &sensor)
                        .map(|s| {
                            self.tags.push(Tag::new(
                                0,
                                format!("SoapySdrSource::sensor_channel_{sensor}"),
                                make_sensor_tag(&sensor, &s),
                            ));
                        }),
                )
            })
            .for_each(|r| {
                if let (s, Err(e)) = r {
                    debug!("SoapySdrSource failed to attach channel sensor tag {s}: {e}");
                }
            });
        Ok(())
    }
}

fn ai_string(ai: &soapysdr::ArgInfo) -> String {
    format!(
        "key={} value={} name={:?} descr={:?} units={:?} data_type={:?} options={:?}",
        ai.key, ai.value, ai.name, ai.description, ai.units, ai.data_type, ai.options
    )
}

impl Block for SoapySdrSource {
    fn work(&mut self) -> Result<BlockRet<'_>> {
        let timeout_us = 10_000;
        let mut o = self.dst.write_buf()?;
        let n = match self.stream.read(&mut [&mut o.slice()], timeout_us) {
            Ok(x) => x,
            Err(e) => {
                if e.code == soapysdr::ErrorCode::Timeout {
                    return Ok(BlockRet::Again);
                }
                return Err(e.into());
            }
        };
        if n > 0 {
            if match self.last_time_tag {
                None => true,
                Some(x) if x.elapsed() > TIME_TAG_INTERVAL => true,
                _ => false,
            } {
                let time_ns = self.stream.time_ns();
                self.tags.push(Tag::new(
                    0,
                    "SoapySdrSource::time_ns",
                    TagValue::I64(time_ns),
                ));
                if let Err(e) = self.add_sensor_tags() {
                    debug!("SoapySdrSource failed to attach sensor tags: {e}");
                }
                if let Err(e) = self.add_channel_sensor_tags() {
                    debug!("SoapySdrSource failed to attach channel sensor tags: {e}");
                }
                self.last_time_tag = Some(std::time::Instant::now());
            }
            // Tags are always with offset zero.
            o.produce(n, &self.tags);
            self.tags.clear();
        }
        Ok(BlockRet::Again)
    }
}