Bus/LinuxGPIB.pm untested

filter: Statementstmt 0.0% 0 / 221 Branchbran 0.0% 0 / 82 Conditioncond 0.0% 0 / 60 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 397 SCAR 75.0
CC
42
Cov
0%
timeout
462.0
connection_write
30.0
new
20.0
CRAP 1806.0
1 package Lab::Bus::LinuxGPIB;
2 #ABSTRACT: LinuxGPIB bus
3 $Lab::Bus::LinuxGPIB::VERSION = '3.881';
4 use v5.20;
5  
6 use strict;
7 use Scalar::Util qw(weaken);
8 use Time::HiRes qw (usleep sleep);
9 use Lab::Bus;
10 use LinuxGpib ':all';
11 use Data::Dumper;
12 use Carp;
13  
14 our @ISA = ("Lab::Bus");
15  
16 our %fields = (
17 gpib_board => 0,
18 type => 'GPIB',
19 brutal => 0, # brutal as default?
20 wait_query => 10e-6, # sec;
21 read_length => 1000, # bytes
22 query_length => 300, # bytes
23 query_long_length => 10240, #bytes
24 );
25  
26 sub new {
27 my $proto = shift;
28 my $class = ref($proto) || $proto;
29 my $twin = undef;
30 my $self = $class->SUPER::new(@_)
31 ; # getting fields and _permitted from parent class
32 $self->${ \( __PACKAGE__ . '::_construct' ) }(__PACKAGE__);
33  
34 $self->gpib_board( $self->config()->{'gpib_board'} )
35 if ( exists $self->config()->{'gpib_board'} );
36  
37 # search for twin in %Lab::Bus::BusList. If there's none, place $self there and weaken it.
38 if ( $class eq __PACKAGE__ )
39 { # careful - do only if this is not a parent class constructor
40 if ( $twin = $self->_search_twin() ) {
41 undef $self;
42 return $twin; # ...and that's it.
43 }
44 else {
45 $Lab::Bus::BusList{ $self->type() }->{ $self->gpib_board() }
46 = $self;
47 weaken(
48 $Lab::Bus::BusList{ $self->type() }->{ $self->gpib_board() }
49 );
50 }
51 }
52  
53 return $self;
54 }
55  
56 sub connection_new { # { gpib_address => primary address }
57 my $self = shift;
58 my $args = undef;
59 if ( ref $_[0] eq 'HASH' ) {
60 $args = shift;
61 } # try to be flexible about options as hash/hashref
62 else { $args = {@_} }
63  
64 if ( !defined $args->{'gpib_address'}
65 || $args->{'gpib_address'} !~ /^[0-9]*$/ ) {
66 Lab::Exception::CorruptParameter->throw(
67 error => "No valid gpib address given to "
68 . __PACKAGE__
69 . "::connection_new()\n", );
70 }
71  
72 my $gpib_address = $args->{'gpib_address'};
73 my $connection_handle = undef;
74 my $gpib_handle = undef;
75  
76 # open device
77 # see: http://linux-gpib.sourceforge.net/doc_html/r1297.html
78 # for timeout constant table: http://linux-gpib.sourceforge.net/doc_html/r2137.html
79 # ibdev arguments: board index, primary address, secondary address, timeout (constants, see link), send_eoi, eos (end-of-string character)
80 # print "Opening device: " . $gpib_address . "\n";
81 $gpib_handle = ibdev( 0, $gpib_address, 0, 12, 1, 0 );
82  
83 #ibconfig($gpib_handle, 'IbcEOSrd', 1);
84  
85 $connection_handle
86 = { valid => 1, type => "GPIB", gpib_handle => $gpib_handle };
87 return $connection_handle;
88 }
89  
90 #
91 # Todo: Evaluate $ibstatus: http://linux-gpib.sourceforge.net/doc_html/r634.html
92 #
93 sub connection_read
94 { # @_ = ( $connection_handle, $args = { read_length, brutal }
95 my $self = shift;
96 my $connection_handle = shift;
97 my $args = undef;
98 if ( ref $_[0] eq 'HASH' ) {
99 $args = shift;
100 } # try to be flexible about options as hash/hashref
101 else { $args = {@_} }
102  
103 my $command = $args->{'command'} || undef;
104 my $brutal = $args->{'brutal'} || $self->brutal();
105 my $read_length = $args->{'read_length'} || $self->read_length();
106  
107 my $result = undef;
108 my $fragment = undef;
109 my $raw = "";
110 my $ib_bits = undef; # hash ref
111 my $ibstatus = undef;
112 my $ibsta_verbose = "";
113 my $decimal = 0;
114  
115 $ibstatus
116 = ibrd( $connection_handle->{'gpib_handle'}, $result, $read_length );
117 $ib_bits = $self->ParseIbstatus($ibstatus);
118  
119 while ( !$ib_bits->{'ERR'} && !$ib_bits->{'TIMO'} && !$ib_bits->{'END'} )
120 { # read on until the END status is set (and the whole string received)
121 $ibstatus = ibrd(
122 $connection_handle->{'gpib_handle'}, $fragment,
123 $read_length
124 );
125 $ib_bits = $self->ParseIbstatus($ibstatus);
126 $result .= $fragment;
127 }
128  
129 if ( $ib_bits->{'ERR'} && !$ib_bits->{'TIMO'} )
130 { # if the error is a timeout, we still evaluate the result and see what to do with the error later
131 Lab::Exception::GPIBError->throw(
132 error => sprintf( "ibrd failed with ibstatus %x\n", $ibstatus ),
133 ibsta => $ibstatus,
134 ibsta_hash => $ib_bits,
135 );
136 }
137  
138 # strip spaces and null byte
139 # note to self: find a way to access the ibcnt variable through the perl binding to use
140 # $result = substr($result, 0, $ibcnt)
141 $raw = $result;
142  
143 #$result =~ /^\s*([+-][0-9]*\.[0-9]*)([eE]([+-]?[0-9]*))?\s*\x00*$/;
144 #$result = $1;
145 $result =~ s/[\n\r\x00]*$//;
146  
147 #
148 # timeout occured - throw exception, but include the received data
149 # if the "Brutal" option is present, ignore the timeout and just return the data
150 #
151 if ( $ib_bits->{'ERR'} && $ib_bits->{'TIMO'} && !$brutal ) {
152 Lab::Exception::GPIBTimeout->throw(
153 error => sprintf(
154 "ibrd failed with a timeout, ibstatus %x\n", $ibstatus
155 ),
156 ibsta => $ibstatus,
157 ibsta_hash => $ib_bits,
158 data => $result
159 );
160 }
161  
162 # no timeout, regular return
163 return $result;
164 }
165  
166 sub connection_query
167 { # @_ = ( $connection_handle, $args = { command, read_length, wait_status, wait_query, brutal }
168 my $self = shift;
169 my $connection_handle = shift;
170 my $args = undef;
171 if ( ref $_[0] eq 'HASH' ) {
172 $args = shift;
173 } # try to be flexible about options as hash/hashref
174 else { $args = {@_} }
175  
176 my $command = $args->{'command'} || undef;
177 my $brutal = $args->{'brutal'} || $self->brutal();
178 my $read_length = $args->{'read_length'} || $self->read_length();
179 my $wait_query = $args->{'wait_query'} || $self->wait_query();
180 my $result = undef;
181  
182 $self->connection_write($args);
183  
184 sleep($wait_query); #<---ensures that asked data presented from the device
185  
186 $result = $self->connection_read($args);
187 return $result;
188 }
189  
190 sub connection_write
191 { # @_ = ( $connection_handle, $args = { command, wait_status }
192 my $self = shift;
193 my $connection_handle = shift;
194 my $args = undef;
195 if ( ref $_[0] eq 'HASH' ) {
196 $args = shift;
197 } # try to be flexible about options as hash/hashref
198 else { $args = {@_} }
199  
200 my $command = $args->{'command'} || undef;
201 my $brutal = $args->{'brutal'} || $self->brutal();
202 my $read_length = $args->{'read_length'} || $self->read_length();
203  
204 my $result = undef;
205 my $raw = "";
206 my $ib_bits = undef; # hash ref
207 my $ibstatus = undef;
208 my $ibsta_verbose = "";
209 my $decimal = 0;
210  
211 if ( !defined $command ) {
212 Lab::Exception::CorruptParameter->throw(
213 error => "No command given to "
214 . __PACKAGE__
215 . "::connection_write().\n", );
216 }
217 else {
218 $ibstatus = ibwrt(
219 $connection_handle->{'gpib_handle'},
220 $command, length($command)
221 );
222 }
223  
224 $ib_bits = $self->ParseIbstatus($ibstatus);
225  
226 # foreach my $key ( keys %IbBits ) {
227 # print "$key: $ib_bits{$key}\n";
228 # }
229  
230 # Todo: better Error checking
231 if ( $ib_bits->{'ERR'} == 1 ) {
232 if ( $ib_bits->{'TIMO'} == 1 ) {
233 Lab::Exception::GPIBTimeout->throw(
234 error => sprintf(
235 "Timeout in "
236 . __PACKAGE__
237 . "::connection_write() while executing $command: ibwrite failed with status %x\n",
238 $ibstatus
239 )
240 . Dumper($ib_bits),
241 ibsta => $ibstatus,
242 ibsta_hash => $ib_bits,
243 );
244 }
245 else {
246 Lab::Exception::GPIBError->throw(
247 error => sprintf(
248 "Error in "
249 . __PACKAGE__
250 . "::connection_write() while executing $command: ibwrite failed with status %x\n",
251 $ibstatus
252 )
253 . Dumper($ib_bits),
254 ibsta => $ibstatus,
255 ibsta_hash => $ib_bits,
256 );
257 }
258 }
259  
260 return 1;
261 }
262  
263 sub connection_settermchar { # @_ = ( $connection_handle, $termchar
264 my $self = shift;
265 my $connection_handle = shift;
266 my $termchar = shift; # string termination character as string
267  
268 my $ib_bits = undef; # hash ref
269 my $ibstatus = undef;
270  
271 my $h = $connection_handle->{'gpib_handle'};
272  
273 my $arg = ord($termchar);
274  
275 $ibstatus = ibconfig( $connection_handle->{'gpib_handle'}, 15, $arg );
276  
277 $ib_bits = $self->ParseIbstatus($ibstatus);
278  
279 if ( $ib_bits->{'ERR'} == 1 ) {
280 Lab::Exception::GPIBError->throw(
281 error => sprintf(
282 "Error in "
283 . __PACKAGE__
284 . "::connection_settermchar(): ibeos failed with status %x\n",
285 $ibstatus
286 )
287 . Dumper($ib_bits),
288 ibsta => $ibstatus,
289 ibsta_hash => $ib_bits,
290 );
291 }
292  
293 return 1;
294 }
295  
296 sub connection_enabletermchar { # @_ = ( $connection_handle, 0/1 off/on
297 my $self = shift;
298 my $connection_handle = shift;
299 my $arg = shift;
300  
301 my $ib_bits = undef; # hash ref
302 my $ibstatus = undef;
303  
304 my $h = $connection_handle->{'gpib_handle'};
305  
306 $ibstatus = ibconfig( $connection_handle->{'gpib_handle'}, 12, $arg );
307  
308 $ib_bits = $self->ParseIbstatus($ibstatus);
309  
310 if ( $ib_bits->{'ERR'} == 1 ) {
311 Lab::Exception::GPIBError->throw(
312 error => sprintf(
313 "Error in "
314 . __PACKAGE__
315 . "::connection_enabletermchar(): ibeos failed with status %x\n",
316 $ibstatus
317 )
318 . Dumper($ib_bits),
319 ibsta => $ibstatus,
320 ibsta_hash => $ib_bits,
321 );
322 }
323  
324 return 1;
325 }
326  
327 sub serial_poll {
328 my $self = shift;
329 my $connection_handle = shift;
330 my $sbyte = undef;
331  
332 my $ibstatus = ibrsp( $connection_handle->{'gpib_handle'}, $sbyte );
333  
334 my $ib_bits = $self->ParseIbstatus($ibstatus);
335  
336 if ( $ib_bits->{'ERR'} == 1 ) {
337 Lab::Exception::GPIBError->throw(
338 error => sprintf(
339 "ibrsp (serial poll) failed with status %x\n",
340 $ibstatus
341 )
342 . Dumper($ib_bits),
343 ibsta => $ibstatus,
344 ibsta_hash => $ib_bits,
345 );
346 }
347  
348 return $sbyte;
349 }
350  
351 sub connection_clear {
352 my $self = shift;
353 my $connection_handle = shift;
354  
355 ibclr( $connection_handle->{'gpib_handle'} );
356 ibloc( $connection_handle->{'gpib_handle'} );
357 }
358  
359 sub timeout {
360 my $self = shift;
361 my $connection_handle = shift;
362 my $timo = shift;
363 my $timoval = undef;
364  
365 Lab::Exception::CorruptParameter->throw( error =>
366 "The timeout value has to be a positive decimal number of seconds, ranging 0-1000.\n"
367 )
368 if ( $timo !~ /^([+]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/
369 || $timo < 0
370 || $timo > 1000 );
371  
372 if ( $timo == 0 ) { $timoval = 0 } # never time out
373 if ( $timo <= 1e-5 ) { $timoval = 1 }
374 elsif ( $timo <= 3e-5 ) { $timoval = 2 }
375 elsif ( $timo <= 1e-4 ) { $timoval = 3 }
376 elsif ( $timo <= 3e-4 ) { $timoval = 4 }
377 elsif ( $timo <= 1e-3 ) { $timoval = 5 }
378 elsif ( $timo <= 3e-3 ) { $timoval = 6 }
379 elsif ( $timo <= 1e-2 ) { $timoval = 7 }
380 elsif ( $timo <= 3e-2 ) { $timoval = 8 }
381 elsif ( $timo <= 1e-1 ) { $timoval = 9 }
382 elsif ( $timo <= 3e-1 ) { $timoval = 10 }
383 elsif ( $timo <= 1 ) { $timoval = 11 }
384 elsif ( $timo <= 3 ) { $timoval = 12 }
385 elsif ( $timo <= 10 ) { $timoval = 13 }
386 elsif ( $timo <= 30 ) { $timoval = 14 }
387 elsif ( $timo <= 100 ) { $timoval = 15 }
388 elsif ( $timo <= 300 ) { $timoval = 16 }
389 elsif ( $timo <= 1000 ) { $timoval = 17 }
390  
391 my $ibstatus = ibtmo( $connection_handle->{'gpib_handle'}, $timoval );
392  
393 my $ib_bits = $self->ParseIbstatus($ibstatus);
394  
395 if ( $ib_bits->{'ERR'} == 1 ) {
396 Lab::Exception::GPIBError->throw(
397 error => sprintf(
398 "Error in "
399 . __PACKAGE__
400 . "::timeout(): ibtmo failed with status %x\n",
401 $ibstatus
402 )
403 . Dumper($ib_bits),
404 ibsta => $ibstatus,
405 ibsta_hash => $ib_bits,
406 );
407 }
408 }
409  
410 sub ParseIbstatus
411 { # Ibstatus http://linux-gpib.sourceforge.net/doc_html/r634.html
412 my $self = shift;
413 my $ibstatus = shift; # 16 Bit int
414 my @ibbits = ();
415  
416 if ( $ibstatus !~ /[0-9]*/ || $ibstatus < 0 || $ibstatus > 0xFFFF )
417 { # should be a 16 bit integer
418 Lab::Exception::CorruptParameter->throw(
419 error =>
420 'Lab::Bus::GPIB::VerboseIbstatus() got an invalid ibstatus.',
421 InvalidParameter => $ibstatus
422 );
423 }
424  
425 for ( my $i = 0; $i < 16; $i++ ) {
426 $ibbits[$i] = 0x0001 & ( $ibstatus >> $i );
427 }
428  
429 my %Ib = ();
430 (
431 $Ib{'DCAS'}, $Ib{'DTAS'}, $Ib{'LACS'}, $Ib{'TACS'},
432 $Ib{'ATN'}, $Ib{'CIC'}, $Ib{'REM'}, $Ib{'LOK'},
433 $Ib{'CMPL'}, $Ib{'EVENT'}, $Ib{'SPOLL'}, $Ib{'RQS'},
434 $Ib{'SRQI'}, $Ib{'END'}, $Ib{'TIMO'}, $Ib{'ERR'}
435 ) = @ibbits;
436  
437 return \%Ib;
438  
439 } # return: ($ERR, $TIMO, $END, $SRQI, $RQS, $SPOLL, $EVENT, $CMPL, $LOK, $REM, $CIC, $ATN, $TACS, $LACS, $DTAS, $DCAS)
440  
441 sub VerboseIbstatus {
442 my $self = shift;
443 my $ibstatus = shift;
444 my $ibstatus_verbose = "";
445  
446 if ( ref( \$ibstatus ) =~ /SCALAR/ ) {
447 $ibstatus = $self->ParseIbstatus($ibstatus);
448 }
449 elsif ( ref($ibstatus) !~ /HASH/ ) {
450 Lab::Exception::CorruptParameter->throw(
451 error =>
452 'Lab::Bus::GPIB::VerboseIbstatus() got an invalid ibstatus.',
453 InvalidParameter => $ibstatus
454 );
455 }
456  
457 while ( my ( $k, $v ) = each %$ibstatus ) {
458 $ibstatus_verbose .= "$k: $v\n";
459 }
460  
461 return $ibstatus_verbose;
462 }
463  
464 #
465 # search and return an instance of the same type in %Lab::Bus::BusList
466 #
467 sub _search_twin {
468 my $self = shift;
469  
470 if ( !$self->ignore_twins() ) {
471 for my $conn ( values %{ $Lab::Bus::BusList{ $self->type() } } ) {
472 return $conn if $conn->gpib_board() == $self->gpib_board();
473 }
474 }
475 return undef;
476 }
477  
478 1;
479  
480  
481 1;
482  
483 __END__
484  
485 =pod
486  
487 =encoding utf-8
488  
489 =head1 NAME
490  
491 Lab::Bus::LinuxGPIB - LinuxGPIB bus
492  
493 =head1 VERSION
494  
495 version 3.881
496  
497 =head1 SYNOPSIS
498  
499 This is the GPIB bus class for the GPIB library C<linux-gpib> (aka C<libgpib0> in the debian world).
500  
501 my $GPIB = new Lab::Bus::LinuxGPIB({ gpib_board => 0 });
502  
503 or implicit through instrument and connection creation:
504  
505 my $instrument = new Lab::Instrument::HP34401A({
506 connection_type => 'LinuxGPIB',
507 gpib_board => 0,
508 gpib_address=>14,
509 }
510  
511 =head1 DESCRIPTION
512  
513 See L<http://linux-gpib.sourceforge.net/> for details on the LinuxGPIB package. The
514 package provides both kernel drivers and Perl bindings. Obviously, this will work for Linux systems only.
515 On Windows, please use L<Lab::Bus::VISA>. The interfaces are (errr, will be) identical.
516  
517 Note: you don't need to explicitly handle bus objects. The Instruments will create them themselves, and existing bus will
518 be automagically reused.
519  
520 In GPIB, instantiating two bus with identical parameter "gpib_board" will logically lead to the reuse of the first one.
521 To override this, use the parameter "ignore_twins" at your own risk.
522  
523 =head1 CONSTRUCTOR
524  
525 =head2 new
526  
527 my $bus = Lab::Bus::GPIB({
528 gpib_board => $board_num
529 });
530  
531 Return blessed $self, with @_ accessible through $self->config().
532  
533 C<gpib_board>: Index of board to use. Can be omitted, 0 is the default.
534  
535 =head1 Thrown Exceptions
536  
537 Lab::Bus::GPIB throws
538  
539 Lab::Exception::GPIBError
540 fields:
541 'ibsta', the raw ibsta status byte received from linux-gpib
542 'ibsta_hash', the ibsta bit values in a named hash ( 'DCAS' => $val, 'DTAS' => $val, ... ).
543 Use Lab::Bus::GPIB::VerboseIbstatus() to get a nice string representation
544  
545 Lab::Exception::GPIBTimeout
546 fields:
547 'Data', this is meant to contain the data that (maybe) has been read/obtained/generated despite and up to the timeout.
548 ... and all the fields of Lab::Exception::GPIBError
549  
550 =head1 METHODS
551  
552 =head2 connection_new
553  
554 $GPIB->connection_new({ gpib_address => $paddr });
555  
556 Creates a new connection ("instrument handle") for this bus. The argument is a hash, whose contents depend on the bus type.
557 For GPIB at least 'gpib_address' is needed.
558  
559 The handle is usually stored in an instrument object and given to connection_read, connection_write etc.
560 to identify and handle the calling instrument:
561  
562 $InstrumentHandle = $GPIB->connection_new({ gpib_address => 13 });
563 $result = $GPIB->connection_read($self->InstrumentHandle(), { options });
564  
565 See C<Lab::Instrument::Read()>.
566  
567 TODO: this is probably not correct anymore
568  
569 =head2 connection_write
570  
571 $GPIB->connection_write( $InstrumentHandle, { Cmd => $Command } );
572  
573 Sends $Command to the instrument specified by the handle.
574  
575 =head2 connection_read
576  
577 $GPIB->connection_read( $InstrumentHandle, { Cmd => $Command, ReadLength => $readlength, Brutal => 0/1 } );
578  
579 Sends $Command to the instrument specified by the handle. Reads back a maximum of $readlength bytes. If a timeout or
580 an error occurs, Lab::Exception::GPIBError or Lab::Exception::GPIBTimeout are thrown, respectively. The Timeout object
581 carries the data received up to the timeout event, accessible through $Exception->Data().
582  
583 Setting C<Brutal> to a true value will result in timeouts being ignored, and the gathered data returned without error.
584  
585 =head2 timeout
586  
587 $GPIB->timeout( $connection_handle, $timeout );
588  
589 Sets the timeout in seconds for GPIB operations on the device/connection specified by $connection_handle.
590  
591 =head2 config
592  
593 Provides unified access to the fields in initial @_ to all the child classes.
594 E.g.
595  
596 $GPIB_Address=$instrument->config(gpib_address);
597  
598 Without arguments, returns a reference to the complete $self->config aka @_ of the constructor.
599  
600 $config = $bus->config();
601 $GPIB_PAddress = $bus->config()->{'gpib_address'};
602  
603 =head1 CAVEATS/BUGS
604  
605 Few. Also, not a lot to be done here.
606  
607 =head1 SEE ALSO
608  
609 =over 4
610  
611 =item
612  
613 L<Lab::Bus>
614  
615 =item
616  
617 L<Lab::Bus::MODBUS>
618  
619 =item
620  
621 and many more...
622  
623 =back
624  
625 =head1 COPYRIGHT AND LICENSE
626  
627 This software is copyright (c) 2023 by the Lab::Measurement team; in detail:
628  
629 Copyright 2011 Andreas K. Huettel, Florian Olbrich
630 2012 Florian Olbrich, Hermann Kraus, Stefan Geissler
631 2016 Charles Lane, Simon Reinhardt
632 2017 Andreas K. Huettel
633 2020 Andreas K. Huettel
634  
635  
636 This is free software; you can redistribute it and/or modify it under
637 the same terms as the Perl 5 programming language system itself.
638  
639 =cut