package n8ur_gpib;

use 5.008004;
use strict;
use warnings;
use Time::HiRes qw(usleep);
use LinuxGpib;
use DateTime;
use n8ur;

require Exporter;

our @ISA = qw(Exporter);

our @EXPORT = qw( checkSRQ serviceSRQ logline );

our $VERSION = '0.1';

sub checkSRQ {
	my $board = shift;
	my $lines;	
	LinuxGpib::iblines($board,$lines);
	# 0x2000 is bit 14, busSRQ
	if ($lines & 0x2000) {
		return 1;
	} else {
		return 0;
	}
}
	
sub serviceSRQ {
	my $device = shift;
	my $status;
	my $device_status;
	my $reading;
	$status = LinuxGpib::ibrsp($device,$device_status);
	usleep(200000);
	# 0x40 is bin 6, "service me, please"
	if ($device_status & 0x40) {
		# get reading
		LinuxGpib::ibrd($device,$reading,2048);
		return $reading;
	} else {
		return 0;
	}
}

sub logline {
	my $tags;
	my $precision = shift;
	my $value1 = shift;
	my $value2 = shift;
	my $timetag;
	my $result;
	
	my $dt = DateTime->now;

	$timetag = "";
	if ($tags eq "mjd") {
		$timetag = sprintf("5.5f",round(5,$dt->mjd));
	}
	if ($tags eq "iso") {
		$timetag = $dt->ymd('-') . 'T' . $dt->hms(':');
	}

	if ($value2) {
		$result = sprintf("%s %1.*e %1.*e\n",
			$timetag,$value1,$precision,$value2,$precision);
	} else {
		$result = sprintf("%s %1.*e\n",
			$timetag,$value1,$precision);
	}
	return $result;
}


# Preloaded methods go here.

1;
__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

n8ur - Functions for GPIB

=head1 SYNOPSIS

	use n8ur;
	checkSRQ($board)
	serviceSRQ($device)
	logline($tagtype,$precision,$value1,[$value2])

=head1 DESCRIPTION

Some useful functions for GPIB programming.

=head2 EXPORT

None by default.

=head1 SEE ALSO

n8ur.pm

=head1 AUTHOR

John Ackermann   N8UR, jra@febo.com

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2005 by John Ackermann N8UR (jra@febo.com)

This program may be copied, modified, distributed and used for 
any legal purpose provided that (a) the copyright notice above as well
as these terms are retained on all copies; (b) any modifications that 
correct bugs or errors, or increase the program's functionality, are 
sent via email to the author at the address above; and (c) such 
modifications are made subject to these license terms.

=cut
