<html>
<head>
<title>getDAQData</title>
</head>
<body>

<?php

	function getXMLValue($name, $fileip)
	{
		$posA = strpos($fileip, '<' . $name . '>');
		$posB = strpos($fileip, '</' . $name . '>');
		$len = strlen($name) + 2;
		return substr($fileip, $posA + $len, $posB - $posA - $len);
	}

	function getADCData($data, $start, $min, $max)
	{
		$counts = 0;
		for ($i = 0; $i < 1000; $i++)
		{
			$help = substr($data, 0, strpos($data, ","));
			if ($i >= $min-$start && $i <= $max-$start) $counts = $counts + $help;
			$data = substr($data, strpos($data, ",") + 1);
		}
		return $counts;
	}



	// get region of interest

	$adeiChannel = array(
		array(
			"fpd__katrin_rep__0__118",
			"fpd__katrin_rep__0__80"
		),
		array(
			"hv__katrin-hv_rep__0__87",
			"hv__katrin-hv_rep__0__95"
		)
	);

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

	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("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 . "&window=60&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);
		//echo $fileip . "<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] . "<br>";
		}
	}

	$roi = ($adeiValue[0][0] + 1000. * $adeiValue[0][1] + $adeiValue[1][0] + $adeiValue[1][1]) / 1000.; // in keV
	$roiMin = sprintf('%.2F', $roi - 3);
	$roiMax = sprintf('%.2F', $roi + 2);
	$roiMinAdc = sprintf('%.0F', 10. * $roiMin);
	$roiMaxAdc = sprintf('%.0F', 10. * $roiMax);



	// connect to data base

	$db_link = mysqli_connect('localhost', 'katrinstatus', 'pjX3nVWhnQNt7nP8', 'katrinstatus');



	// read data base

	$sql = "SELECT pulser, flt, fltCh FROM pulsers";
	$db_erg = mysqli_query($db_link, $sql) or die("Anfrage fehlgeschlagen: " . mysqli_error());
	$id = 0;

	while ($row = mysqli_fetch_array($db_erg, MYSQL_BOTH))
	{
		$pulserId[$id] = $row['pulser'];
		$flt[$id] = $row['flt'];
		$fltCh[$id] = $row['fltCh'];
		$id++;
	}

	mysqli_free_result($db_erg);



	// setup

	$daqMachine = array(438, 433, 374); // FPD, MUON, MOS



	// get pulser data

	$fileip = file_get_contents("http://katrin.kit.edu/OrcaWeb/query.php?tag=dataList&query=select%20name,counts,datastr,start%20from%20Histogram1Ds%20where%20machine_id=" . $daqMachine[0] . "%20ORDER%20BY%20name", false);

	for ($id = 0; $id < sizeof($pulserId); $id++)
	{
		$help = substr($fileip, strpos($fileip, 'FLT,Energy,Crate  0,Station ' . $flt[$id] . ',Channel  '. $fltCh[$id]));
		if (strpos($help, "encoding") > 0) { $pulserCounts[$id] = 0; continue; }
		$pulserCounts[$id] = getXMLValue("counts", $help);
		//if (strpos($pulserCounts[$id], "encoding") !== FALSE) $pulserCounts[$id] = 0;
	}



	// write to data base

	for ($id = 0; $id < sizeof($pulserId); $id++)
	{
		$sql = "UPDATE pulsers SET c0 = " . $pulserCounts[$id] . " WHERE pulser = '" . $pulserId[$id] . "'";
		$db_erg = mysqli_query($db_link, $sql) or die("Anfrage fehlgeschlagen: " . mysqli_error());
	}



	// get FPD data

	$events = 0;
	$pixels = 148+4;

	for ($fltId = 2; $fltId < 10; $fltId++)
	{
		for ($chId = 0; $chId < 19; $chId++)
		{
			if ($chId < 10) $help = substr($fileip, strpos($fileip, 'FLT,Energy,Crate  0,Station  ' . $fltId . ',Channel  '. $chId));
			else $help = substr($fileip, strpos($fileip, 'FLT,Energy,Crate  0,Station  ' . $fltId . ',Channel '. $chId));

			$start = getXMLValue("start", $help);
			if ($start < 1) $pixels = $pixels - 1;

			$events = $events + getADCData(getXMLValue("datastr", $help), $start, $roiMinAdc-5, $roiMaxAdc+5);
		}
	}

	$fileip = file_get_contents("http://katrin.kit.edu/OrcaWeb/query.php?tag=runInfo&query=select%20*%20from%20machines,runs%20where%20runs.machine_id=" . $daqMachine[0] . "%20and%20machines.machine_id=" . $daqMachine[0], false);
	$time = getXMLValue("elapsedTime", $fileip);
	$run = getXMLValue("run", $fileip);

	$rate = sprintf('%.3F', $events / $time);
	$rateError = sprintf('%.3F', sqrt($events) / $time);

	$sql = "UPDATE detector SET rate = " . $rate . " , rateError = " . $rateError . " , roiMin = " . $roiMin . " , roiMax = " . $roiMax . " , pixels = " . $pixels . " , run = " . $run;
	$db_erg = mysqli_query($db_link, $sql) or die("Anfrage fehlgeschlagen: " . mysqli_error());



	echo "It works!";



/*
	// read data base

	for ($id = 0; $id < sizeof($adei_table); $id++)
	{
		$sql = "SELECT * FROM " . $adei_table[$id];

		$db_erg = mysqli_query($db_link, $sql) or die("Anfrage fehlgeschlagen: " . mysqli_error());

		$id2 = 0;
		while ($row = mysqli_fetch_array($db_erg, MYSQL_ASSOC))
		{
			$pulser[$id2][$id] = $row[$adei_column[$id]];
			$id2++;
		}

		mysqli_free_result($db_erg);
	}
*/

/*
	$username = 'katrin';
	$password = 'neutrino';
	$context = stream_context_create(array(
		'http' => array(
			'header'  => "Authorization: Basic " . base64_encode("$username:$password")
		)
	));


	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=60&format=csv", false, $context);
		//echo $fileip . "<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] . "<br>";
		}
	}


*/

/*
	// ÄNDERN

	$sql = "UPDATE sds SET actual = 0, ideal = 0 WHERE system = 'lfcs' AND id = 2";

	$db_erg = mysqli_query($db_link, $sql) or die("Anfrage fehlgeschlagen: " . mysqli_error());
*/

/*
	// LESEN

	$sql = "SELECT * FROM dcct_current WHERE id = 'lfcs 2'";

	$db_erg = mysqli_query($db_link, $sql) or die("Anfrage fehlgeschlagen: " . mysqli_error());

	while ($zeile = mysqli_fetch_array($db_erg, MYSQL_ASSOC))
	{
		echo $zeile['ideal'];
	}

	mysqli_free_result($db_erg);
*/

/*
	// status info DAQ machines
	for ($id = 0; $id < sizeof($daqMachine); $id++)
	{
		$fileip = file_get_contents("http://katrin.kit.edu/OrcaWeb/query.php?tag=runInfo&query=select%20*%20from%20machines,runs%20where%20runs.machine_id=" . $daqMachine[$id] . "%20and%20machines.machine_id=" . $daqMachine[$id], false);

		$daqRun[$id] = getXMLValue("run", $fileip);
		$daqSubrun[$id] = getXMLValue("subrun", $fileip);
		$daqElapsed[$id] = getXMLValue("elapsedTime", $fileip);
		$daqTogo[$id] = getXMLValue("timeToGo", $fileip);
		$daqState[$id] = getXMLValue("state", $fileip);
		$daqRepeat[$id] = getXMLValue("repeatRun", $fileip);
		$daqOffline[$id] = getXMLValue("offline", $fileip);
		$daqTimed[$id] = getXMLValue("timedRun", $fileip);
	}
*/

/*
	// get pulser data

	$fileip = file_get_contents("http://katrin.kit.edu/OrcaWeb/query.php?tag=dataList&query=select%20dataset_id,name,counts%20from%20Histogram1Ds%20where%20machine_id=" . $daqMachine[0] . "%20ORDER%20BY%20name", false);

	$counts[0] = getXMLValue("counts", substr($fileip, strpos($fileip, 'FLT,Energy,Crate  0,Station ' . $pulser[0][1] . ',Channel  '. $pulser[0][2])));
	$counts[1] = getXMLValue("counts", substr($fileip, strpos($fileip, 'FLT,Energy,Crate  0,Station ' . $pulser[1][1] . ',Channel  '. $pulser[1][2])));
	$counts[2] = getXMLValue("counts", substr($fileip, strpos($fileip, 'FLT,Energy,Crate  0,Station ' . $pulser[2][1] . ',Channel  '. $pulser[2][2])));
	$counts[3] = getXMLValue("counts", substr($fileip, strpos($fileip, 'FLT,Energy,Crate  0,Station ' . $pulser[3][1] . ',Channel  '. $pulser[3][2])));

	echo $pulser[0][0] . " " . $counts[0];
	echo "<br>";
	echo $pulser[1][0] . " " . $counts[1];
	echo "<br>";
	echo $pulser[2][0] . " " . $counts[2];
	echo "<br>";
	echo $pulser[3][0] . " " . $counts[3];
*/
?>

</body>
</html>
