#!/usr/bin/perl -w
##
## tsc-fcounter.pl -- get fcounter data from TSC-5120A
## version 0.8 -- 1 October 2007
##
## Copyright 2007 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 DateTime;
use n8ur qw(lower_case trim squash collapse round);
use n8ur_gpib qw(logline logline_tsc);
use Net::Telnet;

my $machine = '192.168.1.248';
my $port = '1299';
my $opt_string = 'hf:';
my $tau = 10;

my $file;
my $t;
my @lines;
my $j;
my $k;
my @tmp;
my @avg;
my $tags = "mjd";
my $dt;
my $current_mjd;
my $current_iso;

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

usage: $0 [-h ] -f filename

-h	: this help
-f	: output file base name using full pathname;
	  for output to console, use "-f -";

EOF
}

getopts( "$opt_string", \my %opt ) or usage() and exit;
usage() and exit if $opt{h};
usage() and exit if !$opt{f};
$file = $opt{f};

open (LOG, ">$file") || die "Can't open $file!\n";
select (LOG), $| = 1;

$t = new Net::Telnet (Timeout => 10,Port=>$port);
$t->open('femto.febo.com');
$t->waitfor("/=192.168.1.248 >/");

while (1) {
@lines = $t->cmd("show fcounter");
# swallow prompt at end
for ($j = 3; $j < @lines-1; $j++) {
	@tmp = split(/\s/,$lines[$j]);
	$avg[$j-2] = $tmp[2];
	}
for ($j = 1; $j < @avg; $j++) {
	if ($avg[$j]) {
		trim($avg[$j]);
		}
	else	{
		$avg[$j] = "";
		}
	}

$dt = DateTime->now;
$current_iso = $dt->ymd('-') . 'T' . $dt->hms(':');
$current_mjd = $dt->mjd;
$tags = $current_iso;

print LOG $tags," ",$avg[1]," ",$avg[2]," ",$avg[3]," ",$avg[4],"\n";

usleep (($tau-0.2)*1e6);
}

close LOG;

$t->print("exit");
$t->close;
