#!/usr/bin/perl -w
#
# tsc-data.pl
# version 0.8 -- 10 March 2007
#
# Capture phase data from TSC-5120A
# 
# 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 = '1298';

my $logfile;
my $data;
my $t;
my $counter;

# 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 = 'n:h:d:i:f:';

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

usage: $0 [-n nth] [-h] [-d description] [-i input frequency]  -f logfile

-d	 : description, surrounded by commas
-i	 : input frequency
-n	 : get every nth sample; default is 100 (tau=100ms)
-h	 : this (help) message
-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

$logfile = $opt{f};

my $description = "";
if ($opt{d}) {
	$description = $opt{d};
	}

my $frequency = "";
if ($opt{i}) {
	$frequency = $opt{i};
	}

my $nth = 100;
if ($opt{n}) {
	$nth = $opt{n};
	}

my $tag = "mjd";
if ($opt{t}) {
	$tag = trim(lower_case($opt{t}));
	}

#----------
# set up logfile ; use buffered since data rate is pretty high
open (LOG, ">>$logfile") || die "Can't open logfile $logfile!\n";
select(LOG), $| = 1;

#----------
# write header line
my $dt = DateTime->now;
my $current_iso = $dt->ymd('-') . 'T' . $dt->hms(':');
my $current_mjd = $dt->mjd;
printf LOG "# TSC-5120A:  Run started at %s (MJD %11.6F).\n",
	$current_iso,$current_mjd;
if ($description) { print LOG "# $description\n"; }
print LOG "# Tau = ",$nth/1000," seconds, phase relative to input frequency.\n";
if ($frequency) { print LOG "# Input frequency: $frequency\n"; }

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

# main loop
$counter = 1;
while (1) {
	$data = $t->getline;
	if ($counter == $nth) {
		print LOG $data;
		$counter = 1;
		}
	else {
		$counter++
		}
	}

$t->close;

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

#----------
sig_handler;
