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
#![forbid(unsafe_code)]
use parking_lot::Mutex;
use pico_common::{PicoChannel, PicoInfo, PicoRange, PicoResult};
use pico_driver::{ArcDriver, PicoDriver};
use std::{
collections::HashMap,
fmt,
fmt::{Debug, Display},
sync::Arc,
};
pub type HandleMutex = Arc<Mutex<Option<i16>>>;
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone)]
pub struct PicoDevice {
#[cfg_attr(feature = "serde", serde(skip))]
pub handle: HandleMutex,
#[cfg_attr(feature = "serde", serde(skip))]
pub driver: ArcDriver,
pub variant: String,
pub serial: String,
pub usb_version: String,
#[cfg_attr(feature = "serde", serde(skip))]
pub max_adc_value: i16,
pub channel_ranges: HashMap<PicoChannel, Vec<PicoRange>>,
}
impl Debug for PicoDevice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.debug_struct("PicoDevice")
.field("variant", &self.variant)
.field("serial", &self.serial)
.finish()
}
}
impl Display for PicoDevice {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ({})", self.variant, self.serial)
}
}
impl PicoDevice {
pub fn try_open(driver: &Arc<dyn PicoDriver>, serial: Option<&str>) -> PicoResult<PicoDevice> {
let handle = driver.open_unit(serial)?;
let serial = match serial {
Some(s) => s.to_string(),
None => driver.get_unit_info(handle, PicoInfo::BATCH_AND_SERIAL)?,
};
let variant = driver.get_unit_info(handle, PicoInfo::VARIANT_INFO)?;
let usb_version = driver.get_unit_info(handle, PicoInfo::USB_VERSION)?;
let ch_count = variant[1..2]
.parse::<i32>()
.expect("Could not parse device variant for number of channels");
let channel_ranges = (0..ch_count)
.map(|ch| -> PicoResult<(PicoChannel, Vec<_>)> {
let ch: PicoChannel = ch.into();
Ok((ch, driver.get_channel_ranges(handle, ch)?))
})
.flatten()
.collect();
let max_adc_value = driver.maximum_value(handle)?;
Ok(PicoDevice {
handle: Arc::new(Mutex::new(Some(handle))),
driver: driver.clone(),
serial,
variant,
usb_version,
max_adc_value,
channel_ranges,
})
}
pub fn get_channels(&self) -> Vec<PicoChannel> {
self.channel_ranges.keys().copied().collect()
}
}
impl Drop for PicoDevice {
#[tracing::instrument(level = "trace", skip(self))]
fn drop(&mut self) {
if let Some(handle) = self.handle.lock().take() {
let _ = self.driver.close(handle);
}
}
}