#!/usr/bin/perl -w

#
# hp5370b-hp3456a.pl
# version 0.9 --  3 September 2005
#
# Record frequency readings from HP 5370B counter and simultaneous
# voltage readings from HP 3456A DMM.
# 
# Copyright 2004-2005 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 DateTime;
use n8ur qw(trim squash collapse round);
use n8ur_gpib qw(checkSRQ serviceSRQ logline);

##########################
my $board = "gpib1";
my $device1 = "hp5370b";
my $device2 = "hp3456a";
##########################

#----------
# 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:a:g:n:s:f:t:';

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

usage: $0 [-h] [-a samples to average] [-g gate time] 
	[-n nominal frequency] [-s scale frequency] -f logfile

-a      : samples to average -- default 1
-g      : gate time (GT1, GT2, GT3, GT4)
-h      : this (help) message
-n      : nominal frequency; readings will be normalized against this
-s      : scale frequency; readings will be divided by this
-t	: timetag format (mjd|iso|none); default mjd
-f      : logfile using full pathname;
          for output to console, use "-f -"

EOF
}

#----------

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 $samples = 1;
if ($opt{a}) {
        $samples = $opt{a};
        }

my $gate = "GT4";
if ($opt{g}) {
        $gate = $opt{g};
        }

my $tags = "mjd";
if ($opt{t}) {
        $tags = lc($opt{t});
        }

my $nominal = 0;
if ($opt{n}) {
	$nominal = $opt{n};
	}

my $scale = 0;
if ($opt{s}) {
	$scale = $opt{s};
	}
	 
my $logfile = $opt{f};

#----------
# initialize variables
my $counter;
my $sum1;
my $sum2;
my $tmp;
my $command;
my $gpib_status;

#----------
# set up logfile
open (LOG, ">>$logfile") ||
	die "Can't open logfile $logfile!\n";
# set nonbuffered mode if slower readings
if ($gate eq "GT4") {
	select(LOG), $| = 1;
	}


#----------
# initialize devices
my $brd = LinuxGpib::ibfind($board);
my $dev1 = LinuxGpib::ibfind($device1);
my $dev2 = LinuxGpib::ibfind($device2);

# clear
LinuxGpib::ibclr($dev1);
usleep(1000000);
LinuxGpib::ibclr($dev2);
usleep(1000000);

# initialize 5370B
$command = "FN3" . $gate . "MD4";
LinuxGpib::ibwrt($dev1,$command,length($command));
usleep(1000000);

# intialize 3456A:
# DCV, autorange, local trigger lockout, autozero on, filter off,
# plc integration 10, ascii output, display 4 digits.
$command = "F1R1T4Z1FL0G4I10";
LinuxGpib::ibwrt($dev2,$command,length($command));
usleep(1000000);

#----------

# write header line
my $dt = DateTime->now;
my $current_iso = $dt->ymd('-') . 'T' . $dt->hms(':');
my $current_mjd = $dt->mjd;
printf LOG "# Run started at %s (MJD %11.6F).\n",$current_iso,$current_mjd;
print LOG "# Frequency from $device1, gate $gate, voltage from $device2.\n";
print LOG "# Average by $samples.";
if ($nominal) {
	print LOG "  Nominal frequency is $nominal.";
	}
else {
	if ($scale) {
		print LOG " Scaled from $scale."
		}
	}
print LOG "\n";
	


#----------
sub dolog {
 my $timetag;
 my $input1 = shift;
 my $input2 = shift;
 my $value1;
 my $value2;
 my $dt = DateTime->now;

        $timetag = "";
        if ($tags eq "mjd") {
                $timetag = sprintf("%6.6f",round(6,$dt->mjd));
        }
        if ($tags eq "iso") {
                $timetag = $dt->ymd('-') . 'T' . $dt->hms(':');
        }
        $value1 = sprintf(" %1.*e",12,$input1);
        $value2 = sprintf(" %1.*f",1,$input2);
return $timetag . " ". $value1 . " " . $value2 . "\n";


}

$counter = 1;
my $result1 = 0;
my $result2 = 0;

# main loop
while (1) {

		# get the frequency
                LinuxGpib::ibrd($dev1,$result1,24);
		usleep(100);
		$result1 = substr($result1,4,18);
		# get the voltage
		LinuxGpib::ibtrg($dev2);
		usleep(100);
                LinuxGpib::ibrd($dev2,$result2,14);
		usleep(100);
		$result2 = substr($result2,0,12);

		print LOG dolog($result1,$result2*1000);
		usleep(50000);
}	

#----------

exit 0;
