Skip to main content

hydrasdr_rs/
config.rs

1//! Receiver configuration.
2
3use crate::errors::{Error, Result};
4use crate::rfone::{
5    RFONE_F32_IQ_SAMPLE_RATES, RFONE_LNA_MAX_GAIN, RFONE_MAX_FREQ_HZ, RFONE_MIN_FREQ_HZ,
6    RFONE_MIXER_MAX_GAIN, RFONE_RAW_ADC_SAMPLE_RATES, RFONE_VGA_MAX_GAIN,
7};
8use core::marker::PhantomData;
9
10const DEFAULT_FREQUENCY_HZ: u64 = 100_000_000;
11const DEFAULT_SAMPLE_RATE_HZ: u32 = 10_000_000;
12const MAX_PRESET_GAIN: u8 = 21;
13
14/// Policy for selecting a firmware rate and host-side IQ decimation factor.
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16pub enum DecimationPolicy {
17    /// Prefer the lowest firmware rate that can produce the requested effective
18    /// IQ rate, reducing USB and host processing bandwidth.
19    LowBandwidth,
20    /// Prefer the highest firmware rate that can produce the requested
21    /// effective IQ rate, then decimate on the host for greater oversampling.
22    HighDefinition,
23}
24
25/// Device selection used by [`crate::DeviceBuilder`].
26#[derive(Clone, Copy, Debug, Eq, PartialEq)]
27pub(crate) enum DeviceSelector {
28    /// Open the first visible HydraSDR RFOne.
29    First,
30    /// Open the HydraSDR RFOne with a normalized 64-bit serial number.
31    ///
32    /// Zero selects any device whose serial is absent, invalid, or zero.
33    Serial(u64),
34}
35
36/// RF input port selector.
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
38#[repr(u8)]
39pub enum RfPort {
40    /// First RF input port.
41    Rx0 = 0,
42    /// Second RF input port.
43    Rx1 = 1,
44    /// Third RF input port.
45    Rx2 = 2,
46}
47
48/// Runtime view of the sample format.
49///
50/// Configuration uses the [`RawAdc`] and [`F32Iq`] marker types instead. This
51/// enum is derived from that marker and is exposed for runtime state reporting.
52#[derive(Clone, Copy, Debug, Eq, PartialEq)]
53pub enum SampleFormat {
54    /// Raw ADC USB blocks measured in real ADC samples per second.
55    ///
56    /// Use [`crate::Device::sample_rates`] to inspect the fixed RFOne rates.
57    RawAdc,
58    /// Converted 32-bit float IQ samples measured in complex samples per second.
59    ///
60    /// The driver may select a higher firmware rate and apply host-side
61    /// decimation to produce the requested effective rate. Use
62    /// [`crate::Device::sample_rates`] to inspect the supported effective rates.
63    F32Iq,
64}
65
66mod private {
67    pub trait Sealed {
68        type Processor: crate::rx::processing::Processor;
69    }
70}
71
72/// Compile-time receiver sample mode.
73///
74/// This trait is sealed because the RFOne API currently supports
75/// only [`RawAdc`] and [`F32Iq`].
76pub trait SampleMode: private::Sealed + Copy + core::fmt::Debug + Eq + 'static {
77    /// Runtime format corresponding to this compile-time mode.
78    const FORMAT: SampleFormat;
79}
80
81/// Raw ADC sample mode.
82#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
83pub struct RawAdc;
84
85/// Converted complex `f32` IQ sample mode.
86#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
87pub struct F32Iq;
88
89impl private::Sealed for RawAdc {
90    type Processor = crate::rx::processing::RawProcessor;
91}
92impl private::Sealed for F32Iq {
93    type Processor = crate::rx::processing::IqProcessor;
94}
95
96impl SampleMode for RawAdc {
97    const FORMAT: SampleFormat = SampleFormat::RawAdc;
98}
99
100impl SampleMode for F32Iq {
101    const FORMAT: SampleFormat = SampleFormat::F32Iq;
102}
103
104/// Preset gain plans for common RFOne operation.
105#[derive(Clone, Copy, Debug, Eq, PartialEq)]
106pub enum GainPreset {
107    /// Apply the RFOne linearity preset table.
108    ///
109    /// The preset index must be in the inclusive range `0..=21`.
110    Linearity(u8),
111    /// Apply the RFOne sensitivity preset table.
112    ///
113    /// The preset index must be in the inclusive range `0..=21`.
114    Sensitivity(u8),
115}
116
117/// Complete gain configuration applied after sample/rate/RF-port setup.
118#[derive(Clone, Copy, Debug, Eq, PartialEq)]
119pub enum GainConfig {
120    /// Apply one RFOne preset.
121    Preset(GainPreset),
122    /// Configure every physical gain stage, including each AGC mode.
123    Stages {
124        /// LNA gain control.
125        lna: StageGain,
126        /// Mixer gain control.
127        mixer: StageGain,
128        /// VGA gain value.
129        ///
130        /// RFOne accepts values in the inclusive range `0..=15`.
131        vga: u8,
132    },
133}
134
135/// Gain control for an LNA or mixer stage.
136#[derive(Clone, Copy, Debug, Eq, PartialEq)]
137pub enum StageGain {
138    /// Use a fixed stage gain.
139    ///
140    /// RFOne accepts LNA values in `0..=14` and mixer values in `0..=15`.
141    Manual(u8),
142    /// Let the hardware AGC control the stage.
143    Agc,
144}
145
146/// Return the standard fixed-gain configuration.
147impl Default for GainConfig {
148    fn default() -> Self {
149        Self::Stages {
150            lna: StageGain::Manual(14),
151            mixer: StageGain::Manual(15),
152            vga: 6,
153        }
154    }
155}
156
157impl From<GainPreset> for GainConfig {
158    fn from(value: GainPreset) -> Self {
159        Self::Preset(value)
160    }
161}
162
163/// Reusable receiver configuration for sample mode `M`.
164///
165/// The generic mode defaults to [`F32Iq`]. Select [`RawAdc`] with
166/// [`ConfigBuilder::raw_adc`].
167///
168/// The default is complete: it selects RX0, disables the bias tee and both
169/// AGCs, and sets 35 dB total gain as LNA 14 dB, mixer 15 dB, and VGA 6 dB.
170///
171/// Building a config validates static RFOne and USB protocol constraints
172/// without opening hardware, including the fixed sample-rate table.
173/// Every `Config` obtainable through the public API has passed this validation.
174///
175/// ```
176/// use hydrasdr_rs::{Config, GainPreset};
177///
178/// let config = Config::builder()
179///     .raw_adc()
180///     .frequency_hz(144_500_000)
181///     .sample_rate_hz(10_000_000)
182///     .gain(GainPreset::Linearity(10))
183///     .build()?;
184///
185/// assert_eq!(config.frequency_hz(), 144_500_000);
186/// # Ok::<(), hydrasdr_rs::Error>(())
187/// ```
188#[derive(Clone, Debug, Eq, PartialEq)]
189pub struct Config<M: SampleMode = F32Iq> {
190    frequency_hz: u64,
191    sample_rate_hz: u32,
192    decimation_policy: DecimationPolicy,
193    rf_port: RfPort,
194    gain: GainConfig,
195    bias_tee: bool,
196    packing: bool,
197    mode: PhantomData<fn() -> M>,
198}
199
200impl<M: SampleMode> Config<M> {
201    fn standard() -> Self {
202        Self {
203            frequency_hz: DEFAULT_FREQUENCY_HZ,
204            sample_rate_hz: DEFAULT_SAMPLE_RATE_HZ,
205            decimation_policy: DecimationPolicy::LowBandwidth,
206            rf_port: RfPort::Rx0,
207            gain: GainConfig::default(),
208            bias_tee: false,
209            packing: false,
210            mode: PhantomData,
211        }
212    }
213
214    fn into_mode<N: SampleMode>(self) -> Config<N> {
215        Config {
216            frequency_hz: self.frequency_hz,
217            sample_rate_hz: self.sample_rate_hz,
218            decimation_policy: self.decimation_policy,
219            rf_port: self.rf_port,
220            gain: self.gain,
221            bias_tee: self.bias_tee,
222            packing: self.packing,
223            mode: PhantomData,
224        }
225    }
226}
227
228impl Default for Config<F32Iq> {
229    fn default() -> Self {
230        Self::standard()
231    }
232}
233
234impl Config<F32Iq> {
235    /// Start building a receiver configuration.
236    ///
237    /// ```
238    /// use hydrasdr_rs::{Config, GainPreset};
239    ///
240    /// let config = Config::builder()
241    ///     .frequency_hz(100_000_000)
242    ///     .sample_rate_hz(10_000_000)
243    ///     .gain(GainPreset::Sensitivity(6))
244    ///     .build()?;
245    ///
246    /// assert_eq!(config.sample_rate_hz(), 10_000_000);
247    /// # Ok::<(), hydrasdr_rs::Error>(())
248    /// ```
249    pub fn builder() -> ConfigBuilder<F32Iq> {
250        ConfigBuilder::default()
251    }
252}
253
254impl<M: SampleMode> Config<M> {
255    /// Tuned center frequency in Hz.
256    pub const fn frequency_hz(&self) -> u64 {
257        self.frequency_hz
258    }
259
260    /// Requested sample rate in Hz.
261    ///
262    /// For [`SampleFormat::RawAdc`] this is a real ADC rate; for
263    /// [`SampleFormat::F32Iq`] it is the effective complex output rate after any
264    /// host-side decimation.
265    pub const fn sample_rate_hz(&self) -> u32 {
266        self.sample_rate_hz
267    }
268
269    /// Runtime view of the compile-time sample mode `M`.
270    pub const fn sample_format(&self) -> SampleFormat {
271        M::FORMAT
272    }
273
274    /// Configured RF port.
275    pub const fn rf_port(&self) -> RfPort {
276        self.rf_port
277    }
278
279    /// Configured gain plan.
280    pub const fn gain(&self) -> GainConfig {
281        self.gain
282    }
283
284    /// Configured bias tee state.
285    pub const fn bias_tee(&self) -> bool {
286        self.bias_tee
287    }
288
289    fn validate(&self) -> Result<()> {
290        validate_frequency(self.frequency_hz)?;
291        validate_sample_rate(self.sample_rate_hz, M::FORMAT)?;
292        validate_gain(self.gain)?;
293        Ok(())
294    }
295
296    pub(crate) const fn decimation_policy_internal(&self) -> DecimationPolicy {
297        self.decimation_policy
298    }
299
300    pub(crate) const fn packing_internal(&self) -> bool {
301        self.packing
302    }
303
304    pub(crate) fn set_frequency_hz_internal(&mut self, value: u64) {
305        self.frequency_hz = value;
306    }
307
308    pub(crate) fn set_sample_rate_hz_internal(&mut self, value: u32) {
309        self.sample_rate_hz = value;
310    }
311
312    pub(crate) fn set_rf_port_internal(&mut self, value: RfPort) {
313        self.rf_port = value;
314    }
315
316    pub(crate) fn set_gain_internal(&mut self, value: GainConfig) {
317        self.gain = value;
318    }
319
320    pub(crate) fn set_bias_tee_internal(&mut self, enabled: bool) {
321        self.bias_tee = enabled;
322    }
323
324    pub(crate) fn set_packing_internal(&mut self, enabled: bool) {
325        self.packing = enabled;
326    }
327
328    pub(crate) fn set_decimation_policy_internal(&mut self, policy: DecimationPolicy) {
329        self.decimation_policy = policy;
330    }
331
332    pub(crate) fn apply_internal(&mut self, applied: &Self) {
333        self.frequency_hz = applied.frequency_hz;
334        self.sample_rate_hz = applied.sample_rate_hz;
335        self.decimation_policy = applied.decimation_policy;
336        self.rf_port = applied.rf_port;
337        self.set_gain_internal(applied.gain);
338        self.bias_tee = applied.bias_tee;
339        self.packing = applied.packing;
340    }
341}
342
343impl Config<RawAdc> {
344    /// Whether packed samples should be requested.
345    pub const fn packing(&self) -> bool {
346        self.packing
347    }
348}
349
350impl Config<F32Iq> {
351    /// Virtual IQ-rate hardware/host decimation policy.
352    pub const fn decimation_policy(&self) -> DecimationPolicy {
353        self.decimation_policy
354    }
355}
356
357/// Builder for [`Config`], defaulting to the [`F32Iq`] sample mode.
358///
359/// ```
360/// use hydrasdr_rs::Config;
361///
362/// let config = Config::builder()
363///     .raw_adc()
364///     .frequency_hz(915_000_000)
365///     .sample_rate_hz(5_000_000)
366///     .packing(true)
367///     .build()?;
368///
369/// assert!(config.packing());
370/// # Ok::<(), hydrasdr_rs::Error>(())
371/// ```
372#[derive(Clone, Debug)]
373pub struct ConfigBuilder<M: SampleMode = F32Iq> {
374    config: Config<M>,
375}
376
377impl Default for ConfigBuilder<F32Iq> {
378    fn default() -> Self {
379        Self {
380            config: Config::default(),
381        }
382    }
383}
384
385impl<M: SampleMode> ConfigBuilder<M> {
386    /// Set the tuned center frequency in Hz.
387    ///
388    /// RFOne accepts center frequencies in the inclusive range
389    /// `24_000_000..=1_800_000_000` Hz.
390    pub fn frequency_hz(mut self, value: u64) -> Self {
391        self.config.frequency_hz = value;
392        self
393    }
394
395    /// Set the requested sample rate in Hz.
396    ///
397    /// For [`SampleFormat::RawAdc`] this is a real ADC rate; for
398    /// [`SampleFormat::F32Iq`] it is the effective complex output rate after any
399    /// host-side decimation. [`ConfigBuilder`] accepts exactly the fixed rates
400    /// returned by [`crate::Device::sample_rates`] for the selected format.
401    pub fn sample_rate_hz(mut self, value: u32) -> Self {
402        self.config.sample_rate_hz = value;
403        self
404    }
405
406    /// Select the RF input port.
407    pub fn rf_port(mut self, value: RfPort) -> Self {
408        self.config.rf_port = value;
409        self
410    }
411
412    /// Set the gain configuration.
413    ///
414    /// Preset gain indexes must be in the inclusive range `0..=21`.
415    /// Stage gains use the ranges documented on [`StageGain::Manual`].
416    pub fn gain(mut self, value: impl Into<GainConfig>) -> Self {
417        self.config.gain = value.into();
418        self
419    }
420
421    /// Enable or disable the RF port bias tee.
422    pub fn bias_tee(mut self, enabled: bool) -> Self {
423        self.config.bias_tee = enabled;
424        self
425    }
426
427    /// Validate and build a reusable configuration.
428    ///
429    /// A successfully built [`Config`] remains valid for its lifetime.
430    pub fn build(self) -> Result<Config<M>> {
431        self.config.validate()?;
432        Ok(self.config)
433    }
434}
435
436impl ConfigBuilder<RawAdc> {
437    /// Enable or disable packed raw-sample transfers.
438    pub fn packing(mut self, enabled: bool) -> Self {
439        self.config.packing = enabled;
440        self
441    }
442}
443
444impl ConfigBuilder<F32Iq> {
445    /// Select raw ADC samples instead of the default converted IQ mode.
446    ///
447    /// Format-specific options are exposed only after selecting their mode:
448    ///
449    /// ```compile_fail
450    /// use hydrasdr_rs::Config;
451    /// let _ = Config::builder().packing(true);
452    /// ```
453    pub fn raw_adc(mut self) -> ConfigBuilder<RawAdc> {
454        self.config.decimation_policy = DecimationPolicy::LowBandwidth;
455        ConfigBuilder {
456            config: self.config.into_mode(),
457        }
458    }
459
460    /// Set the firmware/host decimation policy for float IQ samples.
461    ///
462    /// ```compile_fail
463    /// use hydrasdr_rs::{Config, DecimationPolicy};
464    /// let _ = Config::builder()
465    ///     .raw_adc()
466    ///     .decimation_policy(DecimationPolicy::HighDefinition);
467    /// ```
468    pub fn decimation_policy(mut self, value: DecimationPolicy) -> Self {
469        self.config.decimation_policy = value;
470        self
471    }
472}
473
474pub(crate) fn validate_frequency(value: u64) -> Result<()> {
475    if !(RFONE_MIN_FREQ_HZ..=RFONE_MAX_FREQ_HZ).contains(&value) {
476        return Err(Error::invalid_config(
477            "frequency_hz",
478            "must be in 24_000_000..=1_800_000_000 Hz",
479        ));
480    }
481    Ok(())
482}
483
484pub(crate) fn validate_sample_rate(value: u32, sample_format: SampleFormat) -> Result<()> {
485    let supported = match sample_format {
486        SampleFormat::RawAdc => RFONE_RAW_ADC_SAMPLE_RATES.as_slice(),
487        SampleFormat::F32Iq => RFONE_F32_IQ_SAMPLE_RATES.as_slice(),
488    };
489    if !supported.contains(&value) {
490        return Err(Error::invalid_config(
491            "sample_rate_hz",
492            "is not supported by RFOne and the host decimator",
493        ));
494    }
495    Ok(())
496}
497
498pub(crate) fn validate_gain(gain: GainConfig) -> Result<()> {
499    match gain {
500        GainConfig::Preset(GainPreset::Linearity(value) | GainPreset::Sensitivity(value))
501            if value > MAX_PRESET_GAIN =>
502        {
503            Err(Error::invalid_config(
504                "gain",
505                "RFOne preset gain must be in 0..=21",
506            ))
507        }
508        GainConfig::Stages {
509            lna: StageGain::Manual(value),
510            ..
511        } if value > RFONE_LNA_MAX_GAIN => Err(Error::invalid_config(
512            "gain",
513            "manual LNA gain must be in 0..=14",
514        )),
515        GainConfig::Stages {
516            mixer: StageGain::Manual(value),
517            ..
518        } if value > RFONE_MIXER_MAX_GAIN => Err(Error::invalid_config(
519            "gain",
520            "manual mixer gain must be in 0..=15",
521        )),
522        GainConfig::Stages { vga, .. } if vga > RFONE_VGA_MAX_GAIN => Err(Error::invalid_config(
523            "gain",
524            "manual VGA gain must be in 0..=15",
525        )),
526        _ => Ok(()),
527    }
528}