Instrument.pm untested

filter: Statementstmt 0.0% 0 / 534 Branchbran 0.0% 0 / 232 Conditioncond 0.0% 0 / 88 MC/DCmcdc 0.0% 0 / 56 Subroutinesub 0.0% 0 / 57 Podpod 0.0% 0 / 38 totaltotal 0.0% 0 / 1005 CC 117 SCAR 42.3
CC
117
Cov
0%
_init_cache_handling
342.0
_setconnection
132.0
AUTOLOAD
72.0
CRAP 68.6
1 package Lab::Instrument;
2 $Lab::Instrument::VERSION = '3.899';
3 #ABSTRACT: Instrument base class
4  
5 use v5.20;
6  
7 use strict;
8 use warnings;
9  
10 #use POSIX; # added for int() function
11 use Lab::Generic;
12 use Lab::Exception;
13 use Lab::Connection;
14 use Carp qw(cluck croak);
15 use Data::Dumper;
16 use Clone qw(clone);
17 use Class::ISA qw(self_and_super_path);
18 use Hook::LexWrap;
19  
20 use Time::HiRes qw (usleep sleep);
21  
22 our @ISA = ('Lab::Generic');
23  
24 our $AUTOLOAD;
25  
26 our %fields = (
27  
28 device_name => undef,
29 device_comment => undef,
30  
31 ins_debug => 0, # do we need additional output?
32  
33 connection => undef,
34 supported_connections => ['ALL'],
35  
36 # for connection default settings/user supplied settings. see accessor method.
37 connection_settings => { timeout => 1 },
38  
39 # default device settings/user supplied settings. see accessor method.
40 device_settings => {
41 name => undef,
42 wait_status => 10e-6, # sec
43 wait_query => 10e-6, # sec
44 query_length => 300, # bytes
45 query_long_length => 10240, # bytes
46 },
47  
48 device_cache => {
49  
50 },
51  
52 device_cache_order => [],
53  
54 config => {},
55 );
56  
57 sub new {
58 my $proto = shift;
59 my $class = ref($proto) || $proto;
60 my $config = undef;
61 if ( ref $_[0] eq 'HASH' ) { $config = shift }
62 else { $config = {@_} }
63  
64 my $self = $class->SUPER::new(@_);
65 $self->${ \( __PACKAGE__ . '::_construct' ) }(__PACKAGE__);
66  
67 # wrap additional code for automatic cache-handling aroung all paramter set- and get-functions defined in %fields->{device_cache}
68 my @isa = Class::ISA::self_and_super_path($class);
69 my $flag = 0;
70 while (@isa) {
71 my $isa = pop @isa;
72 if ( $flag == 1 ) {
73 $self->_init_cache_handling($isa);
74 }
75 if ( $isa eq 'Lab::Instrument' ) {
76 $flag = 1;
77 }
78  
79 }
80  
81 $self->config($config);
82  
83 #
84 # In most inherited classes, configure() is run through _construct()
85 #
86 $self->${ \( __PACKAGE__ . '::configure' ) }( $self->config() )
87 ; # use local configure, not possibly overwritten one
88  
89 if ( $class eq __PACKAGE__ ) {
90  
91 # _setconnection after providing $config - needed for direct instantiation of Lab::Instrument
92 $self->_setconnection();
93 }
94  
95 # digest parameters
96 $self->device_name( $self->config('device_name') )
97 if defined $self->config('device_name');
98 $self->device_comment( $self->config('device_comment') )
99 if defined $self->config('device_comment');
100  
101 $self->register_instrument();
102  
103 return $self;
104 }
105  
106 #
107 # Call this in inheriting class's constructors to conveniently initialize the %fields object data.
108 #
109 sub _construct { # _construct(__PACKAGE__);
110 ( my $self, my $package ) = ( shift, shift );
111  
112 my $class = ref($self);
113 my $fields = undef;
114 {
115 no strict 'refs';
116 $fields = *${ \( $package . '::fields' ) }{HASH};
117 }
118  
119 foreach my $element ( keys %{$fields} ) {
120  
121 # handle special subarrays
122 if ( $element eq 'device_settings' ) {
123  
124 # don't overwrite filled hash from ancestor
125 $self->{device_settings} = {}
126 if !exists( $self->{device_settings} );
127 for my $s_key ( keys %{ $fields->{'device_settings'} } ) {
128 $self->{device_settings}->{$s_key}
129 = clone( $fields->{device_settings}->{$s_key} );
130 }
131 }
132 elsif ( $element eq 'connection_settings' ) {
133  
134 # don't overwrite filled hash from ancestor
135 $self->{connection_settings} = {}
136 if !exists( $self->{connection_settings} );
137 for my $s_key ( keys %{ $fields->{connection_settings} } ) {
138 $self->{connection_settings}->{$s_key}
139 = clone( $fields->{connection_settings}->{$s_key} );
140 }
141 }
142 else {
143 # handle the normal fields - can also be hash refs etc, so use clone to get a deep copy
144 $self->{$element} = clone( $fields->{$element} );
145  
146 #warn "here comes\n" if($element eq 'device_cache');
147 #warn Dumper($Lab::Instrument::DummySource::fields) if($element eq 'device_cache');
148 }
149 $self->{_permitted}->{$element} = 1;
150  
151 }
152  
153 # @{$self}{keys %{$fields}} = values %{$fields};
154  
155 #
156 # run configure() of the calling package on the supplied config hash.
157 # this parses the whole config hash on every heritance level (and with every version of configure())
158 # For Lab::Instrument itself it does not make sense, as $self->config() is not set yet. Instead it's run from the new() method, see there.
159 #
160 $self->${ \( $package . '::configure' ) }( $self->config() )
161 if $class ne 'Lab::Instrument'
162 ; # use configure() of calling package, not possibly overwritten one
163  
164 #
165 # Check and parse the connection data OR the connection object in $self->config(), but only if
166 # _construct() has been called from the instantiated class (and not from somewhere up the heritance hierarchy)
167 # That's because child classes can add new entrys to $self->supported_connections(), so delay checking to the top class.
168 # Also, don't run _setconnection() for Lab::Instrument, as in this case the needed fields in $self->config() are not set yet.
169 # It's run in Lab::Instrument::new() instead if needed.
170 #
171 # Also, other stuff that should only happen in the top level class instantiation can go here.
172 #
173  
174 if ( $class eq $package && $class ne 'Lab::Instrument' ) {
175  
176 $self->_setconnection();
177  
178 # Match the device hash with the device
179 # The cache carries the default values set above and was possibly modified with user
180 # defined values through configure() before the connection was set. These settings are now transferred
181 # to the device.
182 $self->_device_init(); # enable device communication if necessary
183 $self->_set_config_parameters(); # transfer configuration to device
184  
185 }
186  
187 }
188  
189 # this methode implements the cache-handling:
190 #
191 # It will wrap all get- and set-functions for parameters initialized in $fields->{device_cache} with additional pre- and post-processing code.
192 # If a get-function is called and read_mode == cache, the $self->{device_cache}->{parameter} will be returned immediately. The original get-function won't be executed in this case.
193 # This behaviour can be disabled by setting the parmeter $self->{config}->{no_cache} = 1.
194 # The return-value of the get-function will be cached in $self->{device_cache}in any case.
195 #
196 # Set-functions will automatically call the corresponding get-function in the post-processing section, in order to keep the cache up to date.
197 #
198 # If a requestID has been set, only the get-function, which placed the request will be executed, while all others return the cache-value. Set-functions won't be executed at all.
199 #
200  
201 sub _init_cache_handling {
202 my $self = shift;
203 my $class = shift;
204  
205 no strict 'refs';
206  
207 # avoid to redefine the subs twice
208 if ( defined ${ $class . '::MODIFIED' } ) {
209 return;
210 }
211  
212 my $fields = *${ \( $class . '::fields' ) }{HASH};
213 my @cache_params = keys %{ $fields->{device_cache} };
214  
215 # wrap parameter function defined in %fields->{device_cache}:
216 foreach my $cache_param (@cache_params) {
217 my $set_sub = "set_" . $cache_param;
218 my $get_sub = "get_" . $cache_param;
219  
220 my $get_methode = *{ $class . "::" . $get_sub };
221 my $set_methode = *{ $class . "::" . $set_sub };
222  
223 if ( $class->can( "set_" . $cache_param ) and exists &$set_methode ) {
224  
225 # Change STDERR to undef, in order to avoid warnings from Hook::LexWrap and
226 # and save original STDERR stream in SAVEERR to be able to restore original
227 # behavior
228 local (*SAVEERR);
229  
230 #open SAVEERR, ">&STDERR";
231 #open(STDERR, '>', undef);
232  
233 # wrap set-function:
234 wrap(
235 $class . "::" . $set_sub,
236  
237 # before set-functions is executed:
238 pre => sub {
239 my $self = shift;
240  
241 ${__PACKAGE__::SELF} = $self;
242 ${__PACKAGE__::SELF}->{fast_cache_value} = $_[0];
243  
244 # read_mode handling: do not execute if request is set:
245 if ( defined $self->{requestID}
246 or $self->connection()->is_blocked() ) {
247 $_[-1] = 'connection blocked';
248 }
249 },
250  
251 # after set-functions is executed:
252 post => sub {
253  
254 if ( not defined ${__PACKAGE__::SELF} ) {
255 return;
256 }
257  
258 # skip get_sub if $self->{config}->{fast_cache} is set.
259 if ( defined ${__PACKAGE__::SELF}->{config}->{fast_cache}
260 and ${__PACKAGE__::SELF}->{config}->{fast_cache} > 0 )
261 {
262 ${__PACKAGE__::SELF}->device_cache(
263 {
264 $cache_param =>
265 ${__PACKAGE__::SELF}->{fast_cache_value}
266 }
267 );
268 return;
269 }
270  
271 # call coresponding get-function in order to keep the cache up to date, if available
272  
273 if ( ${__PACKAGE__::SELF}->can($get_sub)
274 and not ${__PACKAGE__::SELF}->{config}->{no_cache} ) {
275 my $var = ${__PACKAGE__::SELF}->$get_sub();
276 }
277  
278 }
279 );
280  
281 # Restore Warnings:
282 #open STDERR, ">&SAVEERR";
283  
284 }
285  
286 if ( $class->can( "get_" . $cache_param ) and exists &$get_methode ) {
287  
288 # Change STDERR to undef, in order to avoid warnings from Hook::LexWrap and
289 # and save original STDERR stream in SAVEERR to be able to restore original
290 # behavior
291 local (*SAVEERR);
292  
293 #open SAVEERR, ">&STDERR";
294 #open(STDERR, '>', undef);
295  
296 my $parameter = $cache_param;
297  
298 # wrap get-function:
299 wrap(
300 $class . "::" . $get_sub,
301  
302 # before get-functions is executed:
303 pre => sub {
304 my $self = shift;
305  
306 ${__PACKAGE__::SELF} = $self;
307  
308 # read_mode handling:
309 my @args = @_;
310 pop @args;
311 my ( $read_mode, $tail )
312 = $self->_check_args( \@args, ['read_mode'] );
313  
314 # do not read if request has been set. set read_mode to cache if cache is available
315 $read_mode = $self->{config}->{default_read_mode}
316 if !defined($read_mode)
317 and exists( $self->{config}->{default_read_mode} );
318  
319 if ( $self->connection()->is_blocked() == 1 ) {
320 if ( defined $self->device_cache($parameter) ) {
321 $read_mode = 'cache';
322 }
323 else {
324 $_[-1] = 'connection_blocked';
325 }
326 }
327  
328 if ( defined $self->{requestID} ) {
329 my ( $package, $filename, $subroutine, $line )
330 = split( / /, $self->{requestID} );
331  
332 if ( $subroutine ne $class . "::" . $get_sub ) {
333 if ( defined $self->device_cache($parameter) ) {
334  
335 $read_mode = 'cache';
336 }
337 else {
338 $_[-1] = 'connection_blocked';
339 }
340 }
341 else {
342 $read_mode = undef;
343 pop @_;
344 }
345  
346 }
347  
348 # return cache value if read_mode is set to cache
349 if ( defined $read_mode
350 and $read_mode eq 'cache'
351 and defined $self->device_cache($parameter)
352 and not $self->{config}->{no_cache} ) {
353 $_[-1] = $self->device_cache($parameter);
354 }
355  
356 },
357  
358 # after get-functions is executed:
359 post => sub {
360  
361 if ( not defined ${__PACKAGE__::SELF} ) {
362 return;
363 }
364 my $retval = $_[-1];
365  
366 # refresh cache value
367 if ( not defined $retval
368 or ref($retval) eq 'Hook::LexWrap::Cleanup' ) {
369 return;
370 }
371 else {
372 my $cache_value = wantarray ? $retval->[0] : $retval;
373 ${__PACKAGE__::SELF}
374 ->device_cache( { $parameter => $cache_value } );
375 }
376 }
377 );
378  
379 # Restore Warnings:
380 #open STDERR, ">&SAVEERR";
381 }
382  
383 }
384  
385 # remeber that we have allready redefined the functions
386 ${ $class . '::MODIFIED' } = 1;
387  
388 use strict 'refs';
389  
390 }
391  
392 sub register_instrument {
393 my $self = shift;
394  
395 push( @{Lab::Instrument::REGISTERED_INSTRUMENTS}, $self );
396  
397 }
398  
399 sub unregister_instrument {
400 my $self = shift;
401  
402 @{Lab::Instrument::REGISTERED_INSTRUMENTS}
403 = grep { $_ ne $self } @{Lab::Instrument::REGISTERED_INSTRUMENTS};
404  
405 }
406  
407 sub sprint_config {
408 my $self = shift;
409  
410 $Data::Dumper::Varname = "device_cache_";
411 my $config = Dumper $self->device_cache();
412  
413 $config .= "\n";
414  
415 $Data::Dumper::Maxdepth = 1;
416 $Data::Dumper::Varname = "connection_settings_";
417 if ( defined $self->connection() ) {
418 $config .= Dumper $self->connection()->config();
419 }
420 return $config;
421  
422 }
423  
424 sub _set_config_parameters {
425 my $self = shift;
426  
427 my @order = @{ $self->device_cache_order() };
428 my @keys = keys %{ $self->config() };
429  
430 foreach my $ckey (@order) {
431 my $subname = 'set_' . $ckey;
432 if ( defined $self->config($ckey) and $self->can($subname) ) {
433 my $result = $self->$subname( $self->config($ckey) );
434 @keys = grep { $_ ne $ckey } @keys;
435 }
436 }
437  
438 foreach my $ckey (@keys) {
439 my $subname = 'set_' . $ckey;
440 if ( $self->can($subname) ) {
441 my $result = $self->$subname( $self->config($ckey) );
442 }
443 }
444  
445 }
446  
447 # old; replaced by _refresh_cache and _set_config_parameters
448 sub _getset_key {
449 my $self = shift;
450 my $ckey = shift;
451  
452 #print Dumper $self->device_cache();
453  
454 Lab::Exception::CorruptParameter->throw(
455 "No field with name $ckey in device_cache!\n")
456 if !exists $self->device_cache()->{$ckey};
457 if ( !defined $self->device_cache()->{$ckey}
458 and !defined $self->config()->{$ckey} ) {
459 my $subname = 'get_' . $ckey;
460 Lab::Exception::CorruptParameter->throw(
461 "No get method defined for device_cache field $ckey! \n")
462 if !$self->can($subname);
463 my $result = $self->$subname();
464 }
465 else {
466 my $subname = 'set_' . $ckey;
467 print Dumper $self->device_cache() if !$self->can($subname);
468 Lab::Exception::CorruptParameter->throw(
469 "No set method defined for device_cache field $ckey!\n")
470 if !$self->can($subname);
471 my $result = $self->$subname( $self->device_cache()->{$ckey} );
472 }
473  
474 }
475  
476 #
477 # Sync the field set in $self->device_cache with the device.
478 # Undefined fields are filled in from the device, existing values in device_cache are written to the device.
479 # Without parameter, parses the whole $self->device_cache. Else, the parameter list is parsed as a list of
480 # field names. Contained fields for which have no corresponding getter/setter/device_cache entry exists will result in an exception thrown.
481 #
482 # old; replaced by _refresh_cache and _set_config_parameters
483 # still used in Yokogawa7651 and SignalRecovery726x
484 sub _cache_init {
485 my $self = shift;
486 my $subname = shift;
487 my @ckeys = scalar(@_) > 0 ? @_ : keys %{ $self->device_cache() };
488  
489 #print Dumper $self->config();
490  
491 print "ckeys: @ckeys\n";
492  
493 # a key hash, to search for given keys quickly
494 my %ckeyhash;
495 my %orderhash;
496 @ckeyhash{@ckeys} = ();
497  
498 my @order = @{ $self->device_cache_order() };
499  
500 if ( $self->device_cache() && $self->connection() ) {
501  
502 # do we have a preferred order for device cache settings?
503 if (@order) {
504 @orderhash{@order} = ();
505 foreach my $ckey (@order) {
506 $self->_getset_key($ckey) if exists $ckeyhash{$ckey};
507 }
508  
509 # initialize all values not in device_cache_order
510 #for my $ckey (@ckeys){
511 # $self->_getset_key($ckey) if not exists $orderhash{$ckey};
512 #}
513 }
514  
515 # no ordering requestd
516 else {
517 foreach my $ckey (@ckeys) {
518 $self->_getset_key($ckey);
519 }
520 }
521 }
522 }
523  
524 #
525 # Fill $self->device_settings() from config parameters
526 #
527 sub configure {
528 my $self = shift;
529 my $config = shift;
530  
531 if ( ref($config) ne 'HASH' ) {
532 Lab::Exception::CorruptParameter->throw(
533 error => 'Given Configuration is not a hash.' );
534 }
535 else {
536 #
537 # fill matching fields defined in %fields from the configuration hash ($self->config )
538 # this will also catch an explicitly given device_settings, default_device_settings (see Source.pm) or connection_settings hash ( overwritten default config )
539 #
540 for my $fields_key ( keys %{ $self->{_permitted} } ) {
541 { # restrict scope of "no strict"
542 no strict 'refs';
543 $self->$fields_key( $config->{$fields_key} )
544 if exists $config->{$fields_key};
545 }
546 }
547  
548 #
549 # fill fields $self->device_settings and $self->device_cache from entries given in configuration hash (this is usually the same as $self->config )
550 #
551 $self->device_settings($config);
552  
553 #$self->device_cache($config);
554 }
555 }
556  
557 sub _checkconnection
558 { # Connection object or connection_type string (as in Lab::Connections::<connection_type>)
559 my $self = shift;
560 my $connection = shift || undef;
561 my $found = 0;
562  
563 $connection = ref($connection) || $connection;
564  
565 return 0 if !defined $connection;
566  
567 no strict 'refs';
568 if ( grep( /^ALL$/, @{ $self->supported_connections() } ) == 1 ) {
569 return $connection;
570 }
571 elsif ($connection->isa('Lab::Connection::DEBUG')
572 or $connection->isa('Lab::Connection::Mock') ) {
573 return $connection;
574 }
575 else {
576 for my $conn_supp ( @{ $self->supported_connections() } ) {
577 return $conn_supp
578 if ( $connection->isa( 'Lab::Connection::' . $conn_supp ) );
579 }
580 }
581  
582 return undef;
583 }
584  
585 sub _setconnection
586 { # $self->setconnection() create new or use existing connection
587 my $self = shift;
588  
589 #
590 # fill in unset connection parameters with the defaults from $self->connections_settings to $self->config
591 #
592 my $config = $self->config();
593 my $connection_type = undef;
594 my $full_connection = undef;
595  
596 for my $setting_key ( keys %{ $self->connection_settings() } ) {
597 $config->{$setting_key} = $self->connection_settings($setting_key)
598 if !defined $config->{$setting_key};
599 }
600  
601 # check the configuration hash for a valid connection object or connection type, and set the connection
602 if ( defined( $self->config('connection') ) ) {
603  
604 if ( $self->_checkconnection( $self->config('connection') ) ) {
605 $self->connection( $self->config('connection') );
606  
607 }
608 else {
609 Lab::Exception::CorruptParameter->throw(
610 error => "Received invalid connection object!\n" );
611 }
612 }
613  
614 # else {
615 # Lab::Exception::CorruptParameter->throw( error => 'Received no connection object!\n' );
616 # }
617 elsif ( defined $self->config('connection_type') ) {
618  
619 $connection_type = $self->config('connection_type');
620  
621 if ( $connection_type !~ /^[A-Za-z0-9_\-\:]*$/ ) {
622 Lab::Exception::CorruptParameter->throw( error =>
623 "Given connection type is does not look like a valid module name.\n"
624 );
625 }
626  
627 if ( $connection_type eq 'none' ) {
628 if ( grep( /^none$/, @{ $self->supported_connections() } ) == 1 )
629 {
630 return;
631 }
632 else {
633 Lab::Exception::Error->throw( error =>
634 "Sorry, this instrument cannot work without a connection.\n"
635 );
636 }
637 }
638  
639 $full_connection = "Lab::Connection::" . $connection_type;
640 eval("require ${full_connection};");
641 if ($@) {
642 Lab::Exception::Error->throw( error =>
643 "Sorry, I was not able to load the connection ${full_connection}.\n"
644 . "The error received from the connections was\n===\n$@\n===\n"
645 );
646 }
647  
648 if ( $self->_checkconnection( "Lab::Connection::" . $connection_type )
649 ) {
650  
651 # let's get creative
652 no strict 'refs';
653  
654 # yep - pass all the parameters on to the connection, it will take the ones it needs.
655 # This way connection setup can be handled generically. Conflicting parameter names? Let's try it.
656 $self->connection( $full_connection->new($config) )
657 || Lab::Exception::Error->throw(
658 error => "Failed to create connection $full_connection!\n" );
659  
660 use strict;
661 }
662 else {
663 Lab::Exception::CorruptParameter->throw(
664 error => "Given Connection not supported!\n" );
665 }
666 }
667 else {
668 Lab::Exception::CorruptParameter->throw( error =>
669 "Neither a connection nor a connection type was supplied.\n"
670 );
671 }
672  
673 # add predefined connection settings to connection config:
674 # no overwriting of user defined connection settings
675 my $new_config = $self->connection()->config();
676 for my $key ( keys %{ $self->connection_settings() } ) {
677 if ( not defined $self->connection()->config($key) ) {
678 $new_config->{$key} = $self->connection_settings($key);
679 }
680 }
681 $self->connection()->config($new_config);
682 $self->connection()->_configurebus();
683 }
684  
685 sub _checkconfig {
686 my $self = shift;
687 my $config = $self->config();
688  
689 return 1;
690 }
691  
692 #
693 # To be overwritten...
694 # Returned $errcode has to be 0 for "no error"
695 #
696 sub get_error {
697 my $self = shift;
698  
699 # overwrite with device specific error retrieval...
700 warn( "There was an error on the device "
701 . ref($self)
702 . ", but the driver is not able to supply more details.\n" );
703  
704 return ( -1, undef ); # ( $errcode, $message )
705 }
706  
707 #
708 # Optionally implement this to return a hash with device specific named status bits for this device, e.g. from the status byte/serial poll for GPIB
709 # return { ERROR => 1, READY => 1, DATA => 0, ... }
710 #
711 sub get_status {
712 my $self = shift;
713 Lab::Exception::Unimplemented->throw(
714 "get_status() not implemented for " . ref($self) . ".\n" );
715 return undef;
716 }
717  
718 sub check_errors {
719 my $self = shift;
720 my $command = shift;
721 my @errors = ();
722  
723 if ( $self->get_status()->{'ERROR'} ) {
724 my ( $code, $message ) = $self->get_error();
725 while ( $code != 0 && $code != -1 ) {
726 push @errors, [ $code, $message ];
727 warn
728 "\nReceived device error with code $code\nMessage: $message\n";
729 ( $code, $message ) = $self->get_error();
730 }
731  
732 if ( @errors || $code == -1 ) {
733 Lab::Exception::DeviceError->throw(
734 error =>
735 "An Error occured in the device while executing the command: $command \n",
736 device_class => ref $self,
737 command => $command,
738 error_list => \@errors,
739 );
740 }
741 }
742 return 0;
743 }
744  
745 #
746 # Generic utility methods for string based connections (most common, SCPI etc.).
747 # For connections not based on command strings these should probably be overwritten/disabled!
748 #
749  
750 #
751 # passing through generic write, read and query from the connection.
752 #
753  
754 sub set_name {
755 my $self = shift;
756 my ($name) = $self->_check_args( \@_, ['name'] );
757 $self->device_settings( { 'name' => $name } );
758  
759 }
760  
761 sub get_name {
762 my $self = shift;
763 return $self->device_settings('name');
764 }
765  
766 sub get_id {
767 my $self = shift;
768 my @name = split( /::/, ref($self) );
769 return pop(@name);
770 }
771  
772 sub set_id {
773  
774 }
775  
776 sub write {
777 my $self = shift;
778 my $command
779 = scalar(@_) % 2 == 0 && ref $_[1] ne 'HASH'
780 ? undef
781 : shift
782 ; # even sized parameter list and second parm no hashref? => Assume parameter hash
783 my $args
784 = scalar(@_) % 2 == 0
785 ? {@_}
786 : ( ref( $_[0] ) eq 'HASH' ? $_[0] : undef );
787 Lab::Exception::CorruptParameter->throw("Illegal parameter hash given!\n")
788 if !defined($args);
789  
790 $args->{'command'} = $command if defined $command;
791  
792 my $result = $self->connection()->Write($args);
793  
794 $self->check_errors( $args->{'command'} ) if $args->{error_check};
795  
796 return $result;
797 }
798  
799 sub read {
800 my $self = shift;
801 my $args
802 = scalar(@_) % 2 == 0
803 ? {@_}
804 : ( ref( $_[0] ) eq 'HASH' ? $_[0] : undef );
805 Lab::Exception::CorruptParameter->throw("Illegal parameter hash given!\n")
806 if !defined($args);
807  
808 my $result = $self->connection()->Read($args);
809 $self->check_errors('Just a plain and simple read.')
810 if $args->{error_check};
811  
812 $result =~ s/^[\r\t\n]+|[\r\t\n]+$//g;
813 return $result;
814 }
815  
816 sub clear {
817 my $self = shift;
818 $self->connection()->Clear();
819 }
820  
821 sub request {
822 my $self = shift;
823 my ( $command, $args ) = $self->parse_optional(@_);
824 my $read_mode
825 = ( defined $args->{'read_mode'} ) ? $args->{'read_mode'} : 'device';
826  
827 # generate requestID from caller:
828 my ( $package, $filename, $line, $subroutine );
829 ( $package, $filename, $line, $subroutine ) = caller(1);
830 ( $package, $filename, $line ) = caller(0);
831 my $requestID
832 = $package . " " . $filename . " " . $subroutine . " " . $line;
833  
834 # # avoid to return an undef value:
835 if ( $read_mode eq 'request' and not defined $self->{requestID} ) {
836 $self->write(@_);
837 $self->connection()->block_connection();
838 $self->{requestID} = $requestID;
839 return undef;
840 }
841 elsif ( defined $self->{requestID} and $self->{requestID} eq $requestID )
842 {
843 $self->connection()->unblock_connection();
844 $self->{requestID} = undef;
845 return $self->read(@_);
846 }
847 else {
848 return $self->query(@_);
849 }
850  
851 }
852  
853 sub query {
854 my $self = shift;
855 my ( $command, $args ) = $self->parse_optional(@_);
856 my $read_mode
857 = ( defined $args->{'read_mode'} ) ? $args->{'read_mode'} : 'device';
858 $args->{'command'} = $command if defined $command;
859  
860 if ( not defined $args->{'command'} ) {
861 Lab::Exception::CorruptParameter->throw("No 'command' given!\n");
862 }
863  
864 my $result = $self->connection()->Query($args);
865 $self->check_errors( $args->{'command'} ) if $args->{error_check};
866  
867 $result =~ s/^[\r\t\n]+|[\r\t\n]+$//g;
868 return $result;
869  
870 }
871  
872 #
873 # infrastructure stuff below
874 #
875  
876 #
877 # tool function to safely handle an optional scalar parameter in presence with a parameter hash/list
878 # only one optional scalar parameter can be handled, and its value must not be a hashref!
879 #
880 sub parse_optional {
881 my $self = shift;
882  
883 my $optional
884 = scalar(@_) % 2 == 0 && ref $_[1] ne 'HASH'
885 ? undef
886 : shift
887 ; # even sized parameter list and second parm no hashref? => Assume parameter hash
888 my $args
889 = scalar(@_) % 2 == 0
890 ? {@_}
891 : ( ref( $_[0] ) eq 'HASH' ? $_[0] : undef );
892 Lab::Exception::CorruptParameter->throw("Illegal parameter hash given!\n")
893 if !defined($args);
894  
895 return $optional, $args;
896 }
897  
898 #
899 # accessor for device_settings
900 #
901 sub device_settings {
902 my $self = shift;
903 my $value = undef;
904  
905 #warn "device_settings got this:\n" . Dumper(@_) . "\n";
906  
907 if ( scalar(@_) == 0 )
908 { # empty parameters - return whole device_settings hash
909 return $self->{'device_settings'};
910 }
911 elsif ( scalar(@_) == 1 )
912 { # one parm - either a scalar (key) or a hashref (try to merge)
913 $value = shift;
914 }
915 elsif ( scalar(@_) > 1 && scalar(@_) % 2 == 0 )
916 { # even sized list - assume it's keys and values and try to merge it
917 $value = {@_};
918 }
919 else { # uneven sized list - don't know what to do with that one
920 Lab::Exception::CorruptParameter->throw(
921 error => "Corrupt parameters given to "
922 . __PACKAGE__
923 . "::device_settings().\n" );
924 }
925  
926 #warn "Keys present: \n" . Dumper($self->{device_settings}) . "\n";
927  
928 if ( ref($value) =~ /HASH/ ) { # it's a hash - merge into current settings
929 for my $ext_key ( keys %{$value} ) {
930 $self->{'device_settings'}->{$ext_key} = $value->{$ext_key}
931 if ( exists( $self->device_settings()->{$ext_key} ) );
932 }
933 return $self->{'device_settings'};
934 }
935 else { # it's a key - return the corresponding value
936 return $self->{'device_settings'}->{$value};
937 }
938 }
939  
940 #
941 # Accessor for device_cache settings
942 #
943  
944 sub device_cache {
945 my $self = shift;
946 my $value = undef;
947  
948 #warn "device_cache got this:\n" . Dumper(@_) . "\n";
949  
950 if ( scalar(@_) == 0 )
951 { # empty parameters - return whole device_settings hash
952 return $self->{'device_cache'};
953 }
954 elsif ( scalar(@_) == 1 )
955 { # one parm - either a scalar (key) or a hashref (try to merge)
956 $value = shift;
957 }
958 elsif ( scalar(@_) > 1 && scalar(@_) % 2 == 0 )
959 { # even sized list - assume it's keys and values and try to merge it
960 $value = {@_};
961 }
962 else { # uneven sized list - don't know what to do with that one
963 Lab::Exception::CorruptParameter->throw(
964 error => "Corrupt parameters given to "
965 . __PACKAGE__
966 . "::device_cache().\n" );
967 }
968  
969 #warn "Keys present: \n" . Dumper($self->{device_settings}) . "\n";
970  
971 if ( ref($value) =~ /HASH/ ) { # it's a hash - merge into current settings
972 for my $ext_key ( keys %{$value} ) {
973 $self->{'device_cache'}->{$ext_key} = $value->{$ext_key}
974 if ( exists( $self->device_cache()->{$ext_key} ) );
975 }
976 return $self->{'device_cache'};
977 }
978 else { # it's a key - return the corresponding value
979 return $self->{'device_cache'}->{$value};
980 }
981 }
982  
983 sub reset_device_cache {
984 my $self = shift;
985 my @cache_params = keys %{ $self->{'device_cache'} };
986 for my $param (@cache_params) {
987 $self->device_cache( $param => undef );
988 }
989 }
990  
991 #
992 # accessor for connection_settings
993 #
994 sub connection_settings {
995 my $self = shift;
996 my $value = undef;
997  
998 if ( scalar(@_) == 0 )
999 { # empty parameters - return whole device_settings hash
1000 return $self->{'connection_settings'};
1001 }
1002 elsif ( scalar(@_) == 1 )
1003 { # one parm - either a scalar (key) or a hashref (try to merge)
1004 $value = shift;
1005 }
1006 elsif ( scalar(@_) > 1 && scalar(@_) % 2 == 0 )
1007 { # even sized list - assume it's keys and values and try to merge it
1008 $value = {@_};
1009 }
1010 else { # uneven sized list - don't know what to do with that one
1011 Lab::Exception::CorruptParameter->throw(
1012 error => "Corrupt parameters given to "
1013 . __PACKAGE__
1014 . "::connection_settings().\n" );
1015 }
1016  
1017 if ( ref($value) =~ /HASH/ ) { # it's a hash - merge into current settings
1018 for my $ext_key ( keys %{$value} ) {
1019 $self->{'connection_settings'}->{$ext_key} = $value->{$ext_key}
1020 if ( exists( $self->{'connection_settings'}->{$ext_key} ) );
1021  
1022 # warn "merge: set $ext_key to " . $value->{$ext_key} . "\n";
1023 }
1024 return $self->{'connection_settings'};
1025 }
1026 else { # it's a key - return the corresponding value
1027 return $self->{'connection_settings'}->{$value};
1028 }
1029 }
1030  
1031 sub _check_args {
1032 my $self = shift;
1033 my $args = shift;
1034 my $params = shift;
1035  
1036 my $arguments = {};
1037  
1038 my $i = 0;
1039 foreach my $arg ( @{$args} ) {
1040 if ( ref($arg) ne "HASH" ) {
1041 if ( defined @{$params}[$i] ) {
1042 $arguments->{ @{$params}[$i] } = $arg;
1043 }
1044 $i++;
1045 }
1046 else {
1047 %{$arguments} = ( %{$arguments}, %{$arg} );
1048 $i++;
1049 }
1050 }
1051  
1052 my @return_args = ();
1053  
1054 foreach my $param ( @{$params} ) {
1055 if ( exists $arguments->{$param} ) {
1056 push( @return_args, $arguments->{$param} );
1057 delete $arguments->{$param};
1058 }
1059 else {
1060 push( @return_args, undef );
1061 }
1062 }
1063  
1064 foreach my $param ( 'from_device', 'from_cache'
1065 ) # Delete Standard option parameters from $arguments hash if not defined in device driver function
1066 {
1067 if ( exists $arguments->{$param} ) {
1068 delete $arguments->{$param};
1069 }
1070 }
1071  
1072 push( @return_args, $arguments );
1073  
1074 if (wantarray) {
1075 return @return_args;
1076 }
1077 else {
1078 return $return_args[0];
1079 }
1080  
1081 }
1082  
1083 sub _check_args_strict {
1084 my $self = shift;
1085 my $args = shift;
1086 my $params = shift;
1087  
1088 my @result = $self->_check_args( $args, $params );
1089  
1090 my $num_params = @result - 1;
1091  
1092 for ( my $i = 0; $i < $num_params; ++$i ) {
1093 if ( not defined $result[$i] ) {
1094 croak("missing mandatory argument '$params->[$i]'");
1095 }
1096 }
1097  
1098 if (wantarray) {
1099 return @result;
1100 }
1101 else {
1102 return $result[0];
1103 }
1104 }
1105  
1106 #
1107 # config gets it's own accessor - convenient access like $self->config('GPIB_Paddress') instead of $self->config()->{'GPIB_Paddress'}
1108 # with a hashref as argument, set $self->{'config'} to the given hashref.
1109 # without an argument it returns a reference to $self->config (just like AUTOLOAD would)
1110 #
1111 sub config { # $value = self->config($key);
1112 ( my $self, my $key ) = ( shift, shift );
1113  
1114 if ( !defined $key ) {
1115 return $self->{'config'};
1116 }
1117 elsif ( ref($key) =~ /HASH/ ) {
1118 return $self->{'config'} = $key;
1119 }
1120 else {
1121 return $self->{'config'}->{$key};
1122 }
1123 }
1124  
1125 # sub device_cache { # $value = $self->{'device_cache'}($key);
1126 # (my $self, my $key) = (shift, shift);
1127  
1128 # if(!defined $key) {
1129 # return $self->{'device_cache'};
1130 # }
1131 # elsif(ref($key) =~ /HASH/) {
1132 # return $self->{'device_cache'} = ($self->{'device_cache'}, $key);
1133 # }
1134 # else {
1135 # return $self->{'device_cache'}->{$key};
1136 # }
1137 # }
1138  
1139 #
1140 # provides generic accessor methods to the fields defined in %fields and to the elements of $self->device_settings
1141 #
1142 sub AUTOLOAD {
1143  
1144 my $self = shift;
1145 my $type = ref($self) or croak "\$self is not an object";
1146 my $value = undef;
1147  
1148 my $name = $AUTOLOAD;
1149 $name =~ s/.*://; # strip fully qualified portion
1150  
1151 if ( exists $self->{_permitted}->{$name} ) {
1152 if (@_) {
1153 return $self->{$name} = shift;
1154 }
1155 else {
1156 return $self->{$name};
1157 }
1158 }
1159 elsif ( $name =~ qr/^(get_|set_)(.*)$/ ) {
1160 if ( exists $self->device_settings()->{$2} ) {
1161 return $self->getset( $1, $2, "device_settings", @_ );
1162 }
1163 elsif ( exists $self->device_cache()->{$2} ) {
1164 return $self->getset( $1, $2, "device_cache", @_ );
1165 }
1166 else {
1167 Lab::Exception::Warning->throw( error =>
1168 "AUTOLOAD could not find var for getter/setter: $name \n"
1169 );
1170 }
1171 }
1172 elsif ( exists $self->{'device_settings'}->{$name} ) {
1173 if (@_) {
1174 return $self->{'device_settings'}->{$name} = shift;
1175 }
1176 else {
1177 return $self->{'device_settings'}->{$name};
1178 }
1179 }
1180 else {
1181 Lab::Exception::Warning->throw( error => "AUTOLOAD in "
1182 . __PACKAGE__
1183 . " couldn't access field '${name}'.\n" );
1184 }
1185 }
1186  
1187 # needed so AUTOLOAD doesn't try to call DESTROY on cleanup and prevent the inherited DESTROY
1188 sub DESTROY {
1189 my $self = shift;
1190  
1191 #$self->connection()->DESTROY();
1192 $self->SUPER::DESTROY if $self->can("SUPER::DESTROY");
1193 }
1194  
1195 sub getset {
1196 my $self = shift;
1197 my $gs = shift;
1198 my $varname = shift;
1199 my $subfield = shift;
1200 if ( $gs eq 'set_' ) {
1201 my $value = shift;
1202 if ( !defined $value || ref($value) ne "" ) {
1203 Lab::Exception::CorruptParameter->throw( error =>
1204 "No or no scalar value given to generic set function $AUTOLOAD in "
1205 . __PACKAGE__
1206 . "::AUTOLOAD().\n" );
1207 }
1208 if ( @_ > 0 ) {
1209 Lab::Exception::CorruptParameter->throw( error =>
1210 "Too many values given to generic set function $AUTOLOAD "
1211 . __PACKAGE__
1212 . "::AUTOLOAD().\n" );
1213 }
1214 return $self->{$subfield}->{$varname} = $value;
1215 }
1216 else {
1217 if ( @_ > 0 ) {
1218 Lab::Exception::CorruptParameter->throw( error =>
1219 "Too many values given to generic get function $AUTOLOAD "
1220 . __PACKAGE__
1221 . "::AUTOLOAD().\n" );
1222 }
1223 return $self->{$subfield}->{$varname};
1224 }
1225 }
1226  
1227 #
1228 # This is a hook which is called after connection initialization and before the device cache is synced (see _construct).
1229 # Necessary for some devices to put them into e.g. remote control mode or otherwise enable communication.
1230 # Overwrite this if needed.
1231 #
1232 sub _device_init {
1233 }
1234  
1235 #
1236 # This tool just returns the index of the element in the provided list
1237 #
1238  
1239 sub function_list_index {
1240 1 while $_[0] ne pop;
1241 $#_;
1242 }
1243  
1244 # sub WriteConfig {
1245 # my $self = shift;
1246 #
1247 # my %config = @_;
1248 # %config = %{$_[0]} if (ref($_[0]));
1249 #
1250 # my $command = "";
1251 # # function characters init
1252 # my $inCommand = "";
1253 # my $betweenCmdAndData = "";
1254 # my $postData = "";
1255 # # config data
1256 # if (exists $self->{'CommandRules'}) {
1257 # # write stating value by default to command
1258 # $command = $self->{'CommandRules'}->{'preCommand'}
1259 # if (exists $self->{'CommandRules'}->{'preCommand'});
1260 # $inCommand = $self->{'CommandRules'}->{'inCommand'}
1261 # if (exists $self->{'CommandRules'}->{'inCommand'});
1262 # $betweenCmdAndData = $self->{'CommandRules'}->{'betweenCmdAndData'}
1263 # if (exists $self->{'CommandRules'}->{'betweenCmdAndData'});
1264 # $postData = $self->{'CommandRules'}->{'postData'}
1265 # if (exists $self->{'CommandRules'}->{'postData'});
1266 # }
1267 # # get command if sub call from itself
1268 # $command = $_[1] if (ref($_[0]));
1269 #
1270 # # build up commands buffer
1271 # foreach my $key (keys %config) {
1272 # my $value = $config{$key};
1273 #
1274 # # reference again?
1275 # if (ref($value)) {
1276 # $self->WriteConfig($value,$command.$key.$inCommand);
1277 # } else {
1278 # # end of search
1279 # $self->Write($command.$key.$betweenCmdAndData.$value.$postData);
1280 # }
1281 # }
1282 #
1283 # }
1284  
1285 # =head2 WriteConfig
1286 #
1287 # this is NOT YET IMPLEMENTED in this base class so far
1288 #
1289 # $instrument->WriteConfig( 'TRIGGER' => { 'SOURCE' => 'CHANNEL1',
1290 # 'EDGE' => 'RISE' },
1291 # 'AQUIRE' => 'HRES',
1292 # 'MEASURE' => { 'VRISE' => 'ON' });
1293 #
1294 # Builds up the commands and sends them to the instrument. To get the correct
1295 # format a
1296 # command rules hash has to be set up by the driver package
1297 #
1298 # e.g. for SCPI commands
1299 # $instrument->{'CommandRules'} = {
1300 # 'preCommand' => ':',
1301 # 'inCommand' => ':',
1302 # 'betweenCmdAndData' => ' ',
1303 # 'postData' => '' # empty entries can be skipped
1304 # };
1305 #
1306 #
1307 #
1308  
1309  
1310 1;
1311  
1312 __END__