#!/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 = "gpib1";
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:a:d:g:n:s:f:t:';

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

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

-a      : samples to average -- default 1
-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 $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 $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 $last_avg_value = 0;
$sum = 0;

sub dolog {
	my $avg_value = $sum/$samples;
	if ($nominal) {
		$avg_value = $avg_value - $nominal;
		}
	if ($scale) {
		$avg_value = $avg_value/$scale;
		}
	if ($samples <= 10) {
		print LOG logline($tags,12,round(13,$avg_value));
		}
	else {
		print LOG logline($tags,14,round(15,$avg_value));
		}
	
	$last_avg_value = $avg_value;
}

$counter = 1;
my $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);
		$sum += $result;
		if ($counter == $samples) {
			dolog;
			$sum = 0;
			$counter = 1;
		} else {
			$counter++;	
			}
                $command = "MR";
                LinuxGpib::ibwrt($dev,$command,length($command));
	}
	usleep($delay);
}	

#----------

exit 0;
