rfe 0.1.0

Communicate with RF Explorer spectrum analyzers and signal generators over USB serial
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
use std::{
    fmt::Debug,
    io,
    sync::{Arc, Condvar, Mutex},
    thread,
    time::Duration,
};

use super::{
    Attenuation, Config, ConfigAmpSweep, ConfigAmpSweepExp, ConfigCw, ConfigCwExp, ConfigExp,
    ConfigFreqSweep, ConfigFreqSweepExp, Model, PowerLevel, Temperature,
};
use crate::rf_explorer::{
    ConfigCallback, NEXT_SCREEN_DATA_TIMEOUT, RECEIVE_INITIAL_DEVICE_INFO_TIMEOUT, ScreenData,
    SerialNumber, SetupInfo, impl_rf_explorer,
};
use crate::{ConnectionError, ConnectionResult, Device, Error, Frequency, Result};

#[derive(Debug)]
/// RF Explorer signal generator device.
pub struct SignalGenerator {
    rfe: Device<MessageContainer>,
}

impl_rf_explorer!(SignalGenerator, MessageContainer);

impl SignalGenerator {
    const MAX_7_DIGIT_KHZ: u64 = 9_999_999;
    const MAX_4_DIGIT_DECIMAL: u16 = 9_999;
    const MAX_5_DIGIT_MILLIS: u128 = 99_999;
    const MIN_POWER_DB: f64 = -99.9;
    const MAX_POWER_DB: f64 = 99.9;

    /// Returns the RF Explorer's serial number, if it exists.
    pub fn serial_number(&self) -> Option<String> {
        // Return the serial number if we've already received it
        if let Some(ref serial_number) = *self.messages().serial_number.0.lock().unwrap() {
            return Some(serial_number.to_string());
        }

        // If we haven't already received the serial number, request it from the RF Explorer
        self.send_command(crate::rf_explorer::Command::RequestSerialNumber)
            .ok()?;

        // Wait 2 seconds for the RF Explorer to send its serial number
        let (lock, cvar) = &self.messages().serial_number;
        tracing::trace!("Waiting to receive SerialNumber from RF Explorer");
        let _ = cvar
            .wait_timeout_while(
                lock.lock().unwrap(),
                std::time::Duration::from_secs(2),
                |serial_number| serial_number.is_none(),
            )
            .unwrap();

        (*self.messages().serial_number.0.lock().unwrap())
            .as_ref()
            .map(|sn| sn.to_string())
    }

    /// Returns the firmware version reported by the RF Explorer.
    pub fn firmware_version(&self) -> String {
        self.messages()
            .setup_info
            .0
            .lock()
            .unwrap()
            .as_ref()
            .map(|setup_info| setup_info.firmware_version.clone())
            .unwrap_or_default()
    }

    /// Returns the most recent main-module configuration reported by the signal generator.
    pub fn config(&self) -> Option<Config> {
        *self.messages().config.0.lock().unwrap()
    }

    /// Returns the most recent expansion-module configuration reported by the signal generator.
    pub fn config_expansion(&self) -> Option<ConfigExp> {
        *self.messages().config_exp.0.lock().unwrap()
    }

    /// Returns the most recent main-module amplitude sweep configuration.
    pub fn config_amp_sweep(&self) -> Option<ConfigAmpSweep> {
        *self.messages().config_amp_sweep.0.lock().unwrap()
    }

    /// Returns the most recent expansion-module amplitude sweep configuration.
    pub fn config_amp_sweep_expansion(&self) -> Option<ConfigAmpSweepExp> {
        *self.messages().config_amp_sweep_exp.0.lock().unwrap()
    }

    /// Returns the most recent main-module CW configuration.
    pub fn config_cw(&self) -> Option<ConfigCw> {
        *self.messages().config_cw.0.lock().unwrap()
    }

    /// Returns the most recent expansion-module CW configuration.
    pub fn config_cw_expansion(&self) -> Option<ConfigCwExp> {
        *self.messages().config_cw_exp.0.lock().unwrap()
    }

    /// Returns the most recent main-module frequency sweep configuration.
    pub fn config_freq_sweep(&self) -> Option<ConfigFreqSweep> {
        *self.messages().config_freq_sweep.0.lock().unwrap()
    }

    /// Returns the most recent expansion-module frequency sweep configuration.
    pub fn config_freq_sweep_expansion(&self) -> Option<ConfigFreqSweepExp> {
        *self.messages().config_freq_sweep_exp.0.lock().unwrap()
    }

    /// Returns the most recent `ScreenData` captured by the RF Explorer.
    pub fn screen_data(&self) -> Option<ScreenData> {
        self.messages().screen_data.0.lock().unwrap().clone()
    }

    /// Waits for the RF Explorer to capture its next `ScreenData`.
    pub fn wait_for_next_screen_data(&self) -> Result<ScreenData> {
        self.wait_for_next_screen_data_with_timeout(NEXT_SCREEN_DATA_TIMEOUT)
    }

    /// Waits for the RF Explorer to capture its next `ScreenData` or for the timeout duration to elapse.
    pub fn wait_for_next_screen_data_with_timeout(&self, timeout: Duration) -> Result<ScreenData> {
        let previous_screen_data = self.screen_data();
        let (screen_data, condvar) = &self.messages().screen_data;
        let (screen_data, wait_result) = condvar
            .wait_timeout_while(screen_data.lock().unwrap(), timeout, |screen_data| {
                *screen_data == previous_screen_data || screen_data.is_none()
            })
            .unwrap();

        match &*screen_data {
            Some(screen_data) if !wait_result.timed_out() => Ok(screen_data.clone()),
            _ => Err(crate::Error::TimedOut(timeout)),
        }
    }

    /// Returns the most recent temperature range reported by the signal generator.
    pub fn temperature(&self) -> Option<Temperature> {
        *self.messages().temperature.0.lock().unwrap()
    }

    /// Returns the main radio's model.
    pub fn main_radio_model(&self) -> Option<Model> {
        self.messages()
            .setup_info
            .0
            .lock()
            .unwrap()
            .as_ref()
            .unwrap()
            .main_radio_model
    }

    /// Returns the expansion radio's model (if one exists).
    pub fn expansion_radio_model(&self) -> Option<Model> {
        self.messages()
            .setup_info
            .0
            .lock()
            .unwrap()
            .as_ref()
            .unwrap()
            .expansion_radio_model
    }

    /// The active radio's model.
    pub fn active_radio_model(&self) -> Model {
        let Some(exp_model) = self.expansion_radio_model() else {
            return self.main_radio_model().unwrap_or_default();
        };

        if self.config_expansion().is_some() {
            exp_model
        } else {
            self.main_radio_model().unwrap_or_default()
        }
    }

    /// The inactive radio's model.
    pub fn inactive_radio_model(&self) -> Option<Model> {
        let exp_model = self.expansion_radio_model()?;

        if self.config_expansion().is_some() {
            self.main_radio_model()
        } else {
            Some(exp_model)
        }
    }

    /// Starts the signal generator's amplitude sweep mode.
    pub fn start_amp_sweep(
        &self,
        cw: impl Into<Frequency>,
        start_attenuation: Attenuation,
        start_power_level: PowerLevel,
        stop_attenuation: Attenuation,
        stop_power_level: PowerLevel,
        step_delay: Duration,
    ) -> Result<()> {
        let cw = cw.into();
        Self::validate_command_frequency("cw", cw)?;
        Self::validate_step_delay(step_delay)?;

        self.send_command(super::Command::StartAmpSweep {
            cw,
            start_attenuation,
            start_power_level,
            stop_attenuation,
            stop_power_level,
            step_delay,
        })?;

        Ok(())
    }

    /// Starts the signal generator's amplitude sweep mode using the expansion module.
    pub fn start_amp_sweep_exp(
        &self,
        cw: impl Into<Frequency>,
        start_power_dbm: f64,
        step_power_db: f64,
        stop_power_dbm: f64,
        step_delay: Duration,
    ) -> Result<()> {
        let cw = cw.into();
        Self::validate_command_frequency("cw", cw)?;
        Self::validate_power_db("start_power_dbm", start_power_dbm)?;
        Self::validate_power_db("step_power_db", step_power_db)?;
        Self::validate_power_db("stop_power_dbm", stop_power_dbm)?;
        Self::validate_step_delay(step_delay)?;

        self.send_command(super::Command::StartAmpSweepExp {
            cw,
            start_power_dbm,
            step_power_db,
            stop_power_dbm,
            step_delay,
        })?;

        Ok(())
    }

    /// Starts the signal generator's CW mode.
    pub fn start_cw(
        &self,
        cw: impl Into<Frequency>,
        attenuation: Attenuation,
        power_level: PowerLevel,
    ) -> Result<()> {
        let cw = cw.into();
        Self::validate_command_frequency("cw", cw)?;

        self.send_command(super::Command::StartCw {
            cw,
            attenuation,
            power_level,
        })?;

        Ok(())
    }

    /// Starts the signal generator's CW mode using the expansion module.
    pub fn start_cw_exp(&self, cw: impl Into<Frequency>, power_dbm: f64) -> Result<()> {
        let cw = cw.into();
        Self::validate_command_frequency("cw", cw)?;
        Self::validate_power_db("power_dbm", power_dbm)?;

        self.send_command(super::Command::StartCwExp { cw, power_dbm })?;

        Ok(())
    }

    /// Starts the signal generator's frequency sweep mode.
    pub fn start_freq_sweep(
        &self,
        start: impl Into<Frequency>,
        attenuation: Attenuation,
        power_level: PowerLevel,
        sweep_steps: u16,
        step_hz: u64,
        step_delay: Duration,
    ) -> Result<()> {
        let start = start.into();
        let step = Frequency::from_hz(step_hz);
        Self::validate_command_frequency("start", start)?;
        Self::validate_command_frequency("step", step)?;
        Self::validate_sweep_steps(sweep_steps)?;
        Self::validate_step_delay(step_delay)?;

        self.send_command(super::Command::StartFreqSweep {
            start,
            attenuation,
            power_level,
            sweep_steps,
            step,
            step_delay,
        })?;

        Ok(())
    }

    /// Starts the signal generator's frequency sweep mode using the expansion module.
    pub fn start_freq_sweep_exp(
        &self,
        start: impl Into<Frequency>,
        power_dbm: f64,
        sweep_steps: u16,
        step: impl Into<Frequency>,
        step_delay: Duration,
    ) -> Result<()> {
        let start = start.into();
        let step = step.into();
        Self::validate_command_frequency("start", start)?;
        Self::validate_command_frequency("step", step)?;
        Self::validate_power_db("power_dbm", power_dbm)?;
        Self::validate_sweep_steps(sweep_steps)?;
        Self::validate_step_delay(step_delay)?;

        self.send_command(super::Command::StartFreqSweepExp {
            start,
            power_dbm,
            sweep_steps,
            step,
            step_delay,
        })?;

        Ok(())
    }

    /// Starts the signal generator's tracking mode.
    pub fn start_tracking(
        &self,
        start: impl Into<Frequency>,
        attenuation: Attenuation,
        power_level: PowerLevel,
        sweep_steps: u16,
        step: impl Into<Frequency>,
    ) -> Result<()> {
        let start = start.into();
        let step = step.into();
        Self::validate_command_frequency("start", start)?;
        Self::validate_command_frequency("step", step)?;
        Self::validate_sweep_steps(sweep_steps)?;

        self.send_command(super::Command::StartTracking {
            start,
            attenuation,
            power_level,
            sweep_steps,
            step,
        })?;

        Ok(())
    }

    /// Starts the signal generator's tracking mode using the expansion module.
    pub fn start_tracking_exp(
        &self,
        start: impl Into<Frequency>,
        power_dbm: f64,
        sweep_steps: u16,
        step: impl Into<Frequency>,
    ) -> Result<()> {
        let start = start.into();
        let step = step.into();
        Self::validate_command_frequency("start", start)?;
        Self::validate_command_frequency("step", step)?;
        Self::validate_power_db("power_dbm", power_dbm)?;
        Self::validate_sweep_steps(sweep_steps)?;

        self.send_command(super::Command::StartTrackingExp {
            start,
            power_dbm,
            sweep_steps,
            step,
        })?;

        Ok(())
    }

    /// Jumps to a new frequency using the tracking step frequency.
    pub fn tracking_step(&self, steps: u16) -> io::Result<()> {
        self.send_command(super::Command::TrackingStep(steps))
    }

    /// Sets the callback that is executed when the signal generator receives a `Config`.
    pub fn set_config_callback(&self, cb: impl Fn(Config) + Send + Sync + 'static) {
        *self.messages().config_callback.lock().unwrap() = Some(Arc::new(Box::new(cb)));
    }

    /// Removes the callback that is executed when the signal generator receives a `Config`.
    pub fn remove_config_callback(&self) {
        *self.messages().config_callback.lock().unwrap() = None;
    }

    /// Sets the callback that is executed when the signal generator receives a `ConfigExp`.
    pub fn set_config_exp_callback(&self, cb: impl Fn(ConfigExp) + Send + Sync + 'static) {
        *self.messages().config_exp_callback.lock().unwrap() = Some(Arc::new(Box::new(cb)));
    }

    /// Removes the callback that is executed when the signal generator receives a `ConfigExp`.
    pub fn remove_config_exp_callback(&self) {
        *self.messages().config_exp_callback.lock().unwrap() = None;
    }

    /// Sets the callback that is executed when the signal generator receives a `ConfigAmpSweep`.
    pub fn set_config_amp_sweep_callback(
        &self,
        cb: impl Fn(ConfigAmpSweep) + Send + Sync + 'static,
    ) {
        *self.messages().config_amp_sweep_callback.lock().unwrap() = Some(Arc::new(Box::new(cb)));
    }

    /// Removes the callback that is executed when the signal generator receives a `ConfigAmpSweep`.
    pub fn remove_config_amp_sweep_callback(&self) {
        *self.messages().config_amp_sweep_callback.lock().unwrap() = None;
    }

    /// Sets the callback that is executed when the signal generator receives a `ConfigAmpSweepExp`.
    pub fn set_config_amp_sweep_exp_callback(
        &self,
        cb: impl Fn(ConfigAmpSweepExp) + Send + Sync + 'static,
    ) {
        *self
            .messages()
            .config_amp_sweep_exp_callback
            .lock()
            .unwrap() = Some(Arc::new(Box::new(cb)));
    }

    /// Removes the callback that is executed when the signal generator receives a `ConfigAmpSweepExp`.
    pub fn remove_config_amp_sweep_exp_callback(&self) {
        *self
            .messages()
            .config_amp_sweep_exp_callback
            .lock()
            .unwrap() = None;
    }

    /// Sets the callback that is executed when the signal generator receives a `ConfigCw`.
    pub fn set_config_cw_callback(&self, cb: impl Fn(ConfigCw) + Send + Sync + 'static) {
        *self.messages().config_cw_callback.lock().unwrap() = Some(Arc::new(Box::new(cb)));
    }

    /// Removes the callback that is executed when the signal generator receives a `ConfigCw`.
    pub fn remove_config_cw_callback(&self) {
        *self.messages().config_cw_callback.lock().unwrap() = None;
    }

    /// Sets the callback that is executed when the signal generator receives a `ConfigCwExp`.
    pub fn set_config_cw_exp_callback(&self, cb: impl Fn(ConfigCwExp) + Send + Sync + 'static) {
        *self.messages().config_cw_exp_callback.lock().unwrap() = Some(Arc::new(Box::new(cb)));
    }

    /// Removes the callback that is executed when the signal generator receives a `ConfigCwExp`.
    pub fn remove_config_cw_exp_callback(&self) {
        *self.messages().config_cw_exp_callback.lock().unwrap() = None;
    }

    /// Sets the callback that is executed when the signal generator receives a `ConfigFreqSweep`.
    pub fn set_config_freq_sweep_callback(
        &self,
        cb: impl Fn(ConfigFreqSweep) + Send + Sync + 'static,
    ) {
        *self.messages().config_freq_sweep_callback.lock().unwrap() = Some(Arc::new(Box::new(cb)));
    }

    /// Removes the callback that is executed when the signal generator receives a `ConfigFreqSweep`.
    pub fn remove_config_freq_sweep_callback(&self) {
        *self.messages().config_freq_sweep_callback.lock().unwrap() = None;
    }

    /// Sets the callback that is executed when the signal generator receives a `ConfigFreqSweepExp`.
    pub fn set_config_freq_sweep_exp_callback(
        &self,
        cb: impl Fn(ConfigFreqSweepExp) + Send + Sync + 'static,
    ) {
        *self
            .messages()
            .config_freq_sweep_exp_callback
            .lock()
            .unwrap() = Some(Arc::new(Box::new(cb)));
    }

    /// Removes the callback that is executed when the signal generator receives a `ConfigFreqSweepExp`.
    pub fn remove_config_freq_sweep_exp_callback(&self) {
        *self
            .messages()
            .config_freq_sweep_exp_callback
            .lock()
            .unwrap() = None;
    }

    /// Turns on RF power with the current power and frequency configuration.
    pub fn rf_power_on(&self) -> io::Result<()> {
        self.send_command(super::Command::RfPowerOn)
    }

    /// Turns off RF power.
    pub fn rf_power_off(&self) -> io::Result<()> {
        self.send_command(super::Command::RfPowerOff)
    }

    fn validate_command_frequency(name: &str, frequency: Frequency) -> Result<()> {
        if frequency.as_khz() > Self::MAX_7_DIGIT_KHZ {
            return Err(Error::InvalidInput(format!(
                "{name} must be 9,999,999 kHz or less"
            )));
        }

        Ok(())
    }

    fn validate_sweep_steps(sweep_steps: u16) -> Result<()> {
        if sweep_steps > Self::MAX_4_DIGIT_DECIMAL {
            return Err(Error::InvalidInput(
                "sweep_steps must be 9,999 or less".to_string(),
            ));
        }

        Ok(())
    }

    fn validate_step_delay(step_delay: Duration) -> Result<()> {
        if step_delay.as_millis() > Self::MAX_5_DIGIT_MILLIS {
            return Err(Error::InvalidInput(
                "step_delay must be 99,999 ms or less".to_string(),
            ));
        }

        Ok(())
    }

    fn validate_power_db(name: &str, power_db: f64) -> Result<()> {
        if !power_db.is_finite() || !(Self::MIN_POWER_DB..=Self::MAX_POWER_DB).contains(&power_db) {
            return Err(Error::InvalidInput(format!(
                "{name} must be a finite value from -99.9 to 99.9"
            )));
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn validate_command_frequency_accepts_largest_7_digit_khz_value() {
        assert!(
            SignalGenerator::validate_command_frequency(
                "frequency",
                Frequency::from_khz(9_999_999)
            )
            .is_ok()
        );
    }

    #[test]
    fn validate_command_frequency_rejects_8_digit_khz_value() {
        assert!(
            SignalGenerator::validate_command_frequency(
                "frequency",
                Frequency::from_khz(10_000_000)
            )
            .is_err()
        );
    }

    #[test]
    fn validate_sweep_steps_accepts_largest_4_digit_value() {
        assert!(SignalGenerator::validate_sweep_steps(9_999).is_ok());
    }

    #[test]
    fn validate_sweep_steps_rejects_5_digit_value() {
        assert!(SignalGenerator::validate_sweep_steps(10_000).is_err());
    }

    #[test]
    fn validate_step_delay_accepts_largest_5_digit_millisecond_value() {
        assert!(SignalGenerator::validate_step_delay(Duration::from_millis(99_999)).is_ok());
    }

    #[test]
    fn validate_step_delay_rejects_6_digit_millisecond_value() {
        assert!(SignalGenerator::validate_step_delay(Duration::from_millis(100_000)).is_err());
    }

    #[test]
    fn validate_power_db_accepts_boundary_values() {
        assert!(SignalGenerator::validate_power_db("power_dbm", -99.9).is_ok());
        assert!(SignalGenerator::validate_power_db("power_dbm", 99.9).is_ok());
    }

    #[test]
    fn validate_power_db_rejects_out_of_range_and_non_finite_values() {
        assert!(SignalGenerator::validate_power_db("power_dbm", -100.0).is_err());
        assert!(SignalGenerator::validate_power_db("power_dbm", 100.0).is_err());
        assert!(SignalGenerator::validate_power_db("power_dbm", f64::NAN).is_err());
        assert!(SignalGenerator::validate_power_db("power_dbm", f64::INFINITY).is_err());
    }
}

#[derive(Default)]
struct MessageContainer {
    pub(crate) config: (Mutex<Option<Config>>, Condvar),
    pub(crate) config_callback: Mutex<ConfigCallback<Config>>,
    pub(crate) config_exp: (Mutex<Option<ConfigExp>>, Condvar),
    pub(crate) config_exp_callback: Mutex<ConfigCallback<ConfigExp>>,
    pub(crate) config_amp_sweep: (Mutex<Option<ConfigAmpSweep>>, Condvar),
    pub(crate) config_amp_sweep_callback: Mutex<ConfigCallback<ConfigAmpSweep>>,
    pub(crate) config_amp_sweep_exp: (Mutex<Option<ConfigAmpSweepExp>>, Condvar),
    pub(crate) config_amp_sweep_exp_callback: Mutex<ConfigCallback<ConfigAmpSweepExp>>,
    pub(crate) config_cw: (Mutex<Option<ConfigCw>>, Condvar),
    pub(crate) config_cw_callback: Mutex<ConfigCallback<ConfigCw>>,
    pub(crate) config_cw_exp: (Mutex<Option<ConfigCwExp>>, Condvar),
    pub(crate) config_cw_exp_callback: Mutex<ConfigCallback<ConfigCwExp>>,
    pub(crate) config_freq_sweep: (Mutex<Option<ConfigFreqSweep>>, Condvar),
    pub(crate) config_freq_sweep_callback: Mutex<ConfigCallback<ConfigFreqSweep>>,
    pub(crate) config_freq_sweep_exp: (Mutex<Option<ConfigFreqSweepExp>>, Condvar),
    pub(crate) config_freq_sweep_exp_callback: Mutex<ConfigCallback<ConfigFreqSweepExp>>,
    pub(crate) screen_data: (Mutex<Option<ScreenData>>, Condvar),
    pub(crate) temperature: (Mutex<Option<Temperature>>, Condvar),
    pub(crate) setup_info: (Mutex<Option<SetupInfo<Model>>>, Condvar),
    pub(crate) serial_number: (Mutex<Option<SerialNumber>>, Condvar),
}

impl crate::common::MessageContainer for MessageContainer {
    type Message = super::Message;

    fn cache_message(&self, message: Self::Message) {
        match message {
            Self::Message::Config(config) => {
                *self.config.0.lock().unwrap() = Some(config);
                self.config.1.notify_one();
                if let Some(cb) = self.config_callback.lock().unwrap().clone() {
                    thread::spawn(move || {
                        cb(config);
                    });
                }
            }
            Self::Message::ConfigAmpSweep(config) => {
                *self.config_amp_sweep.0.lock().unwrap() = Some(config);
                self.config_amp_sweep.1.notify_one();
                if let Some(cb) = self.config_amp_sweep_callback.lock().unwrap().clone() {
                    thread::spawn(move || {
                        cb(config);
                    });
                }
            }
            Self::Message::ConfigCw(config) => {
                *self.config_cw.0.lock().unwrap() = Some(config);
                self.config_cw.1.notify_one();
                if let Some(cb) = self.config_cw_callback.lock().unwrap().clone() {
                    thread::spawn(move || {
                        cb(config);
                    });
                }
            }
            Self::Message::ConfigFreqSweep(config) => {
                *self.config_freq_sweep.0.lock().unwrap() = Some(config);
                self.config_freq_sweep.1.notify_one();
                if let Some(cb) = self.config_freq_sweep_callback.lock().unwrap().clone() {
                    thread::spawn(move || {
                        cb(config);
                    });
                }
            }
            Self::Message::ConfigExp(config) => {
                *self.config_exp.0.lock().unwrap() = Some(config);
                self.config_exp.1.notify_one();
                if let Some(cb) = self.config_exp_callback.lock().unwrap().clone() {
                    thread::spawn(move || {
                        cb(config);
                    });
                }
            }
            Self::Message::ConfigAmpSweepExp(config) => {
                *self.config_amp_sweep_exp.0.lock().unwrap() = Some(config);
                self.config_amp_sweep_exp.1.notify_one();
                if let Some(cb) = self.config_amp_sweep_exp_callback.lock().unwrap().clone() {
                    thread::spawn(move || {
                        cb(config);
                    });
                }
            }
            Self::Message::ConfigCwExp(config) => {
                *self.config_cw_exp.0.lock().unwrap() = Some(config);
                self.config_cw_exp.1.notify_one();
                if let Some(cb) = self.config_cw_exp_callback.lock().unwrap().clone() {
                    thread::spawn(move || {
                        cb(config);
                    });
                }
            }
            Self::Message::ConfigFreqSweepExp(config) => {
                *self.config_freq_sweep_exp.0.lock().unwrap() = Some(config);
                self.config_freq_sweep_exp.1.notify_one();
                if let Some(cb) = self.config_freq_sweep_exp_callback.lock().unwrap().clone() {
                    thread::spawn(move || {
                        cb(config);
                    });
                }
            }
            Self::Message::ScreenData(screen_data) => {
                *self.screen_data.0.lock().unwrap() = Some(screen_data);
                self.screen_data.1.notify_one();
            }
            Self::Message::SerialNumber(serial_number) => {
                *self.serial_number.0.lock().unwrap() = Some(serial_number);
                self.serial_number.1.notify_one();
            }
            Self::Message::SetupInfo(setup_info) => {
                *self.setup_info.0.lock().unwrap() = Some(setup_info);
                self.setup_info.1.notify_one();
            }
            Self::Message::Temperature(temperature) => {
                *self.temperature.0.lock().unwrap() = Some(temperature);
                self.temperature.1.notify_one();
            }
        }
    }

    fn wait_for_device_info(&self) -> ConnectionResult<()> {
        let (config_lock, config_cvar) = &self.config;
        let (setup_info_lock, setup_info_cvar) = &self.setup_info;

        // Check to see if we've already received a Config and SetupInfo
        if config_lock.lock().unwrap().is_some() && setup_info_lock.lock().unwrap().is_some() {
            return Ok(());
        }

        // Wait to see if we receive a Config and SetupInfo before timing out
        if config_cvar
            .wait_timeout_while(
                config_lock.lock().unwrap(),
                RECEIVE_INITIAL_DEVICE_INFO_TIMEOUT,
                |config| config.is_none(),
            )
            .unwrap()
            .0
            .is_some()
            && setup_info_cvar
                .wait_timeout_while(
                    setup_info_lock.lock().unwrap(),
                    RECEIVE_INITIAL_DEVICE_INFO_TIMEOUT,
                    |setup_info| setup_info.is_none(),
                )
                .unwrap()
                .0
                .is_some()
        {
            Ok(())
        } else {
            Err(ConnectionError::DeviceInfoNotReceived)
        }
    }
}

impl Debug for MessageContainer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MessageContainer")
            .field("config", &self.config.0.lock().unwrap())
            .field("config_exp", &self.config_exp.0.lock().unwrap())
            .field("config_cw", &self.config_cw.0.lock().unwrap())
            .field("config_cw_exp", &self.config_cw_exp.0.lock().unwrap())
            .field("config_amp_sweep", &self.config_amp_sweep.0.lock().unwrap())
            .field(
                "config_amp_sweep_exp",
                &self.config_amp_sweep_exp.0.lock().unwrap(),
            )
            .field(
                "config_freq_sweep",
                &self.config_freq_sweep.0.lock().unwrap(),
            )
            .field(
                "config_freq_sweep_exp",
                &self.config_freq_sweep_exp.0.lock().unwrap(),
            )
            .field("screen_data", &self.screen_data.0.lock().unwrap())
            .field("temperature", &self.temperature.0.lock().unwrap())
            .field("setup_info", &self.setup_info.0.lock().unwrap())
            .field("serial_number", &self.serial_number.0.lock().unwrap())
            .finish()
    }
}