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
use super::*;
use crate::measurement::*;
use crate::*;
use anyhow::{Result, anyhow};
use serde::{Deserialize, Serialize};
use snafu::prelude::*;
use std::{collections::HashMap, default, ops::Index, path::PathBuf, rc::Rc};
#[derive(Serialize, Default, Deserialize, Clone, Debug, PartialEq)]
#[cfg_attr(
feature = "python-bindings",
gen_stub_pyclass_enum,
pyclass(eq, eq_int, from_py_object)
)]
pub enum CouplingMode {
/// DC coupling
#[default]
DC,
/// AC coupling
AC,
/// AC coupling with IEPE (constant current power supply)
ACWithIEPE,
}
/// DAQ Configuration for a single channel
#[derive(Serialize, Deserialize, Clone, Debug)]
#[cfg_attr(
feature = "python-bindings",
gen_stub_pyclass,
pyclass(get_all, set_all, from_py_object)
)]
pub struct DaqChannel {
/// Whether the channel is enabled
pub enabled: bool,
/// Readable name for channel
pub name: String,
/// To convert to physical units. Divide values by this to obtain it.
pub sensitivity: Flt,
/// Enabled hardware AC coupling (if)
pub couplingMode: CouplingMode,
/// The configured range (minumum, maximum) value
pub range: (Flt, Flt),
/// Physical quantity
pub qty: Qty,
/// Apply digital highpass filter to remove D.C. before processing
/// Value is in Hz. A value <= 0 means it is disabled.
pub digitalHighpassCutOn: Option<Positive>,
}
impl PartialEq for DaqChannel {
/// Custom implementation of PartialEq that only compares name and
/// sensitivity
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.sensitivity == other.sensitivity && self.qty == other.qty
}
}
impl Default for DaqChannel {
fn default() -> Self {
DaqChannel {
enabled: false,
name: "".into(),
sensitivity: 1.0,
couplingMode: Default::default(),
range: (-1.0, 1.0),
qty: Qty::Number,
digitalHighpassCutOn: None,
}
}
}
impl DaqChannel {
/// Default channel configuration for audio input from a certain channel
pub fn defaultAudio<T: Into<String>>(name: T) -> Self {
DaqChannel {
enabled: true,
name: name.into(),
sensitivity: 1.0,
couplingMode: CouplingMode::AC,
range: (-1.0, 1.0),
qty: Qty::Number,
digitalHighpassCutOn: None,
}
}
/// Create a vector of `DaqChannel` from separate slices of channel names,
/// quantities, and sensitivities. Sets all other fields to default values.
///
/// # Arguments
///
/// * `nchannels` - Number of channels to create
/// * `names` - Optional slice of channel names
/// * `qtys` - Optional slice of channel quantities
/// * `sensitivities` - Optional slice of channel sensitivities
/// * `context` - Context string for error messages
///
pub fn fromMultipleSeparateSlices(
nchannels: usize,
names: Option<&[&str]>,
qtys: Option<&[Qty]>,
sensitivities: Option<&[Flt]>,
context: &str,
) -> std::result::Result<Vec<Self>, MeasurementError> {
// Validate optional arguments against channel count
let channel_names = if let Some(names) = names {
ensure!(
names.len() == nchannels,
LogicSnafu {
name: context,
message: format!(
"Number of channel names ({}) does not match channel count ({nchannels})",
names.len()
)
}
);
names.iter().map(|n| n.to_string()).collect::<Vec<_>>()
} else {
Vec::from_iter((0..nchannels).map(|i| format!("Unnamed input channel {i}")))
};
let sensitivities = if let Some(sens) = sensitivities {
ensure!(
sens.len() == nchannels,
LogicSnafu {
name: context,
message: format!(
"Number of sensitivities ({}) must match channel count ({nchannels})",
sens.len()
)
}
);
sens.to_vec()
} else {
Vec::from_iter((0..nchannels).map(|_| 1.0))
};
let quantities = if let Some(qty) = qtys {
ensure!(
qty.len() == nchannels,
LogicSnafu {
name: context,
message: format!(
"Number of quantities ({}) must match channel count ({nchannels})",
qty.len()
)
}
);
qty.to_vec()
} else {
Vec::from_iter((0..nchannels).map(|_| Qty::default()))
};
Ok(channel_names
.into_iter()
.zip(quantities.into_iter().zip(sensitivities))
.map(|(name, (qty, sensitivity))| Self {
name,
qty,
sensitivity,
..Self::default()
})
.collect::<Vec<_>>())
}
}
#[cfg_attr(feature = "python-bindings", pymethods, gen_stub_pymethods)]
impl DaqChannel {
#[cfg(feature = "python-bindings")]
#[new]
fn new() -> Self {
Self::default()
}
}
/// Configuration of a device.
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(
feature = "python-bindings",
gen_stub_pyclass,
pyclass(get_all, set_all, from_py_object)
)]
pub struct DaqConfig {
/// The API
pub api: DaqApiDescriptor,
/// Device name. Should match when starting a stream
pub device_name: String,
/// Configuration of the input channels
pub inchannel_config: Vec<DaqChannel>,
/// Configuration of the output channels
pub outchannel_config: Vec<DaqChannel>,
/// The data type to use
pub dtype: DataType,
/// The index to use in the list of possible sample rates
pub sampleRateIndex: usize,
/// The index to use in the list of possible frames per block
pub framesPerBlockIndex: usize,
/// Used when output channels should be monitored, i.e. reverse-looped back as input channels.
pub monitorOutput: bool,
}
impl Eq for DaqConfig {}
#[cfg_attr(feature = "python-bindings", gen_stub_pymethods, pymethods)]
impl DaqConfig {
#[cfg(feature = "python-bindings")]
#[pyo3(name = "newFromDeviceInfo")]
#[staticmethod]
fn newFromDeviceInfo_py(d: &DeviceInfo) -> PyResult<DaqConfig> {
Ok(DaqConfig::newFromDeviceInfo(d))
}
#[cfg(feature = "python-bindings")]
fn __repr__(&self) -> String {
format!("{self:#?}")
}
/// Returns the total number of channels that appear in a running input stream.
pub fn numberEnabledInChannels(&self) -> usize {
self.inchannel_config.iter().filter(|ch| ch.enabled).count()
}
/// Returns the total number of channels that appear in a running output stream.
pub fn numberEnabledOutChannels(&self) -> usize {
self.outchannel_config
.iter()
.filter(|ch| ch.enabled)
.count()
}
/// Provide samplerate, based on device and specified sample rate index
pub fn sampleRate(&self, dev: &DeviceInfo) -> Flt {
*dev.avSampleRates.get(self.sampleRateIndex).unwrap()
}
/// Provide samplerate, based on device and specified sample rate index
pub fn framesPerBlock(&self, dev: &DeviceInfo) -> usize {
dev.avFramesPerBlock[self.framesPerBlockIndex]
}
/// Returns vec of channel configuration for enabled input channels only
pub fn enabledInChannels(&self) -> Vec<DaqChannel> {
self.inchannel_config
.iter()
.filter(|ch| ch.enabled)
.cloned()
.collect()
}
/// Returns a list of enabled input channel numbers as indices
/// in the list of all input channels (enabled and not)
pub fn enabledInchannelsList(&self) -> Vec<usize> {
self.inchannel_config
.iter()
.enumerate()
.filter(|(_, ch)| ch.enabled)
.map(|(i, _)| i)
.collect()
}
/// Returns vec of channel configuration for enabled output channels only
pub fn enabledOutChannels(&self) -> Vec<DaqChannel> {
self.outchannel_config
.iter()
.filter(|ch| ch.enabled)
.cloned()
.collect()
}
/// Returns the channel number of the highest enabled input channel, if any.
pub fn highestEnabledInChannel(&self) -> Option<usize> {
let mut highest = None;
self.inchannel_config.iter().enumerate().for_each(|(i, c)| {
if c.enabled {
highest = Some(i);
}
});
highest
}
/// Returns the channel number of the highest enabled output channel, if any.
pub fn highestEnabledOutChannel(&self) -> Option<usize> {
let mut highest = None;
self.outchannel_config
.iter()
.enumerate()
.for_each(|(i, c)| {
if c.enabled {
highest = Some(i);
}
});
highest
}
/// Change state of all output channels, enables them all, or disables them
/// all.
pub fn setAllOutputEnabled(&mut self, enabled: bool) {
self.outchannel_config
.iter_mut()
.for_each(|ch| ch.enabled = enabled);
}
}
impl DaqConfig {
/// Creates a new default device configuration for a given device as specified with
/// the DeviceInfo descriptor.
pub fn newFromDeviceInfo(devinfo: &DeviceInfo) -> DaqConfig {
let inchannel_config = (0..devinfo.iChannelCount)
.map(|i| DaqChannel {
name: format!("Unnamed input channel {i}"),
..Default::default()
})
.collect();
let outchannel_config = (0..devinfo.oChannelCount)
.map(|i| DaqChannel {
name: format!("Unnamed output channel {i}"),
..Default::default()
})
.collect();
let sampleRateIndex = devinfo
.avSampleRates
.iter()
.position(|x| x == &devinfo.prefSampleRate)
.unwrap_or(devinfo.avSampleRates.len() / 2);
// Choose 4096 when in list, otherwise choose the highes available value in list
let framesPerBlockIndex = devinfo
.avFramesPerBlock
.iter()
.position(|x| x == &4096)
.unwrap_or(devinfo.avFramesPerBlock.len() - 1);
DaqConfig {
api: devinfo.api.clone(),
device_name: devinfo.device_name.clone(),
inchannel_config,
outchannel_config,
dtype: devinfo.prefDataType,
sampleRateIndex,
framesPerBlockIndex,
monitorOutput: false,
}
}
/// Serialize DaqConfig object to TOML.
///
/// Args
///
/// * writer: Output writer, can be file or string, or anything that *is* std::io::Write
///
pub fn serialize_TOML(&self, writer: &mut dyn std::io::Write) -> Result<()> {
let ser_str = toml::to_string(&self)?;
writer.write_all(ser_str.as_bytes())?;
Ok(())
}
/// Deserialize structure from TOML data
///
/// # Args
///
/// * reader: implements the Read trait, from which we read the data.
pub fn deserialize_TOML<T>(reader: &mut T) -> Result<DaqConfig>
where
T: std::io::Read,
{
let mut read_str = vec![];
reader.read_to_end(&mut read_str)?;
let read_str = String::from_utf8(read_str)?;
DaqConfig::deserialize_TOML_str(&read_str)
}
/// Deserialize from TOML string
///
/// # Args
///
/// * st: string containing TOML data.
pub fn deserialize_TOML_str(st: &str) -> Result<DaqConfig> {
let res: DaqConfig = toml::from_str(st)?;
Ok(res)
}
/// Write this configuration to a TOML file.
///
/// Args
///
/// * file: Name of file to write to
///
pub fn serialize_TOML_file(&self, file: &PathBuf) -> Result<()> {
let mut file = std::fs::File::create(file)?;
self.serialize_TOML(&mut file)?;
Ok(())
}
}