uldaqrs 0.2.0

Safe Rust bindings for the uldaq library (Measurement Computing / Data Translation DAQ devices)
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
//! Device enumeration and the device handle wrapper.

use std::os::raw::{c_char, c_int, c_longlong};

use uldaq_sys as sys;

use crate::error::*;
use crate::types::*;

/// The maximum number of devices that can be enumerated in a single call to
/// [`get_device_inventory`].
const MAX_DEV_COUNT: u32 = 100;

/// Interpret a NUL-terminated (or fully filled) C character array as a
/// `String`. Never reads out of bounds.
fn c_char_array_to_string(arr: &[c_char]) -> String {
    let len = arr.iter().position(|&c| c == 0).unwrap_or(arr.len());
    // SAFETY: `len` is bounded by `arr.len()`, and the pointer cast is valid
    // for reading `len` bytes since `c_char` has the same size as `u8`.
    let bytes = unsafe { std::slice::from_raw_parts(arr.as_ptr() as *const u8, len) };
    String::from_utf8_lossy(bytes).into_owned()
}

/// Copy a string into a NUL-terminated C character array of fixed size,
/// truncating when the string does not fit (reserving one byte for the
/// terminator).
fn string_to_c_char_array<const N: usize>(s: &str) -> [c_char; N] {
    let mut arr = [0 as c_char; N];
    let bytes = s.as_bytes();
    let n = bytes.len().min(N - 1);
    // SAFETY: `n` is bounded by `N`, and `c_char` has the same size as `u8`.
    arr[..n]
        .copy_from_slice(unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const c_char, n) });
    arr
}

/// A descriptor of a DAQ device, as returned by the device inventory.
///
/// This is the safe counterpart of the raw `DaqDeviceDescriptor` struct in the
/// bindings; the fixed-size C string fields are converted to owned `String`s.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DaqDeviceDescriptor {
    /// The generic (unqualified) product name of the device.
    pub product_name: String,
    /// The numeric product type identifier.
    pub product_id: u32,
    /// The physical connection interface of the device.
    pub interface: DaqDeviceInterface,
    /// Similar to the product name, but may contain additional information.
    pub dev_string: String,
    /// A string that uniquely identifies the device (serial number or MAC address).
    pub unique_id: String,
}

impl DaqDeviceDescriptor {
    /// Convert from the raw C struct.
    fn from_sys(d: &sys::DaqDeviceDescriptor) -> DaqDeviceDescriptor {
        DaqDeviceDescriptor {
            product_name: c_char_array_to_string(&d.productName),
            product_id: d.productId,
            interface: DaqDeviceInterface::from_bits_truncate(d.devInterface),
            dev_string: c_char_array_to_string(&d.devString),
            unique_id: c_char_array_to_string(&d.uniqueId),
        }
    }

    /// Convert to the raw C struct.
    fn to_sys(&self) -> sys::DaqDeviceDescriptor {
        let mut d: sys::DaqDeviceDescriptor = unsafe { std::mem::zeroed() };
        d.productName = string_to_c_char_array(&self.product_name);
        d.productId = self.product_id;
        d.devInterface = self.interface.bits();
        d.devString = string_to_c_char_array(&self.dev_string);
        d.uniqueId = string_to_c_char_array(&self.unique_id);
        d
    }
}

/// Enumerate the DAQ devices connected to the system that match `interface`.
///
/// # Example
///
/// ```
/// let devs = uldaqrs::get_device_inventory(uldaqrs::DaqDeviceInterface::ANY)
///     .expect("Failed to enumerate devices");
/// for dev in devs {
///     println!("{} ({})", dev.product_name, dev.unique_id);
/// }
/// ```
pub fn get_device_inventory(interface: DaqDeviceInterface) -> Result<Vec<DaqDeviceDescriptor>> {
    let mut descriptors: Vec<sys::DaqDeviceDescriptor> = (0..MAX_DEV_COUNT)
        .map(|_| unsafe { std::mem::zeroed() })
        .collect();
    let mut num_devices = MAX_DEV_COUNT;
    // SAFETY: `descriptors` is `MAX_DEV_COUNT` elements long, which matches
    // the capacity reported to the library through `num_devices`. The library
    // fills the array and sets `num_devices` to the number of devices found.
    let err = unsafe {
        sys::ulGetDaqDeviceInventory(interface.bits(), descriptors.as_mut_ptr(), &mut num_devices)
    };
    check(err)?;
    let num_devices = num_devices as usize;
    descriptors.truncate(num_devices);
    Ok(descriptors
        .iter()
        .map(DaqDeviceDescriptor::from_sys)
        .collect())
}

/// A handle to a DAQ device.
///
/// Obtained with [`DaqDevice::create`], which must be followed by a successful
/// [`DaqDevice::connect`] before the device can be used.
///
/// # Safety / threading
///
/// - The underlying UL library is **not** thread-safe with respect to a single
///   device handle. A `DaqDevice` must be used from a single thread at a time.
///   The type is `Send` but deliberately not `Sync`; the intended usage
///   pattern is to move the device into the thread that performs the I/O and
///   have that thread return it (or drop it) on exit.
/// - All active scans must be stopped (with the scan stop functions) before
///   the device is dropped, otherwise the drop will disconnect/release the
///   device while the driver may still be transferring data.
///
/// When the `DaqDevice` is dropped, the device is disconnected and the handle
/// is released automatically.
#[derive(Debug)]
pub struct DaqDevice {
    handle: sys::DaqDeviceHandle,
}

impl DaqDevice {
    /// Create a device handle for the device described by `desc`.
    ///
    /// This does not yet connect to the device; call [`connect`](DaqDevice::connect)
    /// afterwards. Fails with [`Error::DeviceCreateFailed`] when the library
    /// cannot create a handle, which typically means the device is already in
    /// use.
    pub fn create(desc: &DaqDeviceDescriptor) -> Result<DaqDevice> {
        let sysdesc = desc.to_sys();
        // SAFETY: `ulCreateDaqDevice` takes the descriptor by value and
        // returns a handle; no further preconditions apply. A zero handle
        // indicates failure.
        let handle = unsafe { sys::ulCreateDaqDevice(sysdesc) };
        if handle == 0 {
            return Err(Error::DeviceCreateFailed);
        }
        Ok(DaqDevice { handle })
    }

    /// Connect to the device. Must be called before any other operation on the
    /// device.
    pub fn connect(&self) -> Result<()> {
        // SAFETY: `handle` is valid and the device is not connected yet.
        check(unsafe { sys::ulConnectDaqDevice(self.handle) })
    }

    /// Disconnect from the device. The handle remains valid and can be
    /// reconnected with [`connect`](DaqDevice::connect).
    pub fn disconnect(&self) -> Result<()> {
        // SAFETY: `handle` is valid.
        check(unsafe { sys::ulDisconnectDaqDevice(self.handle) })
    }

    /// Release the device handle. The handle becomes invalid; a new one must
    /// be created with [`create`](DaqDevice::create).
    pub fn release(&self) -> Result<()> {
        // SAFETY: `handle` is valid.
        check(unsafe { sys::ulReleaseDaqDevice(self.handle) })
    }

    /// Set an integer-valued AI configuration item for `channel`.
    pub fn set_ai_config(&self, item: AiConfigItem, channel: u32, value: i64) -> Result<()> {
        // SAFETY: `handle` is valid and the device is connected. The remaining
        // arguments are plain values.
        check(unsafe { sys::ulAISetConfig(self.handle, item.into(), channel, value as c_longlong) })
    }

    /// Set a floating-point-valued AI configuration item for `channel`.
    pub fn set_ai_config_dbl(&self, item: AiConfigItemDbl, channel: u32, value: f64) -> Result<()> {
        // SAFETY: `handle` is valid and the device is connected. The remaining
        // arguments are plain values.
        check(unsafe { sys::ulAISetConfigDbl(self.handle, item.into(), channel, value) })
    }

    /// Set the sensor sensitivity (in the device's native unit, e.g. V/g or
    /// mV/Pa) of an input channel. Used to normalize the measured signal.
    pub fn set_ai_sensor_sensitivity(&self, channel: u32, sensitivity: f64) -> Result<()> {
        self.set_ai_config_dbl(AiConfigItemDbl::ChanSensorSensitivity, channel, sensitivity)
    }

    /// Set the input coupling mode (AC or DC) of an input channel.
    pub fn set_ai_coupling_mode(&self, channel: u32, mode: CouplingMode) -> Result<()> {
        self.set_ai_config(AiConfigItem::ChanCouplingMode, channel, mode as i64)
    }

    /// Enable or disable the IEPE constant current excitation of an input
    /// channel.
    pub fn set_ai_iepe_mode(&self, channel: u32, mode: IepeMode) -> Result<()> {
        self.set_ai_config(AiConfigItem::ChanIepeMode, channel, mode as i64)
    }

    /// Start a continuous input scan on the given channels.
    ///
    /// The data is written to `data` in interleaved format: for each frame,
    /// one sample per channel, in the order of `channels`. The buffer must
    /// hold at least `channels.len() * samples_per_channel` samples.
    ///
    /// On success, returns the *actual* sample rate used by the driver, which
    /// may differ from the requested `rate`.
    ///
    /// # Safety
    ///
    /// The driver writes into `data` asynchronously for as long as the scan
    /// runs. The buffer must not be resized, reallocated, or read while the
    /// buffer must not be resized, reallocated, or read while the scan is
    /// active unless the caller knows that the driver is not writing
    /// into it. Stop the scan with [`daq_in_scan_stop`](DaqDevice::daq_in_scan_stop)
    /// before dropping the buffer.
    #[allow(clippy::too_many_arguments)]
    pub fn daq_in_scan(
        &self,
        channels: &[DaqInChanDescriptor],
        samples_per_channel: usize,
        rate: f64,
        options: ScanOption,
        flags: DaqInScanFlag,
        data: &mut [f64],
    ) -> Result<f64> {
        if channels.is_empty() {
            return Err(Error::InvalidArgument("at least one channel is required"));
        }
        if samples_per_channel == 0 {
            return Err(Error::InvalidArgument(
                "samples per channel must be greater than zero",
            ));
        }
        let required = channels.len() * samples_per_channel;
        if data.len() < required {
            return Err(Error::InvalidArgument(
                "data buffer too small: expected at least channels.len() * samples_per_channel samples",
            ));
        }
        let mut sysdescs: Vec<sys::DaqInChanDescriptor> = channels.iter().map(Into::into).collect();
        let mut rate = rate;
        // SAFETY: `sysdescs` is valid for `channels.len()` elements,
        // `samples_per_channel` and `data.len()` are checked above, and the
        // output `rate` is updated by the driver on success.
        let err = unsafe {
            sys::ulDaqInScan(
                self.handle,
                sysdescs.as_mut_ptr(),
                sysdescs.len() as c_int,
                samples_per_channel as c_int,
                &mut rate,
                options.bits(),
                flags.into(),
                data.as_mut_ptr(),
            )
        };
        check(err)?;
        Ok(rate)
    }

    /// Obtain the status and transfer progress of the running input scan.
    pub fn daq_in_scan_status(&self) -> Result<(ScanStatus, TransferStatus)> {
        let mut status: sys::ScanStatus = 0;
        let mut xfer: sys::TransferStatus = unsafe { std::mem::zeroed() };
        // SAFETY: both out-parameters point to valid memory.
        let err = unsafe { sys::ulDaqInScanStatus(self.handle, &mut status, &mut xfer) };
        check(err)?;
        let status = ScanStatus::from_raw(status)
            .ok_or(Error::Internal("driver returned an unknown scan status"))?;
        Ok((status, xfer.into()))
    }

    /// Stop the running input scan.
    pub fn daq_in_scan_stop(&self) -> Result<()> {
        // SAFETY: `handle` is valid.
        check(unsafe { sys::ulDaqInScanStop(self.handle) })
    }

    /// Start a continuous analog output scan for channels `low_chan` through
    /// `high_chan` (inclusive) at the given `range`.
    ///
    /// The data in `data` is interleaved: for each frame, one sample per
    /// channel, starting with `low_chan`. The buffer must hold at least
    /// `(high_chan - low_chan + 1) * samples_per_channel` samples.
    ///
    /// On success, returns the *actual* sample rate used by the driver.
    ///
    /// # Safety
    ///
    /// The driver reads from `data` asynchronously for as long as the scan
    /// runs. The buffer must not be resized or reallocated while the scan is
    /// active, and a half that has not yet been consumed by the driver must
    /// not be overwritten. Stop the scan with
    /// [`a_out_scan_stop`](DaqDevice::a_out_scan_stop) before dropping the
    /// buffer.
    #[allow(clippy::too_many_arguments)]
    pub fn a_out_scan(
        &self,
        low_chan: i32,
        high_chan: i32,
        range: Range,
        samples_per_channel: usize,
        rate: f64,
        options: ScanOption,
        flags: AOutScanFlag,
        data: &mut [f64],
    ) -> Result<f64> {
        if low_chan < 0 || high_chan < low_chan {
            return Err(Error::InvalidArgument(
                "invalid channel range: require 0 <= low_chan <= high_chan",
            ));
        }
        if samples_per_channel == 0 {
            return Err(Error::InvalidArgument(
                "samples per channel must be greater than zero",
            ));
        }
        let nchannels = (high_chan - low_chan + 1) as usize;
        if data.len() < nchannels * samples_per_channel {
            return Err(Error::InvalidArgument(
                "data buffer too small: expected at least (high_chan - low_chan + 1) * samples_per_channel samples",
            ));
        }
        let mut rate = rate;
        // SAFETY: channel range and buffer size are checked above, and the
        // output `rate` is updated by the driver on success.
        let err = unsafe {
            sys::ulAOutScan(
                self.handle,
                low_chan,
                high_chan,
                range.into(),
                samples_per_channel as c_int,
                &mut rate,
                options.bits(),
                flags.into(),
                data.as_mut_ptr(),
            )
        };
        check(err)?;
        Ok(rate)
    }

    /// Obtain the status and transfer progress of the running output scan.
    pub fn a_out_scan_status(&self) -> Result<(ScanStatus, TransferStatus)> {
        let mut status: sys::ScanStatus = 0;
        let mut xfer: sys::TransferStatus = unsafe { std::mem::zeroed() };
        // SAFETY: both out-parameters point to valid memory.
        let err = unsafe { sys::ulAOutScanStatus(self.handle, &mut status, &mut xfer) };
        check(err)?;
        let status = ScanStatus::from_raw(status)
            .ok_or(Error::Internal("driver returned an unknown scan status"))?;
        Ok((status, xfer.into()))
    }

    /// Stop the running output scan.
    pub fn a_out_scan_stop(&self) -> Result<()> {
        // SAFETY: `handle` is valid.
        check(unsafe { sys::ulAOutScanStop(self.handle) })
    }
}

impl Drop for DaqDevice {
    fn drop(&mut self) {
        // Disconnect and release the handle. Errors are ignored here: the
        // device is going away anyway, and the library returns error codes for
        // a device that was already disconnected/released.
        // SAFETY: `handle` is valid, or already released by a previous call;
        // the library handles both cases.
        unsafe {
            let _ = sys::ulDisconnectDaqDevice(self.handle);
            let _ = sys::ulReleaseDaqDevice(self.handle);
        }
    }
}

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

    #[test]
    fn c_string_conversion_roundtrip() {
        let arr = string_to_c_char_array::<64>("DT9837A");
        assert_eq!(c_char_array_to_string(&arr), "DT9837A");
    }

    #[test]
    fn descriptor_roundtrip() {
        let desc = DaqDeviceDescriptor {
            product_name: "DT9837A".into(),
            product_id: 0x3998A,
            interface: DaqDeviceInterface::USB,
            dev_string: "DT9837A".into(),
            unique_id: "ABCDEF".into(),
        };
        let sysdesc = desc.to_sys();
        let back = DaqDeviceDescriptor::from_sys(&sysdesc);
        assert_eq!(back, desc);
    }

    #[test]
    fn long_string_is_truncated() {
        let arr = string_to_c_char_array::<16>("this string is way too long for the array");
        // Must be NUL-terminated
        assert_eq!(arr[15], 0);
        let s = c_char_array_to_string(&arr);
        assert!(s.len() < 16);
    }
}