<?php
// This is a PHP only file i.e. does not generate any HTML output
// This file is run with one argument only i.e. name of the DIDDB.args file
// All information to run this script is then obtained from that file

// Copy file read by entget to standard location in Inputs/$dbase/$source_name/$attribute
// Read this file in to database
require '../Common/openDB.php';
require '../Common/preferences.php';
if($oper_sys == "windows"){
  if(file_exists("C:\\Program Files (x86)\\Ampps\\www\\EnTrak\\EnTrak\\2_Projects")){
    $wget = "wget64.exe";
    $bax2csv = "bax2csv.exe";
  }elseif(file_exists("C:\\Program Files\\Ampps\\www\\EnTrak\\EnTrak\\2_Projects")){
    $wget = "wget.exe";
    $bax2csv = "bax2csv32.exe";
  }else{
    echo "<h1> Error: MDFCron.php WAMP server not found";
    exit;
  }
}elseif($oper_sys == "linux"){
  $wget = "wget";
  $bax2csv = "./bax2csv";
}
$LRS_time_shift = 946684800; // time by which hLRS titme isi shifted from UNIX epoch
$echo_to_logfile = true;
$echo_to_console = true;
$iter_lim = 2;

// open arguments file to read information
$argsf = fopen($argv[1],"r");
if ($argsf) {
  while (($line = fgets($argsf)) !== false) {
    $argm = strtok($line,",");
	  $argm = trim($argm);
	  $remainder = substr($line, strpos($line, ",") + 1);
	  //echo $argm . " is " . $remainder;
	  if($argm == "fetcher_id"){
		  $fetcher_id = trim($remainder);
	  }else if($argm == "dbase"){
		  $dbase = trim($remainder);
	  }else if($argm == "fetcher_name"){
		  $fetcher_name = trim($remainder);
	  }else if($argm == "local_app"){
		  $localapp = trim($remainder);
    }else if($argm == "description"){
      $fetcher_description = trim($remainder);
    }else if($argm == "EG_user"){
      $username = trim($remainder);
    }else if($argm == "EG_password"){
		  $password = trim($remainder);
	  }else if($argm == "EG_IP"){
		  $IP = trim($remainder);
    }
  }
  fclose($argsf);
}else{
  fwrite($logfile,"Error: args file could not be downloaded from LRS \n");
  exit;
}

// Start write of log file
$logfilename = "../../Inputs/{$dbase}/MDF/{$fetcher_name}.log";
if(file_exists($logfilename)){
	$logfile = fopen($logfilename,"a");
}else{
  $logfile = fopen($logfilename,"w");
	fwrite($logfile,"ENTRAK Version {$Version} data input log file \n");
	fwrite($logfile,"website: {$website}\n");
	fwrite($logfile,"userid: {$username}\n");
	fwrite($logfile,"MDF name: {$fetcher_name}\n");
	fwrite($logfile,"MDF type: {$localapp}\n");
	fwrite($logfile,"MDF description: {$fetcher_description}\n");
}

echo "starting logfile write\n";

// Connect to database
mysql_query("SET foreign_key_checks = 0",$con);
mysql_select_db($dbase, $con);

// Get time to add to file name
date_default_timezone_set($TimeZone);

$current_time = date('Y-m-d H:i:s');
$timeStr = str_replace(" ","_",$current_time);
$timeStr = str_replace(":",".",$timeStr);
// Get data fetch frequency
$res = mysql_query("SELECT frequency_id FROM Fetcher WHERE fetcher_id = {$fetcher_id}",$con);
while ($row = mysql_fetch_array($res))$frequency_id = $row[0];
$res = mysql_query("SELECT period,times_per_period FROM Frequency WHERE frequency_id = {$frequency_id}",$con);
while ($row = mysql_fetch_array($res)){
  $period = $row[0];
  $times_per_period = $row[1];
  $current_mnth = date('F');
  $current_year = date('Y');
  $period_from_db = GetTimePeriodFromFrequency($period,$times_per_period,$current_mnth,$current_year);
	//>>>>>>>>> CHANGE NEXT LINE TO CALL NEWER FUNCTION in openDB
	//$period_from_db = GetTimePeriod($row[0],$row[1]);
}
echo "time period to fetch data for = " . $period_from_db;
echo "local app is {$localapp}\n";

// MDF for buildax
// MDF will collect data from buildax as follows:
// MDF assumes that each buildax sensor is a separate entity with a number of dynamic attributes
// one for each of temperature, RH, lux etc.
// The sensor must have a static attribute named as shown below
// The attributes collected must be named as shown below as well i.e.
// there must be dynamic entities with attribute as $BAX_? below (the value could be anything)
$BAX_code = "sensor code";
$BAX_B = "Battery Level";
$BAX_T = "Temperature";
$BAX_R = "Relative Humidity";
$BAX_P = "PIR";
$BAX_L = "Illuminance";

if($localapp == "bax2csv"){

  // first get cookies
  echo "Getting cookies \n";
  $cookies_file = "cookies_" . $fetcher_id . $dbase . ".txt";
  if(file_exists($cookies_file))unlink($cookies_file);
  $command = "{$wget} --keep-session-cookies --save-cookies {$cookies_file} --post-data \"user={$username}&pass={$password}\" http://{$IP}/WWW/login.htm 2>&1 --delete-after";
  fwrite($logfile,"####### Fetching Cookies #######\n");
  run_cmd($command,$logfile,$echo_to_console,$echo_to_logfile);

  // get last timestamp on LRS -- get bin file
  $tmpFile_bin = "tempfile_" . $fetcher_id . $dbase . ".bin";
  $tmpFile_txt = "tempfile_" . $fetcher_id . $dbase . ".txt";
  if(file_exists($tmpFile_bin))unlink($tmpFile_bin);
  if(file_exists($tmpFile_txt))unlink($tmpFile_txt);
  $command = "{$wget} --load-cookies {$cookies_file} -O {$tmpFile_bin} --tries=1 --read-timeout=5 --no-http-keep-alive --content-disposition http://{$IP}/fetch?type=LS\"\\&\"start=2\"\\&\"end= 2>&1";
  fwrite($logfile,"####### Getting last entry on LRS #######\n");
  run_cmd($command,$logfile,$echo_to_console,$echo_to_logfile);

  // get last timestamp on LRS -- convert to ascii
  $command = "{$bax2csv} {$tmpFile_bin} {$tmpFile_txt} 2>&1";
  run_cmd($command,$logfile,$echo_to_console,$echo_to_logfile);

  // get timestamps to fetch data for
  $tmpfile = fopen($tmpFile_txt,"r");
  if($tmpfile){
    $line = fgets($tmpfile);
    $tokens = explode(",",$line);
    $last_LRS_date = $tokens[0];
    $last_LRS_time = $tokens[1];
    $stop_time = strtotime("{$last_LRS_date} {$last_LRS_time}"); // time from epoch
    $stop_time = $stop_time - $LRS_time_shift;
    $start_time = $stop_time - $period_from_db;
    echo "To fetch data from $start_time to $stop_time \n";
  }else{
    fwrite($logfile,"Error reading timestamp from tmp file 1 line big at {$current_time} \n");
  }
  fclose($tmpfile);
  unlink($tmpFile_bin);
  unlink($tmpFile_txt);

  // fetch the data -- first fetch cookies again
  if(file_exists($cookies_file))unlink($cookies_file);
  $command = "{$wget} --keep-session-cookies --save-cookies {$cookies_file} --post-data \"user={$username}&pass={$password}\" http://{$IP}/WWW/login.htm 2>&1 --delete-after";
  fwrite($logfile,"####### Fetching Cookies Again #######\n");
  run_cmd($command,$logfile,$echo_to_console,$echo_to_logfile);

  // fetch the data -- from start to stop time
  $command = "{$wget} --load-cookies {$cookies_file} -O {$tmpFile_bin} --tries=1 --read-timeout=5 --no-http-keep-alive --content-disposition http://{$IP}/fetch?type=BT\"\\&\"start={$start_time}\"\\&\"end={$stop_time} 2>&1";
  fwrite($logfile,"####### Fetching Data from {$start_time} to {$stop_time} #######\n");
  run_cmd($command,$logfile,$echo_to_console,$echo_to_logfile);

  // convert to ascii
  $command = "{$bax2csv} {$tmpFile_bin} {$tmpFile_txt} 2>&1";
  run_cmd($command,$logfile,$echo_to_console,$echo_to_logfile);

  // read whether to create entities based on read data or not
  $res = mysql_query("SELECT value FROM HighLevInfo WHERE name='MDF'",$con);
  while($row = mysql_fetch_array($res))$create_entities = $row[0]; // possible values are yes and no

  // make arrays for "Existing Entities Table" EET sensor code, variable to be read and DID to put data into
  $EET_code = array();
  $EET_var = array();
  $EET_DID = array();

  $res = mysql_query("SELECT value,source_id FROM Static WHERE attribute = 'sensor code'",$con);
  while($row = mysql_fetch_array($res)){
    $sensor_code = $row[0];
    $SRCID = $row[1];

    $Dres = mysql_query("SELECT attribute,value,dynamic_id FROM Dynamic WHERE source_id = {$SRCID}",$con);
    while($Drow = mysql_fetch_array($Dres)){
      $DIDs = "";
      $fetchthis = false;
      $Dattribute = $Drow[0];
      $Dvalue = $Drow[1];
      $DID = $Drow[2];
      if( $Dattribute == $BAX_B || $Dattribute == $BAX_T ||
          $Dattribute == $BAX_R || $Dattribute == $BAX_P || $Dattribute == $BAX_L){
        $fetchthis = true;
      }
      if($fetchthis){
        array_push($EET_code,$sensor_code);
        array_push($EET_var,$Dattribute);
        array_push($EET_DID,$DID);
      }
    }
  }

  // read data into DB
  // bax2csv writes in the following fashion e.g. for the line
  // 2015/03/03,14:25:03,42E3ED59,-67,1,200,20,3063,45.05,162,0,0,24032,1
  // token number   value what is it?
  //  0  2015/03/03 is the date (YYYY/MM/DD)
  //  1  14:25:03 is the time (hh:mm:ss)
  //  2  42E3ED59 is the 8 character ID of the BuildAX ENV sensor
  //  3  -67   is the radio signal strength
  //  4  1     is the packet type: 1=normal, 2=PIR event, 3=Switch event
  //  5  200   packet counter
  //  6  20    can be ignored
  //  7  3063  is the battery level mV
  //  8  45.05 is the humidity
  //  9  162   it temperature in tenths of a degreee i.e. 16.2C
  // 10  0     lux level
  // 11  0     PIR event counter
  // 12  24032 PIR energy level (needs to be post-processed)
  // 13  1     Switch event conter (increments as events are recorded)

  $tmpfile = fopen($tmpFile_txt,"r");
  while( ($line = fgets($tmpfile)) !== false){
    $tokens = explode(",",$line);
    $timestamp = $tokens[0] . " " . $tokens[1];
    $timestamp = str_replace("/","-",$timestamp);
    $sensor_code = $tokens[2];
    $batt_lev = $tokens[7];
    $RH_lev = $tokens[8];
    $temp_lev = $tokens[9];
    $lux_lev = $tokens[10];
    $PIR_lev = $tokens[11];

    $BAX_array = array($BAX_B,$BAX_T,$BAX_R,$BAX_P,$BAX_L);
    if($create_entities == "yes"){
      // Get frequency table elements
      $res = mysql_query("SELECT frequency_id FROM Fetcher WHERE fetcher_id = {$fetcher_id}",$con);
      while($row = mysql_fetch_array($res))$master_freq_id = $row[0];
      $res = mysql_query("SELECT period,times_per_period FROM Frequency WHERE frequency_id = {$master_freq_id}",$con);
      while($row = mysql_fetch_array($res)){
        $freq_period = $row[0];
        $freq_TPP = $row[1];
      }

      if(!in_array($sensor_code,$EET_code)){
        // make db entries
        // only one source required for one BAX sensor
        $res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Source'",$con);
    		while($row = mysql_fetch_array($res))$SID = $row[0];
        mysql_query("INSERT INTO Source(name) VALUES('{$sensor_code}')",$con);
        mysql_query("INSERT INTO Static(attribute,value,source_id) VALUES('{$BAX_code}','{$sensor_code}',{$SID})",$con);

        foreach($BAX_array as $BAXvalue){
          // make dummy fetchers to link to all newly created DIDs, this fetcher is a copy of the MDF fetcher
          // a dummy frequency is required for each DID
          $res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Frequency'",$con);
          while($row = mysql_fetch_array($res))$Freq_id = $row[0];
          mysql_query("INSERT INTO Frequency(name,period,times_per_period) VALUES('dynamic_id ','{$freq_period}','{$freq_TPP}')",$con);

          // a fetcher is required for each DID
          $res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Fetcher'",$con);
          while($row = mysql_fetch_array($res))$FID = $row[0];
          mysql_query("INSERT INTO Fetcher(frequency_id) VALUES($Freq_id)",$con);
          mysql_query("UPDATE Fetcher SET name='dynamic_id ',
                                          description='Dummy fetcher',
                                          input_method='Online',
                                          EG_IP='{$IP}',
                                          EG_user='{$username}',
                                          EG_password='{$password}',
                                          EG_appdestinationLocal='{$localapp}' WHERE fetcher_id = {$FID}",$con);
          $res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Dynamic'",$con);
          while($row = mysql_fetch_array($res))$DID = $row[0];
          mysql_query("INSERT INTO Dynamic(attribute,source_id,fetcher_id,status,fetch_status,MDF_status) VALUES('{$BAXvalue}',{$SID},{$FID},'stopped','NA','MDF')",$con);

          // Add elements to the EET table
          array_push($EET_DID,$DID);
          array_push($EET_code,$sensor_code); // Once for every variable to be read in Batt lev,temp,RH,PIR,Lux
          array_push($EET_var,$BAXvalue); // again once for every variable to be read in
        }
      } // end if sensorcode is already present in EET_code i.e. will not create entities if this code is found
    } // end if $create_entities

    foreach($EET_code as $code){
      if($sensor_code == $code){
        unset($index);
        $index = array();
        $index = array_keys($EET_code,$code);
        foreach($index as $i){
          $var = $EET_var[$i];
          $DID = $EET_DID[$i];
          if($var == $BAX_B){
            mysql_query("INSERT INTO DynamicValue(dynamic_id,timestamp,value) VALUES({$DID},'{$timestamp}',$batt_lev)",$con);
          }elseif($var == $BAX_T){
            mysql_query("INSERT INTO DynamicValue(dynamic_id,timestamp,value) VALUES({$DID},'{$timestamp}',$temp_lev)",$con);
          }elseif($var == $BAX_R){
            mysql_query("INSERT INTO DynamicValue(dynamic_id,timestamp,value) VALUES({$DID},'{$timestamp}',$RH_lev)",$con);
          }elseif($var == $BAX_P){
            mysql_query("INSERT INTO DynamicValue(dynamic_id,timestamp,value) VALUES({$DID},'{$timestamp}',$PIR_lev)",$con);
          }elseif($var == $BAX_L){
            mysql_query("INSERT INTO DynamicValue(dynamic_id,timestamp,value) VALUES({$DID},'{$timestamp}',$lux_lev)",$con);
          }
        }
      } // if sensor code == code
    } // for each EET_code as code
  } // while every line is being read
} // if local app = bax2csv
fclose($tmpfile);
unlink($tmpFile_bin);
unlink($tmpFile_txt);
fclose($logfile);
exit;

function run_cmd($command,$logfile,$output_to_cmdline,$output_to_logfile){
  fwrite($logfile,"####### Issuing command ####### {$command}\n");
  exec($command,$output);

  // by forcing output of exec to go through the loop php is forced to wait til the exec command has returned
  foreach($output as $key => $value){
    if($output_to_cmdline)echo $key . " " . $value . "\n";
    if($output_to_logfile)fwrite($logfile,$value . "\n");
  }
  return;
}
?>
