#!/usr/bin/perl

# The following command was used to create the rrd for this
#> rrdtool create cable_modem.rrd --start 1077559431 --step 1800 \
#  DS:tx:GAUGE:3600:0:70 DS:rx:GAUGE:3600:-20:20 DS:snr:GAUGE:3600:20:50 \
#  RRA:AVERAGE:0.5:1:336 RRA:AVERAGE:0.5:12:124

use strict;
use warnings;
use LWP::Simple;

my $url    = 'http://192.168.100.1/showModemRf';
my $rrd = "/usr/bin/rrdtool";
my $html = get($url) or die "Couldn't get RF page";
my $workdir = "/home/godber/public_html/info/";
my $rrdfile = "/home/godber/var/cable_modem/cable_modem.rrd";

#print $html;

my $time=time();
chdir $workdir;

$html =~ m{Tx Power</FONT></TD><TD BGCOLOR="#FFFFFF"><FONT COLOR="#336699">([\d.]+)</FONT>} || die "Can't get TX";
my $tx_power = $1;
$html =~ m{Rx Power</FONT></TD><TD BGCOLOR="#FFFFFF"><FONT COLOR="#336699">([-\d.]+)</FONT>} || die "Can't get RX";
my $rx_power = $1;
$html =~ m{Downstream SNR</FONT></TD><TD BGCOLOR="#FFFFFF"><FONT COLOR="#336699">([\d.]+)</FONT>} || die "Can't get SNR";
my $snr = $1;
#print "TX Power is $tx_power dBmV\n";
#print "RX Power is $rx_power dBmV\n";
#print "Downstream SNR is $snr dB\n";

# update the RRD
`$rrd update $rrdfile $time:$tx_power:$rx_power:$snr`;

#make some plots
my $plot_tx = "$rrd graph tx.png --start ".($time-604800).
              " --end $time --title 'Transmission Power' ".
              "--imgformat PNG --units-exponent 0 -v 'Power (dBmV)' ".
              "-l 0 -u 70 --alt-y-grid ".
              "DEF:tx=$rrdfile:tx:AVERAGE LINE1:tx#FF0000:'TX Power' ";

my $plot_rx = "$rrd graph rx.png --start ".($time-604800).
              " --end $time --title 'Receive Power' ".
              "--imgformat PNG --units-exponent 0 -v 'Power (dBmV)' ".
              "-l -20 -u 20 ".
              "DEF:rx=$rrdfile:rx:AVERAGE LINE1:rx#FF0000:'RX Power'";

my $plot_snr = "$rrd graph snr.png --start ".($time-604800).
              " --end $time --title 'SNR' ".
              "--imgformat PNG --units-exponent 0 -v 'SNR (dB)' ".
              "-l 20 -u 50 ".
               "DEF:snr=$rrdfile:snr:AVERAGE LINE1:snr#FF0000:'SNR'";

`$plot_tx`;
`$plot_rx`;
`$plot_snr`;

my $plot_all = "$rrd graph all.png --start ".($time-604800).
               " --end $time --title 'Terayon Cable Modem RF Parameters' ".
               "--imgformat PNG --units-exponent 0 -v 'Power (dBmV)' ".
               "-l -20 -u 70 --alt-y-grid -h 200 ".
               "DEF:tx=$rrdfile:tx:AVERAGE LINE1:tx#FF0000:'TX Power' ".
               "DEF:rx=$rrdfile:rx:AVERAGE LINE2:rx#00FF00:'RX Power' ".
               "DEF:snr=$rrdfile:snr:AVERAGE LINE3:snr#0000FF:'SNR'";

`$plot_all`;

