getData.php 2.85 KB
<?php

if (php_sapi_name() !='cli') die("This script can be only executed from command line");

require_once '../php/config.php';

$shortopts  = "";

$longopts  = array(
	"id:",
	"parameters:",
	"start:",
	"stop:",
);
$options = getopt($shortopts, $longopts);

if (!isset($options['id']) || !isset($options['parameters']) || !isset($options['start']) || !isset($options['stop'])) {
	exit(1);
}

$query = array(
	"startTime" => str_replace("000000Z", "Z", $options['start']),
	"stopTime"  => str_replace("000000Z", "Z", $options['stop']),
	"outputFormat" => "ASCII",
	"timeFormat" => "ISO8601",
);

$getDataset = FALSE;
$paramers = trim($options['parameters']);
$parameterId = array();
if (!empty($paramers)) {
	$parametersId = explode(',', $paramers);
	for ($i = 0; $i < count($parametersId); ++$i) {
		$parametersId[$i] = trim($parametersId[$i]);
	}
	if ((count($parametersId) == 1) && ($parametersId[0] == 'Time')) {
		$getDataset = TRUE;
	}
	else {
		if (($key = array_search('Time', $parametersId)) !== FALSE) {
			unset($parametersId[$key]);
		}
	}
}
else {
	$getDataset = TRUE;
}

//Get token
$url = webAlias . "/php/rest/auth.php";
$token = file_get_contents($url);
if (empty($token)) {
	exit(1);
}
$query["token"] = $token;

//Get data
$url = webAlias . "/php/rest/";
if ($getDataset) {
	$query["datasetID"] = $options['id'];
	$url .= "getDataset.php";
}
else {
	$query["parameterID"] = implode(',', $parametersId);
	$url .= "getParameter.php";
}
$url .= "?" . http_build_query($query);

$result = file_get_contents($url);

//Check result
if (empty($result)) {
        exit(1);
}

$result = json_decode($result,TRUE);

if (!$result || empty($result['success']) || empty($result['dataFileURLs'])) {
        exit(1);
}

$data_path = $result['dataFileURLs'];

ob_start();

$columns = array();
$data_handle = fopen($data_path, 'r');
while(1)
{
        $data_line = fgets($data_handle);
        if (!$data_line) {
                break;
        }
        if (strpos($data_line, '#') === 0) {
                if (strpos($data_line, '# DATA_COLUMNS : ') === 0) {
                        $data_line = str_replace('# DATA_COLUMNS : ', '', $data_line);
                        $columns = explode(',', $data_line);
                }
                continue;
        }
        if (!empty($columns)) {
                $exploded_data = explode(' ', $data_line);
		$data = array();
		foreach ($exploded_data as $d) {
			if ($d != "") {
				$data[] = $d;
			}
		}
                foreach ($columns as $col_key => $col_name) {
                        if ($col_key != 0)
                                echo ",";
			$val = trim($data[$col_key]);
			if ($val == "NaN") {
				$val = "-1e31";
			}
                        echo $val;
                        if ($col_key == 0)
                                echo "Z";
                }
                echo PHP_EOL;
        }
        ob_flush();
        flush();
}

ob_end_flush();
?>