#!/usr/bin/perl -w
#
# hp5370-freq.pl
# version 0.95 --  8 December 2005
#
# Record frequency readings from HP 5370b counter
# 
# 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 = "gpib0";
my $device = "hp5370b";
##########################

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

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

usage: $0 [-h] [-a] [-g gate time] 
	[-n nominal frequency] [-d delay between readings]
	[-s scale frequency] -f logfile

-a      : average 100 samples
-g      : gate time (GT1, GT2, GT3, GT4)
-h      : this (help) message
-d	: delay in seconds between readings
-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 $samplesize = "SS1";
my $samples = 1;
if ($opt{a}) {
        $samplesize = "SS5";
        $samples = 100;
        }

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

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

my $delay = 0;
if ($opt{d}) {
        $delay = ($opt{d} + 0.05)*1e6;
        }

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 $reading;
my $freq;
my $bytecount;
my $counter;
my $badcount;
my $sum;
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 counter
my $brd = LinuxGpib::ibfind($board);
my $dev = LinuxGpib::ibfind($device);

# clear
LinuxGpib::ibclr($dev);

$command = "FN3" . $gate . "MD4";


LinuxGpib::ibwrt($dev,$command,length($command));
usleep(50000);

#----------

# 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 "# Data from $device, gate $gate.  Average by $samples.";
if ($nominal) {
	print LOG "  Nominal frequency is $nominal.";
	}
else {
	if ($scale) {
		print LOG " Scaled from $scale."
		}
	}
print LOG "\n";
	

my $result;

#----------
sub dolog {
	if ($nominal) {
		$result = $result - $nominal;
		}
	if ($scale) {
		$result  = $result/$scale;
		}
	if ($samples < 100) {
		print LOG logline($tags,12,round(13,$result));
		}
	else {
		print LOG logline($tags,14,round(15,$result));
		}
}


# main loop
$command = "MR";
LinuxGpib::ibwrt($dev,$command,length($command));
while (1) {

        if (checkSRQ($brd)) {
                $result = substr(substr(squash(trim(serviceSRQ($dev))),1),3);
		dolog;
                $command = "MR";
                LinuxGpib::ibwrt($dev,$command,length($command));
	}
	usleep($delay);
}	

#----------

exit 0;
