21 Commits

Author SHA1 Message Date
haitem
04e83dccf6 Merge branch 'remastering' of https://git.steelants.cz/SH/PHP_SMART_HOME_V3 into remastering 2021-03-01 17:39:01 +01:00
haitem
4ab70a1c2d Remake approved view and add rename input in setting for room name 2021-03-01 17:38:44 +01:00
haitem
5f03295ad3 Add approve changer in actions in device list 2021-03-01 17:24:24 +01:00
GamerClassN7
66dc2a3670 Bug Hunting 2021-03-01 17:10:58 +01:00
GamerClassN7
b9a967642a Git Ignore 2021-03-01 17:07:49 +01:00
GamerClassN7
fe1247fdaf FTP -> GIT Diff 2021-03-01 16:02:21 +01:00
GamerClassN7
9d9304d30e Automation Fix 2021-02-24 17:20:49 +01:00
GamerClassN7
c6f57a3661 Damejídlo Value Fix 2021-02-24 17:20:35 +01:00
GamerClassN7
adfb564ccc Automation create Auth enable 2021-02-23 12:41:48 +01:00
GamerClassN7
a3eaf16fd6 Automation Endpoints Create 2021-02-23 12:41:34 +01:00
8b32ecc619 Automation API #FIX 2021-02-17 08:41:08 +01:00
7ea4a90980 Automations Endpoint Detail + Cron Endpoint 2021-02-16 14:59:27 +01:00
38b29a2a4a Automation api Endpoint 2021-02-16 14:28:31 +01:00
821c0926e8 DB Backup Plugin Sync Time Setting Fields 2021-02-15 14:18:44 +01:00
3d3b073131 Synch 2021-02-15 14:03:29 +01:00
GamerClassN7
485709d61f Git Stats + Remove Empty Rooms 2021-02-14 20:13:29 +01:00
GamerClassN7
1d44bd62e2 Pugins Fixes + Dame Jídlo Fix 2021-02-10 16:13:22 +01:00
GamerClassN7
75dab33c9a Repository Statistic 2021-02-10 16:12:51 +01:00
2410441b88 Keep record of record origin 2021-02-02 12:47:41 +01:00
GamerClassN7
1f49391b36 Google Home api Fix 2021-01-24 19:56:53 +01:00
haitem
c17e3090a8 repairt bug 2021-01-15 13:38:47 +01:00
41 changed files with 859 additions and 2887 deletions

View File

@@ -1,6 +0,0 @@
.git
_FIRMWARE
_INSTALATION
_README_IMG
README.md
.todo

9
.gitignore vendored
View File

@@ -13,9 +13,8 @@ _nemazat/css/font-awesome.min.css
.vscode/ .vscode/
.vscode/sftp.json .vscode/sftp.json
app/updater/*.bin
app/logs/*.log
backup/*.zip
vendor/ vendor/
logs/*.log
updater/*.bin
backup/*.zip

1
.todo
View File

@@ -11,3 +11,4 @@
//TODO: Fix Default Room selection //TODO: Fix Default Room selection
//TODO: Fix User Delete button //TODO: Fix User Delete button
//TODO: Fix new add email form //TODO: Fix new add email form
//BUG: API RETURN ERROR VHEN NO ROOM IS PRESENT

View File

@@ -1,255 +0,0 @@
<pre>
<?php
var_dump($_POST);
var_dump(file_exists("./app/updater/" . "3C71BF22FDCF" . ".bin"));
?>
</pre>
<form class="" action="" method="post">
<label for="operator">Typ podmínky</label>
<select class="" name="operator">
<option value="or">OR</option>
<option value="and">AND</option>
</select>
<div class="variableArea">
<button name="addButton" id="addButton">+</button>
</div>
<br>
<label for="resetOperator">Typ podmínky</label>
<select class="" name="resetOperator">
<option value="or">OR</option>
<option value="and">AND</option>
</select>
<div class="resetvariableArea">
<button name="restartaAddButton" id="restartAddButton">+</button>
</div>
<br>
<button type="submit" name="button">Odeslat</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
function foo(element){
var id = element.attr("name").match(/\d+/)[0]
$("[name='variable["+id+"][value]']").remove();
$("[name='variable["+id+"][equaler]']").remove();
if (element.val() == "atDeviceValue") {
var arrVarOperator = [
{val : '>', text: '>'},
{val : '<', text: '<'},
];
var varOperator = $('<select name="variable['+id+'][equaler]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
element.parent().append(varOperator);
var input = $("<input/>");
input.attr("type","text");
input.attr("name","variable["+id+"][value]");
element.parent().append(input);
} else if (element.val() == "time") {
var arrVarOperator = [
{val : '>', text: '>'},
{val : '<', text: '<'},
];
var varOperator = $('<select name="variable['+id+'][equaler]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
element.parent().append(varOperator);
var input = $("<input/>");
input.attr("type","time");
input.attr("name","variable["+id+"][value]");
element.parent().append(input);
}else {
var arrVarOperator = [
{val : '=', text: '=='},
{val : '!=', text: '!='},
];
var varOperator = $('<select name="variable['+id+'][equaler]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
element.parent().append(varOperator);
var arrVarValue = [
{val : 'true', text: 'True'},
{val : 'false', text: 'False'},
];
var varValue = $('<select name="variable['+id+'][value]">');
$(arrVarValue).each(function() {
varValue.append($('<option>').attr('value',this.val).text(this.text));
});
element.parent().append(varValue);
}
}
$("#addButton,#restartAddButton").click( function (event) {
event.preventDefault();
var numItems = $('.var').length
var arrVarSelect = [
{val : 'sunSet', text: 'Západ Slunce'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'inHome', text: 'Příchod'},
{val : 'outHome', text: 'Odchod'},
{val : 'time', text: 'Čas'},
{val : 'atDeviceValue', text: 'Při hodnotě zařízení'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'noOneHome', text: 'Nikdo Doma'},
{val : 'someOneHome', text: 'Nekdo Doma'},
];
var varSelect = $('<select name="variable['+numItems+'][what]">');
$(arrVarSelect).each(function() {
varSelect.append($('<option>').attr('value',this.val).text(this.text));
});
varSelect.attr("onchange", "foo($(this))");
/*onchange = function(e) {
console.log(this.value);
if (this.value == 'atDeviceValue') {
alert("ok");
}
};*/
var arrVarOperator = [
{val : '>', text: '>'},
{val : '<', text: '<'},
{val : '=', text: '=='},
{val : '!=', text: '!='},
];
var varOperator = $('<select name="variable['+numItems+'][equaler]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
var arrVarValue = [
{val : 'true', text: 'True'},
{val : 'false', text: 'False'},
];
var varValue = $('<select name="variable['+numItems+'][value]">');
$(arrVarValue).each(function() {
varValue.append($('<option>').attr('value',this.val).text(this.text));
});
var newDiv = $("<div class=var>").append(varSelect);
newDiv = newDiv.append(varOperator);
newDiv = newDiv.append(varValue);
$(this).parent().append(newDiv);
});
/*var arrVarSelect = [
{val : 'sunSet', text: 'Západ Slunce'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'inHome', text: 'Příchod'},
{val : 'outHome', text: 'Odchod'},
{val : 'time', text: 'Čas'},
{val : 'atDeviceValue', text: 'Při hodnotě zařízení'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'noOneHome', text: 'Nikdo Doma'},
{val : 'someOneHome', text: 'Nekdo Doma'},
];
var varSelect = $('<select name="variable['+numItems+'][]">');
$(arrVarSelect).each(function() {
varSelect.append($('<option>').attr('value',this.val).text(this.text));
});
var arrVarOperator = [
{val : '>', text: '>'},
{val : '<', text: '<'},
{val : '=', text: '=='},
{val : '!=', text: '!='},
];
var varOperator = $('<select name="variable['+numItems+'][]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
var arrVarValue = [
{val : 'true', text: 'True'},
{val : 'false', text: 'False'},
];
var varValue = $('<select name="variable['+numItems+'][]">');
$(arrVarValue).each(function() {
varValue.append($('<option>').attr('value',this.val).text(this.text));
});
//TODO změna výstupní proměné na základě vstupu date,num etc
var newDiv = $("<div class=var>").append(varSelect);/*.change(
function (subEvent) {
alert(subEvent);
}
);*/
/*newDiv = newDiv.append(varOperator);
newDiv = newDiv.append(varValue);
$(".restartaAddButton")append(newDiv);*/
/*
var arrVarSelect = [
{val : 'sunSet', text: 'Západ Slunce'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'inHome', text: 'Příchod'},
{val : 'outHome', text: 'Odchod'},
{val : 'time', text: 'Čas'},
{val : 'atDeviceValue', text: 'Při hodnotě zařízení'},
{val : 'sunRise', text: 'Východ Slunce'},
{val : 'noOneHome', text: 'Nikdo Doma'},
{val : 'someOneHome', text: 'Nekdo Doma'},
];
var varSelect = $('<select name="variable['+numItems+'][]">');
$(arrVarSelect).each(function() {
varSelect.append($('<option>').attr('value',this.val).text(this.text));
});
var arrVarOperator = [
{val : '>', text: '>'},
{val : '<', text: '<'},
{val : '=', text: '=='},
{val : '!=', text: '!='},
];
var varOperator = $('<select name="variable['+numItems+'][]">');
$(arrVarOperator).each(function() {
varOperator.append($('<option>').attr('value',this.val).text(this.text));
});
var arrVarValue = [
{val : 'true', text: 'True'},
{val : 'false', text: 'False'},
];
var varValue = $('<select name="variable['+numItems+'][]">');
$(arrVarValue).each(function() {
varValue.append($('<option>').attr('value',this.val).text(this.text));
});
//TODO změna výstupní proměné na základě vstupu date,num etc
var newDiv = $("<div class=var>").append(varSelect);/*.change(
function (subEvent) {
alert(subEvent);
}
);*/
/* newDiv = newDiv.append(varOperator);
newDiv = newDiv.append(varValue);
$(".variableArea").parent().append(newDiv);*/
</script>

View File

@@ -136,6 +136,17 @@ Distributed under the MIT License. See `LICENSE` for more information.
Project Link: [https://github.com/GamerClassN7/Smart_Home/](https://github.com/GamerClassN7/Smart_Home/) <br> <br> Project Link: [https://github.com/GamerClassN7/Smart_Home/](https://github.com/GamerClassN7/Smart_Home/) <br> <br>
<sup><sub>Tags (ignore): ESP32 ESP12 ESP08 ESP01 ESP Smart Home Automation System PWA PHP HTML JS DHT11 DHT22 <sup><sub>Tags (ignore): ESP32 ESP12 ESP08 ESP01 ESP Smart Home Automation System PWA PHP HTML JS DHT11 DHT22
## Code Statistics
Type | Files | Lines
-----|-------|-----------
php | 2 | 2298 (89%)
md | 1 | 171 (7%)
js | 1 | 64 (2%)
sh | 1 | 34 (1%)
json | 1 | 10 (0.4%)
-----|-------|-----------
All | 6 | 2577
## Folder structure ## Folder structure
``` ```
- /app # app specific files - /app # app specific files

File diff suppressed because one or more lines are too long

View File

@@ -105,8 +105,6 @@ $apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRI
$apiLogManager->write("[API] POST body\n" . json_encode($_POST, JSON_PRETTY_PRINT), LogRecordTypes::INFO); $apiLogManager->write("[API] POST body\n" . json_encode($_POST, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
$apiLogManager->write("[API] GET body\n" . json_encode($_GET, JSON_PRETTY_PRINT), LogRecordTypes::INFO); $apiLogManager->write("[API] GET body\n" . json_encode($_GET, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
Debugger::flag('dbconnect'); Debugger::flag('dbconnect');
//DB Conector //DB Conector
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME); Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);

View File

@@ -24,37 +24,54 @@ $router->any('/plugins', 'Plugins');
$router->any('/ajax', 'Ajax'); $router->any('/ajax', 'Ajax');
$router->any('/oauth', 'Oauth'); $router->any('/oauth', 'Oauth');
//Vue APP //Vue APP - Authentication
$router->post('/api/login', 'AuthApi@login'); $router->post('/api/login', 'AuthApi@login');
$router->post('/api/logout', 'AuthApi@logout'); $router->post('/api/logout', 'AuthApi@logout');
//Vue APP - Rooms
$router->get('/api/rooms', 'RoomsApi@default'); $router->get('/api/rooms', 'RoomsApi@default');
$router->get('/api/rooms/{roomId}/update', 'RoomsApi@update'); $router->get('/api/rooms/{roomId}/update', 'RoomsApi@update');
$router->get('/api/devices', 'DevicesApi@default'); $router->get('/api/devices', 'DevicesApi@default');
$router->get('/api/plugins', 'PluginsApi@default'); $router->get('/api/plugins', 'PluginsApi@default');
$router->get('/api/users', 'UsersApi@default'); $router->get('/api/users', 'UsersApi@default');
//Vue APP - Server Info
$router->get('/api/server', 'ServerApi@default'); $router->get('/api/server', 'ServerApi@default');
$router->get('/api/server/log', 'ServerApi@logStatus'); $router->get('/api/server/log', 'ServerApi@logStatus');
//Vue APP - Widgets
$router->post('/api/widgets/{widgetId}/run', 'WidgetApi@run'); $router->post('/api/widgets/{widgetId}/run', 'WidgetApi@run');
$router->get('/api/widgets/{widgetId}/detail', 'WidgetApi@detail'); $router->get('/api/widgets/{widgetId}/detail', 'WidgetApi@detail');
$router->get('/api/widgets/{widgetId}/detail/{period}', 'WidgetApi@detail'); $router->get('/api/widgets/{widgetId}/detail/{period}', 'WidgetApi@detail');
//Vue APP - Automations Endpoints
$router->get('/api/automations', 'AutomationsApi@default');
$router->get('/api/automations/{automationId}/detail', 'AutomationsApi@detail');
$router->post('/api/automations/create', 'AutomationsApi@create');
//cron //cron
$router->post('/cron/clean', 'CronApi@clean'); $router->post('/cron/clean', 'CronApi@clean');
$router->post('/cron/fetch', 'CronApi@fetch'); $router->post('/cron/fetch', 'CronApi@fetch');
$router->post('/cron/automations', 'CronApi@automations');
//Google Home - API //Google Home - API
$router->any('/api/HA/auth', 'Oauth'); $router->any('/api/HA/auth', 'Oauth');
$router->any('/api/HA', 'GoogleHomeApi@response'); $router->any('/api/HA', 'GoogleHomeApi@response');
//Endpoints API //Endpoints API
$router->post('/api/endpoint/', 'EndpointsApi@default'); $router->post('/api/endpoint/', 'EndpointsApi@default');
$router->any('/api/update/', 'UpdatesApi@default'); $router->any('/api/update/', 'UpdatesApi@default');
$router->any('/api/users/status', 'UsersApi@status'); $router->any('/api/users/status', 'UsersApi@status');
$router->any('/api/users/subscribe', 'UsersApi@subscribe'); $router->any('/api/users/subscribe', 'UsersApi@subscribe');
// examples // examples
$router->any('/api/example', 'ExampleApi@example'); $router->any('/api/example', 'ExampleApi@example');
$router->any('/example', 'ExampleController@index'); $router->any('/example', 'ExampleController@index');

View File

@@ -0,0 +1,44 @@
<?php
class AutomationsApi extends ApiController
{
public function default()
{
//$this->requireAuth();
$response = [];
$response = AutomationManager::getAll(["automation_id","name","enabled"]);
$this->response($response);
}
public function detail($automationId)
{
//$this->requireAuth();
$response = [];
$response = AutomationManager::getById($automationId, ["automation_id", "last_execution_time", "owner_id", "conditions", "tasks"]);
$this->response($response);
}
public function create()
{
$this->requireAuth();
$obj = $this->input;
if (
empty($obj['name']) ||
!isset($obj['name']) ||
!isset($obj['conditions']) ||
!isset($obj['tasks']) ||
!isset($obj['days'])
) {
throw new Exception("Invalid request payload", 400);
}
$response = [];
$response = AutomationManager::create($obj['name'],json_encode($obj['days']), json_encode($obj['tasks']), json_encode($obj['conditions']));
$this->response(['value'=>'OK']);
}
}

View File

@@ -20,8 +20,7 @@ class CronApi extends ApiController
$this->response(['Value' => 'OK']); $this->response(['Value' => 'OK']);
} }
public function fetch() public function fetch(){
{
//Run Plugins //Run Plugins
$result = []; $result = [];
$dir = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/'; $dir = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/';
@@ -60,4 +59,9 @@ class CronApi extends ApiController
//Print Result //Print Result
$this->response($result); $this->response($result);
} }
public function automations(){
AutomationManager:executeAll();
$this->response(['Value' => 'OK']);
}
} }

View File

@@ -78,7 +78,9 @@ class EndpointsApi extends ApiController{
foreach ($obj['logs'] as $log) { foreach ($obj['logs'] as $log) {
$deviceLogManager = new LogManager('../logs/devices/'. date("Y-m-d").'.log'); $deviceLogManager = new LogManager('../logs/devices/'. date("Y-m-d").'.log');
$deviceLogManager->setLevel(LOGLEVEL); $deviceLogManager->setLevel(LOGLEVEL);
if ($log != 'HTTP_UPDATE_FAILD code-102 messageFile Not Found (404)'){
$deviceLogManager->write("[Device Log Msg] Device_ID " . $device['device_id'] . "->" . $log, LogRecordTypes::ERROR); $deviceLogManager->write("[Device Log Msg] Device_ID " . $device['device_id'] . "->" . $log, LogRecordTypes::ERROR);
}
unset($deviceLogManager); unset($deviceLogManager);
} }
$this->response([ $this->response([
@@ -113,7 +115,7 @@ class EndpointsApi extends ApiController{
} }
$subDeviceLastReordValue[$key] = $value['value']; $subDeviceLastReordValue[$key] = $value['value'];
RecordManager::create($device['device_id'], $key, round($value['value'],3)); RecordManager::create($device['device_id'], $key, round($value['value'],3), 'device');
$logManager->write("[API] Device_ID " . $device['device_id'] . " writed value " . $key . ' ' . $value['value'], LogRecordTypes::INFO); $logManager->write("[API] Device_ID " . $device['device_id'] . " writed value " . $key . ' ' . $value['value'], LogRecordTypes::INFO);
//notification //notification

View File

@@ -54,6 +54,7 @@ class RoomsApi extends ApiController
foreach ($roomsData as $roomKey => $roomData) { foreach ($roomsData as $roomKey => $roomData) {
if ($roomData['device_count'] == 0) continue; if ($roomData['device_count'] == 0) continue;
$subDevicesSorted = isset($subDevicesData[$roomData['room_id']]) ? Utilities::sortArrayByKey($subDevicesData[$roomData['room_id']], 'connection_error', 'asc') : []; $subDevicesSorted = isset($subDevicesData[$roomData['room_id']]) ? Utilities::sortArrayByKey($subDevicesData[$roomData['room_id']], 'connection_error', 'asc') : [];
if (count($subDevicesSorted) == 0) continue;
$response[] = [ $response[] = [
'room_id' => $roomData['room_id'], 'room_id' => $roomData['room_id'],
'name' => $roomData['name'], 'name' => $roomData['name'],

View File

@@ -14,7 +14,7 @@ class WidgetApi extends ApiController
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId); $subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
if ($subDeviceData['type'] == 'on/off') { if ($subDeviceData['type'] == 'on/off') {
$lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value']; $lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'];
RecordManager::create($subDeviceData['device_id'], 'on/off', (int) !$lastValue); RecordManager::create($subDeviceData['device_id'], 'on/off', (int) !$lastValue, "vue-app");
$response = !$lastValue; $response = !$lastValue;
} else { } else {
throw new Exception("Bad Request", 403); throw new Exception("Bad Request", 403);

View File

@@ -28,6 +28,9 @@ if (!empty ($_POST)){
if (!empty ($_POST['deviceName']) && !empty ($_POST['deviceId'])) { if (!empty ($_POST['deviceName']) && !empty ($_POST['deviceId'])) {
$deviceManager->edit ($_POST['deviceId'], array ('name' => $_POST['deviceName'])); $deviceManager->edit ($_POST['deviceId'], array ('name' => $_POST['deviceName']));
} }
if (!empty ($_POST['deviceApproved']) && !empty ($_POST['deviceId'])) {
$deviceManager->edit ($_POST['deviceId'], array ('approved' => $_POST['deviceApproved']));
}
if (isset ($_POST['deviceHistory']) && !empty ($_POST['deviceId'])) { if (isset ($_POST['deviceHistory']) && !empty ($_POST['deviceId'])) {
$subDeviceManager->editSubDevicesByDevice($_POST['deviceId'], array ('history' => $_POST['deviceHistory'])); $subDeviceManager->editSubDevicesByDevice($_POST['deviceId'], array ('history' => $_POST['deviceHistory']));
} }

View File

@@ -1,6 +1,7 @@
<?php <?php
if (isset($_POST) && !empty($_POST)){ if (isset($_POST) && !empty($_POST)){
$userManager = new UserManager(); $userManager = new UserManager();
$roomManager = new RoomManager();
if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") { if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") {
$oldPassword = $_POST['oldPassword']; $oldPassword = $_POST['oldPassword'];
$newPassword = $_POST['newPassword1']; $newPassword = $_POST['newPassword1'];
@@ -30,6 +31,10 @@ if (isset($_POST) && !empty($_POST)){
$userManager->setUserDataAdmin("permission", $_POST['userPermission'], $_POST['userID']); $userManager->setUserDataAdmin("permission", $_POST['userPermission'], $_POST['userID']);
header('Location: ' . BASEURL . 'setting'); header('Location: ' . BASEURL . 'setting');
die(); die();
} if (isset ($_POST['roomName']) && !empty ($_POST['roomId'])) {
$roomManager->edit($_POST['roomId'], array("name" => $_POST['roomName']));
header('Location: ' . BASEURL . 'setting');
die();
} else { } else {
foreach ($_POST as $key => $value) { foreach ($_POST as $key => $value) {
if ($key == 'submit') continue; if ($key == 'submit') continue;

View File

@@ -112,7 +112,7 @@ class Form {
* [render function whitch dysplay generated form] * [render function whitch dysplay generated form]
*/ */
function render(){ function render(){
self::addInput(InputTypes::SUBMIT, 'formSubmit', '', 'Submit', 'Submit'); self::addInput(InputTypes::SUBMIT, 'formSubmit', '', '', 'Submit');
$form = '<form '.$this->formName.$this->formId.$this->method.$this->action.'">'; $form = '<form '.$this->formName.$this->formId.$this->method.$this->action.'">';
$form .= $this->formContent; $form .= $this->formContent;
$form .= '</form>'; $form .= '</form>';

View File

@@ -1,6 +1,8 @@
<?php <?php
class GoogleHome { class GoogleHome
static function sync($requestId){ {
static function sync($requestId)
{
$devices = []; $devices = [];
$roomsData = RoomManager::getAllRooms(); $roomsData = RoomManager::getAllRooms();
foreach ($roomsData as $roomKey => $roomData) { foreach ($roomsData as $roomKey => $roomData) {
@@ -64,19 +66,21 @@ class GoogleHome {
echo json_encode($response); echo json_encode($response);
} }
static function query($requestId, $payload){ static function query($requestId, $payload)
{
$devices = []; $devices = [];
$num = 0; $num = 0;
foreach ($payload['devices'] as $deviceId) { foreach ($payload['devices'] as $deviceId) {
$subDevicesData = SubDeviceManager::getAllSubDevices($deviceId['id']);
$tempDevice[$deviceId['id']] = [ $tempDevice[$deviceId['id']] = [
'online' => false, 'online' => false,
'status' => 'OFFLINE', 'status' => 'OFFLINE',
]; ];
if ($subDevicesData = SubDeviceManager::getAllSubDevices($deviceId['id'])) {
foreach ($subDevicesData as $key => $subDeviceData) { foreach ($subDevicesData as $key => $subDeviceData) {
$lastRecord = RecordManager::getLastRecord($subDeviceData['subdevice_id']); $lastRecord = RecordManager::getLastRecord($subDeviceData['subdevice_id']);
if ($lastRecord['execuded'] == 1){ if ($lastRecord != false && $lastRecord['execuded'] == 1) {
$tempDevice[$deviceId['id']]['online'] = true; $tempDevice[$deviceId['id']]['online'] = true;
$tempDevice[$deviceId['id']]['status'] = "SUCCESS"; $tempDevice[$deviceId['id']]['status'] = "SUCCESS";
} else { } else {
@@ -121,11 +125,14 @@ class GoogleHome {
break; break;
} }
} }
}
if ($lastRecord['execuded'] == 1){ // $lastRecord = RecordManager::getLastRecord($deviceId['id']);
$online = true; // //var_dump($lastRecord);
$status = 'SUCCESS'; // if ($lastRecord['execuded'] == 1) {
} else { // $online = true;
// $status = 'SUCCESS';
// } else {
$executed = 0; $executed = 0;
$waiting = 0; $waiting = 0;
foreach (RecordManager::getLastRecord($deviceId['id'], 6) as $key => $value) { foreach (RecordManager::getLastRecord($deviceId['id'], 6) as $key => $value) {
@@ -135,15 +142,16 @@ class GoogleHome {
$waiting++; $waiting++;
} }
} }
if ($waiting < $executed) { if ($waiting < $executed) {
$status = "PENDING"; $status = "PENDING";
$online = true; $online = true;
} }
} // }
$devices = $tempDevice; $devices = $tempDevice;
/*if (count($devices)> 1){ if (count($devices)> 1){
$devices[] = $tempDevice; $devices[] = $tempDevice;
}*/ }
} }
$response = [ $response = [
'requestId' => $requestId, 'requestId' => $requestId,
@@ -157,7 +165,8 @@ class GoogleHome {
echo json_encode($response); echo json_encode($response);
} }
static function execute($requestId, $payload){ static function execute($requestId, $payload)
{
$commands = []; $commands = [];
foreach ($payload['commands'] as $key => $command) { foreach ($payload['commands'] as $key => $command) {
foreach ($command['devices'] as $key2 => $device) { foreach ($command['devices'] as $key2 => $device) {
@@ -167,7 +176,8 @@ static function execute($requestId, $payload){
} }
$deviceType = GoogleHomeDeviceTypes::getType($executionCommand['command']); $deviceType = GoogleHomeDeviceTypes::getType($executionCommand['command']);
$subDeviceId = SubDeviceManager::getSubDeviceByMasterAndType($device['id'], $deviceType)['subdevice_id']; if ($subDeviceId = SubDeviceManager::getSubDeviceByMasterAndType($device['id'], $deviceType)) {
$subDeviceId = $subDeviceId['subdevice_id'];
switch ($executionCommand['command']) { switch ($executionCommand['command']) {
case 'action.devices.commands.OnOff': case 'action.devices.commands.OnOff':
$commands[] = self::executeSwitch($subDeviceId, $executionCommand); $commands[] = self::executeSwitch($subDeviceId, $executionCommand);
@@ -212,9 +222,10 @@ static function execute($requestId, $payload){
case 'action.devices.commands.mediaStop': case 'action.devices.commands.mediaStop':
$commands[] = self::executeMediaCont($subDeviceId, $executionCommand); $commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
break; break;
} }
} }
}
} }
$response = [ $response = [
'requestId' => $requestId, 'requestId' => $requestId,
@@ -230,14 +241,15 @@ static function execute($requestId, $payload){
echo json_encode($response); echo json_encode($response);
} }
static function executeSwitch($subDeviceId, $executionCommand){ static function executeSwitch($subDeviceId, $executionCommand)
{
$value = 0; $value = 0;
$status = 'OFFLINE'; $status = 'OFFLINE';
$online = false; $online = false;
if ($executionCommand['params']['on']) $value = 1; if ($executionCommand['params']['on']) $value = 1;
RecordManager::createWithSubId($subDeviceId, $value); RecordManager::createWithSubId($subDeviceId, $value, 'google');
$executed = 0; $executed = 0;
$waiting = 0; $waiting = 0;
@@ -266,7 +278,8 @@ static function executeSwitch($subDeviceId, $executionCommand){
return $commandTemp; return $commandTemp;
} }
static function executeTermostatValue($subDeviceId, $executionCommand){ static function executeTermostatValue($subDeviceId, $executionCommand)
{
$value = 0; $value = 0;
$status = 'OFFLINE'; $status = 'OFFLINE';
$online = false; $online = false;
@@ -275,7 +288,7 @@ static function executeTermostatValue($subDeviceId, $executionCommand){
$value = $executionCommand['params']['thermostatTemperatureSetpoint']; $value = $executionCommand['params']['thermostatTemperatureSetpoint'];
} }
RecordManager::createWithSubId($subDeviceId, $value); RecordManager::createWithSubId($subDeviceId, $value, 'google');
$executed = 0; $executed = 0;
$waiting = 0; $waiting = 0;
@@ -307,7 +320,8 @@ static function executeTermostatValue($subDeviceId, $executionCommand){
return $commandTemp; return $commandTemp;
} }
static function executeTermostatMode($subDeviceId, $executionCommand){ static function executeTermostatMode($subDeviceId, $executionCommand)
{
$mode = "off"; $mode = "off";
$value = 0; $value = 0;
$status = 'OFFLINE'; $status = 'OFFLINE';
@@ -318,7 +332,7 @@ static function executeTermostatMode($subDeviceId, $executionCommand){
$value = RecordManager::getLastRecordNotNull($subDeviceId)['value']; $value = RecordManager::getLastRecordNotNull($subDeviceId)['value'];
} }
RecordManager::createWithSubId($subDeviceId, $value); RecordManager::createWithSubId($subDeviceId, $value, 'google');
$executed = 0; $executed = 0;
$waiting = 0; $waiting = 0;
@@ -348,7 +362,8 @@ static function executeTermostatMode($subDeviceId, $executionCommand){
return $commandTemp; return $commandTemp;
} }
static function executeVolume($subDeviceId, $executionCommand){ static function executeVolume($subDeviceId, $executionCommand)
{
//echo $executionCommand['params']['volumeLevel']; //echo $executionCommand['params']['volumeLevel'];
$status = 'OFFLINE'; $status = 'OFFLINE';
$online = false; $online = false;
@@ -386,7 +401,8 @@ static function executeVolume($subDeviceId, $executionCommand){
return $commandTemp; return $commandTemp;
} }
static function executeApp($subDeviceId, $executionCommand){ static function executeApp($subDeviceId, $executionCommand)
{
//echo $executionCommand['params']['newApplication']; //echo $executionCommand['params']['newApplication'];
$status = 'OFFLINE'; $status = 'OFFLINE';
$online = false; $online = false;
@@ -424,7 +440,8 @@ static function executeApp($subDeviceId, $executionCommand){
return $commandTemp; return $commandTemp;
} }
static function executeInput($subDeviceId, $executionCommand){ static function executeInput($subDeviceId, $executionCommand)
{
//echo $executionCommand['params']['newInput']; //echo $executionCommand['params']['newInput'];
$status = 'OFFLINE'; $status = 'OFFLINE';
$online = false; $online = false;
@@ -462,7 +479,8 @@ static function executeInput($subDeviceId, $executionCommand){
return $commandTemp; return $commandTemp;
} }
static function executeMediaCont($subDeviceId, $executionCommand){ static function executeMediaCont($subDeviceId, $executionCommand)
{
$status = 'SUCCESS'; $status = 'SUCCESS';
$online = true; $online = true;

View File

@@ -8,23 +8,23 @@ class AutomationManager{
} }
public static function deactive($automationId) { public static function deactive($automationId) {
$automation = Db::loadOne ("SELECT * FROM automation WHERE automation_id=?" , array ($automationId)); $automation = self::getById($automationId,["enabled"]);
$flipedValue = ($automation['active'] == 1 ? 0 : 1); $flipedValue = ($automation['enabled'] == 1 ? 0 : 1);
return Db::command ('UPDATE automation SET active = ? WHERE automation_id=?', array ($flipedValue,$automationId)); return Db::command ('UPDATE automation SET enabled = ? WHERE automation_id=?', array ($flipedValue,$automationId));
} }
public static function restart($automationId) { public static function restart($automationId) {
return Db::command ('UPDATE automation SET executed = 0 WHERE automation_id=?', array ($automationId)); return Db::command ('UPDATE automation SET executed = 0 WHERE automation_id=?', array ($automationId));
} }
public static function create ($name, $onDays, $doCode, $ifCode, $automationId = "") { public static function create ($name, $onDays, $doCode, $ifCode, $userId = 1, $automationId = "") {
$userId = UserManager::getUserData('user_id'); $userId = UserManager::getUserData('user_id', $userId);
$scene = array ( $scene = array (
'name' => $name, 'name' => $name,
'owner_id' => $userId, 'owner_id' => $userId,
'on_days' => $onDays, 'on_days' => $onDays,
'if_something' => $ifCode, 'conditions' => $ifCode,
'do_something' => $doCode, 'tasks' => $doCode,
); );
try { try {
if ($automationId == "") { if ($automationId == "") {
@@ -34,19 +34,24 @@ class AutomationManager{
} }
} catch(PDOException $error) { } catch(PDOException $error) {
echo $error->getMessage(); echo $error->getMessage();
return false;
die(); die();
} }
} }
public static function getAll(){ public static function getAll($collums = ['*']){
return Db::loadAll ("SELECT * FROM automation"); return Db::loadAll ("SELECT ". implode("," , $collums)." FROM automation");
}
public static function getById($automationId, $collums = ['*']){
return Db::loadOne("SELECT ". implode("," , $collums)." FROM automation WHERE automation_id = ?", [$automationId]);
} }
public static function executeAll(){ public static function executeAll(){
global $logManager; global $logManager;
$automations = Db::loadAll ("SELECT * FROM automation"); /*$automations = Db::loadAll ("SELECT * FROM automation");
$dayNameNow = strtolower (date('D', time())); $dayNameNow = strtolower (date('D', time()));
foreach ($automations as $automation) { foreach ($automations as $automation) {
@@ -170,6 +175,6 @@ class AutomationManager{
Db::edit('automation', array('locked' => 0), 'WHERE automation_id = ?', array($automation['automation_id'])); Db::edit('automation', array('locked' => 0), 'WHERE automation_id = ?', array($automation['automation_id']));
} }
} }
} }*/
} }
} }

View File

@@ -0,0 +1,29 @@
<?php
class PluginManager
{
public function load(){
$dir = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . '/backup/';
$pluginsFiles = scandir ($dir);
foreach ($pluginsFiles as $key => $pluginFile) {
$className = str_replace(".zip", "", $pluginsFiles);
if(class_exists($className)){
(new $className)->make();
}
}
$sleepTime = DeviceManager::getDeviceById($deviceId)['sleep_time'];
$LastRecordTime = new DateTime(RecordManager::getLastRecord($subDeviceId, 1)['time']);
$interval = $LastRecordTime->diff(new DateTime());
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
$lastSeen = ($hours * 60 + $minutes);
if ($lastSeen > $sleepTime || $sleepTime == 0) {
return true;
}
return false;
}
}

View File

@@ -2,16 +2,21 @@
class RecordManager{ class RecordManager{
public static $records; public static $records;
public static function createWithSubId ($subDeviceId, $value) { public static function createWithSubId ($subDeviceId, $value, $origin = false) {
try { try {
$record = [ $record = [
'execuded' => 1, 'execuded' => 1,
]; ];
Db::edit ('records', $record, 'WHERE subdevice_id = ?', array ($subDeviceId)); Db::edit ('records', $record, 'WHERE subdevice_id = ?', array ($subDeviceId));
$record = array ( $record = array (
'subdevice_id' => $subDeviceId, 'subdevice_id' => $subDeviceId,
'value' => $value, 'value' => $value,
); );
if ($origin != false)
$record['Origin'] = $origin;
return Db::add ('records', $record); return Db::add ('records', $record);
} catch(PDOException $error) { } catch(PDOException $error) {
echo $error->getMessage(); echo $error->getMessage();
@@ -19,7 +24,7 @@ class RecordManager{
} }
} }
public static function create ($deviceId, $type, $value) { public static function create ($deviceId, $type, $value, $origin = false) {
$subDeviceId = Db::loadOne('SELECT * FROM subdevices WHERE device_id = ? AND type = ?;', array($deviceId, $type))['subdevice_id']; $subDeviceId = Db::loadOne('SELECT * FROM subdevices WHERE device_id = ? AND type = ?;', array($deviceId, $type))['subdevice_id'];
if ($subDeviceId == '') { if ($subDeviceId == '') {
return false; return false;
@@ -28,7 +33,7 @@ class RecordManager{
//Ochrana proti duplicitním hodnotám zapisují se jen změny //Ochrana proti duplicitním hodnotám zapisují se jen změny
$lastRecord = self::getLastRecord($subDeviceId, 1); $lastRecord = self::getLastRecord($subDeviceId, 1);
if ($lastRecord['value'] == $value){ if (isset($lastRecord['value']) && $lastRecord['value'] == $value){
return false; return false;
} }
@@ -42,6 +47,10 @@ class RecordManager{
'subdevice_id' => $subDeviceId, 'subdevice_id' => $subDeviceId,
'value' => $value, 'value' => $value,
); );
if ($origin != false)
$record['Origin'] = $origin;
return Db::add ('records', $record); return Db::add ('records', $record);
} catch(PDOException $error) { } catch(PDOException $error) {
echo $error->getMessage(); echo $error->getMessage();
@@ -87,7 +96,7 @@ class RecordManager{
$dateTime = $dateTime->modify($periodLocal); $dateTime = $dateTime->modify($periodLocal);
$dateTime = $dateTime->format('Y-m-d H:i:s'); $dateTime = $dateTime->format('Y-m-d H:i:s');
$groupBy = strtoupper($groupBy).'(time)'; $groupBy = strtoupper($groupBy).'(time)';
$sql = 'SELECT value, time, execuded FROM records $sql = 'SELECT value, time, execuded, origin FROM records
WHERE WHERE
subdevice_id = ? subdevice_id = ?
AND AND

View File

@@ -37,6 +37,15 @@ class RoomManager{
} }
} }
public static function edit ($roomId, $values = []) {
try {
Db::edit ('rooms', $values, 'WHERE room_id = ?', array($roomId));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public static function delete ($roomId) { public static function delete ($roomId) {
Db::command ('DELETE FROM rooms WHERE room_id=?', array ($roomId)); Db::command ('DELETE FROM rooms WHERE room_id=?', array ($roomId));
} }

View File

@@ -66,10 +66,6 @@ class SubDeviceManager
} }
} }
public static function editSubDevicesByDevice ($deviceId, $subDeviceParameters) {
DB::edit('subdevices', $subDeviceParameters, 'WHERE device_id=?', array ($deviceId));
}
public static function remove($subDeviceId) public static function remove($subDeviceId)
{ {
RecordManager::cleanSubdeviceRecords($subDeviceId); RecordManager::cleanSubdeviceRecords($subDeviceId);

View File

@@ -22,7 +22,7 @@ class AirQuality extends VirtualDeviceManager
$finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id); $finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id);
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true); $json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi']); RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi'], 'plugin');
} else { } else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual'); DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');
DeviceManager::approved($this->virtual_device_name); DeviceManager::approved($this->virtual_device_name);

View File

@@ -0,0 +1,11 @@
<?php
class ExamplePlugin extends VirtualDeviceManager
{
function make(){
//Getting Data
}
function translate($value){
//Translation of numeric values
}
}

39
app/plugins/!_Covid.php Normal file
View File

@@ -0,0 +1,39 @@
<?php
class Covid extends VirtualDeviceManager
{
private $country_sluig = "czech-republic";
private $api_uri = 'https://api.covid19api.com/live/country/%s/status/confirmed'; // Your redirect uri
private $virtual_device_name = "Covid";
function make()
{
try {
if (DeviceManager::registeret($this->virtual_device_name)) {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
$dataItems = ['Confirmed', 'Deaths', 'Recovered', 'Active'];
foreach ($dataItems as $dataItem) {
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) {
SubDeviceManager::create($deviceId, strtolower($dataItem), $dataItem);
sleep(1);
$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem));
}
}
if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die();
$finalUrl = sprintf($this->api_uri, $this->country_sluig);
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
foreach ($dataItems as $dataItem) {
RecordManager::create($deviceId, strtolower($dataItem), end($json)[$dataItem]);
}
} else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');
DeviceManager::approved($this->virtual_device_name);
}
return 'sucessful';
} catch (Exception $e) {
return 'exception: ' . $e->getMessage();
}
}
}

View File

@@ -9,14 +9,6 @@ class AirQuality extends VirtualDeviceManager
function make() function make()
{ {
//Register the settings
$settingMng = new SettingsManager();
if (!($settingField = $settingMng->getByName("airquality"))) {
$settingMng->create("token", "", "airquality");
} else {
$app_id = $settingField['value'];
}
try { try {
if (DeviceManager::registeret($this->virtual_device_name)) { if (DeviceManager::registeret($this->virtual_device_name)) {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
@@ -30,7 +22,7 @@ class AirQuality extends VirtualDeviceManager
$finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id); $finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id);
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true); $json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi']); RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi'], 'plugin');
} else { } else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual'); DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');
DeviceManager::approved($this->virtual_device_name); DeviceManager::approved($this->virtual_device_name);

View File

@@ -31,7 +31,7 @@ class CovidV2 extends VirtualDeviceManager
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true)['data']; $json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true)['data'];
foreach ($dataItems as $dataItem) { foreach ($dataItems as $dataItem) {
RecordManager::create($deviceId, strtolower($dataItem), end($json)[$this->name_index[$dataItem]]); RecordManager::create($deviceId, strtolower($dataItem), end($json)[$this->name_index[$dataItem]], 'plugin');
} }
} else { } else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, strtolower($this->virtual_device_name)); DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, strtolower($this->virtual_device_name));

85
app/plugins/DameJidlo.php Normal file
View File

@@ -0,0 +1,85 @@
<?php
class DameJidlo extends VirtualDeviceManager
{
private $virtual_device_name = "Dáme Jídlo";
private $device_type = "virtual-device";
private $subdevice_type = "dame-jidlo";
public function deliveryTime($token)
{
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://cz.fd-api.com/api/v5/tracking/active-orders?time_variation=Variation2');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
$headers = array();
$headers[] = 'Authority: cz.fd-api.com';
$headers[] = 'Sec-Ch-Ua: \"Chromium\";v=\"88\", \"Google Chrome\";v=\"88\", \";Not A Brand\";v=\"99\"';
$headers[] = 'Accept: application/json, text/plain, */*';
$headers[] = 'Authorization: Bearer ' . $token;
$headers[] = 'X-Pd-Language-Id: 2';
$headers[] = 'Sec-Ch-Ua-Mobile: ?0';
$headers[] = 'X-Fp-Api-Key: volo';
$headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36';
$headers[] = 'Origin: https://www.damejidlo.cz';
$headers[] = 'Sec-Fetch-Site: cross-site';
$headers[] = 'Sec-Fetch-Mode: cors';
$headers[] = 'Sec-Fetch-Dest: empty';
$headers[] = 'Referer: https://www.damejidlo.cz/';
$headers[] = 'Accept-Language: en-US,en;q=0.9,cs-CZ;q=0.8,cs;q=0.7';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
var_dump(isset(json_decode($result, true)['data']['active_orders'][0]['delivery']['time']['eta']) ? json_decode($result, true)['data']['active_orders'][0]['delivery']['time']['eta'] : 0);
return (isset(json_decode($result, true)['data']['active_orders'][0]['delivery']['time']['eta']) ? json_decode($result, true)['data']['active_orders'][0]['delivery']['time']['eta'] : 0);
}
function make()
{
//Register the settings
$settingMng = new SettingsManager();
if (!($settingField = $settingMng->getByName("damejidlo_token","damejidlo"))) {
$settingMng->create("damejidlo_token", "", "damejidlo");
} else {
$bearer = $settingField['value'];
}
try {
if (DeviceManager::registeret($this->virtual_device_name)) {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) {
SubDeviceManager::create($deviceId, $this->subdevice_type, '');
sleep(1);
$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($this->subdevice_type));
}
//if (!$this->fetchEnabled($deviceId,$subDevice['subdevice_id'])) die();
RecordManager::create($deviceId, $this->subdevice_type, $this->deliveryTime($bearer), 'plugin');
} else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');
DeviceManager::approved($this->virtual_device_name);
}
return 'sucessful';
} catch (Exception $e) {
return 'exception: ' . $e->getMessage();
}
}
function translate($value){
if ($value == 0) {
return " Delivered";
} else if ($value <= 1) {
return "less " . $value;
}
return $value;
}
}

View File

@@ -3,6 +3,19 @@ class DatabaseBackup
{ {
public function make() public function make()
{ {
//Register the settings
$time = '00:00';
$settingMng = new SettingsManager();
if (!($settingField = $settingMng->getByName("backup_time","db_backup"))) {
$settingMng->create("backup_time", $time, "db_backup");
} else {
$time = $settingField['value'];
}
//Time to Backup ?
if (date("H:i",time()) != $time)
return 'pending';
try { try {
$filenames = []; $filenames = [];
$backupWorker = new DatabaseBackup; $backupWorker = new DatabaseBackup;
@@ -19,6 +32,7 @@ class DatabaseBackup
private function data() private function data()
{ {
$backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . "/backup/" . DBNAME . '_data_' . date("Y-m-d", time()) . '.sql'; $backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . "/backup/" . DBNAME . '_data_' . date("Y-m-d", time()) . '.sql';
if (file_exists($backupfile)) return null;
$command = "mysqldump --skip-comments --no-create-info -h localhost -u " . DBUSER . " -p" . DBPASS . " " . DBNAME . " -r $backupfile 2>&1"; $command = "mysqldump --skip-comments --no-create-info -h localhost -u " . DBUSER . " -p" . DBPASS . " " . DBNAME . " -r $backupfile 2>&1";
$this->executeCommand($command); $this->executeCommand($command);
return $backupfile; return $backupfile;
@@ -27,6 +41,7 @@ class DatabaseBackup
private function scheme() private function scheme()
{ {
$backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . "/backup/" . DBNAME . '_scheme_' . date("Y-m-d", time()) . '.sql'; $backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . "/backup/" . DBNAME . '_scheme_' . date("Y-m-d", time()) . '.sql';
if (file_exists($backupfile)) return null;
$command = "mysqldump --skip-comments --no-data -h localhost -u " . DBUSER . " -p" . DBPASS . " " . DBNAME . " -r $backupfile 2>&1"; $command = "mysqldump --skip-comments --no-data -h localhost -u " . DBUSER . " -p" . DBPASS . " " . DBNAME . " -r $backupfile 2>&1";
$this->executeCommand($command); $this->executeCommand($command);
return $backupfile; return $backupfile;

View File

@@ -29,7 +29,7 @@ class N7Day extends VirtualDeviceManager
$datediff = $now - $your_date; $datediff = $now - $your_date;
$daysUntilN7Day = round($datediff / (60 * 60 * 24)); $daysUntilN7Day = round($datediff / (60 * 60 * 24));
RecordManager::create($deviceId, $this->subdevice_type, $daysUntilN7Day); RecordManager::create($deviceId, $this->subdevice_type, $daysUntilN7Day, 'plugin');
} else { } else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, $this->device_type); DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, $this->device_type);
DeviceManager::approved($this->virtual_device_name); DeviceManager::approved($this->virtual_device_name);

View File

@@ -55,7 +55,7 @@ class OpenWeatherMap extends VirtualDeviceManager
} }
RecordManager::create($deviceId, $this->subdevice_type, $json['weather'][0]['id']); RecordManager::create($deviceId, $this->subdevice_type, $json['weather'][0]['id'], 'plugin');
} else { } else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual'); DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');
DeviceManager::approved($this->virtual_device_name); DeviceManager::approved($this->virtual_device_name);

View File

@@ -52,7 +52,7 @@ class UsaElection extends VirtualDeviceManager
$OnePercent = ($Trump + $Biden + $Unknown) / 100; $OnePercent = ($Trump + $Biden + $Unknown) / 100;
foreach ($dataItems as $Category) { foreach ($dataItems as $Category) {
RecordManager::create($deviceId, strtolower($Category), round(($$Category / $OnePercent))); RecordManager::create($deviceId, strtolower($Category), round(($$Category / $OnePercent)), 'plugin');
} }
} else { } else {
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual'); DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');

View File

@@ -24,7 +24,15 @@ $partial = new Partial('head');
<div class="col-md-9 main-body"> <div class="col-md-9 main-body">
<a class="button is-primary m-1" onClick="$('#modal').removeClass('modal-container-hiden').show();"><?php $LANGMNG->echo('t_createAutomation'); ?></a> <a class="button is-primary m-1" onClick="$('#modal').removeClass('modal-container-hiden').show();"><?php $LANGMNG->echo('t_createAutomation'); ?></a>
<div class="row no-gutters"> <div class="row no-gutters">
<?php foreach ($AUTOMATIONS as $automationId => $automationData) {
<?php
foreach ($AUTOMATIONS as $automationId => $automationData) {
//BUTTON //BUTTON
$partial = new Partial('automationButton'); $partial = new Partial('automationButton');
$partial->prepare('langMng',$LANGMNG); $partial->prepare('langMng',$LANGMNG);
@@ -57,6 +65,28 @@ $partial = new Partial('head');
$partial->prepare('subDevices',$SUBDEVICES); $partial->prepare('subDevices',$SUBDEVICES);
$partial->render(); $partial->render();
$form = new Form('Automation', 'automation-1', 'POST', '');
$form->addInput('text','name', 'name', '', true, true);
$form->addSelect('run-condition', 'run-condition', 'l_run_condition', [
'test' => 'test',
'test1' => 'test',
'test2' => 'test',
'test3' => 'test',
'test4' => 'test',
'test5' => 'test',
], true, true, true);
$form->addInput('button','add-condition', 'add-condition', 'l_condition', true, true);
$form->addSelect('active-time', 'active-time', 'l_run_schedule', [
'all' => 'l_all',
'day' => 'l_day',
'night' => 'l_night',
'custome' => 'l_custome',
], true, true, true);
$form->render();
}?> }?>
<script src="./app/templates/js/automation.js"></script> <script src="./app/templates/js/automation.js"></script>
<?php <?php

View File

@@ -115,6 +115,12 @@
<input type="hidden" name="deviceId" value="<?php echo (!empty($device['device_id']) ? $device['device_id'] : ""); ?>"> <input type="hidden" name="deviceId" value="<?php echo (!empty($device['device_id']) ? $device['device_id'] : ""); ?>">
<button class="fa custom-file-input" <?php echo (!empty($device['command']) && $device['command'] == "reset" ? "style=\"color:red;\"" : ""); ?> type="submit" name="deviceCommand" value="reset" title="Reset">&#xf01e;</button> <button class="fa custom-file-input" <?php echo (!empty($device['command']) && $device['command'] == "reset" ? "style=\"color:red;\"" : ""); ?> type="submit" name="deviceCommand" value="reset" title="Reset">&#xf01e;</button>
<button class="fa custom-file-input" <?php echo (!empty($device['command']) && $device['command'] == "config" ? "style=\"color:red;\"" : ""); ?> type="submit" name="deviceCommand" value="config" title="Config">&#xf013;</button> <button class="fa custom-file-input" <?php echo (!empty($device['command']) && $device['command'] == "config" ? "style=\"color:red;\"" : ""); ?> type="submit" name="deviceCommand" value="config" title="Config">&#xf013;</button>
<?php if (isset($device['approved']) && $device['approved'] == 0) : ?>
<button class="fas fa custom-file-input" type="submit" name="deviceApproved" value="1" title="Approved">&#xf00c;</button>
<?php endif; ?>
<?php if (isset($device['approved']) && $device['approved'] < 2) : ?>
<button class="fas fa custom-file-input" type="submit" name="deviceApproved" value="2" title="Blocked">&#xf00d;</button>
<?php endif; ?>
<div style="float: clear;"></div> <div style="float: clear;"></div>
</form> </form>
<?php endif; ?> <?php endif; ?>

View File

@@ -8,61 +8,27 @@
<div class="field"> <div class="field">
<input class="input" type="text" name="name" required/> <input class="input" type="text" name="name" required/>
</div> </div>
<div class="label"><?php $LANGMNG->echo('l_runAt')?></div>
<div class="field">
<select class="input" name="atSelector" id="valueSelector" required>
<option value="sunSet"><?php $LANGMNG->echo('l_sunSet')?></option>
<option value="sunRise"><?php $LANGMNG->echo('l_sunRice')?></option>
<option value="inHome"><?php $LANGMNG->echo('l_inHome')?></option>
<option value="outHome"><?php $LANGMNG->echo('l_outHome')?></option>
<option value="time"><?php $LANGMNG->echo('l_time')?></option>
<option value="atDeviceValue"><?php $LANGMNG->echo('l_deviceValue');?></option>
<option value="noOneHome"><?php $LANGMNG->echo('w_noOne') . ' ' . $LANGMNG->get('w_neni') . ' ' . $LANGMNG->get('w_home');?></option>
<option value="someOneHome"><?php $LANGMNG->echo('w_someOne') . ' ' . $LANGMNG->get('w_is') . ' ' . $LANGMNG->get('w_home');?></option>
</select>
<input class="input" type="time" name="atTime" id="atTime" disabled/>
<select class="input" name="atDeviceValue" id="atDeviceValue" disabled>
<?php foreach ($SUBDEVICES as $subDeviceKey => $subDeviceValue){ ?>
<option value="<?php echo $subDeviceKey; ?>"><?php echo $subDeviceValue['name']; ?>[<?php echo $subDeviceValue['type']; ?>]</option>
<?php } ?>
</select>
=
<input class="input" type="num" name="atDeviceValueInt" id="atDeviceValueInt" required disabled/>
</div>
<div class="label"><?php $LANGMNG->echo('l_affectedDevices')?></div> <div class="label"><?php $LANGMNG->echo('l_runCondition')?></div>
<div class="field"> <select class="input" name="condOper" id="valueSelector" required>
<select class="input" name="devices[]" multiple> <option value="or"><?php $LANGMNG->echo('l_oneNeedToBeWaild')?></option>
<?php foreach ($SUBDEVICES as $subDeviceKey => $subDeviceValue){ <option value="and"><?php $LANGMNG->echo('l_allNeedToBeWalid')?></option>
if ($subDeviceValue['type'] != 'on/off') continue;?> </select>
<option value="<?php echo $subDeviceValue['masterDevice']; ?>"><?php echo $subDeviceValue['name']; ?></option> <input type="button" class="button" name="addCondition" value="<?php $LANGMNG->echo('b_add')?>"/>
<?php } ?>
<div class="label"><?php $LANGMNG->echo('l_runTask')?></div>
<input type="button" class="button" name="addTask" value="<?php $LANGMNG->echo('b_add')?>"/>
<div class="label"><?php $LANGMNG->echo('l_activeTime')?></div>
<select class="input" name="condOper" id="valueSelector" required>
<option value="allday"><?php $LANGMNG->echo('l_all')?></option>
<option value="daytime"><?php $LANGMNG->echo('l_day')?></option>
<option value="night"><?php $LANGMNG->echo('l_night')?></option>
<option value="custom"><?php $LANGMNG->echo('l_custome')?></option>
</select> </select>
</div> </div>
<div class="label"><?php $LANGMNG->echo('l_atDays')?></div>
<div class="field">
<input type="checkbox" name="day[]" value="mon"/> <?php $LANGMNG->echo('d_monday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="tue"/> <?php $LANGMNG->echo('d_tuesday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="wed"/> <?php $LANGMNG->echo('d_wednesday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="thu"/> <?php $LANGMNG->echo('d_thursday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="fri"/> <?php $LANGMNG->echo('d_friday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="sat"/> <?php $LANGMNG->echo('d_saturday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="sun"/> <?php $LANGMNG->echo('d_sunday'); ?>
</div>
</div>
<input type="submit" class="button" name="modalNext" value="<?php $LANGMNG->echo('b_next')?>"/> <input type="submit" class="button" name="modalNext" value="<?php $LANGMNG->echo('b_next')?>"/>
</form> </form>
</div> </div>

View File

@@ -0,0 +1,69 @@
<div class="modal-container modal-container-hiden" id="modal">
<div class="modal">
<a href=""><i class="fa fa-times close"></i></a>
<h4 class="mb-4"><?php $LANGMNG->echo('t_createAutomation')?></h4>
<form method="post" action="" >
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_nameAt')?></div>
<div class="field">
<input class="input" type="text" name="name" required/>
</div>
<div class="label"><?php $LANGMNG->echo('l_runAt')?></div>
<div class="field">
<select class="input" name="atSelector" id="valueSelector" required>
<option value="sunSet"><?php $LANGMNG->echo('l_sunSet')?></option>
<option value="sunRise"><?php $LANGMNG->echo('l_sunRice')?></option>
<option value="inHome"><?php $LANGMNG->echo('l_inHome')?></option>
<option value="outHome"><?php $LANGMNG->echo('l_outHome')?></option>
<option value="time"><?php $LANGMNG->echo('l_time')?></option>
<option value="atDeviceValue"><?php $LANGMNG->echo('l_deviceValue');?></option>
<option value="noOneHome"><?php $LANGMNG->echo('w_noOne') . ' ' . $LANGMNG->get('w_neni') . ' ' . $LANGMNG->get('w_home');?></option>
<option value="someOneHome"><?php $LANGMNG->echo('w_someOne') . ' ' . $LANGMNG->get('w_is') . ' ' . $LANGMNG->get('w_home');?></option>
</select>
<input class="input" type="time" name="atTime" id="atTime" disabled/>
<select class="input" name="atDeviceValue" id="atDeviceValue" disabled>
<?php foreach ($SUBDEVICES as $subDeviceKey => $subDeviceValue){ ?>
<option value="<?php echo $subDeviceKey; ?>"><?php echo $subDeviceValue['name']; ?>[<?php echo $subDeviceValue['type']; ?>]</option>
<?php } ?>
</select>
=
<input class="input" type="num" name="atDeviceValueInt" id="atDeviceValueInt" required disabled/>
</div>
<div class="label"><?php $LANGMNG->echo('l_affectedDevices')?></div>
<div class="field">
<select class="input" name="devices[]" multiple>
<?php foreach ($SUBDEVICES as $subDeviceKey => $subDeviceValue){
if ($subDeviceValue['type'] != 'on/off') continue;?>
<option value="<?php echo $subDeviceValue['masterDevice']; ?>"><?php echo $subDeviceValue['name']; ?></option>
<?php } ?>
</select>
</div>
<div class="label"><?php $LANGMNG->echo('l_atDays')?></div>
<div class="field">
<input type="checkbox" name="day[]" value="mon"/> <?php $LANGMNG->echo('d_monday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="tue"/> <?php $LANGMNG->echo('d_tuesday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="wed"/> <?php $LANGMNG->echo('d_wednesday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="thu"/> <?php $LANGMNG->echo('d_thursday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="fri"/> <?php $LANGMNG->echo('d_friday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="sat"/> <?php $LANGMNG->echo('d_saturday'); ?>
</div>
<div class="field">
<input type="checkbox" name="day[]" value="sun"/> <?php $LANGMNG->echo('d_sunday'); ?>
</div>
</div>
<input type="submit" class="button" name="modalNext" value="<?php $LANGMNG->echo('b_next')?>"/>
</form>
</div>
</div>

View File

@@ -177,7 +177,12 @@ $partial = new Partial('head');
<tbody> <tbody>
<?php foreach ($ROOMS as $key => $room) { ?> <?php foreach ($ROOMS as $key => $room) { ?>
<tr> <tr>
<td><?php echo $room['name']; ?></td> <td>
<form method="post" action="">
<input type="hidden" name="roomId" value="<?php echo (!empty($room['room_id']) ? $room['room_id'] : ""); ?>">
<input class="input" type="text" onchange="this.form.submit();" name="roomName" value="<?php echo (!empty($room['name']) ? $room['name'] : ""); ?>">
</form>
</td>
<td> <td>
<button name="deleteRoom" type="button" class="button is-danger fa">&#xf1f8;</button> <button name="deleteRoom" type="button" class="button is-danger fa">&#xf1f8;</button>
<button name="defaultRoom" type="button" class="button fa" <?php echo ($room['default'] ? 'disabled' : ''); ?>>&#xf140;</button> <button name="defaultRoom" type="button" class="button fa" <?php echo ($room['default'] ? 'disabled' : ''); ?>>&#xf140;</button>

2
git-stats.ps1 Normal file
View File

@@ -0,0 +1,2 @@
$lines = (ls -r|sls '^\s*(#|$)' -a -n).Count
write-host $lines" of code"

View File

@@ -5,14 +5,14 @@ RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !.css RewriteCond %{REQUEST_FILENAME} !.css
RewriteCond %{REQUEST_FILENAME} !.js RewriteCond %{REQUEST_FILENAME} !.js
RewriteRule (.*) ./index.php?url=$1 [QSA,L] RewriteRule (.*) ./index.php?url=$1#$2 [QSA,L]
#token to HTTP_AUTHORIZATION #token to HTTP_AUTHORIZATION
RewriteCond %{HTTP:Authorization} ^(.*) RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule . - [e=HTTP_AUTHORIZATION:%1] RewriteRule . - [e=HTTP_AUTHORIZATION:%1]
RewriteCond %{HTTPS} off #RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/api/update #RewriteCond %{REQUEST_URI} !^/api/update
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] #RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
AddType application/x-httpd-php .php .phtml AddType application/x-httpd-php .php .phtml

View File

@@ -1,33 +1,3 @@
<?php <?php
/**
* Composer autoload
*/
use Core\Application\Application;
use Core\Configuration\Configurations;
use Illuminate\Container\Container;
require_once __DIR__ . '/../vendor/autoload.php';
$container = new Container();
$container->singleton(
Configurations::class,
Configurations::class
);
/**
* Create application & run
*/
$application = new Application(
$container,
$container->make(Configurations::class)
);
$application->run();
/**
* Bootstrap v1.0
*/
require_once __DIR__ . '/../app/Bootstrap.php'; require_once __DIR__ . '/../app/Bootstrap.php';

View File

@@ -1,64 +0,0 @@
importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase-messaging.js');
/**
* Cache version, change name to force reload
*/
var CACHE_VERSION = 'v1';
/**
* Stuff to put in the cache at install
*/
var CACHE_FILES = [
'templates/automatio.phtml',
'templates/dashboard.phtml',
'templates/home.phtml',
'templates/login.phtml',
'templates/scene.phtml',
'templates/setting.phtml',
'views/Automation.phtml',
'views/Dashboard.phtml',
'views/Home.phtml',
'views/Login.phtml',
'views/Scene.phtml',
'views/Setting.phtml',
'assets/logo.svg'
];
self.addEventListener('install', function(event) {
console.info('Installed');
});
self.addEventListener('push', function(event) {
console.log('Received a push message', event);
if (event && event.data) {
var data = event.data.json();
data = JSON.parse(data.data.notification);
console.log(data);
event.waitUntil(self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon || null
}));
}
});
self.addEventListener('sync', function(event) {
console.info('Event: Sync');
});
self.addEventListener('fetch', function (event) {
});
self.addEventListener("online", function (event) {
});
self.addEventListener("offline", function (event) {
});
self.addEventListener('notificationclick', function(e) {
});