1use crate::{
2 dependencies::{load_dependencies, LoadedDependencies},
3 get_version_string, parse_enum_result,
4 trampoline::split_closure,
5 EnumerationResult, PicoDriver,
6};
7use parking_lot::RwLock;
8use pico_common::{
9 ChannelConfig, Driver, FromPicoStr, PicoChannel, PicoError, PicoInfo, PicoRange, PicoResult,
10 PicoStatus, SampleConfig, ToPicoStr,
11};
12use pico_sys_dynamic::ps4000::PS4000Loader;
13use std::{pin::Pin, sync::Arc};
14
15pub struct PS4000Driver {
16 _dependencies: LoadedDependencies,
17 bindings: PS4000Loader,
18}
19
20impl std::fmt::Debug for PS4000Driver {
21 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 f.debug_struct("PS4000Driver").finish()
23 }
24}
25
26impl PS4000Driver {
27 pub fn new<P>(path: P) -> Result<Self, ::libloading::Error>
28 where
29 P: AsRef<::std::ffi::OsStr>,
30 {
31 let dependencies = load_dependencies(&path.as_ref());
32 let bindings = unsafe { PS4000Loader::new(path)? };
33 unsafe { bindings.ps4000ApplyFix(0x1ced9168, 0x11e6) };
35 Ok(PS4000Driver {
36 bindings,
37 _dependencies: dependencies,
38 })
39 }
40}
41
42impl PicoDriver for PS4000Driver {
43 fn get_driver(&self) -> Driver {
44 Driver::PS3000A
45 }
46
47 #[tracing::instrument(level = "trace", skip(self))]
48 fn get_version(&self) -> PicoResult<String> {
49 let raw_version = self.get_unit_info(0, PicoInfo::DRIVER_VERSION)?;
50
51 Ok(get_version_string(&raw_version))
54 }
55
56 #[tracing::instrument(level = "trace", skip(self))]
57 fn get_path(&self) -> PicoResult<Option<String>> {
58 Ok(Some(self.get_unit_info(0, PicoInfo::DRIVER_PATH)?))
59 }
60
61 #[tracing::instrument(level = "trace", skip(self))]
62 fn enumerate_units(&self) -> PicoResult<Vec<EnumerationResult>> {
63 let mut device_count = 0;
64 let mut serial_buf = "-v".into_pico_i8_string();
65 serial_buf.extend(vec![0i8; 1000]);
66 let mut serial_buf_len = serial_buf.len() as i16;
67
68 let status = PicoStatus::from(unsafe {
69 self.bindings.ps4000EnumerateUnits(
70 &mut device_count,
71 serial_buf.as_mut_ptr(),
72 &mut serial_buf_len,
73 )
74 });
75
76 match status {
77 PicoStatus::NOT_FOUND => Ok(Vec::new()),
78 PicoStatus::OK => Ok(parse_enum_result(&serial_buf, serial_buf_len as usize)),
79 x => Err(PicoError::from_status(x, "enumerate_units")),
80 }
81 }
82
83 #[tracing::instrument(level = "trace", skip(self))]
84 fn open_unit(&self, serial: Option<&str>) -> PicoResult<i16> {
85 let serial = serial.map(|s| s.into_pico_i8_string());
86
87 let mut handle = -1i16;
88 let status = PicoStatus::from(unsafe {
89 match serial {
90 Some(mut serial) => self
91 .bindings
92 .ps4000OpenUnitEx(&mut handle, serial.as_mut_ptr()),
93 None => self
94 .bindings
95 .ps4000OpenUnitEx(&mut handle, std::ptr::null_mut()),
96 }
97 });
98
99 match status {
100 PicoStatus::OK => Ok(handle),
101 x => Err(PicoError::from_status(x, "open_unit")),
102 }
103 }
104
105 #[tracing::instrument(level = "trace", skip(self))]
106 fn ping_unit(&self, handle: i16) -> PicoResult<()> {
107 PicoStatus::from(unsafe { self.bindings.ps4000PingUnit(handle) }).to_result((), "ping_unit")
108 }
109
110 #[tracing::instrument(level = "trace", skip(self))]
111 fn maximum_value(&self, handle: i16) -> PicoResult<i16> {
112 Ok(32_764)
113 }
114
115 #[tracing::instrument(level = "trace", skip(self))]
116 fn close(&self, handle: i16) -> PicoResult<()> {
117 PicoStatus::from(unsafe { self.bindings.ps4000CloseUnit(handle) })
118 .to_result((), "close_unit")
119 }
120
121 #[tracing::instrument(level = "trace", skip(self))]
122 fn get_unit_info(&self, handle: i16, info_type: PicoInfo) -> PicoResult<String> {
123 let mut string_buf: Vec<i8> = vec![0i8; 256];
124 let mut string_buf_out_len = vec![0i16];
125
126 let status = PicoStatus::from(unsafe {
127 self.bindings.ps4000GetUnitInfo(
128 handle,
129 string_buf.as_mut_ptr(),
130 string_buf.len() as i16,
131 string_buf_out_len.as_mut_ptr(),
132 info_type.into(),
133 )
134 });
135
136 match status {
137 PicoStatus::OK => Ok(string_buf.from_pico_i8_string(string_buf_out_len[0] as usize)),
138 x => Err(PicoError::from_status(x, "get_unit_info")),
139 }
140 }
141
142 #[tracing::instrument(level = "trace", skip(self))]
143 fn get_channel_ranges(&self, handle: i16, channel: PicoChannel) -> PicoResult<Vec<PicoRange>> {
144 let mut ranges = vec![0i32; 30];
145 let mut len = vec![30i32];
146
147 let status = PicoStatus::from(unsafe {
148 self.bindings.ps4000GetChannelInformation(
149 handle,
150 0,
151 0,
152 ranges.as_mut_ptr(),
153 len.as_mut_ptr(),
154 channel.into(),
155 )
156 });
157
158 match status {
159 PicoStatus::OK => Ok(ranges[0..len[0] as usize]
160 .to_vec()
161 .iter()
162 .map(|v| PicoRange::from(*v))
163 .collect()),
164 x => Err(PicoError::from_status(x, "get_channel_ranges")),
165 }
166 }
167
168 #[tracing::instrument(level = "trace", skip(self))]
169 fn enable_channel(
170 &self,
171 handle: i16,
172 channel: PicoChannel,
173 config: &ChannelConfig,
174 ) -> PicoResult<()> {
175 PicoStatus::from(unsafe {
176 self.bindings.ps4000SetChannel(
177 handle,
178 channel.into(),
179 1,
180 config.coupling.into(),
181 config.range.into(),
182 )
183 })
184 .to_result((), "set_channel")
185 }
186
187 #[tracing::instrument(level = "trace", skip(self))]
188 fn disable_channel(&self, handle: i16, channel: PicoChannel) -> PicoResult<()> {
189 PicoStatus::from(unsafe {
190 self.bindings
191 .ps4000SetChannel(handle, channel.into(), 0, 0, 0)
192 })
193 .to_result((), "set_channel")
194 }
195
196 #[tracing::instrument(level = "trace", skip(self, buffer))]
197 fn set_data_buffer(
198 &self,
199 handle: i16,
200 channel: PicoChannel,
201 buffer: Arc<RwLock<Pin<Vec<i16>>>>,
202 buffer_len: usize,
203 ) -> PicoResult<()> {
204 let mut buffer = buffer.write();
205
206 PicoStatus::from(unsafe {
207 self.bindings.ps4000SetDataBuffer(
208 handle,
209 channel.into(),
210 buffer.as_mut_ptr(),
211 buffer_len as i32,
212 )
213 })
214 .to_result((), "set_data_buffer")
215 }
216
217 #[tracing::instrument(level = "trace", skip(self))]
218 fn start_streaming(
219 &self,
220 handle: i16,
221 sample_config: &SampleConfig,
222 ) -> PicoResult<SampleConfig> {
223 let mut sample_interval = vec![sample_config.interval];
224
225 PicoStatus::from(unsafe {
226 self.bindings.ps4000RunStreaming(
227 handle,
228 sample_interval.as_mut_ptr(),
229 sample_config.units.into(),
230 0,
231 0,
232 (false).into(),
233 1,
234 sample_config.samples_per_second(),
235 )
236 })
237 .to_result(
238 sample_config.with_interval(sample_interval[0]),
239 "start_streaming",
240 )
241 }
242
243 #[tracing::instrument(level = "trace", skip(self, callback))]
244 fn get_latest_streaming_values<'a>(
245 &self,
246 handle: i16,
247 _channels: &[PicoChannel],
248 mut callback: Box<dyn FnMut(usize, usize) + 'a>,
249 ) -> PicoResult<()> {
250 let mut simplify_args =
251 |_: i16, sample_count: i32, start_index: u32, _: i16, _: u32, _: i16, _: i16| {
252 callback(start_index as usize, sample_count as usize);
253 };
254
255 let status = PicoStatus::from(unsafe {
256 let (state, callback) = split_closure(&mut simplify_args);
257
258 self.bindings
259 .ps4000GetStreamingLatestValues(handle, Some(callback), state)
260 });
261
262 match status {
263 PicoStatus::OK | PicoStatus::BUSY => Ok(()),
264 x => Err(PicoError::from_status(x, "get_latest_streaming_values")),
265 }
266 }
267
268 #[tracing::instrument(level = "trace", skip(self))]
269 fn stop(&self, handle: i16) -> PicoResult<()> {
270 PicoStatus::from(unsafe { self.bindings.ps4000Stop(handle) }).to_result((), "stop")
271 }
272}