PHP_SMART_HOME_V3/app/api/WidgetApi.php

83 lines
2.2 KiB
PHP
Raw Normal View History

2020-05-24 17:35:19 +00:00
<?php
class WidgetApi extends ApiController{
2020-05-24 17:37:29 +00:00
public function run($subDeviceId){
2020-05-24 17:35:19 +00:00
//$this->requireAuth();
2020-07-20 09:07:32 +00:00
2020-05-24 17:35:19 +00:00
$response = null;
2020-07-20 09:07:32 +00:00
if (RecordManager::getLastRecord($subDeviceId)['execuded'] === 0) {
throw new Exception("Unreachable", 409);
}
2020-05-24 17:35:19 +00:00
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
if ($subDeviceData['type'] == 'on/off'){
$lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'];
RecordManager::create($subDeviceData['device_id'], 'on/off', (int) !$lastValue);
2020-05-24 17:35:19 +00:00
$response = !$lastValue;
2020-07-20 09:07:32 +00:00
} else {
throw new Exception("Bad Request", 403);
2020-05-24 17:35:19 +00:00
}
2020-07-20 09:07:32 +00:00
$i = 0;
$timeout = 20;
while (RecordManager::getLastRecord($subDeviceId)['execuded'] == 0){
if ($i == $timeout) {
throw new Exception("Timeout", 444);
}
$i++;
usleep(250000);
}
$this->response(['value' => $response]);
2020-05-26 19:42:39 +00:00
}
2020-05-26 19:47:36 +00:00
public function detail($subDeviceId){
//$this->requireAuth();
$response = null;
2020-05-27 19:37:35 +00:00
$connectionError = true;
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
2020-10-05 19:11:44 +00:00
$deviceData = DeviceManager::getDeviceById($subDeviceData['device_id']);
2020-05-27 19:37:35 +00:00
$events = RecordManager::getLastRecord($subDeviceId, 5);
2020-07-20 09:07:32 +00:00
$LastRecordTime = new DateTime($events[4]['time']);
2020-05-27 19:37:35 +00:00
$niceTime = Utilities::ago($LastRecordTime);
$interval = $LastRecordTime->diff(new DateTime());
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
$lastSeen = ($hours * 60 + $minutes);
if (
$lastSeen < $deviceData['sleep_time'] ||
$subDeviceData['type'] == "on/off" ||
2020-10-05 19:11:44 +00:00
$subDeviceData['type'] == "door" ||
$subDeviceData['type'] == "wather"
) {
$connectionError = false;
}
2020-05-27 19:37:35 +00:00
2020-10-05 19:11:44 +00:00
$labels = [];
$values = [];
foreach ($events as $key => $event) {
$labels[] = $event['value'];
$values[] = $event['time'];
}
$response = [
'records'=> $events,
'graph'=> [
'labels' => $values,
'values' => $labels,
'min' => RANGES[$subDeviceData['type']]['min'],
'max' => RANGES[$subDeviceData['type']]['max'],
'scale' => RANGES[$subDeviceData['type']]['scale'],
'graph' => RANGES[$subDeviceData['type']]['graph'],
],
'comError' => $connectionError,
'lastConnectionTime' => (empty($niceTime) ? "00:00" : $niceTime),
];
2020-05-26 19:47:36 +00:00
2020-10-05 19:11:44 +00:00
$this->response($response);
}
2020-05-26 19:47:36 +00:00
}