#!/usr/bin/perl
#
# power_on_dcs_sail.pl - Steven Lerner 6/2005
#                        Woods Hole Oceanographic Institution
#
#       Description: Quick script that turns on ALL dcs loads 
#                    via mars power controller via obc xbar7/sail/NPC
#                    serial port
#
#       Assumptions: Reguires that the serial connection to power ctrl
#                    is already logged-in (ie; open minicom session,
#                    log-in, and then quit w/o reset via ctl-a q)
#                    
#       Usage: power_on_dcs_sail.pl [off]
#
#       Output: writes log to Data/date.pwron.dat
#
# History:
#       Date       Who    Description
#       ----       ---    ---------------------------------------------------
#      06/20/2005  SL     Create from get_power_data.pl
#      06/24/2005  SL     Added killing and starting get_power_data.pl
#      08/20/2005  SL     Modified for running over sail
#################################################################################
require "getopts.pl";
require "flush.pl";
require "ctime.pl";
require "timelocal.pl";

$VERSION = "v1.0";
$DEBUG = 0;

$sail = "/home/stevel/sail_driver/sail";

use FileHandle;
use IPC::Open3;

my $in  = new FileHandle;
my $out = new FileHandle;
my $err = new FileHandle;


$POWER_ON = 1;

if ($#ARGV >= 0 && $ARGV[0] eq "off") 
   {print "Turn OFF DCS Loads\n"; 
    print "Confirm? ";$ans=<STDIN>; chomp($ans);
    if ($ans ne "y" && $ans ne "yes") {exit;}
    $POWER_ON = 0;
    }

$sleep_amt = 1;
$prev_datafile = "";

#Kill get_power_data.pl just in case
system("killall -q get_power_data_sail.pl");


#open com port
open3 ($out,$in,$err,"$sail -s#S01A -x7") || die "Unable to open sail driver $!\n";

#Set labels
$load_label[3]="Cisco MRA01-01";
$load_label[4]="Cisco MRA01-02";
$load_label[5]="OE West 75";
$load_label[6]="Cyclades";
$load_label[7]="OE East 75";
$load_label[8]="OE East 98";
$load_label[9]="OE West 98";
$load_label[10]="West NE Optical Switch";
$load_label[11]="West EDFA";
$load_label[13]="East NE Optical Switch";
$load_label[14]="East EDFA";

if ($POWER_ON) {$power_on_str = "ON";}
          else {$power_on_str = "OFF";}

$timestamp = gmtimestamp(1);
print     "\n\n$timestamp ============= Powering $power_on_str MARS DCS Loads =============\n";

# Loop for each DCS load - turn load on, look at current...
foreach $load (3,4,5,6,7,8,9,10,11,13,14)
  {$tag = gmtimestamp_file();
   $datafile = "Data/$tag";
   if ($datafile ne "$prev_datafile")
     {#Open power-on data files
      open(RAW,">>$datafile.pwron.dat") || die "Unable to open data file: $datafile.pwron.dat\n";
      print RAW "\n\n$timestamp ============= Powering $power_on_str MARS DCS Loads =============\n";
      open(CURR_DAT,">>$datafile.cur.dat") || die "Unable to open data file: $datafile.cur.dat\n";
      open(STATE_DAT,">>$datafile.state.dat") || die "Unable to open data file: $datafile.state.dat\n";

      #write header record for dat file
      print CURR_DAT "#fields: date,time,load01,load02,load03,load04,load05,load06,load07,load08,";
      print CURR_DAT "load09,load10,load11,load12,load13,load14,load15,load16\n";
      flush(CURR_DAT);
      
      print STATE_DAT "#fields: date,time,load01,load02,load03,load04,load05,load06,load07,load08,";
      print STATE_DAT "load09,load10,load11,load12,load13,load14,load15,load16\n";
      flush(STATE_DAT);
      }
   $prev_datafile = "$datafile";


   #set Load on
   $timestamp = gmtimestamp(1);
   print "Powering $load_label[$load] [Load $load]\n";
   print "\ttime=$timestamp\n";
   print "\tsets $load $POWER_ON\n";
   print RAW "Powering $load_label[$load] [Load $load]\n";
   print RAW "\ttime=$timestamp\n";
   print RAW "\tsets $load $POWER_ON\n";
   $cmd = "sets $load $POWER_ON\n";
   print "Sending $cmd to $port\n" if $DEBUG;
   print $out "$cmd"; #flush(COM);
   while ($line = <$in>)
     {last if ($line =~ /load/);
      }

   $cnt = 0;

   #Get Current value for load
   for ($i=0;$i<3;$i++) {
   $cmd = "getc $load\n";
   print "Sending $cmd to $port\n" if $DEBUG;
   print $out "$cmd"; #flush(COM);
   while ($line = <$in>)
     {next if ($line =~ /getc/ || $line !~ /load/);
      if ($DEBUG) {print "\n[$line]"; flush(STDOUT);}
      if ($cnt++ == 1) {$timestamp = gmtimestamp(1);
                        print "time=$timestamp\n" if ($DEBUG);
                        print RAW "\ttime=$timestamp\n";
                        flush(RAW);
                        }
      if ($line =~ /load/) {$line =~ s/\> //;
                            print RAW "\t$line"; flush(RAW);
                            print "\t$line"; flush(STDOUT);
                            last;
			    }
      }
   sleep 1;
   
   }

   #Get State values and update data file
   $cmd = "gets 0\n";
   print "Sending $cmd to $port\n" if $DEBUG;
   print $out "$cmd"; #flush(COM);
   $cnt = 0;
   while ($line = <$in>)
     {if ($DEBUG) {print "$line"; flush(STDOUT);}
      if ($cnt++ == 1) {$timestamp = gmtimestamp(1);
                        print "time=$timestamp\n" if ($DEBUG);
                        print STATE_DAT "$timestamp ";
                        flush(STATE_RAW); flush(STATE_DAT)
                        }
      if ($line =~ /load/) {$line =~ s/\> //;
                            ($attr,$val) = split('=',$line,2);
                            chop($val); chop($val);
                            print STATE_DAT "$val "; flush(STATE_DAT);
                            }
      #last if ($line =~ /^>/);
      if ($line =~ /load16/) {print STATE_DAT "\n"; flush(STATE_DAT);
                              last;
                              }
      }


   #Get Current values and update data file
   $cmd = "getc 0\n";
   print "Sending $cmd to $port\n" if $DEBUG;
   print $out "$cmd"; #flush(COM);
   $cnt = 0;
   while ($line = <$in>)
     {if ($DEBUG) {print "$line"; flush(STDOUT);}
      if ($cnt++ == 1) {$timestamp = gmtimestamp(1);
                        print "time=$timestamp\n" if ($DEBUG);
                        print CURR_DAT "$timestamp ";
                        flush(CURR_RAW); flush(CURR_DAT)
                        }
      if ($line =~ /load/) {$line =~ s/\> //;
                            ($attr,$val) = split('=',$line,2);
                            chop($val); chop($val);
                            print CURR_DAT "$val "; flush(CURR_DAT);
                            }
      #last if ($line =~ /^>/);
      if ($line =~ /load16/) {print CURR_DAT "\n"; flush(CURR_DAT);
                              last;
                              }
      }



   print "Sleeping $sleep_amt...\n" if ($DEBUG);
   sleep $sleep_amt;

   } #end for-each load

close(CURR_DAT);
close(STATE_DAT);

   #Get State values
   $timestamp = gmtimestamp(1);
   print "\n\n--------------Switch States ----------------\n";
   print "\ntime=$timestamp\n";
   print RAW "\n\n--------------Switch States ----------------\n";
   print RAW "\ntime=$timestamp\n";
   $cmd = "gets 0\n";
   print "Sending $cmd to $port\n" if $DEBUG;
   print $out "$cmd"; flush($out);
   $cnt = 0;
   while ($line = <$in>)
     {next if ($line !~ /load/);
      if ($cnt++ == 1) {$timestamp = gmtimestamp(1);
                        print "time=$timestamp\n" if ($DEBUG);
                        print RAW "\ttime=$timestamp\n";
                        flush(RAW);
                        }
      if ($line =~ /load/) {$line =~ s/\> //;
                            print RAW "\t$line"; flush(RAW);
                            print "$line"; flush(STDOUT);
                            }
      #last if ($line =~ /^>/);
      last if ($line =~ /load16/);
      }
   print "------------------------------------------------\n";
   print RAW "------------------------------------------------\n";


print "\n\nStarting get_power_data_sail.pl...\n";
system("./start_sail");

exit;

#
#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";}
}




sub gmtimestamp_file {
        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;
        return "$year$mon$mday";
}

