PHP_SMART_HOME_V3/api.php

271 lines
7.8 KiB
PHP
Raw Normal View History

2019-08-23 11:39:42 +00:00
<?php
/** Includes **/
include_once('./config.php');
//Autoloader
2019-09-19 12:48:31 +00:00
$files = scandir('./app/class/');
$files = array_diff($files, array(
'.',
'..',
'app',
'ChartJS.php',
'ChartJS_Line.php',
'ChartManager.php',
'DashboardManager.php',
'Partial.php',
'Form.php',
'Route.php',
'Template.php',
'Ajax.php',
));
foreach($files as $file) {
include './app/class/'. $file;
}
//Allow acces only wia Curl, Ajax ETC
$restAcess = 'XMLHttpRequest' == ( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );
if (!$restAcess){
header('Location: ./');
2019-08-23 11:39:42 +00:00
}
2019-08-30 15:29:34 +00:00
//Log
$logManager = new LogManager();
2019-08-23 11:39:42 +00:00
//DB Conector
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
//Read API data
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
2020-03-11 11:22:44 +00:00
2020-03-09 18:45:49 +00:00
if (defined(DEBUGMOD) && DEBUGMOD == 1) {
2020-03-11 11:22:44 +00:00
$logManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordType::INFO);
2020-03-09 18:45:49 +00:00
}
2019-08-23 11:39:42 +00:00
2019-08-25 12:09:08 +00:00
//zabespecit proti Ddosu
2019-08-23 11:39:42 +00:00
if (isset($obj['user']) && $obj['user'] != ''){
//user at home
$user = UserManager::getUser($obj['user']);
2019-09-01 15:36:46 +00:00
if (!empty($user)) {
$userId = $user['user_id'];
2019-09-19 12:48:31 +00:00
$atHome = $obj['atHome'];
UserManager::atHome($userId, $atHome);
2020-03-09 18:45:49 +00:00
$logManager->write("[Record] user " . $userId . " changet his home state to " . $atHome . " " . RECORDTIMOUT , LogRecordType::INFO);
2019-09-19 12:48:31 +00:00
echo 'Saved: ' . $atHome;
2020-03-11 11:22:44 +00:00
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
2019-09-04 17:09:36 +00:00
die();
2019-09-01 15:36:46 +00:00
}
2019-08-23 11:39:42 +00:00
}
//Filtrování IP adress
2019-08-25 12:09:08 +00:00
if (DEBUGMOD != 1) {
if (!in_array($_SERVER['REMOTE_ADDR'], HOMEIP)) {
echo json_encode(array(
'state' => 'unsuccess',
2019-09-01 13:01:57 +00:00
'errorMSG' => "Using API from your IP insnt alowed!",
));
2020-03-11 11:22:44 +00:00
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
2019-08-30 15:44:22 +00:00
$logManager->write("[API] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING);
exit();
}
2019-08-25 12:09:08 +00:00
}
2019-08-23 11:39:42 +00:00
//automationExecution
2019-09-01 13:01:57 +00:00
try {
2020-02-18 20:30:44 +00:00
AutomationManager::executeAll();
2020-02-11 15:01:00 +00:00
$fallbackManager = new FallbackManager(RANGES);
$fallbackManager->check();
2020-02-18 20:30:44 +00:00
//LogKeeper::purge(LOGTIMOUT);
2019-09-01 13:01:57 +00:00
} catch (\Exception $e) {
$logManager->write("[Automation] Something happen during automation execution", LogRecordType::ERROR);
}
2019-08-23 11:39:42 +00:00
//Record Cleaning
2019-09-01 13:01:57 +00:00
try {
RecordManager::clean(RECORDTIMOUT);
} catch (\Exception $e) {
2019-09-19 12:48:31 +00:00
$logManager->write("[Record] cleaning record older that " . RECORDTIMOUT , LogRecordType::ERROR);
2019-09-01 13:01:57 +00:00
}
2020-02-11 14:09:15 +00:00
2019-08-23 11:39:42 +00:00
//Variables
$token = $obj['token'];
$values = null;
2020-03-11 11:22:44 +00:00
$settings = null;
2019-08-23 11:39:42 +00:00
if (isset($obj['values'])) {
$values = $obj['values'];
}
2020-03-11 11:22:44 +00:00
if (isset($obj['settings'])) {
$settings = $obj['settings'];
}
2019-08-23 11:39:42 +00:00
//Checks
if ($token == null || $token == "") {
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Missing Value Token in JSON payload",
));
2020-03-11 11:22:44 +00:00
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
2019-08-23 11:39:42 +00:00
die();
}
//Vstupní Checky
if (!DeviceManager::registeret($token)) {
2019-12-31 22:05:19 +00:00
$notificationMng = new NotificationManager;
$notificationData = [];
$notificationData = [
'title' => 'Info',
2019-12-31 22:05:19 +00:00
'body' => 'New device Detected Found',
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
2019-10-09 08:53:52 +00:00
$deviceId = DeviceManager::create($token, $token);
foreach ($values as $key => $value) {
if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) {
SubDeviceManager::create($deviceId, $key, UNITS[$key]);
}
2020-03-11 11:22:44 +00:00
2019-12-31 22:05:19 +00:00
if ($notificationData != []) {
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
2020-03-11 11:22:44 +00:00
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO);
2019-12-31 22:05:19 +00:00
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
}
2019-10-09 08:53:52 +00:00
}
2020-03-11 11:22:44 +00:00
//Notification for newly added Device
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
2020-03-11 11:22:44 +00:00
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO);
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
2020-03-11 11:22:44 +00:00
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
2019-08-23 11:39:42 +00:00
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Device not registeret",
));
2019-08-30 15:44:22 +00:00
$logManager->write("[API] Registering Device", LogRecordType::INFO);
2019-08-23 11:39:42 +00:00
exit();
}
if (!DeviceManager::approved($token)) {
2020-03-11 11:22:44 +00:00
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
2019-08-23 11:39:42 +00:00
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Unaproved Device",
));
exit();
}
2020-03-11 11:22:44 +00:00
// Diagnostic Data Write to DB
2020-03-12 09:28:36 +00:00
if ($settings != null || $settings != ""){
2020-03-11 11:43:37 +00:00
$data = ['mac' => $settings["network"]["mac"], 'ip_address' => $settings["network"]["ip"]];
if (array_key_exists("firmware_hash", $settings)) {
$data .= ['firmware_hash'=>$settings["firmware_hash"]];
}
DeviceManager::editByToken($token, $data);
2020-03-11 11:22:44 +00:00
}
2019-08-23 11:39:42 +00:00
// Subdevices first data!
if ($values != null || $values != "") {
2020-03-11 11:22:44 +00:00
2019-08-23 11:39:42 +00:00
//ZAPIS
$device = DeviceManager::getDeviceByToken($token);
$deviceId = $device['device_id'];
foreach ($values as $key => $value) {
if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) {
SubDeviceManager::create($deviceId, $key, UNITS[$key]);
}
2020-02-11 14:09:15 +00:00
RecordManager::create($deviceId, $key, round($value['value'],3));
2019-09-19 12:48:31 +00:00
$logManager->write("[API] Device_ID " . $deviceId . " writed value " . $key . ' ' . $value['value'], LogRecordType::INFO);
2020-03-11 11:22:44 +00:00
2019-10-09 08:56:09 +00:00
//notification
if ($key == 'door' || $key == 'water') {
$notificationMng = new NotificationManager;
$notificationData = [];
2020-03-11 11:22:44 +00:00
2019-10-09 08:56:09 +00:00
switch ($key) {
case 'door':
2020-03-11 11:22:44 +00:00
$notificationData = [
'title' => 'Info',
'body' => 'Someone just open up '.$device['name'],
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
2019-10-09 08:56:09 +00:00
break;
case 'water':
2020-03-11 11:22:44 +00:00
$notificationData = [
'title' => 'Alert',
'body' => 'Wather leak detected by '.$device['name'],
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
2019-10-09 08:56:09 +00:00
break;
}
2019-10-30 14:18:29 +00:00
if (DEBUGMOD) $notificationData['body'] .= ' value='.$value['value'];
2019-10-09 08:56:09 +00:00
if ($notificationData != []) {
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
2020-03-11 11:22:44 +00:00
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO);
2019-10-09 08:56:09 +00:00
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
}
}
2019-08-23 11:39:42 +00:00
}
2020-03-11 11:22:44 +00:00
2019-08-23 11:39:42 +00:00
$hostname = strtolower($device['name']);
$hostname = str_replace(' ', '_', $hostname);
2019-10-09 08:56:09 +00:00
$jsonAnswer = [
2019-08-23 11:39:42 +00:00
'device' => [
'hostname' => $hostname,
2019-11-27 16:05:49 +00:00
'ipAddress' => $device['ip_address'],
2019-11-28 13:34:32 +00:00
'subnet' => $device['subnet'],
'gateway' => $device['gateway'],
2019-10-09 08:56:09 +00:00
],
'state' => 'succes',
];
2020-03-11 11:22:44 +00:00
2019-10-09 08:56:09 +00:00
$subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($deviceId);
if (!in_array($subDevicesTypeList, ['on/off', 'door', 'water'])) {
2019-11-26 12:32:08 +00:00
$jsonAnswer['device']['sleepTime'] = $device['sleep_time'];
2019-10-09 08:56:09 +00:00
}
echo json_encode($jsonAnswer);
2020-03-11 11:22:44 +00:00
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
2019-10-09 08:56:09 +00:00
} else {
//Vypis
$device = DeviceManager::getDeviceByToken($token);
$deviceId = $device['device_id'];
2020-03-11 11:22:44 +00:00
2019-10-09 08:56:09 +00:00
if (count(SubDeviceManager::getAllSubDevices($deviceId)) == 0) {
SubDeviceManager::create($deviceId, 'on/off', UNITS[$key]);
//RecordManager::create($deviceId, 'on/off', 0);
}
2020-03-11 11:22:44 +00:00
2019-10-09 08:56:09 +00:00
$subDeviceId = SubDeviceManager::getAllSubDevices($deviceId)[0]['subdevice_id'];
$subDeviceLastReord = RecordManager::getLastRecord($subDeviceId);
$subDeviceLastReordValue = $subDeviceLastReord['value'];
2020-03-11 11:22:44 +00:00
2019-10-09 08:56:09 +00:00
if ($subDeviceLastReord['execuded'] == 0){
$logManager->write("[API] subDevice id ".$subDeviceId . " executed comand with value " .$subDeviceLastReordValue . " record id " . $subDeviceLastReord['record_id'] . " executed " . $subDeviceLastReord['execuded']);
RecordManager::setExecuted($subDeviceLastReord['record_id']);
}
2020-03-11 11:22:44 +00:00
2019-10-09 08:56:09 +00:00
echo json_encode(array(
'device' => [
'hostname' => $device['name'],
2019-11-27 16:05:49 +00:00
'ipAddress' => $device['ip_address'],
2019-11-28 13:34:32 +00:00
'subnet' => $device['subnet'],
'gateway' => $device['gateway'],
2020-03-11 11:22:44 +00:00
],
'state' => 'succes',
'value' => $subDeviceLastReordValue
));
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
}
2020-03-11 11:22:44 +00:00
unset($logManager);
Db::disconect();
die();