PHP_SMART_HOME_V3/api.php

327 lines
9.0 KiB
PHP
Raw Permalink 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',
));
2020-04-24 16:37:43 +00:00
2019-09-19 12:48:31 +00:00
foreach($files as $file) {
include './app/class/'. $file;
}
//Allow acces only wia Curl, Ajax ETC
2020-04-24 16:37:43 +00:00
/*$restAcess = 'XMLHttpRequest' == ( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );
2019-09-19 12:48:31 +00:00
if (!$restAcess){
header('Location: ./');
2020-04-24 16:37:43 +00:00
}*/
2019-08-23 11:39:42 +00:00
2019-08-30 15:29:34 +00:00
//Log
$logManager = new LogManager();
2020-03-16 15:34:37 +00:00
$apiLogManager = new LogManager('./app/logs/api/'. date("Y-m-d").'.log');
2019-08-30 15:29:34 +00:00
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-16 15:34:37 +00:00
//Log RAW api request
if (API_DEBUGMOD == 1) {
$apiLogManager->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']);
2020-03-17 08:17:01 +00:00
$userAtHome = $user['at_home'];
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'];
2020-03-16 14:07:44 +00:00
if($userAtHome != $atHome){
UserManager::atHome($userId, $atHome);
$logManager->write("[USER] user " . $userId . " changet his home state to " . $atHome , 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-13 15:28:50 +00:00
), JSON_PRETTY_PRINT);
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;
2020-03-16 13:52:36 +00:00
$deviceLogs = null;
2020-03-13 15:20:14 +00:00
$command = "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'];
}
2020-03-16 13:52:36 +00:00
if (isset($obj['logs'])) {
$deviceLogs = $obj['logs'];
}
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-13 15:28:50 +00:00
), JSON_PRETTY_PRINT);
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)) {
//Notification data setup
2019-12-31 22:05:19 +00:00
$notificationMng = new NotificationManager;
$notificationData = [
'title' => 'Info',
2019-12-31 22:05:19 +00:00
'body' => 'New device Detected Found',
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
//Subdevice Registration
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]);
}
}
//Notification for newly added Device
if ($notificationData != []) {
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO);
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
}
2020-03-12 20:34:12 +00:00
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",
2020-03-13 15:28:50 +00:00
), JSON_PRETTY_PRINT);
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",
2020-03-13 15:28:50 +00:00
), JSON_PRETTY_PRINT);
2019-08-23 11:39:42 +00:00
exit();
}
2020-03-11 11:22:44 +00:00
// Diagnostic Data Write to DB
2020-03-16 13:52: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)) {
2020-03-12 20:34:12 +00:00
$data['firmware_hash'] = $settings["firmware_hash"];
2020-03-11 11:43:37 +00:00
}
DeviceManager::editByToken($token, $data);
2020-03-25 14:58:47 +00:00
$jsonAnswer = [
'state' => 'succes',
'command' => $command,
];
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
die();
2020-03-11 11:22:44 +00:00
}
2020-03-13 15:20:14 +00:00
// Issuing command
if ($command == "null"){
2020-03-13 15:25:09 +00:00
$device = DeviceManager::getDeviceByToken($token);
$deviceId = $device['device_id'];
$deviceCommand = $device["command"];
2020-03-16 13:52:36 +00:00
if ($deviceCommand != '' && $deviceCommand != null && $deviceCommand != "null")
2020-03-13 15:20:14 +00:00
{
2020-03-16 13:52:36 +00:00
$command = $deviceCommand;
$data = [
'command'=>'null'
];
DeviceManager::editByToken($token, $data);
$logManager->write("[API] Device_ID " . $deviceId . " executing command " . $command, LogRecordType::INFO);
2020-03-13 15:20:14 +00:00
}
2020-03-16 13:52:36 +00:00
}
2020-03-13 15:20:14 +00:00
2020-03-16 13:52:36 +00:00
// Diagnostic Logs Write To log File
if ($deviceLogs != null && $deviceLogs != ""){
foreach ($deviceLogs as $log) {
$logManager->write("[Device Log Msg] Device_ID " . $deviceId . "->" . $log, LogRecordType::ERROR);
}
$jsonAnswer = [
'state' => 'succes',
'command' => $command,
2020-03-13 15:20:14 +00:00
];
2020-03-16 13:52:36 +00:00
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
die();
2020-03-13 15:20:14 +00:00
}
2020-04-24 16:37:43 +00:00
//
if (count($values) == 1){
unset($values["wifi"]);
}
2019-08-23 11:39:42 +00:00
// Subdevices first data!
2020-03-16 13:52:36 +00:00
if ($values != null && $values != "") {
2020-03-12 20:34:12 +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-12 20:34:12 +00:00
2019-10-09 08:56:09 +00:00
//notification
if ($key == 'door' || $key == 'water') {
$notificationMng = new NotificationManager;
$notificationData = [];
2020-03-12 20:34:12 +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',
];
2020-03-12 20:34:12 +00:00
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-12 20:34:12 +00:00
2019-08-23 11:39:42 +00:00
$hostname = strtolower($device['name']);
$hostname = str_replace(' ', '_', $hostname);
2020-03-12 20:34:12 +00:00
//upravit format na setings-> netvork etc
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-13 15:20:14 +00:00
'command' => $command,
2019-10-09 08:56:09 +00:00
];
2020-03-12 20:34:12 +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
}
2020-03-13 15:28:50 +00:00
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
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-12 20:34:12 +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-12 20:34:12 +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-12 20:34:12 +00:00
2019-10-09 08:56:09 +00:00
if ($subDeviceLastReord['execuded'] == 0){
2020-03-16 14:03:43 +00:00
$logManager->write("[API] subDevice_ID ".$subDeviceId . " executed comand with value " .$subDeviceLastReordValue . " record id " . $subDeviceLastReord['record_id'] . " executed " . $subDeviceLastReord['execuded'], LogRecordType::INFO);
2019-10-09 08:56:09 +00:00
RecordManager::setExecuted($subDeviceLastReord['record_id']);
}
2020-03-12 20:34:12 +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',
2020-03-13 15:14:22 +00:00
'value' => $subDeviceLastReordValue,
2020-03-13 15:20:14 +00:00
'command' => $command,
2020-03-13 15:28:50 +00:00
), JSON_PRETTY_PRINT);
2020-03-11 11:22:44 +00:00
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
}
2020-03-11 11:22:44 +00:00
unset($logManager);
Db::disconect();
die();