<?php
    // include channel list
    $adeiChannel = array(
        // Voltage monitoring K35 etc. (index 30)
        array(
            "hv__katrin-hv_rep__7__2", //K35 divided voltage reading
            "hv__katrin-hv_rep__7__5", //K65 divided voltage reading
            "hv__katrin-hv_rep__7__3", //K35 divided voltage timestamp
            "hv__katrin-hv_rep__7__6", //K65 divided voltage timestamp

        )
    );

    // include previous values
    //include "ADEI_HV_readings.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');

    sleep(2);

    $counter = 0;
    $calltime = time();
    $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 = $calltime;
    $n = 0;
    //echo "started ".date("r", $starttime).PHP_EOL;
//    do {
        $n++;
        $currenttime = time();
        $delaytime = 10 - ($currenttime % 10);
        sleep($delaytime);

        //  echo "start polling ".time().PHP_EOL;
        //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);

            // 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=400&format=csv", false, $context);
            sleep(1);

            //echo $fileip.PHP_EOL;
            $adeiArray = explode("\n", $fileip);

            //convert ADEI response into array with all values
            $oldTS1 = 0;
            $oldTS2 = 0;
            $readings1 = array();
            $readings2 = array();
            foreach ($adeiArray as $key => $element) {
                $adeiLine = explode(",", $element);
                //echo $key." ".sizeof($adeiLine).PHP_EOL;
                if (sizeof($adeiLine) == 5) {
                    $voltage = floatval($adeiLine[1]);
                    $voltageTS = floatval($adeiLine[3]);
                    if (($voltageTS > 0) && ($voltageTS > $oldTS1)) {
                        $readings1[] = array(
                            $voltageTS,
                            $voltage
                        );
                        $oldTS1 = $voltageTS;
                    }
                    $voltage = floatval($adeiLine[2]);
                    $voltageTS = floatval($adeiLine[4]);
                    if (($voltageTS > 0) && ($voltageTS > $oldTS2)) {
                        $readings2[] = array(
                            $voltageTS,
                            $voltage
                        );
                        $oldTS2 = $voltageTS;
                    }
                }
            }
            unset($element);

            // filter and extract FlukeA values and calculate mean and deviations for a set of entries
            $index = array(-5, -10, -30, -150, -300);
            foreach ($index as $slice) {
                if (sizeof($readings1) > abs($slice)) {
                    $arrayslice = array_slice($readings1, $slice);
                    $entries = count($arrayslice);
                    if ($entries > 2) {
                        $voltages = array_column($arrayslice, 1);
                        $mean = array_sum($voltages) / $entries;
                        $carry = 0.0;
                        foreach ($voltages as $val) {
                            $d = ((double)$val) - $mean;
                            $carry += $d * $d;
                        }
                    }
                    $mean1 = $mean;
                    $stddev1 = sqrt($carry / $entries);
                    $stddev1_rel = $stddev1 / abs($mean1);
                    $endTS = $arrayslice[sizeof($arrayslice) - 1][0];
                    $span = round($endTS - $arrayslice[0][0]);

                    $time_conversion_factor = 2082844800;

                    //echo "Number of aquired elements: ".sizeof($arrayslice).PHP_EOL;
                    //echo "Mean Value:                 ".sprintf('%.6F', $mean1).PHP_EOL;
                    //echo "Standard Deviation:         ".sprintf('%.2E', $stddev1).PHP_EOL;
                    //echo "Rel. Standard Deviation:    ".sprintf('%.2E', $stddev1_rel).PHP_EOL;
                    //echo "TS at end:                  ".date("r", $endTS-$time_conversion_factor).PHP_EOL;
                    //echo "Timespan:                   ".$span.PHP_EOL;
                    //echo PHP_EOL;
                    $results1[] = array(
                        "number" => sizeof($arrayslice) ,
                        "timespan" => $span,
                        "timestamp" => $endTS - $time_conversion_factor,
                        "humantime" => date("r", $endTS - $time_conversion_factor) ,
                        "mean" => $mean1,
                        "stddev" => $stddev1,
                        "ppmdev" => $stddev1_rel
                    );

                }
            }

            // filter and extract FlukeE values and calculate mean and deviations for a set of entries
            $index = array(-5, -10, -30, -150, -300);
            foreach ($index as $slice) {
                if (sizeof($readings2) > abs($slice)) {
                    $arrayslice = array_slice($readings2, $slice);
                    $entries = count($arrayslice);
                    if ($entries > 2) {
                        $voltages = array_column($arrayslice, 1);
                        $mean = array_sum($voltages) / $entries;
                        $carry = 0.0;
                        foreach ($voltages as $val) {
                            $d = ((double)$val) - $mean;
                            $carry += $d * $d;
                        }
                    }
                    $mean2 = $mean;
                    $stddev2 = sqrt($carry / $entries);
                    $stddev2_rel = $stddev2 / abs($mean2);
                    $endTS = $arrayslice[sizeof($arrayslice) - 1][0];
                    $span = round($endTS - $arrayslice[0][0]);

                    $time_conversion_factor = 2082844800;

                    //echo "Number of aquired elements: ".sizeof($arrayslice).PHP_EOL;
                    //echo "Mean Value:                 ".sprintf('%.6F', $mean2).PHP_EOL;
                    //echo "Standard Deviation:         ".sprintf('%.2E', $stddev2).PHP_EOL;
                    //echo "Rel. Standard Deviation:    ".sprintf('%.2E', $stddev2_rel).PHP_EOL;
                    //echo "TS at end:                  ".date("r", $endTS-$time_conversion_factor).PHP_EOL;
                    //echo "Timespan:                   ".$span.PHP_EOL;
                    //echo PHP_EOL;
                    $results2[] = array(
                        "number" => sizeof($arrayslice) ,
                        "timespan" => $span,
                        "timestamp" => $endTS - $time_conversion_factor,
                        "humantime" => date("r", $endTS - $time_conversion_factor) ,
                        "mean" => $mean2,
                        "stddev" => $stddev2,
                        "ppmdev" => $stddev2_rel
                    );

                }
            }

            //var_dump( $results2 );
            //var_dump( $results1 );
            // error handling
            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;

	    //echo "Writing data into formatted string.".PHP_EOL;
 	 	$strFileContent = "<"."?php".PHP_EOL.PHP_EOL."$"."REU0201 = ".var_export($results1, true).";".PHP_EOL.PHP_EOL;
  		$strFileContent .= "$"."REU0301 = ".var_export($results2, true).";".PHP_EOL.PHP_EOL;
  		$strFileContent .= "$"."extraction_time_HV = '". date(DATE_RFC850) ."';".PHP_EOL.PHP_EOL;
  		$strFileContent .= "?".">".PHP_EOL;

        // write ADEI data to file
        //echo "Writing data to file.".PHP_EOL;
        $file_w = fopen('ADEI_HV_readings.php', 'w+');
        sleep(1);
        fwrite($file_w, $strFileContent);
        fclose($file_w);

        //echo $strFileContent.PHP_EOL;
        //echo $n." ".time().PHP_EOL;

//    }
//    while (time() < $starttime + 50);

    //echo "stopped".date("r", time()).PHP_EOL;
    //echo "Data extraction done.".PHP_EOL;

?>
