<?php

$body = file_get_contents('php://input');
$t = time();
$date = date('d.m.Y');
$ip = $_SERVER["REMOTE_ADDR"];
$agent = $_SERVER["HTTP_USER_AGENT"];

#file_put_contents('API-ethernet.raw', $body . ' ' . $t . ' ' . $date . $ms . PHP_EOL, FILE_APPEND);
file_put_contents('API-ethernet.raw', $body . ' ' . $t . ' ' . $date . ' ' . $ip . ' ' . $agent . ' ' . PHP_EOL, FILE_APPEND);


$vars = preg_split('/\s+/', $body);

if ((string) $vars[3] !== "V") { exit(0); }

$node_id = (string) $vars[2];

switch ($node_id) {
	case "N18":
		file_put_contents('N18/data.raw', $body . ' ' . $t . ' ' . $date . PHP_EOL, FILE_APPEND);
		$location = "Osenets";
		$altitude = 236;
		break;
	case "N21":
		file_put_contents('N21/data.raw', $body . ' ' . $t . ' ' . $date . PHP_EOL, FILE_APPEND);
		$location = "Yarlovo";
		$altitude = 1136.7;
		break;
	case "N30":
		file_put_contents('N30/data.raw', $body . ' ' . $t . ' ' . $date . PHP_EOL, FILE_APPEND);
		$location = "Pleven_Hut";
		$altitude = 1399;
		break;
	case "N40":
		file_put_contents('N40/data.raw', $body . ' ' . $t . ' ' . $date . PHP_EOL, FILE_APPEND);
		$location = "Sarnegor";
		$altitude = 408.3;
		break;
	default:
		file_put_contents('API-ethernet-unexpected-data.raw', $body . ' ' . $t . ' ' . $ip . ' ' . $date . PHP_EOL, FILE_APPEND);
		$location = "unknown";
		$altitude = 0;
	}

$t_raw = (float) $vars[12];
$p_raw = (float) $vars[11];
$rh = (int) $vars[13];
$pm25 = (int) $vars[9];
$pm10 = (int) $vars[10];
$gamma_raw = (int) $vars[14];
$signal = (int) $vars[4];

# t_dew calculations
$a=6.1121;
$d=234.5;
if ($t_raw < 0) {
	$b=17.966;
	$c=247.15;
}
else {
	$b=17.368;
	$c=238.88;
}
$gm = log( $rh*0.01*( pow(exp(1),(($b-(1*$t_raw)/$d)*((1*$t_raw)/($c+(1*$t_raw))))) ) );
$t_dew = round($c*(1*$gm)/($b-(1*$gm)), 1);

# p_sea calculations
$p_sea = round($p_raw*pow((1-(0.0065*$altitude)/($t_raw+0.0065*$altitude+273.15)),-5.257), 1);

# gamma_cpm calculations
$gamma_cpm = round($gamma_raw/5, 0);

# Submit data to local instance of InfluxDB through HTTP API call
$pm25 .= "i";
$pm10 .= "i";
$gamma_raw .= "i";
$gamma_cpm .= "i";
$signal .= "i";
$ts = $t;
$ts .= "i";

$curl = curl_init();
curl_setopt_array($curl, array(
	CURLOPT_URL => 'http://localhost:8086/write?db=meter&precision=s&u=editor&p=HFZhChwzKv2yahsF',
	CURLOPT_SSL_VERIFYPEER => 0,
	CURLOPT_SSL_VERIFYHOST => 0,
	CURLOPT_RETURNTRANSFER => 0,
	CURLOPT_POST => 1,
	CURLOPT_POSTFIELDS => "box,node_id=$node_id,altitude=$altitude,location=$location,phy=ethernet t_raw=$t_raw,t_dew=$t_dew,p_raw=$p_raw,p_sea=$p_sea,rh=$rh,pm25=$pm25,pm10=$pm10,gamma_raw=$gamma_raw,gamma_cpm=$gamma_cpm,signal=$signal,ip=\"$ip\",ts=$ts $t",
	CURLOPT_HTTPHEADER => array('Content-Type: text/plain')
));
curl_exec($curl);
curl_close($curl);
?>

