#!/usr/bin/perl -w
# Display PPS debugging info by reading variables from kernel using /proc
# $Id: PPSspy.pl,v 1.2 2003/03/21 22:09:55 windl Exp $
# Copyright (c) 2003 by Ulrich Windl <Ulrich.Windl@rz.uni-regensburg.de>
use strict;
local *PPS;
my $ppsinfo = "/proc/sys/kernel/time/pps";
my $last_line = '';
my $line;
my @vals;

warn "$ppsinfo is an unofficial interface that may be\n";
warn "removed or changed any time!\n";
if (open(PPS, "<$ppsinfo")) {
    while (seek(PPS, 0, 0) && read(PPS, $line, 512) > 0) {
	select(undef, undef, undef, 0.25), next
	    if ($line eq $last_line);
	@vals = split("\t", $line);

	my @tf;
	my ($freq, $lastfreq, $fcount, $jitter, $stabil, $lastsec);
	my ($valid, $shift, $shiftmax, $intcnt);
	my ($calcnt, $jitcnt, $stbcnt, $errcnt);
	my ($fmin, $fmax, $frange);

	foreach (1..3) {
	    push(@tf, $vals[0] + $vals[1] * 1e-9); splice(@vals, 0, 2);
	}
	print "tf[]=", join(", ", map { sprintf("%20.9f", $_) } @tf), "\n";

	$freq = abs($vals[1]) + $vals[0] / 2**32;
	$freq = -$freq if ($vals[1] < 0);
	splice(@vals, 0, 2);
	$lastfreq = shift(@vals);
	$fcount = shift(@vals);
	printf("freq=%15.10f, lastfreq=$lastfreq, fcount=$fcount\n",
	       $freq / 1000);

	$jitter = shift(@vals);
	$stabil = shift(@vals);
	$lastsec = shift(@vals);
	print "jitter=$jitter, stabil=$stabil, lastsec=$lastsec\n";

	$valid = shift(@vals);
	$shift = shift(@vals);
	$shiftmax = shift(@vals);
	$intcnt = shift(@vals);
	print "valid=$valid, shift=$shift, shiftmax=$shiftmax, intcnt=$intcnt\n";
	$calcnt = shift(@vals);
	$jitcnt = shift(@vals);
	$stbcnt = shift(@vals);
	$errcnt = shift(@vals);
	print "calcnt=$calcnt, jitcnt=$jitcnt, stbcnt=$stbcnt, errcnt=$errcnt\n";

	$fmin = shift(@vals) / 1000;
	$fmax = shift(@vals) / 1000;
	$frange = shift(@vals) / 1000;
	printf("Linux: fmin=%8.3f, fmax=%8.3f, frange=%8.3f\n",
	       $fmin, $fmax, $frange);

	print join(",", @vals), "\n";	# should be empty line
	$last_line = $line;
    }
    close(PPS);
} else {
    die "cannot open $ppsinfo: $!\n";
}
