<?php


function show_status($done, $total, $size=30) {

    static $start_time;

    // if we go over our bound, just ignore it
    if($done > $total) return;

    if(empty($start_time)) $start_time=time();
    $now = time();

    $perc=(double)($done/$total);

    $bar=floor($perc*$size);

    $status_bar="\r[";
    $status_bar.=str_repeat("=", $bar);
    if($bar<$size){
        $status_bar.=">";
        $status_bar.=str_repeat(" ", $size-$bar);
    } else {
        $status_bar.="=";
    }

    $disp=number_format($perc*100, 0);

    $status_bar.="] $disp%  $done/$total";

    $rate = ($now-$start_time)/$done;
    $left = $total - $done;
    $eta = round($rate * $left, 2);

    $elapsed = $now - $start_time;

    $status_bar.= " remaining: ".number_format($eta)." sec.  elapsed: ".number_format($elapsed)." sec.";

    echo "$status_bar  ";

    flush();

    // when done, send a newline
    if($done == $total) {
        echo "\n";
    }

}

// include channel list
include "SDS_status_channels.php";

$username = getenv('PHP_ADEI_USERNAME');
$password = getenv('PHP_ADEI_PASSWORD');
$context = stream_context_create(array(
		'http' => array(
			'header'  => "Authorization: Basic " . base64_encode("$username:$password"), "Connection: close\r\n"
		)
	));


// set time zone to local German time
date_default_timezone_set('Europe/Berlin');

$counter = 0;
$calltime = time();
//do {
        $errorcount = 0;
        $errormessage = '<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>';

	$starttime = time();
	
        //echo "Polling ADEI data.".PHP_EOL;

	for ($id = 0; $id < sizeof($adeiChannel); $id++)
	{
		$adeiChannels = "";
		for ($id2 = 0; $id2 < sizeof($adeiChannel[$id]); $id2++)
		{
			$adeiChannels = $adeiChannels . $adeiChannel[$id][$id2] . ",";
		}
		$adeiChannels = substr($adeiChannels, 0, strlen($adeiChannels) - 1);

      		//$fileip = file_get_contents("http://katrin.kit.edu/adei/services/getdata.php?db_server=virtual&db_name=srctree&db_group=-3&control_group=-3&virtual=srctree&srctree=" . $adeiChannels . "&window=50&format=csv", false, $context);
      		//$fileip = file_get_contents("http://ipekatrinbackupserv1.ipe.kit.edu/adei/services/getdata.php?db_server=virtual&db_name=srctree&db_group=-3&control_group=-3&virtual=srctree&srctree=" . $adeiChannels . "&window=60&format=csv", false, $context);
		
		//                $fileip = file_get_contents("http://katrin.kit.edu/adei-katrin/services/getdata.php?db_server=virtual&db_name=srctree&db_group=-3&control_group=-3&virtual=srctree&srctree=" . $adeiChannels . "&window=50&format=csv", false, $context);

		// new adei-katrin.kaas.kit.edu added
                //$fileip = file_get_contents("http://adei-katrin.kaas.kit.edu/adei/services/getdata.php?db_server=virtual&db_name=srctree&db_group=-3&control_group=-3&virtual=srctree&srctree=" . $adeiChannels . "&window=50&format=csv", false, $context);

		// new adei-katrin.kaas.kit.edu added and optimized readout parameters
		$fileip = file_get_contents("https://adei-katrin.kaas.kit.edu/adei/services/getdata.php?db_server=virtual&db_name=srctree&db_group=-3&control_group=-3&virtual=srctree&srctree=" . $adeiChannels . "&rt=full&window=3600,-1&format=csv", false, $context);
		
                //show_status($id+1,sizeof($adeiChannel));

                if (substr($fileip,0,5) == "ERROR")
                {$errorcount++; $errormessage = $errormessage . "Error loading ADEI channel " . $id . "<br>";}

		for ($id2 = sizeof($adeiChannel[$id]) - 1 ; $id2 > -1; $id2--)
		{
			$pos = strrpos($fileip, ",");
			$adeiValue[$id][$id2] = floatval(substr($fileip, $pos + 2));
			$fileip = substr($fileip, 0, $pos);
			//echo $id . " " . $id2 . " " . $adeiValue[$id][$id2] . PHP_EOL;
		}
	}

        if ($errorcount >0) echo $errormessage;

        // increse loop counter
	$counter ++;
	$stoptime = time();
//	$wait_till = $starttime + 11;

	if ($stoptime-$starttime > 10) {$errormessage .= "ERROR: delayed readout ".($stoptime-$starttime)." s "; $errorcount++;}
	
        //echo "Writing ADEI data to file.".PHP_EOL;

        $strFileContent = "<"."?php".PHP_EOL."$"."adeiValue = ".var_export($adeiValue, true).";".PHP_EOL.PHP_EOL;
        $strFileContent .= "$"."extraction_time = '". date(DATE_RFC850) ."';".PHP_EOL.PHP_EOL;
	$strFileContent .= "$"."extraction_timestamp = ". time() .";".PHP_EOL.PHP_EOL;
        $strFileContent .= "$"."errorcount = ". $errorcount .";".PHP_EOL.PHP_EOL;
        $strFileContent .= "$"."errormessage = '". $errormessage ."';".PHP_EOL.PHP_EOL;
        $strFileContent .= "$"."valuesincluded = 1;".PHP_EOL.PHP_EOL;
        $strFileContent .= "?".">".PHP_EOL;

	// write ADEI data to file
        $file_w = fopen('ADEIvalues.php', 'w+');
        //sleep(5);
        fwrite($file_w, $strFileContent);
        fclose($file_w);
	
	// write log file
	$log_message = "";
	$log_message = date(DATE_RFC850).": ADEI data polled: loop ".$counter;
	$log_message .= ", poll time ".($stoptime-$starttime)." s";
	if ($stoptime-$starttime > 15) $log_message .= ", delayed readout";
        $log_message .= PHP_EOL;
        $file_log = fopen('logs/poll_adei_data.log', 'a');
        fwrite($file_log, $log_message);
        fclose($file_log);
        
	//echo "Loop ".$counter." done.".PHP_EOL;

//        if ($wait_till <= $stoptime) sleep(3);
//        else time_sleep_until($wait_till);

//} while (($counter < 10) && (time() < $calltime + 51));

//echo "All loops done.".PHP_EOL;

?>
