#!/usr/bin/perl -w
#
# 5334a.pl
# version 0.6 -- 28 September 2003
#
# Record time interval readings from HP 5370b counter
# 
# Copyright 2003 by John R. 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.

use strict;
use POSIX qw(setsid);
use Getopt::Std;
use Time::HiRes qw(usleep);
use LinuxGpib;
use n8ur qw(trim squash collapse round);
use n8ur_gpib qw(checkSRQ serviceSRQ logline);

# device name from /etc/gpib.conf
my $board = "gpib0";
my $device1 = "5334a1";
my $device2 = "5334a2";

my $brd;
my $dev1;
my $dev2;
#----------
# handle signals and errors -- mainly to clear lockfile on termination
sub sig_handler {
	sleep 2;
	close LOG;
	exit(0);
}

# there's got to be a better way!
$SIG{'HUP'} = 'sig_handler';
$SIG{'INT'} = 'sig_handler';
$SIG{'KILL'} = 'sig_handler';
$SIG{'STOP'} = 'sig_handler';
$SIG{'TERM'} = 'sig_handler';
#----------

#----------
# display usage
my $opt_string = 'h:f:';

sub usage() {
print STDERR << "EOF";

usage: $0 [-h] [-a samples to average] [-g gate time] -f logfile

-h	: this (help) message
-f	: logfile using full pathname;
	  for output to console, use "-f -"

EOF
}

# main loop
#----------

getopts( "$opt_string", \my %opt ) or usage() and exit;

# print usage
usage() and exit if $opt{h};
usage() and exit if !$opt{f};

# set variables to command line params
my $logfile;

$logfile = $opt{f};

#----------


#----------
# initialize variables
my $reading;
my $time_int;
my $last_time_int;
my $command;
my $gpib_status;

#----------
# set up logfile
open (LOG, ">>$logfile") ||
	die "Can't open logfile $logfile!\n";
# set nonbuffered mode
select(LOG), $| = 1;

#----------
# initialize counter
$brd = LinuxGpib::ibfind($board);
$dev1 = LinuxGpib::ibfind($device1);
$dev2 = LinuxGpib::ibfind($device2);
# clear
LinuxGpib::ibclr($dev1);
LinuxGpib::ibclr($dev2);
# set up
$command = "INREWA1FN5AU0SM1";
LinuxGpib::ibwrt($dev1,$command,length($command));
LinuxGpib::ibwrt($dev2,$command,length($command));
usleep(50000);
#----------

my $result1;
my $result2;
my $tag = "mjd";

while (1) {

	if (checkSRQ($brd)) {
		$result1 = substr(squash(trim(serviceSRQ($dev1))),1);
		$result2 = substr(squash(trim(serviceSRQ($dev2))),1);
		print logline($tag,4,$result1,$result2);
		}
}

#----------

exit 0;
