rooms api

This commit is contained in:
xinatorus 2020-05-15 20:59:12 +02:00
parent 02ba4e5d6f
commit c3d8a211ed
3 changed files with 41 additions and 23 deletions

View File

@ -4,33 +4,23 @@ class RoomsApi extends ApiController{
public function default(){
//$this->requireAuth();
$rooms = [];
$roomsData = RoomManager::getAllRooms();
foreach ($roomsData as $roomKey => $roomData) {
$widgets = [];
$devicesData = DeviceManager::getAllDevicesInRoom($roomData['room_id']);
foreach ($devicesData as $deviceKey => $deviceData) {
$subDevicesData = SubDeviceManager::getAllSubDevices($deviceData['device_id']);
foreach ($subDevicesData as $subDeviceKey => $subDeviceData) {
$lastRecord = RecordManager::getLastRecord($subDeviceData['subdevice_id']);
$widgets[] = [
'subdevice_id' => $subDeviceData['subdevice_id'],
'device_id' => $deviceData['device_id'],
'name' => $deviceData['name'],
'type' => $subDeviceData['type'],
'icon' => $deviceData['icon'],
'value' => $lastRecord['value'],
'unit' => $subDeviceData['unit'],
];
}
$response = [];
$roomIds = [];
$roomsData = RoomManager::getRoomsDefault();
foreach ($roomsData as $roomKey => $room) {
$roomIds[] = $room['room_id'];
}
$rooms[] = [
$subDevicesData = SubDeviceManager::getSubdevicesByRoomIds($roomIds);
foreach ($roomsData as $roomKey => $roomData) {
$response[] = [
'room_id' => $roomData['room_id'],
'name' => $roomData['name'],
'widgets' => $widgets,
'widgets' => isset($subDevicesData[$roomData['room_id']]) ? $subDevicesData[$roomData['room_id']] : [],
];
}
$this->response($rooms);
$this->response($response);
}
}

View File

@ -12,6 +12,11 @@ class RoomManager{
return $allRoom;
}
static function getRoomsDefault () {
$allRoom = Db::loadAll ("SELECT room_id, name FROM rooms");
return $allRoom;
}
public static function create ($name) {
$room = array (
'name' => $name,

View File

@ -71,4 +71,27 @@ class SubDeviceManager
RecordManager::cleanSubdeviceRecords($subDeviceId);
return Db::loadAll("DELETE FROM subdevices WHERE subdevice_id = ?", array($subDeviceId));
}
public static function getSubdevicesByRoomIds($roomIds = NULL) {
if(empty($roomIds)) return NULL;
$rows = Db::loadAll("
SELECT d.room_id, sd.subdevice_id, sd.device_id, d.name, sd.type, sd.unit, r.value FROM subdevices sd
JOIN devices d ON sd.device_id = d.device_id
JOIN records r ON r.subdevice_id = sd.subdevice_id
WHERE d.room_id IN (".str_repeat("?,", count($roomIds)-1)."?)
AND r.record_id IN (
SELECT MAX(record_id)
FROM records
GROUP BY subdevice_id
)
", $roomIds);
$ret = [];
foreach($rows as $row){
$ret[$row['room_id']][] = $row;
}
return $ret;
}
}