linux-gpib-rs 0.2.6

Low-level wrapper for Linux GPIB
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
#![allow(non_snake_case)]
use crate::error::{GpibError, IbError};
use crate::lowlevel::utility::Addr4882;
#[cfg(feature = "linuxgpib")]
use crate::lowlevel::utility::{ThreadIbcnt, ThreadIbcntl};
#[cfg(feature = "nigpib")]
use crate::lowlevel::utility::Ibcnt;

use crate::status::IbStatus;
use crate::types::{IbSendEOI, PrimaryAddress, SecondaryAddress};
use linux_gpib_sys::Addr4882_t;
use std::default::Default;
use std::os::raw::{c_int, c_uint, c_short, c_void};

/// find devices
///
/// FindLstn() will check the primary addresses in the padList array for devices. The GPIB addresses of all devices found will be stored in the resultList array, and ibcnt will be set to the number of devices found. The maxNumResults parameter limits the maximum number of results that will be returned, and is usually set to the number of elements in the resultList array. If more than maxNumResults devices are found, an ETAB error is returned in iberr. The padList should consist of primary addresses only, with no secondary addresses (all possible secondary addresses will be checked as necessary).
///
/// Your GPIB board must have the capability to monitor the NDAC bus line in order to use this function (see iblines).
///
/// This function has the additional effect of addressing the board as talker for the duration of the Find Listeners protocol, which is beyond what IEEE 488.2 specifies. This is done because some boards cannot reliably read the state of the NDAC bus line unless they are the talker. Being the talker causes the board's gpib transceiver to configure NDAC as an input, so its state can be reliably read from the bus through the transceiver.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-findlstn.html)
///
pub fn FindLstn(board_desc: c_int, padList: Vec<Addr4882>) -> Result<Vec<Addr4882>, GpibError> {
    let mut result: Vec<Addr4882_t> = Vec::new();
    result.resize_with(31, || linux_gpib_sys::NOADDR);
    let mut padList = padList
        .into_iter()
        .map(|a| a.addr)
        .collect::<Vec<Addr4882_t>>();
    padList.push(linux_gpib_sys::NOADDR);
    log::debug!("FindLstn({}, {:?})", board_desc, padList);
    unsafe {
        linux_gpib_sys::FindLstn(
            board_desc,
            padList.as_ptr(),
            result.as_mut_ptr(),
            padList.len().try_into()?,
        )
    };

    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };

    if status.err {
        #[cfg(feature = "linuxgpib")]
        let error = IbError::current_thread_local_error()?;
        #[cfg(feature = "nigpib")]
        let error = unsafe { IbError::current_global_error() }?;

        match error {
            IbError::EARG => {
                #[cfg(feature = "linuxgpib")]
                log::error!(
                    "Invalid primary address at index {} in padlist",
                    ThreadIbcnt(),
                );
                #[cfg(feature = "nigpib")]
                log::error!(
                    "Invalid primary address at index {} in padlist",
                    Ibcnt(),
                );
            }
            IbError::EBUS => {
                log::error!("No devices are connected to the GPIB.");
            }
            IbError::ETAB => {
                log::error!("The number of devices found on the GPIB exceed limit.");
            }
            _ => {}
        }
        log::debug!("-> {:?}", error);
        Err(GpibError::DriverError(status, error))
    } else {
        #[cfg(feature = "linuxgpib")]
        let n_values: usize = ThreadIbcntl().try_into()?;
        #[cfg(feature = "nigpib")]
        let n_values: usize = Ibcnt().try_into()?;

        result.truncate(n_values);
        log::debug!("-> {:?}", result);
        Ok(result.into_iter().map(|a| Addr4882 { addr: a }).collect())
    }
}

/// Find all listeners on board.
pub fn FindAllLstn(board_desc: c_int) -> Result<Vec<Addr4882>, GpibError> {
    let padList = (1..31)
        .into_iter()
        .map(|pad| Addr4882::new(PrimaryAddress::new(pad)?, SecondaryAddress::default()))
        .collect::<Result<Vec<Addr4882>, GpibError>>()?;
    FindLstn(board_desc, padList)
}

/// clear a device
///
/// DevClear() causes the interface board specified by board_desc to send the clear command to the GPIB addresses specified by address. The results of the serial polls are stored into resultList. If you wish to clear multiple devices simultaneously, use DevClearList()
pub fn DevClear(board: c_int, address: Addr4882) -> Result<(), GpibError> {
    log::debug!("DevClear({}, {})", board, address);
    unsafe {
        linux_gpib_sys::DevClear(board, address.addr);
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        log::debug!("-> {:?}", status);
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        log::debug!("-> {:?}", status);
        Ok(())
    }
}

/// clear multiple devices
///
/// DevClear() causes the interface board specified by board_desc to send the clear command simultaneously to all the GPIB addresses specified by the addressList array. If addressList is empty or NULL, then the clear command is sent to all devices on the bus. If you only wish to clear a single device, DevClear() or ibclr() may be slightly more convenient.
pub fn DevClearList(board: c_int, addresses: &Vec<Addr4882>) -> Result<(), GpibError> {
    let mut instruments = addresses
        .iter()
        .map(|a| a.addr)
        .collect::<Vec<Addr4882_t>>();
    instruments.push(linux_gpib_sys::NOADDR);
    log::debug!("DevClearList({:?}, {:?})", board, addresses);
    unsafe {
        linux_gpib_sys::DevClearList(board, instruments.as_ptr());
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    log::debug!("-> {:?}", status);
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// put devices into local mode.
///
/// 	EnableLocal() addresses all of the devices in the addressList array as listeners then sends the GTL (go to local) command byte, causing them to enter local mode. This requires that the board is the controller-in-charge. Note that while the REN (remote enable) bus line is asserted, the devices will return to remote mode the next time they are addressed.
///
///If addressList is empty or NULL, then the REN line is unasserted and all devices enter local mode. The board must be system controller to change the state of the REN line.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-enablelocal.html)
pub fn EnableLocal(board: c_int, addresses: &Vec<Addr4882>) -> Result<(), GpibError> {
    let mut instruments = addresses
        .iter()
        .map(|a| a.addr)
        .collect::<Vec<Addr4882_t>>();
    instruments.push(linux_gpib_sys::NOADDR);
    unsafe {
        linux_gpib_sys::EnableLocal(board, instruments.as_ptr());
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// put devices into remote mode.
///
/// EnableRemote() asserts the REN (remote enable) line, and addresses all of the devices in the addressList array as listeners (causing them to enter remote mode). The board must be system controller.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-enableremote.html)
pub fn EnableRemote(board: c_int, addresses: &Vec<Addr4882>) -> Result<(), GpibError> {
    let mut instruments = addresses
        .iter()
        .map(|a| a.addr)
        .collect::<Vec<Addr4882_t>>();
    instruments.push(linux_gpib_sys::NOADDR);
    unsafe {
        linux_gpib_sys::EnableRemote(board, instruments.as_ptr());
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// find device requesting service and read its status byte
///
/// FindRQS will serial poll the GPIB addresses specified in the addressList array until it finds a device requesting service. The status byte of the device requesting service and its address are returned. If no device requesting service is found, an ETAB error is returned.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-findrqs.html)
pub fn FindRQS(board: c_int, addresses: &Vec<Addr4882>) -> Result<(Addr4882, c_short), GpibError> {
    let mut instruments = addresses
        .iter()
        .map(|a| a.addr)
        .collect::<Vec<Addr4882_t>>();
    instruments.push(linux_gpib_sys::NOADDR);
    let mut status_byte: c_short = 0;
    unsafe {
        linux_gpib_sys::FindRQS(board, instruments.as_ptr(), &mut status_byte);
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        #[cfg(feature = "linuxgpib")]
        let index: usize = ThreadIbcnt().try_into()?;
        #[cfg(feature = "nigpib")]
        let index: usize = Ibcnt().try_into()?;
        if index >= addresses.len() {
            Err(GpibError::ValueError(
                "index stored in Ibcnt is larger than addresses array length".to_owned(),
            ))
        } else {
            Ok((addresses[index], status_byte))
        }
    }
}

/// make device controller-in-charge
///
/// PassControl() causes the board specified by board_desc to pass control to the device specified by address. On success, the device becomes the new controller-in-charge.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-passcontrol.html)
pub fn PassControl(board: c_int, address: Addr4882) -> Result<(), GpibError> {
    unsafe {
        linux_gpib_sys::PassControl(board, address.addr);
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// parallel poll devices
///
/// PPoll() is similar to the 'traditional' API function ibrpp(). It causes the interface board to perform a parallel poll, and stores the parallel poll byte in the location specified by result. Bits 0 to 7 of the parallel poll byte correspond to the dio lines 1 to 8, with a 1 indicating the corresponding dio line is asserted. The devices on the bus you wish to poll should be configured beforehand with PPollConfig(). The board must be controller-in-charge to perform a parallel poll.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-ppoll.html)
pub fn PPoll(board: c_int) -> Result<c_short, GpibError> {
    let mut result: c_short = 0;
    unsafe {
        linux_gpib_sys::PPoll(board, &mut result);
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(result)
    }
}

/// configure a device's parallel poll response
///
/// PPollConfig() configures the device specified by address to respond to parallel polls. The dio_line (valid values are 1 through 8) specifies which dio line the device being configured should use to send back its parallel poll response. The line_sense argument specifies the polarity of the response. If line_sense is nonzero, then the specified dio line will be asserted to indicate that the 'individual status bit' (or 'ist') is 1. If sense is zero, then the specified dio line will be asserted when ist is zero.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-ppollconfig.html)
pub fn PPollConfig(
    board: c_int,
    address: Addr4882,
    dio_line: c_int,
    line_sense: c_int,
) -> Result<(), GpibError> {
    unsafe {
        linux_gpib_sys::PPollConfig(board, address.addr, dio_line, line_sense);
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// disable devices' parallel poll response
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-ppollunconfig.html)
pub fn PPollUnconfig(board: c_int, addresses: &Vec<Addr4882>) -> Result<(), GpibError> {
    let mut instruments = addresses
        .iter()
        .map(|a| a.addr)
        .collect::<Vec<Addr4882_t>>();
    instruments.push(linux_gpib_sys::NOADDR);
    unsafe {
        linux_gpib_sys::PPollUnconfig(board, instruments.as_ptr());
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// read data
///
/// 	RcvRespMsg() reads data from the bus. A device must have already been addressed as talker (and the board as listener) before calling this function. Addressing may be accomplished with the ReceiveSetup() function.
///
/// Up to count bytes are read into the array specified by buffer. The termination argument specifies the 8-bit end-of-string character (which must be a value from 0 to 255) whose reception will terminate a read. termination can also be set to the 'STOPend' constant, in which case no end-of-string character will be used. Assertion of the EOI line will always end a read.
///
/// You may find it simpler to use the slightly higher level function Receive(), since it does not require addressing and reading of data to be performed separately.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-rcvrespmsg.html)
pub fn RcvRespMsg(board: c_int, buffer: &mut [u8], termination: c_int) -> Result<(), GpibError> {
    unsafe {
        linux_gpib_sys::RcvRespMsg(
            board,
            buffer.as_mut_ptr() as *mut c_void,
            buffer.len().try_into()?,
            termination,
        );
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// serial poll a device
///
/// ReadStatusByte() causes the board specified by the board descriptor board_desc to serial poll the GPIB address specified by address. The status byte is stored at the location specified by the result pointer. If you wish to serial poll multiple devices, it may be slightly more efficient to use AllSPoll(). Serial polls may also be conducted with the 'traditional API' function ibrsp().
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-readstatusbyte.html)
pub fn ReadStatusByte(board: c_int, address: Addr4882) -> Result<c_short, GpibError> {
    let mut result: c_short = 0;
    unsafe {
        linux_gpib_sys::ReadStatusByte(board, address.addr, &mut result);
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(result)
    }
}

/// perform receive addressing and read data
///
/// Receive() performs the necessary addressing, then reads data from the device specified by address. It is equivalent to a ReceiveSetup() call followed by a RcvRespMsg() call.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-receive.html)
pub fn Receive(
    board: c_int,
    address: Addr4882,
    buffer: &mut [u8],
    termination: c_int,
) -> Result<(IbStatus, usize), GpibError> {
    log::debug!("Receive({:?}, {:?})", board, address);
    unsafe {
        linux_gpib_sys::Receive(
            board,
            address.addr,
            buffer.as_mut_ptr() as *mut c_void,
            buffer.len().try_into()?,
            termination,
        );
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        log::debug!("-> {:?}", status);
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        #[cfg(feature = "linuxgpib")]
        let n_read = ThreadIbcntl().try_into()?;
        #[cfg(feature = "nigpib")]
        let n_read = Ibcnt().try_into()?;
        log::debug!(
            "Receive({:?}, {:?}) -> Read {} bytes",
            board,
            address,
            n_read
        );
        Ok((status, n_read))
    }
}

/// perform receive addressing
///
/// 	ReceiveSetup() addresses the device specified by address as talker, and addresses the interface board as listener. A subsequent RcvRespMsg() call will read data from the device.
///
///You may find it simpler to use the slightly higher level function Receive(), since it does not require addressing and reading of data to be performed separately.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-receivesetup.html)
pub fn ReceiveSetup(board: c_int, address: Addr4882) -> Result<(), GpibError> {
    unsafe {
        linux_gpib_sys::ReceiveSetup(board, address.addr);
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// reset system
///
/// ResetSys() has the following effects:
///
/// - The remote enable bus line is asserted.
/// - An interface clear is performed (the interface clear bus line is asserted for at least 100 microseconds).
/// - The device clear command is sent to all the devices on the bus.
/// - The *RST message is sent to every device specified in the addressList.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-resetsys.html)
pub fn ResetSys(board: c_int, addresses: &Vec<Addr4882>) -> Result<(), GpibError> {
    let mut instruments = addresses
        .iter()
        .map(|a| a.addr)
        .collect::<Vec<Addr4882_t>>();
    instruments.push(linux_gpib_sys::NOADDR);
    unsafe {
        linux_gpib_sys::ResetSys(board, instruments.as_ptr());
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// perform send addressing and write data
///
/// Send() addresses the device specified by address as listener, then writes data onto the bus. It is equivalent to a SendList() except it only uses a single GPIB address to specify the listener instead of allowing an array of listeners.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-send.html)
pub fn Send(
    board: c_int,
    address: Addr4882,
    buffer: &[u8],
    eot_mode: IbSendEOI,
) -> Result<(), GpibError> {
    log::debug!("Send({:?}, {:?}, {:?})", board, address, buffer);
    unsafe {
        linux_gpib_sys::Send(
            board,
            address.addr,
            buffer.as_ptr() as *const c_void,
            buffer.len().try_into()?,
            eot_mode.as_eot(),
        );
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    log::debug!(
        "Send({:?}, {:?}, {:?}) -> {:?}",
        board,
        address,
        buffer,
        status
    );
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// perform interface clear
///
/// SendIFC() resets the GPIB bus by asserting the 'interface clear' (IFC) bus line for a duration of at least 100 microseconds. The board specified by board_desc must be the system controller in order to assert IFC. The interface clear causes all devices to untalk and unlisten, puts them into serial poll disabled state (don't worry, you will still be able to conduct serial polls), and the board becomes controller-in-charge.
pub fn SendIFC(board: c_int) -> Result<(), GpibError> {
    log::debug!("SendIFC({})", board);
    unsafe {
        linux_gpib_sys::SendIFC(board);
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    log::debug!("endIFC({}) -> {:?}", board, status);
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// write data to multiple devices
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-sendlist.html)
pub fn SendList(
    board: c_int,
    addresses: &Vec<Addr4882>,
    buffer: &[u8],
    eot_mode: IbSendEOI,
) -> Result<(), GpibError> {
    log::debug!("SendList({:?}, {:?}, {:?})", board, addresses, buffer);
    let mut instruments = addresses
        .iter()
        .map(|a| a.addr)
        .collect::<Vec<Addr4882_t>>();
    instruments.push(linux_gpib_sys::NOADDR);
    unsafe {
        linux_gpib_sys::SendList(
            board,
            instruments.as_ptr(),
            buffer.as_ptr() as *const c_void,
            buffer.len().try_into()?,
            eot_mode.as_eot(),
        );
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    log::debug!(
        "SendList({:?}, {:?}, {:?}) -> {:?}",
        board,
        addresses,
        buffer,
        status
    );
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// put devices into local lockout mode
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-sendllo.html)
pub fn SendLLO(board: c_int) -> Result<(), GpibError> {
    unsafe {
        linux_gpib_sys::SendLLO(board);
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// put devices into remote with lockout state
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-setrwls.html)
pub fn SetRWLS(board: c_int, addresses: &Vec<Addr4882>) -> Result<(), GpibError> {
    let mut instruments = addresses
        .iter()
        .map(|a| a.addr)
        .collect::<Vec<Addr4882_t>>();
    instruments.push(linux_gpib_sys::NOADDR);
    unsafe {
        linux_gpib_sys::SetRWLS(board, instruments.as_ptr());
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

///  query state of SRQ bus line
///
/// Returns true if the SRQ line is asserted, false if it is not asserted.
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-testsrq.html)
pub fn TestSRQ(board: c_int) -> Result<bool, GpibError> {
    let mut result: c_short = 10;
    unsafe {
        linux_gpib_sys::TestSRQ(board, &mut result);
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        match result {
            0 => Ok(false),
            1 => Ok(true),
            other => Err(GpibError::ValueError(format!("Unexpected value {}", other))),
        }
    }
}

/// perform self-test queries on devices
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-testsys.html)
pub fn TestSys(board: c_int, addresses: &Vec<Addr4882>) -> Result<Vec<c_short>, GpibError> {
    let mut instruments = addresses
        .iter()
        .map(|a| a.addr)
        .collect::<Vec<Addr4882_t>>();
    instruments.push(linux_gpib_sys::NOADDR);
    let mut results: Vec<c_short> = Vec::with_capacity(addresses.len());
    results.resize(addresses.len(), 0);
    unsafe {
        linux_gpib_sys::TestSys(board, instruments.as_ptr(), results.as_mut_ptr());
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(results)
    }
}

/// trigger a device
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-trigger.html)
pub fn Trigger(board: c_int, address: Addr4882) -> Result<(), GpibError> {
    unsafe {
        linux_gpib_sys::Trigger(board, address.addr);
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

/// trigger multiple devices
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-triggerlist.html)
pub fn TriggerList(board: c_int, addresses: &Vec<Addr4882>) -> Result<(), GpibError> {
    let mut instruments = addresses
        .iter()
        .map(|a| a.addr)
        .collect::<Vec<Addr4882_t>>();
    instruments.push(linux_gpib_sys::NOADDR);
    unsafe {
        linux_gpib_sys::TriggerList(board, instruments.as_ptr());
    }
    #[cfg(feature = "linuxgpib")]
    let status = IbStatus::current_thread_local_status();
    #[cfg(feature = "nigpib")]
    let status = unsafe { IbStatus::current_global_status() };
    if status.err {
        Err(GpibError::DriverError(
            status,
            #[cfg(feature = "linuxgpib")]
            IbError::current_thread_local_error()?,
            #[cfg(feature = "nigpib")]
            unsafe { IbError::current_global_error() }?,
        ))
    } else {
        Ok(())
    }
}

#[cfg(feature = "async-tokio")]
/// sleep until the SRQ bus line is asserted
///
/// See: [Linux GPIB Reference](https://linux-gpib.sourceforge.io/doc_html/reference-function-waitsrq.html)
pub async fn WaitSRQ(board: c_int) -> Result<c_short, GpibError> {
    tokio::task::spawn_blocking(move || {
        let mut result: c_short = 0;
        unsafe {
            linux_gpib_sys::WaitSRQ(board, &mut result);
        }
        #[cfg(feature = "linuxgpib")]
        let status = IbStatus::current_thread_local_status();
        #[cfg(feature = "nigpib")]
        let status = unsafe { IbStatus::current_global_status() };
        if status.err {
            Err(GpibError::DriverError(
                status,
                #[cfg(feature = "linuxgpib")]
                IbError::current_thread_local_error()?,
                #[cfg(feature = "nigpib")]
                unsafe { IbError::current_global_error() }?,
            ))
        } else {
            Ok(result)
        }
    })
    .await?
}