#
# display_ra24e.pl - Ken Heller 04/17/2015
#
#       Description: Displays Room Alert 24e status
#
#       Usage: display_ra24e.pl
#
#       Output:  html form to stdout
#
# History:
#       Date       Who     Description
#       ----       ---     ---------------------------------------------------
#      04/17/2015   KH     Create
################################################################################ 
##require "flush.pl";
require "marsdcslib.pl";
##%Cfg = &load_cfgfile("../Cfg/marsdcs.cfg");
%Cfg = &load_cfgfile("marsdcs.cfg");

#
# Create key/value parameter pairs based on the request method
#
if ($ENV{'REQUEST_METHOD'} eq "POST")
     {read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
      @pairs = split(/&/, $buffer);
      } 
else {@pairs = split(/&/, $ENV{'QUERY_STRING'});
      $buffer = "$ENV{'QUERY_STRING'}";
      }

#if ($#ARGV >= 0) {@pairs = @ARGV;}

print "Content-type: text/html\n\n";

#
# Put the keys and values in an associative array.
# The value of a form variable can then be referenced
# as $form{variable_name}
#
foreach $pair (@pairs) {
    ($key, $value) = split(/=/, $pair);
    $key =~ tr/+/ /;
    $key =~ s/%([a-fA-F0-9]{2})/pack("C", hex($1))/eg;
    $key =~ tr/\cM/\n/;
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9]{2})/pack("C", hex($1))/eg;
    $value =~ tr/\cM/\n/;
    $arg{$key} = $value;
    #print stderr "arg{$key} = $value\n";
}

if (! defined $arg{'LastN'} || $arg{'LastN'} eq "") {$arg{'LastN'} = 120;}
if    ($arg{'LineStyle'} eq "lines")       {$CheckedLines  = "CHECKED";}
elsif ($arg{'LineStyle'} eq "points")      {$CheckedPoints = "CHECKED";}
elsif ($arg{'LineStyle'} eq "linespoints") {$CheckedBoth   = "CHECKED";}
else {$arg{'LineStyle'} = "lines"; $CheckedLines = "CHECKED"};

if (! defined $arg{'Refresh'}) {$arg{'Refresh'} = 60;}

$timestamp = gmtimestamp();
#$curr_year = substr("$timestamp",0,4);

###$last_rec = `/usr/bin/tail -n 1 ra24.dat`; chomp($last_rec);

($date,$time,$int_temp,$int_humd,$ext_temp,$pge_ph_0,$pge_ph_1,$pge_ph_2,$ups_ph_0,$ups_ph_1,$ups_ph_2,$motion,$door) = split(' ',$last_rec);

#print "$date $time $int_temp $int_humd $ext_temp $pge_ph_0 $pge_ph_1 $pge_ph_2 $ups_ph_0 $ups_ph_1 $ups_ph_2 $motion $door\n"; exit;

$LastUpdateTime = "$date $time";

#
#Check modified time of data file. If not within n minutes,
#
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,
 $blksize,$blocks) = stat("ra24.dat");

$utime = time; $dtime = $utime - $mtime;
if (($dtime) > 300)
     {$last_update_color = "#EE0000"; $plot_color = "ls 1";}
else {$last_update_color = "#00aa00"; $plot_color = "ls 2";}

$timestamp = gmtimestamp();
print <<"EndHTML";

<html>
<head>
<title>Mars EOI RA24e Status</title>

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<meta content=$arg{'Refresh'};url="display_ra24e.pl?LastN=$arg{'LastN'}&Refresh=$arg{'Refresh'}&LineStyle=$arg{'LineStyle'}" http-equiv="refresh">
</head>
<body bgcolor=004466 xxbgcolor=4488aa>
<center> 
<table bgcolor=black cellspacing=5 cellpadding=0 border=0>
<td valign=top align=center rowspan=1>
<table border=0 bgcolor=gray cellspacing=5 cellpadding=0>
  <form method="post" name="MyForm1">
  <tr>
  <td>   
         <font size=2>Refresh 
         <input type="text" name="Refresh" size=2 value="$arg{'Refresh'}"> &nbsp 
         <font size=2>LastN Rec: 
         <input type="text" name="LastN" size=4 value="$arg{'LastN'}">
         <xxinput type="hidden" name="LastN" value="$arg{'LastN'}">
 </td>
  </tr><tr>
  <td>  <input type="Radio" name="LineStyle" value="lines" $CheckedLines>Lines
         <input type="Radio" name="LineStyle" value="points" $CheckedPoints>Points
         <input type="Radio" name="LineStyle" value="linespoints" $CheckedBoth>Both
  </td>
  </tr><tr>
  <td align=center>
     <input type="submit" name="Replot" value="Refresh">
   </form>
</td>
</table>

<br>

<table bgcolor=004488 cellspacing=1 border=0>
<td colspan=3><font color=white face=sans-serif size=2>Last Update: </font>
              <font color=$last_update_color face=sans-serif size=2><b>$LastUpdateTime</b></font></td>

</table>

</td>
<td>
   <table border=0 cellspacing=0 cellpadding=0 width=100%>
   <td>
   <font color=#00aaee face=sans-serif><b>Mars EOI Temperature</b></font><br>
   <font color=white face=sans-serif>Current Time: <b>$timestamp</b></font>
   <td><img src="mbari_black.jpg">
   </table>
<tr></tr>
<td><img alt="ext temp" src="plot_ra24_temp_room.pl?LastN=$arg{'LastN'}&i=ra24.dat&l=$arg{'LineStyle'}&c=$plot_color" border=0 width=960 height=480>
<td><img alt="int humid" src="plot_ra24_int_humid.pl?LastN=$arg{'LastN'}&i=ra24.dat&l=$arg{'LineStyle'}&c=$plot_color" border=0 width=480 height=240>
</tr>
</table>
</center>

EndHTML

#
# Subroutines Follow
#
sub gmtimestamp {local($no_gmtlabel) = $_[0];
        local($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime;
        # zero fill hour,min,sec and month
        if ($sec < 10) {$sec = "0$sec";}
        if ($min < 10) {$min = "0$min";}
        if ($hour < 10) {$hour = "0$hour";}
        $mon += 1; #from gmtime defined 0-11, make it 1-12
        if ($mon < 10) {$mon = "0$mon";}
        if ($mday < 10) {$mday = "0$mday";}
   	#make year 4-digits - Note: Year is years since 1900
   	$year += 1900; 
	if ($no_gmtlabel)
             {return "$year/$mon/$mday $hour:$min:$sec";}
        else {return "$year/$mon/$mday $hour:$min:$sec GMT";}
}


#Calculate ave response time and loss seq numbers
sub calc_resp_loss {my($data_file) = $_[0];
        my($line) = <CMD>;
        my($date,$time,$ip,$seq,$resp) = split(' ',$line);
        my($prev_seq) = "";
        my($total_resp,$cnt,$loss_cnt);
        $total_resp = 0; $cnt = 0; $loss_cnt = 0;
        open(CMD,"/usr/bin/tail -$arg{'LastN'} $data_file|");
        while ($line = <CMD>)
          {chomp($line);
           ($date,$time,$ip,$seq,$resp) = split(' ',$line);
           $total_resp += $resp;
           if ($seq != ($prev_seq + 1) && $prev_seq ne "") {$loss_cnt++;}
           $prev_seq = $seq;
           $cnt++;
           }
        $resp = sprintf("%.4f", $total_resp/$cnt);
        close(CMD);
        return  "$resp $loss_cnt";
}

