API: Add csv format to device-data action

This commit is contained in:
Starbeamrainbowlabs 2019-02-24 16:55:33 +00:00
parent 0d3f55fc6a
commit 263658d735
Signed by: sbrl
GPG key ID: 1BE5172E637709C2
3 changed files with 43 additions and 2 deletions

View file

@ -153,6 +153,8 @@ Parameter | Type | Meaning
`start` | datetime | The starting datetime.
`end` | datetime | The ending datetime.
`average-seconds` | int | Optional. If specified, readings will be grouped into lumps of this many seconds and averaged. For example a value of 3600 (1 hour) will return 1 data point per hour, with the value of each point an average of all the readings for that hour.
`format` | string | Optional. Specifies the format that the response will be returned in. Valid values: `json`, `csv`. Default: `json`
### changelog
> Gets the changelog as a fragment of HTML.

View file

@ -49,8 +49,14 @@ class DeviceData implements IAction {
$this->validator->is_max_length("reading-type", 256);
$this->validator->is_datetime("start");
$this->validator->is_datetime("end");
if(!empty($_GET["format"]))
$this->validator->is_preset_value("format", ["json", "csv"], 406);
$this->validator->run();
$format = $_GET["format"] ?? "json";
if(new \DateTime($_GET["start"]) > new \DateTime($_GET["end"])) {
$this->sender->send_error_plain(
400, "Error: The start date must be earlier than the end date.", [
@ -101,12 +107,35 @@ class DeviceData implements IAction {
// 3: Serialise data
$start_encode = microtime(true);
$response_type = "application/octet-stream";
$response_suggested_filename = "data-" . date(\DateTime::ATOM) . "";
$response = null;
switch($format) {
case "json":
$response_type = "application/json";
$response_suggested_filename .= ".json";
$response = json_encode($data);
break;
case "csv":
$result = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
fputcsv($result, array_keys($data[0]));
foreach($data as $row)
fputcsv($result, array_values($row));
rewind($result);
$response_type = "text/csv";
$response_suggested_filename .= ".json";
$response = \stream_get_contents($result);
fclose($result);
break;
}
// 4: Send response
header("content-length: " . strlen($response));
header("content-type: application/json");
header("content-type: $response_type");
header("content-disposition: inline; filename=data.csv");
header("x-time-taken: " . PerfFormatter::format_perf_data($start_time, $start_handle, $start_encode));
echo($response);
return true;

View file

@ -42,6 +42,16 @@ class Validator {
"Error: The field $key is too long - it must be a maximum of $max_length characters."
);
}
public function is_preset_value(string $key, array $values, int $error_code) {
$this->add_test(
$key,
function($data) use ($values) {
return in_array($data, $values);
},
$error_code,
"Error: The value for the field $key is not valid. Valid values: " . implode(", ", $values) . "."
);
}
public function are_equal($key_a, $key_b, $message) {
$key_b_data = $this->target_data[$key_b];