This commit is contained in:
JonatanRek 2019-09-01 15:55:49 +02:00
commit b5024351c5
14 changed files with 170 additions and 78 deletions

1
.gitignore vendored
View File

@ -4,3 +4,4 @@ _nemazat/index.html
_nemazat/css/main.css.map _nemazat/css/main.css.map
_nemazat/css/main.css _nemazat/css/main.css
_nemazat/css/font-awesome.min.css _nemazat/css/font-awesome.min.css
logs/*.log

74
api.php
View File

@ -11,41 +11,55 @@ foreach (["class", "views"] as $dir) {
} }
} }
//Log
$logManager = new LogManager();
//DB Conector //DB Conector
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME); Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
//Filtrování IP adress
/*if (DEBUGMOD != 1) {
if (!in_array($_SERVER['REMOTE_ADDR'], HOMEIP)) {
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Using API from your IP insn´t alowed!",
));
header("HTTP/1.1 401 Unauthorized");
exit();
}
}*/
//Read API data //Read API data
$json = file_get_contents('php://input'); $json = file_get_contents('php://input');
$obj = json_decode($json, true); $obj = json_decode($json, true);
//zabespecit proti Ddosu
if (isset($obj['user']) && $obj['user'] != ''){ if (isset($obj['user']) && $obj['user'] != ''){
//user at home //user at home
$user = UserManager::getUser($obj['user']); $user = UserManager::getUser($obj['user']);
$userId = $user['user_id']; $userId = $user['user_id'];
UserManager::atHome($userId, $obj['location']); $keyWords = ['entered', 'connected', 'connected to'];
UserManager::atHome($userId, $obj['atHome']);
echo 'saved';
die(); die();
} }
//Filtrování IP adress
if (DEBUGMOD != 1) {
if (!in_array($_SERVER['REMOTE_ADDR'], HOMEIP)) {
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Using API from your IP insnt alowed!",
));
header("HTTP/1.1 401 Unauthorized");
$logManager->write("[API] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING);
exit();
}
}
//automationExecution //automationExecution
AutomationManager::executeAll(); try {
AutomationManager::executeAll();
} catch (\Exception $e) {
$logManager->write("[Automation] Something happen during automation execution", LogRecordType::ERROR);
}
//Record Cleaning //Record Cleaning
RecordManager::clean(RECORDTIMOUT); try {
RecordManager::clean(RECORDTIMOUT);
} catch (\Exception $e) {
$logManager->write("[Record] cleaning record older that" . RECORDTIMOUT , LogRecordType::ERROR);
}
//Variables //Variables
$token = $obj['token']; $token = $obj['token'];
$values = null; $values = null;
@ -72,6 +86,7 @@ if (!DeviceManager::registeret($token)) {
'state' => 'unsuccess', 'state' => 'unsuccess',
'errorMSG' => "Device not registeret", 'errorMSG' => "Device not registeret",
)); ));
$logManager->write("[API] Registering Device", LogRecordType::INFO);
exit(); exit();
} }
@ -84,16 +99,6 @@ if (!DeviceManager::approved($token)) {
exit(); exit();
} }
if (!DeviceManager::approved($token)) {
header("HTTP/1.1 401 Unauthorized");
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Unaproved Device",
));
exit();
}
// Subdevices first data! // Subdevices first data!
if ($values != null || $values != "") { if ($values != null || $values != "") {
@ -105,6 +110,7 @@ if ($values != null || $values != "") {
SubDeviceManager::create($deviceId, $key, UNITS[$key]); SubDeviceManager::create($deviceId, $key, UNITS[$key]);
} }
RecordManager::create($deviceId, $key, round($value['value'],2)); RecordManager::create($deviceId, $key, round($value['value'],2));
$logManager->write("[API] Device_ID " . $deviceId . " writed value " . $key . $value['value'], LogRecordType::INFO);
} }
$hostname = strtolower($device['name']); $hostname = strtolower($device['name']);
@ -117,7 +123,6 @@ if ($values != null || $values != "") {
'state' => 'succes', 'state' => 'succes',
)); ));
header("HTTP/1.1 200 OK"); header("HTTP/1.1 200 OK");
die();
} else { } else {
//Vypis //Vypis
//TODO: doděla uložení výpisu jinými slovy zda li byl comman vykonán //TODO: doděla uložení výpisu jinými slovy zda li byl comman vykonán
@ -126,15 +131,17 @@ if ($values != null || $values != "") {
if (count(SubDeviceManager::getAllSubDevices($deviceId)) == 0) { if (count(SubDeviceManager::getAllSubDevices($deviceId)) == 0) {
SubDeviceManager::create($deviceId, 'on/off', UNITS[$key]); SubDeviceManager::create($deviceId, 'on/off', UNITS[$key]);
RecordManager::create($deviceId, 'on/off', 0); //RecordManager::create($deviceId, 'on/off', 0);
} }
$subDeviceId = SubDeviceManager::getAllSubDevices($deviceId)[0]['subdevice_id']; $subDeviceId = SubDeviceManager::getAllSubDevices($deviceId)[0]['subdevice_id'];
$subDeviceLastReord = RecordManager::getLastRecord($subDeviceId); $subDeviceLastReord = RecordManager::getLastRecord($subDeviceId);
$subDeviceLastReordValue = $subDeviceLastReord['value']; $subDeviceLastReordValue = $subDeviceLastReord['value'];
RecordManager::setExecuted($subDeviceLastReord['record_id']); 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']);
}
echo json_encode(array( echo json_encode(array(
'device' => [ 'device' => [
@ -145,5 +152,8 @@ if ($values != null || $values != "") {
'value' => $subDeviceLastReordValue 'value' => $subDeviceLastReordValue
)); ));
header("HTTP/1.1 200 OK"); header("HTTP/1.1 200 OK");
die();
} }
unset($logManager);
Db::disconect();
die();

View File

@ -73,13 +73,40 @@ class AutomationManager{
$restart = true; $restart = true;
} }
} }
} } else if ($onValue['type'] == 'outHome') {
if ($onValue == 'outHome') { } else if ($onValue['type'] == 'inHome') {
} } else if ($onValue['type'] == 'noOneHome') {
$users = UserManager::getUsers();
if ($onValue == 'inHome') { $membersHome = 0;
foreach ($users as $key => $user) {
if ($user['at_home'] == 'true'){
$membersHome++;
}
}
if ($membersHome == 0 && $automation['executed'] == 0) {
$run = true;
} else if ($membersHome > 0 && $automation['executed'] == 1){
$restart = true;
}
} else if ($onValue['type'] == 'someOneHome') {
$users = UserManager::getUsers();
$membersHome = 0;
foreach ($users as $key => $user) {
if ($user['at_home'] == 'true'){
$membersHome++;
}
}
if ($membersHome == 0 && $automation['executed'] == 1) {
$restart = true;
} else if ($membersHome > 0 && $automation['executed'] == 0){
$run = true;
}
/*echo "Someone Home". '<br>';
echo "at home" . $membersHome. '<br>';
echo "run" . $run. '<br>';
echo "restart" . $restart. '<br>';*/
} }
@ -89,8 +116,10 @@ class AutomationManager{
foreach ($sceneDoArray as $deviceId => $deviceState) { foreach ($sceneDoArray as $deviceId => $deviceState) {
RecordManager::create($deviceId, 'on/off', $deviceState); RecordManager::create($deviceId, 'on/off', $deviceState);
} }
$logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was executed");
Db::edit('automation', array('executed' => 1), 'WHERE automation_id = ?', array($automation['automation_id'])); Db::edit('automation', array('executed' => 1), 'WHERE automation_id = ?', array($automation['automation_id']));
} else if ($restart) { } else if ($restart) {
$logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was restarted");
Db::edit('automation', array('executed' => 0), 'WHERE automation_id = ?', array($automation['automation_id'])); Db::edit('automation', array('executed' => 0), 'WHERE automation_id = ?', array($automation['automation_id']));
} }
} }

View File

@ -19,6 +19,10 @@ class Db{
} }
} }
public static function disconect(){
self::$join = null;
}
public static function loadOne ($sql, $values = array (), $numberKey = false) { public static function loadOne ($sql, $values = array (), $numberKey = false) {
$answer = self::$join->prepare ($sql); $answer = self::$join->prepare ($sql);
$answer->execute ($values); $answer->execute ($values);

38
class/LogManager.php Normal file
View File

@ -0,0 +1,38 @@
<?php
/**
*
*/
class LogRecordType{
const WARNING = 'warning';
const ERROR = 'error';
const INFO = 'info';
}
class LogManager
{
private $logFile;
function __construct($fileName = "")
{
if ($fileName == ""){
$fileName = './logs/'. date("Y-m-d").'.log';
}
if(!is_dir("./logs/"))
{
mkdir("./logs/");
}
$this->logFile = fopen($fileName, "a") or die("Unable to open file!");
}
function write($value, $type = LogRecordType::ERROR){
$record = "[".date("H:m:s")."][".$type."]" .$value . "\n";
fwrite($this->logFile, $record);
}
function __destruct(){
if (isset($this->logFile)) {
fclose($this->logFile);
}
}
}

View File

@ -63,8 +63,12 @@ $lang = [
'w_icon' => 'Ikona', 'w_icon' => 'Ikona',
'w_no' => 'žádná', 'w_no' => 'žádná',
'w_noOne' => 'Nikdo', 'w_noOne' => 'Nikdo',
'w_someOne' => 'Někdo',
'w_room' => 'Místnost', 'w_room' => 'Místnost',
'w_moduls' => 'Moduly', 'w_moduls' => 'Moduly',
'w_home' => 'Doma',
'w_neni' => 'Není',
'w_is' => 'je',
//example //example
'' => '', '' => '',

View File

@ -63,8 +63,12 @@ $lang = [
'w_icon' => 'Icon', 'w_icon' => 'Icon',
'w_no' => 'no', 'w_no' => 'no',
'w_noOne' => 'noone', 'w_noOne' => 'noone',
'w_someOne' => 'Some',
'w_room' => 'Room', 'w_room' => 'Room',
'w_moduls' => 'Moduls', 'w_moduls' => 'Moduls',
'w_home' => 'Home',
'w_neni' => 'At',
'w_is' => 'is',
//example //example
'' => '', '' => '',

View File

@ -48,7 +48,7 @@
<i class="fa fa-times"></i> <i class="fa fa-times"></i>
</div> </div>
<h4 class="mb-4">Modal bitch</h4> <h4 class="mb-4">Modal bitch</h4>
<form method="post" action="controls/dashboard.php"> <form method="post">
<div class="field px-2"> <div class="field px-2">
<div class="label">Zvolte zařízení:</div> <div class="label">Zvolte zařízení:</div>
<select class="input" name="devices[]" multiple> <select class="input" name="devices[]" multiple>

View File

@ -35,10 +35,8 @@
<div class="col-md-9 main-body"> <div class="col-md-9 main-body">
<div class="label m-1"> <div class="label m-1">
doma jsou: doma jsou:
<?php <?php foreach ($USERS as $user) {
$keyWords = ['entered', 'connected', 'connected to']; if ($user['at_home'] == 'true') {
foreach ($USERS as $user) {
if (in_array(trim($user['at_home']), $keyWords)) {
echo $user['username'] . ' '; echo $user['username'] . ' ';
} }
} ?> } ?>

View File

@ -33,7 +33,7 @@ function ajaxPost(path, params, self, reload = false) {
} }
console.log(msg); console.log(msg);
if (reload){ if (reload){
//location.reload(); location.reload();
} }
}, },
error: function (request, status, error) { error: function (request, status, error) {

View File

@ -182,36 +182,36 @@ $( '[name="room"]' ).change(function (e) {
}); });
var windowLoc = $(location).attr('pathname'); // var windowLoc = $(location).attr('pathname');
windowLoc = windowLoc.substring(windowLoc.lastIndexOf("/")); // windowLoc = windowLoc.substring(windowLoc.lastIndexOf("/"));
console.log(); // console.log();
if (windowLoc == "/") { // if (windowLoc == "/") {
var autoUpdate = setInterval(function(){ // var autoUpdate = setInterval(function(){
$.ajax({ // $.ajax({
url: 'ajax', // url: 'ajax',
type: 'POST', // type: 'POST',
dataType: 'json', // dataType: 'json',
data: { // data: {
"action": 'getState' // "action": 'getState'
}, // },
success: function(data){ // success: function(data){
// console.log('DATA: ', data); // // console.log('DATA: ', data);
for (const key in data) { // for (const key in data) {
if (data.hasOwnProperty(key)) { // if (data.hasOwnProperty(key)) {
const device = data[key]; // const device = data[key];
$('[data-sub-device-id="'+key+'"]') // $('[data-sub-device-id="'+key+'"]')
.find('.device-button-value') // .find('.device-button-value')
.text(device['value']) // .text(device['value'])
.attr('title',device['time']) // .attr('title',device['time'])
} // }
} // }
}, // },
error: function (request, status, error) { // error: function (request, status, error) {
console.log("ERROR ajaxChart():", request, error); // console.log("ERROR ajaxChart():", request, error);
} // }
}); // });
},2000); // },2000);
} // }

View File

@ -12,7 +12,10 @@
<option value="inHome"><?php echo $LANG['l_inHome']?></option> <option value="inHome"><?php echo $LANG['l_inHome']?></option>
<option value="outHome"><?php echo $LANG['l_outHome']?></option> <option value="outHome"><?php echo $LANG['l_outHome']?></option>
<option value="time"><?php echo $LANG['l_time']?></option> <option value="time"><?php echo $LANG['l_time']?></option>
<option value="atDeviceValue"><?php echo $LANG['l_deviceValue']?></option> <option value="noOneHome"><?php echo $LANG['l_time']?></option>
<option value="atDeviceValue"><?php echo $LANG['l_deviceValue'];?></option>
<option value="noOneHome"><?php echo $LANG['w_noOne'] . ' ' . $LANG['w_neni'] . ' ' . $LANG['w_home'];?></option>
<option value="someOneHome"><?php echo $LANG['w_someOne'] . ' ' . $LANG['w_is'] . ' ' . $LANG['w_home'];?></option>
</select> </select>
<input class="input" type="time" name="atTime" id="atTime" disabled/> <input class="input" type="time" name="atTime" id="atTime" disabled/>
<select class="input" name="atDeviceValue" id="atDeviceValue" disabled> <select class="input" name="atDeviceValue" id="atDeviceValue" disabled>

View File

@ -30,6 +30,7 @@ class Ajax extends Template
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId); $subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id']; $deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
if ($subDeviceData['type'] == 'on/off'){ if ($subDeviceData['type'] == 'on/off'){
//TODO: Pridelat kontrolu změnit stav pouze pokud se poslední [executed] stav != novému
if (RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'] == 0){ if (RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'] == 0){
RecordManager::create($deviceId, 'on/off', 1); RecordManager::create($deviceId, 'on/off', 1);
echo 'ON'; echo 'ON';

View File

@ -20,9 +20,9 @@ class Automation extends Template
$automationsData = AutomationManager::getAll(); $automationsData = AutomationManager::getAll();
foreach ($automationsData as $automationKey => $automationData) { foreach ($automationsData as $automationKey => $automationData) {
$doSomething = []; $doSomething = [];
foreach (json_decode($automationData['do_something']) as $subdeviceId => $subDeviceState) { foreach (json_decode($automationData['do_something']) as $deviceId => $subDeviceState) {
$subDeviceMasterDeviceData = SubDeviceManager::getSubDeviceMaster($subdeviceId); $subDeviceMasterDeviceData = DeviceManager::getDeviceById($deviceId);
$doSomething[$subdeviceId] = [ $doSomething[$deviceId] = [
'name' => $subDeviceMasterDeviceData['name'], 'name' => $subDeviceMasterDeviceData['name'],
'state' => $subDeviceState, 'state' => $subDeviceState,
]; ];
@ -43,7 +43,7 @@ class Automation extends Template
$allSubDevicesData = SubDeviceManager::getAllSubDevices($deviceValue['device_id']); $allSubDevicesData = SubDeviceManager::getAllSubDevices($deviceValue['device_id']);
foreach ($allSubDevicesData as $subDeviceKey => $subDeviceValue) { foreach ($allSubDevicesData as $subDeviceKey => $subDeviceValue) {
$approvedSubDevices[$subDeviceValue['subdevice_id']] = [ $approvedSubDevices[$subDeviceValue['subdevice_id']] = [
'name' => $allDevicesData[$deviceKey]['name'], 'name' => $allDevicesData[$deviceKey]['name'] . $allDevicesData[$deviceKey]['device_id'],
'type' => $subDeviceValue['type'], 'type' => $subDeviceValue['type'],
'masterDevice' => $subDeviceValue['device_id'], 'masterDevice' => $subDeviceValue['device_id'],
]; ];