Compare commits
4 Commits
38cc436f4d
...
master
Author | SHA1 | Date | |
---|---|---|---|
|
599ef47cd9 | ||
|
c68c051777 | ||
|
c381261a01 | ||
|
e39efd9176 |
1
.docker
1
.docker
Submodule .docker deleted from 0ee345e496
@@ -3,16 +3,29 @@
|
|||||||
root = true
|
root = true
|
||||||
|
|
||||||
[*]
|
[*]
|
||||||
indent_style = tab
|
tab_width = 4
|
||||||
indent_size = 3
|
|
||||||
end_of_line = lf
|
[*.{php,phpt,inc}]
|
||||||
charset = utf-8
|
charset = utf-8
|
||||||
|
end_of_line = lf
|
||||||
|
indent_size = 2
|
||||||
|
indent_style = tab
|
||||||
trim_trailing_whitespace = true
|
trim_trailing_whitespace = true
|
||||||
insert_final_newline = true
|
insert_final_newline = true
|
||||||
|
|
||||||
[*.md]
|
[*.md]
|
||||||
|
charset = utf-8
|
||||||
|
end_of_line = lf
|
||||||
|
indent_style = tab
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
insert_final_newline = true
|
||||||
max_line_length = 80
|
max_line_length = 80
|
||||||
|
|
||||||
[COMMIT_EDITMSG]
|
[COMMIT_EDITMSG]
|
||||||
|
charset = utf-8
|
||||||
|
end_of_line = lf
|
||||||
indent_size = 4
|
indent_size = 4
|
||||||
max_line_length = 80
|
indent_style = tab
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
insert_final_newline = true
|
||||||
|
max_line_length = 80
|
10
.gitignore
vendored
10
.gitignore
vendored
@@ -1,17 +1,13 @@
|
|||||||
|
|
||||||
.ftpconfig
|
.ftpconfig
|
||||||
.ftpconfig2
|
.ftpconfig2
|
||||||
*.log
|
|
||||||
config.php
|
config.php
|
||||||
|
|
||||||
_nemazat/index.html
|
_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
|
||||||
|
app/logs/*.log
|
||||||
.vscode/
|
.vscode/
|
||||||
.vscode/sftp.json
|
.vscode/sftp.json
|
||||||
|
|
||||||
app/updater/*.bin
|
app/updater/*.bin
|
||||||
app/logs/*.log
|
logs/*
|
||||||
backup/*.zip
|
|
||||||
|
30
.htaccess
30
.htaccess
@@ -1,22 +1,18 @@
|
|||||||
|
Options -Indexes
|
||||||
|
Options -MultiViews -Indexes
|
||||||
|
|
||||||
RewriteEngine On
|
RewriteEngine On
|
||||||
|
RewriteBase /vasek/home/
|
||||||
|
|
||||||
# require https
|
RewriteCond %{REQUEST_FILENAME} !-f
|
||||||
#RewriteCond %{HTTPS} off
|
RewriteCond %{REQUEST_FILENAME} !-d
|
||||||
#RewriteCond %{REQUEST_URI} !^/api/update
|
RewriteCond %{REQUEST_FILENAME} !.css
|
||||||
#RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
|
RewriteCond %{REQUEST_FILENAME} !.js
|
||||||
|
RewriteRule (.*) index.php?url=$1 [QSA,L]
|
||||||
|
|
||||||
#token to HTTP_AUTHORIZATION
|
RewriteCond %{HTTPS} off
|
||||||
RewriteCond %{HTTP:Authorization} ^(.*)
|
RewriteCond %{REQUEST_FILENAME} !api.php
|
||||||
RewriteRule . - [e=HTTP_AUTHORIZATION:%1]
|
RewriteCond %{REQUEST_FILENAME} !apiFront.php
|
||||||
|
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
|
||||||
# serve all files from public subfolder
|
|
||||||
RewriteCond %{REQUEST_FILENAME} !.php
|
|
||||||
RewriteCond %{REQUEST_FILENAME} !.log
|
|
||||||
RewriteCond %{REQUEST_FILENAME} !.ttfnot
|
|
||||||
RewriteCond %{REQUEST_FILENAME} \.
|
|
||||||
RewriteRule (.*) ./public/$1 [L]
|
|
||||||
|
|
||||||
# serve all other request as query parameters
|
|
||||||
RewriteRule (.*) ./public/index.php?url=$1 [L,QSA]
|
|
||||||
|
|
||||||
AddType application/x-httpd-php .php .phtml
|
AddType application/x-httpd-php .php .phtml
|
||||||
|
4
Docs_api.md
Normal file
4
Docs_api.md
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
Login
|
||||||
|
https://dev.steelants.cz/vasek/home/apiFront.php
|
||||||
|
```json
|
||||||
|
{"username":"username","password":"password"}```
|
34
README.md
34
README.md
@@ -135,37 +135,3 @@ 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
|
||||||
|
|
||||||
## Folder structure
|
|
||||||
```
|
|
||||||
- /app # app specific files
|
|
||||||
- /controllers
|
|
||||||
- UserController.php
|
|
||||||
- /library # helpers etc.
|
|
||||||
- /models
|
|
||||||
- /types
|
|
||||||
- Units.php
|
|
||||||
- UserModal.php
|
|
||||||
- /views
|
|
||||||
- /layouts
|
|
||||||
- default.phtml
|
|
||||||
- /templates
|
|
||||||
- /components
|
|
||||||
- /pages
|
|
||||||
- Bootstrap.php
|
|
||||||
- Db.php
|
|
||||||
- Routes.php
|
|
||||||
- /library # framework, 3rd libraries etc.
|
|
||||||
- /vendor
|
|
||||||
- Controller.php
|
|
||||||
- Db.php
|
|
||||||
- Router.php
|
|
||||||
- config
|
|
||||||
- config.php /
|
|
||||||
- public
|
|
||||||
- /css
|
|
||||||
- /images
|
|
||||||
- /js
|
|
||||||
- .htaccess
|
|
||||||
- index.php
|
|
||||||
```
|
|
||||||
|
298
_INSTALATION/_SQL_TABLES.sql
Normal file
298
_INSTALATION/_SQL_TABLES.sql
Normal file
@@ -0,0 +1,298 @@
|
|||||||
|
-- phpMyAdmin SQL Dump
|
||||||
|
-- version 4.6.6deb4
|
||||||
|
-- https://www.phpmyadmin.net/
|
||||||
|
--
|
||||||
|
-- Počítač: localhost:3306
|
||||||
|
-- Vytvořeno: Úte 08. říj 2019, 18:05
|
||||||
|
-- Verze serveru: 10.1.41-MariaDB-0+deb9u1
|
||||||
|
-- Verze PHP: 7.0.33-0+deb9u5
|
||||||
|
|
||||||
|
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
|
||||||
|
SET time_zone = "+00:00";
|
||||||
|
|
||||||
|
|
||||||
|
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
|
||||||
|
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
|
||||||
|
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
|
||||||
|
/*!40101 SET NAMES utf8mb4 */;
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Databáze: `smart-home`
|
||||||
|
--
|
||||||
|
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Struktura tabulky `automation`
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE `automation` (
|
||||||
|
`automation_id` int(11) NOT NULL,
|
||||||
|
`name` varchar(255) NOT NULL,
|
||||||
|
`on_days` varchar(255) NOT NULL,
|
||||||
|
`if_something` varchar(255) NOT NULL,
|
||||||
|
`do_something` varchar(255) NOT NULL,
|
||||||
|
`executed` tinyint(4) NOT NULL,
|
||||||
|
`active` tinyint(4) NOT NULL DEFAULT '1',
|
||||||
|
`locked` tinyint(4) DEFAULT '0'
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||||
|
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Struktura tabulky `dashboard`
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE `dashboard` (
|
||||||
|
`dashboard_id` int(11) NOT NULL,
|
||||||
|
`user_id` int(11) NOT NULL,
|
||||||
|
`subdevice_id` int(11) NOT NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||||
|
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Struktura tabulky `devices`
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE `devices` (
|
||||||
|
`device_id` int(11) NOT NULL,
|
||||||
|
`room_id` int(11) DEFAULT NULL,
|
||||||
|
`name` varchar(255) NOT NULL,
|
||||||
|
`token` varchar(255) NOT NULL,
|
||||||
|
`sleep_time` int(13) NOT NULL,
|
||||||
|
`owner` int(13) NOT NULL,
|
||||||
|
`permission` varchar(255) NOT NULL,
|
||||||
|
`approved` int(11) NOT NULL,
|
||||||
|
`icon` varchar(255) NOT NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||||
|
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Struktura tabulky `notifications`
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE `notifications` (
|
||||||
|
`id` int(13) NOT NULL,
|
||||||
|
`user_id` varchar(255) NOT NULL,
|
||||||
|
`token` varchar(255) NOT NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||||
|
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Struktura tabulky `records`
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE `records` (
|
||||||
|
`record_id` int(11) NOT NULL,
|
||||||
|
`subdevice_id` int(11) NOT NULL,
|
||||||
|
`value` smallint(6) NOT NULL,
|
||||||
|
`time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`execuded` tinyint(4) NOT NULL DEFAULT '0'
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||||
|
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Struktura tabulky `rooms`
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE `rooms` (
|
||||||
|
`room_id` int(11) NOT NULL,
|
||||||
|
`name` varchar(255) NOT NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||||
|
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Struktura tabulky `scenes`
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE `scenes` (
|
||||||
|
`scene_id` int(11) NOT NULL,
|
||||||
|
`icon` varchar(255) NOT NULL,
|
||||||
|
`name` varchar(255) NOT NULL,
|
||||||
|
`do_something` varchar(255) NOT NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||||
|
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Struktura tabulky `subdevices`
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE `subdevices` (
|
||||||
|
`subdevice_id` int(11) NOT NULL,
|
||||||
|
`device_id` int(11) NOT NULL,
|
||||||
|
`type` varchar(255) NOT NULL,
|
||||||
|
`unit` varchar(255) NOT NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||||
|
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Struktura tabulky `users`
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE `users` (
|
||||||
|
`user_id` int(11) NOT NULL,
|
||||||
|
`username` varchar(255) NOT NULL,
|
||||||
|
`password` varchar(255) NOT NULL,
|
||||||
|
`startPage` int(11) NOT NULL,
|
||||||
|
`at_home` varchar(255) NOT NULL DEFAULT 'false'
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Vypisuji data pro tabulku `users`
|
||||||
|
--
|
||||||
|
|
||||||
|
INSERT INTO `users` (`user_id`, `username`, `password`, `startPage`) VALUES
|
||||||
|
(2, 'Admin', '08abb3ff83dfae60fb4591125fc49dc80cf7ef28224c2d5df86e2d0d037c553bc7f30e859348fd745c9c07a4edde4863e866a7d45356cf08a22e5e1eafa13406', 1);
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Klíče pro exportované tabulky
|
||||||
|
--
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Klíče pro tabulku `automation`
|
||||||
|
--
|
||||||
|
ALTER TABLE `automation`
|
||||||
|
ADD PRIMARY KEY (`automation_id`);
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Klíče pro tabulku `dashboard`
|
||||||
|
--
|
||||||
|
ALTER TABLE `dashboard`
|
||||||
|
ADD PRIMARY KEY (`dashboard_id`),
|
||||||
|
ADD KEY `user_id` (`user_id`),
|
||||||
|
ADD KEY `subdevice_id` (`subdevice_id`);
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Klíče pro tabulku `devices`
|
||||||
|
--
|
||||||
|
ALTER TABLE `devices`
|
||||||
|
ADD PRIMARY KEY (`device_id`),
|
||||||
|
ADD KEY `room_id` (`room_id`);
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Klíče pro tabulku `notifications`
|
||||||
|
--
|
||||||
|
ALTER TABLE `notifications`
|
||||||
|
ADD PRIMARY KEY (`id`);
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Klíče pro tabulku `records`
|
||||||
|
--
|
||||||
|
ALTER TABLE `records`
|
||||||
|
ADD PRIMARY KEY (`record_id`),
|
||||||
|
ADD KEY `device_id` (`subdevice_id`);
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Klíče pro tabulku `rooms`
|
||||||
|
--
|
||||||
|
ALTER TABLE `rooms`
|
||||||
|
ADD PRIMARY KEY (`room_id`);
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Klíče pro tabulku `scenes`
|
||||||
|
--
|
||||||
|
ALTER TABLE `scenes`
|
||||||
|
ADD PRIMARY KEY (`scene_id`);
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Klíče pro tabulku `subdevices`
|
||||||
|
--
|
||||||
|
ALTER TABLE `subdevices`
|
||||||
|
ADD PRIMARY KEY (`subdevice_id`),
|
||||||
|
ADD KEY `device_id` (`device_id`);
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Klíče pro tabulku `users`
|
||||||
|
--
|
||||||
|
ALTER TABLE `users`
|
||||||
|
ADD PRIMARY KEY (`user_id`);
|
||||||
|
|
||||||
|
--
|
||||||
|
-- AUTO_INCREMENT pro tabulky
|
||||||
|
--
|
||||||
|
|
||||||
|
--
|
||||||
|
-- AUTO_INCREMENT pro tabulku `automation`
|
||||||
|
--
|
||||||
|
ALTER TABLE `automation`
|
||||||
|
MODIFY `automation_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=58;
|
||||||
|
--
|
||||||
|
-- AUTO_INCREMENT pro tabulku `dashboard`
|
||||||
|
--
|
||||||
|
ALTER TABLE `dashboard`
|
||||||
|
MODIFY `dashboard_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
|
||||||
|
--
|
||||||
|
-- AUTO_INCREMENT pro tabulku `devices`
|
||||||
|
--
|
||||||
|
ALTER TABLE `devices`
|
||||||
|
MODIFY `device_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
|
||||||
|
--
|
||||||
|
-- AUTO_INCREMENT pro tabulku `notifications`
|
||||||
|
--
|
||||||
|
ALTER TABLE `notifications`
|
||||||
|
MODIFY `id` int(13) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
|
||||||
|
--
|
||||||
|
-- AUTO_INCREMENT pro tabulku `records`
|
||||||
|
--
|
||||||
|
ALTER TABLE `records`
|
||||||
|
MODIFY `record_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=352338;
|
||||||
|
--
|
||||||
|
-- AUTO_INCREMENT pro tabulku `rooms`
|
||||||
|
--
|
||||||
|
ALTER TABLE `rooms`
|
||||||
|
MODIFY `room_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
|
||||||
|
--
|
||||||
|
-- AUTO_INCREMENT pro tabulku `scenes`
|
||||||
|
--
|
||||||
|
ALTER TABLE `scenes`
|
||||||
|
MODIFY `scene_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
|
||||||
|
--
|
||||||
|
-- AUTO_INCREMENT pro tabulku `subdevices`
|
||||||
|
--
|
||||||
|
ALTER TABLE `subdevices`
|
||||||
|
MODIFY `subdevice_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27;
|
||||||
|
--
|
||||||
|
-- AUTO_INCREMENT pro tabulku `users`
|
||||||
|
--
|
||||||
|
ALTER TABLE `users`
|
||||||
|
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
|
||||||
|
--
|
||||||
|
-- Omezení pro exportované tabulky
|
||||||
|
--
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Omezení pro tabulku `dashboard`
|
||||||
|
--
|
||||||
|
ALTER TABLE `dashboard`
|
||||||
|
ADD CONSTRAINT `dashboard_ibfk_2` FOREIGN KEY (`subdevice_id`) REFERENCES `subdevices` (`subdevice_id`) ON DELETE CASCADE ON UPDATE NO ACTION,
|
||||||
|
ADD CONSTRAINT `dashboard_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Omezení pro tabulku `devices`
|
||||||
|
--
|
||||||
|
ALTER TABLE `devices`
|
||||||
|
ADD CONSTRAINT `devices_ibfk_1` FOREIGN KEY (`room_id`) REFERENCES `rooms` (`room_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Omezení pro tabulku `records`
|
||||||
|
--
|
||||||
|
ALTER TABLE `records`
|
||||||
|
ADD CONSTRAINT `records_ibfk_1` FOREIGN KEY (`subdevice_id`) REFERENCES `subdevices` (`subdevice_id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Omezení pro tabulku `subdevices`
|
||||||
|
--
|
||||||
|
ALTER TABLE `subdevices`
|
||||||
|
ADD CONSTRAINT `subdevices_ibfk_1` FOREIGN KEY (`device_id`) REFERENCES `devices` (`device_id`);
|
||||||
|
|
||||||
|
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
||||||
|
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
|
||||||
|
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
BIN
_README_IMG/desktop1.png
Normal file
BIN
_README_IMG/desktop1.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 77 KiB |
BIN
_README_IMG/desktop2.png
Normal file
BIN
_README_IMG/desktop2.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 66 KiB |
BIN
_README_IMG/desktop3.png
Normal file
BIN
_README_IMG/desktop3.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 45 KiB |
BIN
_README_IMG/mobile1.png
Normal file
BIN
_README_IMG/mobile1.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 108 KiB |
BIN
_README_IMG/mobile2.png
Normal file
BIN
_README_IMG/mobile2.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 76 KiB |
BIN
_README_IMG/mobile3.png
Normal file
BIN
_README_IMG/mobile3.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 58 KiB |
2044
adminer.php
2044
adminer.php
File diff suppressed because one or more lines are too long
326
api.php
Normal file
326
api.php
Normal file
@@ -0,0 +1,326 @@
|
|||||||
|
<?php
|
||||||
|
/** Includes **/
|
||||||
|
include_once('./config.php');
|
||||||
|
|
||||||
|
//Autoloader
|
||||||
|
$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: ./');
|
||||||
|
}*/
|
||||||
|
|
||||||
|
//Log
|
||||||
|
$logManager = new LogManager();
|
||||||
|
$apiLogManager = new LogManager('./app/logs/api/'. date("Y-m-d").'.log');
|
||||||
|
|
||||||
|
//DB Conector
|
||||||
|
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
|
||||||
|
|
||||||
|
//Read API data
|
||||||
|
$json = file_get_contents('php://input');
|
||||||
|
$obj = json_decode($json, true);
|
||||||
|
|
||||||
|
//Log RAW api request
|
||||||
|
if (API_DEBUGMOD == 1) {
|
||||||
|
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordType::INFO);
|
||||||
|
}
|
||||||
|
|
||||||
|
//zabespecit proti Ddosu
|
||||||
|
if (isset($obj['user']) && $obj['user'] != ''){
|
||||||
|
//user at home
|
||||||
|
$user = UserManager::getUser($obj['user']);
|
||||||
|
$userAtHome = $user['at_home'];
|
||||||
|
if (!empty($user)) {
|
||||||
|
$userId = $user['user_id'];
|
||||||
|
$atHome = $obj['atHome'];
|
||||||
|
if($userAtHome != $atHome){
|
||||||
|
UserManager::atHome($userId, $atHome);
|
||||||
|
$logManager->write("[USER] user " . $userId . " changet his home state to " . $atHome , LogRecordType::INFO);
|
||||||
|
}
|
||||||
|
echo 'Saved: ' . $atHome;
|
||||||
|
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
|
||||||
|
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!",
|
||||||
|
), JSON_PRETTY_PRINT);
|
||||||
|
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
|
||||||
|
$logManager->write("[API] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//automationExecution
|
||||||
|
try {
|
||||||
|
AutomationManager::executeAll();
|
||||||
|
$fallbackManager = new FallbackManager(RANGES);
|
||||||
|
$fallbackManager->check();
|
||||||
|
//LogKeeper::purge(LOGTIMOUT);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
$logManager->write("[Automation] Something happen during automation execution", LogRecordType::ERROR);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Record Cleaning
|
||||||
|
try {
|
||||||
|
RecordManager::clean(RECORDTIMOUT);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
$logManager->write("[Record] cleaning record older that " . RECORDTIMOUT , LogRecordType::ERROR);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Variables
|
||||||
|
$token = $obj['token'];
|
||||||
|
$values = null;
|
||||||
|
$settings = null;
|
||||||
|
$deviceLogs = null;
|
||||||
|
$command = "null";
|
||||||
|
|
||||||
|
if (isset($obj['values'])) {
|
||||||
|
$values = $obj['values'];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($obj['settings'])) {
|
||||||
|
$settings = $obj['settings'];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($obj['logs'])) {
|
||||||
|
$deviceLogs = $obj['logs'];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//Checks
|
||||||
|
if ($token == null || $token == "") {
|
||||||
|
echo json_encode(array(
|
||||||
|
'state' => 'unsuccess',
|
||||||
|
'errorMSG' => "Missing Value Token in JSON payload",
|
||||||
|
), JSON_PRETTY_PRINT);
|
||||||
|
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
|
||||||
|
//Vstupní Checky
|
||||||
|
if (!DeviceManager::registeret($token)) {
|
||||||
|
//Notification data setup
|
||||||
|
$notificationMng = new NotificationManager;
|
||||||
|
$notificationData = [
|
||||||
|
'title' => 'Info',
|
||||||
|
'body' => 'New device Detected Found',
|
||||||
|
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
|
||||||
|
];
|
||||||
|
|
||||||
|
//Subdevice Registration
|
||||||
|
$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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
|
||||||
|
echo json_encode(array(
|
||||||
|
'state' => 'unsuccess',
|
||||||
|
'errorMSG' => "Device not registeret",
|
||||||
|
), JSON_PRETTY_PRINT);
|
||||||
|
$logManager->write("[API] Registering Device", LogRecordType::INFO);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!DeviceManager::approved($token)) {
|
||||||
|
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
|
||||||
|
echo json_encode(array(
|
||||||
|
'state' => 'unsuccess',
|
||||||
|
'errorMSG' => "Unaproved Device",
|
||||||
|
), JSON_PRETTY_PRINT);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Diagnostic Data Write to DB
|
||||||
|
if ($settings != null && $settings != ""){
|
||||||
|
$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);
|
||||||
|
$jsonAnswer = [
|
||||||
|
'state' => 'succes',
|
||||||
|
'command' => $command,
|
||||||
|
];
|
||||||
|
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
|
||||||
|
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Issuing command
|
||||||
|
if ($command == "null"){
|
||||||
|
$device = DeviceManager::getDeviceByToken($token);
|
||||||
|
$deviceId = $device['device_id'];
|
||||||
|
$deviceCommand = $device["command"];
|
||||||
|
if ($deviceCommand != '' && $deviceCommand != null && $deviceCommand != "null")
|
||||||
|
{
|
||||||
|
$command = $deviceCommand;
|
||||||
|
$data = [
|
||||||
|
'command'=>'null'
|
||||||
|
];
|
||||||
|
DeviceManager::editByToken($token, $data);
|
||||||
|
$logManager->write("[API] Device_ID " . $deviceId . " executing command " . $command, LogRecordType::INFO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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,
|
||||||
|
];
|
||||||
|
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
|
||||||
|
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//
|
||||||
|
if (count($values) == 1){
|
||||||
|
unset($values["wifi"]);
|
||||||
|
}
|
||||||
|
// Subdevices first data!
|
||||||
|
if ($values != null && $values != "") {
|
||||||
|
|
||||||
|
//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]);
|
||||||
|
}
|
||||||
|
RecordManager::create($deviceId, $key, round($value['value'],3));
|
||||||
|
$logManager->write("[API] Device_ID " . $deviceId . " writed value " . $key . ' ' . $value['value'], LogRecordType::INFO);
|
||||||
|
|
||||||
|
//notification
|
||||||
|
if ($key == 'door' || $key == 'water') {
|
||||||
|
$notificationMng = new NotificationManager;
|
||||||
|
$notificationData = [];
|
||||||
|
|
||||||
|
switch ($key) {
|
||||||
|
case 'door':
|
||||||
|
$notificationData = [
|
||||||
|
'title' => 'Info',
|
||||||
|
'body' => 'Someone just open up '.$device['name'],
|
||||||
|
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
|
||||||
|
];
|
||||||
|
|
||||||
|
break;
|
||||||
|
case 'water':
|
||||||
|
$notificationData = [
|
||||||
|
'title' => 'Alert',
|
||||||
|
'body' => 'Wather leak detected by '.$device['name'],
|
||||||
|
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
|
||||||
|
];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (DEBUGMOD) $notificationData['body'] .= ' value='.$value['value'];
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$hostname = strtolower($device['name']);
|
||||||
|
$hostname = str_replace(' ', '_', $hostname);
|
||||||
|
//upravit format na setings-> netvork etc
|
||||||
|
$jsonAnswer = [
|
||||||
|
'device' => [
|
||||||
|
'hostname' => $hostname,
|
||||||
|
'ipAddress' => $device['ip_address'],
|
||||||
|
'subnet' => $device['subnet'],
|
||||||
|
'gateway' => $device['gateway'],
|
||||||
|
],
|
||||||
|
'state' => 'succes',
|
||||||
|
'command' => $command,
|
||||||
|
];
|
||||||
|
|
||||||
|
$subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($deviceId);
|
||||||
|
if (!in_array($subDevicesTypeList, ['on/off', 'door', 'water'])) {
|
||||||
|
$jsonAnswer['device']['sleepTime'] = $device['sleep_time'];
|
||||||
|
}
|
||||||
|
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
|
||||||
|
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
|
||||||
|
} else {
|
||||||
|
//Vypis
|
||||||
|
$device = DeviceManager::getDeviceByToken($token);
|
||||||
|
$deviceId = $device['device_id'];
|
||||||
|
|
||||||
|
if (count(SubDeviceManager::getAllSubDevices($deviceId)) == 0) {
|
||||||
|
SubDeviceManager::create($deviceId, 'on/off', UNITS[$key]);
|
||||||
|
//RecordManager::create($deviceId, 'on/off', 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
$subDeviceId = SubDeviceManager::getAllSubDevices($deviceId)[0]['subdevice_id'];
|
||||||
|
$subDeviceLastReord = RecordManager::getLastRecord($subDeviceId);
|
||||||
|
$subDeviceLastReordValue = $subDeviceLastReord['value'];
|
||||||
|
|
||||||
|
if ($subDeviceLastReord['execuded'] == 0){
|
||||||
|
$logManager->write("[API] subDevice_ID ".$subDeviceId . " executed comand with value " .$subDeviceLastReordValue . " record id " . $subDeviceLastReord['record_id'] . " executed " . $subDeviceLastReord['execuded'], LogRecordType::INFO);
|
||||||
|
RecordManager::setExecuted($subDeviceLastReord['record_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
echo json_encode(array(
|
||||||
|
'device' => [
|
||||||
|
'hostname' => $device['name'],
|
||||||
|
'ipAddress' => $device['ip_address'],
|
||||||
|
'subnet' => $device['subnet'],
|
||||||
|
'gateway' => $device['gateway'],
|
||||||
|
],
|
||||||
|
'state' => 'succes',
|
||||||
|
'value' => $subDeviceLastReordValue,
|
||||||
|
'command' => $command,
|
||||||
|
), JSON_PRETTY_PRINT);
|
||||||
|
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($logManager);
|
||||||
|
Db::disconect();
|
||||||
|
die();
|
98
apiFront.php
Normal file
98
apiFront.php
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
<?php
|
||||||
|
/** Includes **/
|
||||||
|
include_once('./config.php');
|
||||||
|
|
||||||
|
//Autoloader
|
||||||
|
$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;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Log
|
||||||
|
$apiLogManager = new LogManager('./app/logs/apiFront/'. date("Y-m-d").'.log');
|
||||||
|
|
||||||
|
//DB Conector
|
||||||
|
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
|
||||||
|
|
||||||
|
//Read API data
|
||||||
|
$json = file_get_contents('php://input');
|
||||||
|
$obj = json_decode($json, true);
|
||||||
|
|
||||||
|
//Log RAW api request
|
||||||
|
if (API_DEBUGMOD == 1) {
|
||||||
|
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordType::INFO);
|
||||||
|
}
|
||||||
|
|
||||||
|
$apiManager = new ApiManager();
|
||||||
|
echo $apiManager->generateToken($obj['username'],$obj['password']);
|
||||||
|
die();
|
||||||
|
|
||||||
|
/*
|
||||||
|
if (
|
||||||
|
isset($obj['username']) &&
|
||||||
|
$obj['username'] != '' &&
|
||||||
|
isset($obj['password']) &&
|
||||||
|
$obj['password'] != ''
|
||||||
|
){
|
||||||
|
$ota = false;
|
||||||
|
$userName = $_POST['username'];
|
||||||
|
$userPassword = $_POST['password'];
|
||||||
|
$rememberMe = (isset ($_POST['remember']) ? $_POST['remember'] : "");
|
||||||
|
$ota = $userManager->haveOtaEnabled($userName);
|
||||||
|
if ($ota == "") {
|
||||||
|
$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
|
||||||
|
header('Location: ' . BASEDIR . $landingPage);
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
|
||||||
|
$_SESSION['USERNAME'] = $userName;
|
||||||
|
$_SESSION['PASSWORD'] = $userPassword;
|
||||||
|
$_SESSION['REMEMBER'] = $rememberMe;
|
||||||
|
$_SESSION['OTA'] = $ota;
|
||||||
|
} else if (
|
||||||
|
isset($_POST['otaCode']) &&
|
||||||
|
$_POST['otaCode'] != ''
|
||||||
|
) {
|
||||||
|
|
||||||
|
$otaCode = $_POST['otaCode'];
|
||||||
|
$otaSecret = $_POST['otaSecret'];
|
||||||
|
|
||||||
|
$ga = new PHPGangsta_GoogleAuthenticator();
|
||||||
|
$ota = $_SESSION['OTA'];
|
||||||
|
$userName = $_SESSION['USERNAME'];
|
||||||
|
$userPassword = $_SESSION['PASSWORD'];
|
||||||
|
$rememberMe = $_SESSION['REMEMBER'];
|
||||||
|
unset($_SESSION['OTA']);
|
||||||
|
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
|
||||||
|
if ($checkResult) {
|
||||||
|
$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
|
||||||
|
header('Location: ' . BASEDIR . $landingPage);
|
||||||
|
echo 'OK';
|
||||||
|
} else {
|
||||||
|
echo 'FAILED';
|
||||||
|
}
|
||||||
|
//TODO: upravi a ověřit jeslti ja zabezpečené
|
||||||
|
//TODO:
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/*unset($logManager);
|
||||||
|
Db::disconect();
|
||||||
|
die();*/
|
@@ -1,110 +0,0 @@
|
|||||||
<?php
|
|
||||||
//Debug
|
|
||||||
error_reporting(E_ALL);
|
|
||||||
ini_set( 'display_errors','1');
|
|
||||||
|
|
||||||
//setup
|
|
||||||
parse_str($_SERVER['QUERY_STRING'], $params);
|
|
||||||
$urlSes = str_replace((!empty ($params['url']) ? $params['url'] : ""), "", str_replace('https://' . $_SERVER['HTTP_HOST'], "", $_SERVER['REQUEST_URI']));
|
|
||||||
session_set_cookie_params(
|
|
||||||
1209600,
|
|
||||||
$urlSes,
|
|
||||||
str_replace("/var/www/", "", $_SERVER['DOCUMENT_ROOT']),
|
|
||||||
true,
|
|
||||||
true
|
|
||||||
);
|
|
||||||
/*ini_set ('session.cookie_httponly', '1');
|
|
||||||
ini_set('session.cookie_domain', $_SERVER['HTTP_HOST']);
|
|
||||||
ini_set('session.cookie_path', str_replace('login', "", str_replace('https://' . $_SERVER['HTTP_HOST'], "", $_SERVER['REQUEST_URI'])));
|
|
||||||
ini_set('session.cookie_secure', '1');
|
|
||||||
ini_set('session.gc_maxlifetime', 1209600);*/
|
|
||||||
mb_internal_encoding ("UTF-8");
|
|
||||||
|
|
||||||
session_start();
|
|
||||||
|
|
||||||
// import configs
|
|
||||||
require_once '../library/Debugger.php';
|
|
||||||
|
|
||||||
Debugger::flag('loaders');
|
|
||||||
|
|
||||||
//Autoloader
|
|
||||||
class Autoloader {
|
|
||||||
protected static $extension = ".php";
|
|
||||||
protected static $root = __DIR__;
|
|
||||||
protected static $files = [];
|
|
||||||
|
|
||||||
static function ClassLoader ($className = ""){
|
|
||||||
$directorys = new RecursiveDirectoryIterator(static::$root, RecursiveDirectoryIterator::SKIP_DOTS);
|
|
||||||
|
|
||||||
//echo '<pre>';
|
|
||||||
//var_dump($directorys);
|
|
||||||
//echo '</pre>';
|
|
||||||
|
|
||||||
$files = new RecursiveIteratorIterator($directorys, RecursiveIteratorIterator::LEAVES_ONLY);
|
|
||||||
|
|
||||||
$filename = $className . static::$extension;
|
|
||||||
|
|
||||||
foreach ($files as $key => $file) {
|
|
||||||
if (strtolower($file->getFilename()) === strtolower($filename) && $file->isReadable()) {
|
|
||||||
include_once $file->getPathname();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static function setRoot($rootPath){
|
|
||||||
static::$root = $rootPath;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
spl_autoload_register("Autoloader::ClassLoader");
|
|
||||||
Autoloader::setRoot('/var/www/dev.steelants.cz/vasek/home-update/');
|
|
||||||
|
|
||||||
// import configs
|
|
||||||
require_once '../config/config.php';
|
|
||||||
|
|
||||||
class ErrorHandler {
|
|
||||||
static function exception($exception){
|
|
||||||
error_log($exception);
|
|
||||||
http_response_code($exception->getCode());
|
|
||||||
$message = [
|
|
||||||
'code' => $exception->getCode(),
|
|
||||||
'message' => $exception->getMessage(),
|
|
||||||
'file' => $exception->getFile(),
|
|
||||||
'line' => $exception->getLine(),
|
|
||||||
'trace' => $exception->getTrace(),
|
|
||||||
];
|
|
||||||
echo json_encode($message);
|
|
||||||
|
|
||||||
$apiLogManager = new LogManager('../logs/apache/'. date("Y-m-d").'.log');
|
|
||||||
$apiLogManager->setLevel(LOGLEVEL);
|
|
||||||
$apiLogManager->write("[APACHE]\n" . json_encode($message, JSON_PRETTY_PRINT), LogRecordTypes::ERROR);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
set_exception_handler("ErrorHandler::exception");
|
|
||||||
|
|
||||||
Debugger::flag('preload');
|
|
||||||
|
|
||||||
$json = file_get_contents('php://input');
|
|
||||||
$obj = json_decode($json, true);
|
|
||||||
|
|
||||||
$apiLogManager = new LogManager('../logs/api/'. date("Y-m-d").'.log');
|
|
||||||
$apiLogManager->setLevel(LOGLEVEL);
|
|
||||||
|
|
||||||
$apiLogManager->write("[API] headers\n" . json_encode($_SERVER, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
|
|
||||||
$apiLogManager->write("[API] request body\n" . json_encode($obj, 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);
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Debugger::flag('dbconnect');
|
|
||||||
//D B Conector
|
|
||||||
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
|
|
||||||
|
|
||||||
Debugger::flag('routes');
|
|
||||||
// import routes
|
|
||||||
require_once '../app/Routes.php';
|
|
||||||
|
|
||||||
Debugger::flag('done');
|
|
||||||
// echo Debugger::showFlags(false);
|
|
@@ -1,60 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
$router = new Router();
|
|
||||||
|
|
||||||
$router->setDefault(function(){
|
|
||||||
echo $_GET['url'].': 404';
|
|
||||||
$logManager = new LogManager();
|
|
||||||
$logManager->setLevel(LOGLEVEL);
|
|
||||||
$logManager->write("[ROUTER]" . $_GET['url'] . "not found", LogRecordTypes::WARNING);
|
|
||||||
unset($logManager);
|
|
||||||
});
|
|
||||||
|
|
||||||
//Pages
|
|
||||||
$router->any('/', 'Log');
|
|
||||||
$router->any('/log', 'Log');
|
|
||||||
$router->any('/server', 'Server');
|
|
||||||
$router->any('/login', 'Login');
|
|
||||||
$router->any('/logout', 'Logout');
|
|
||||||
$router->any('/automation', 'Automation');
|
|
||||||
$router->any('/setting', 'Setting');
|
|
||||||
$router->any('/device', 'Device');
|
|
||||||
$router->any('/plugins', 'Plugins');
|
|
||||||
$router->any('/ajax', 'Ajax');
|
|
||||||
$router->any('/oauth', 'Oauth');
|
|
||||||
|
|
||||||
//Vue APP
|
|
||||||
$router->post('/api/login', 'AuthApi@login');
|
|
||||||
$router->post('/api/logout', 'AuthApi@logout');
|
|
||||||
$router->get('/api/rooms', 'RoomsApi@default');
|
|
||||||
$router->get('/api/rooms/{roomId}/update', 'RoomsApi@update');
|
|
||||||
$router->get('/api/devices', 'DevicesApi@default');
|
|
||||||
$router->get('/api/plugins', 'PluginsApi@default');
|
|
||||||
$router->get('/api/users', 'UsersApi@default');
|
|
||||||
$router->get('/api/server', 'ServerApi@default');
|
|
||||||
$router->get('/api/server/log', 'ServerApi@logStatus');
|
|
||||||
$router->post('/api/widgets/{widgetId}/run', 'WidgetApi@run');
|
|
||||||
$router->get('/api/widgets/{widgetId}/detail', 'WidgetApi@detail');
|
|
||||||
|
|
||||||
//cron
|
|
||||||
$router->post('/cron/clean', 'CronApi@clean');
|
|
||||||
$router->post('/cron/fetch', 'CronApi@fetch');
|
|
||||||
|
|
||||||
//Google Home - API
|
|
||||||
$router->any('/api/HA/auth', 'Oauth');
|
|
||||||
$router->any('/api/HA', 'GoogleHomeApi@response');
|
|
||||||
|
|
||||||
//Endpoints API
|
|
||||||
$router->post('/api/endpoint/', 'EndpointsApi@default');
|
|
||||||
$router->any('/api/update/', 'UpdatesApi@default');
|
|
||||||
$router->any('/api/users/status', 'UsersApi@status');
|
|
||||||
|
|
||||||
// examples
|
|
||||||
$router->any('/api/example', 'ExampleApi@example');
|
|
||||||
$router->any('/example', 'ExampleController@index');
|
|
||||||
$router->any('/example/subpage', 'ExampleController@subpage');
|
|
||||||
|
|
||||||
//module routes
|
|
||||||
//$router->any('/plugins/spotify/callback', 'Spotify@callback');
|
|
||||||
|
|
||||||
$router->run($_SERVER['REQUEST_METHOD'], '/'.(isset($_GET['url']) ? $_GET['url'] : ''));
|
|
@@ -1,25 +0,0 @@
|
|||||||
<?php
|
|
||||||
class AuthApi extends ApiController {
|
|
||||||
public function login(){
|
|
||||||
$token = (new AuthManager)->getToken($this->input['username'],$this->input['password']);
|
|
||||||
if (!$token) {
|
|
||||||
throw new Exception("Auth failed", 401);
|
|
||||||
}
|
|
||||||
$this->response(['token' => $token]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function logout(){
|
|
||||||
$authenticationBearrer = $_SERVER['HTTP_AUTHORIZATION'];
|
|
||||||
if (!(new AuthManager)->deleteToken($authenticationBearrer)) {
|
|
||||||
throw new Exception("logout Failed", 401);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function registration(){
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public function restartPassword(){
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,58 +0,0 @@
|
|||||||
<?php
|
|
||||||
class CronApi extends ApiController
|
|
||||||
{
|
|
||||||
|
|
||||||
public function clean()
|
|
||||||
{
|
|
||||||
//Log Cleaning
|
|
||||||
$logKeeper = new LogMaintainer();
|
|
||||||
$logKeeper->purge(LOGTIMOUT);
|
|
||||||
|
|
||||||
//Database Backup Cleanup
|
|
||||||
$backupWorker = new DatabaseBackup();
|
|
||||||
$backupWorker->purge(5);
|
|
||||||
|
|
||||||
$this->response(['Value' => 'OK']);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function fetch()
|
|
||||||
{
|
|
||||||
//Run Plugins
|
|
||||||
$result = [];
|
|
||||||
$dir = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/';
|
|
||||||
$pluginsFiles = array_diff(scandir($dir), ['..', '.']);
|
|
||||||
foreach ($pluginsFiles as $key => $pluginFile) {
|
|
||||||
if (strpos($pluginFile, "!") === false) {
|
|
||||||
$className = str_replace(".php", "", $pluginFile);
|
|
||||||
if (strpos($pluginFile, '_') === true) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!class_exists($className)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$pluginMakeClass = new $className;
|
|
||||||
if (!method_exists($pluginMakeClass, 'make')) {
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$result[$className] = $pluginMakeClass->make();
|
|
||||||
} else {
|
|
||||||
$className = str_replace("!", "", str_replace(".php", "", $pluginFile));
|
|
||||||
if (strpos($pluginFile, '_') === true) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!class_exists($className)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$pluginMakeClass = new $className;
|
|
||||||
if (!method_exists($pluginMakeClass, 'disable')) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$result[$className] = $pluginMakeClass->disable();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//Print Result
|
|
||||||
$this->response($result);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,17 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
class DevicesApi extends ApiController{
|
|
||||||
|
|
||||||
public function default(){
|
|
||||||
$this->requireAuth();
|
|
||||||
$response = [];
|
|
||||||
|
|
||||||
// TODO: process the request
|
|
||||||
|
|
||||||
$this->response($response);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getDevicesByRoom($roomId){
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,196 +0,0 @@
|
|||||||
<?php
|
|
||||||
class EndpointsApi extends ApiController{
|
|
||||||
public function default(){
|
|
||||||
// $this->requireAuth();
|
|
||||||
$obj = $this->input;
|
|
||||||
|
|
||||||
//variables Definition
|
|
||||||
$command = "null";
|
|
||||||
|
|
||||||
//Log
|
|
||||||
$logManager = new LogManager('../logs/api/'. date("Y-m-d").'.log');
|
|
||||||
$logManager->setLevel(LOGLEVEL);
|
|
||||||
|
|
||||||
//Token Checks
|
|
||||||
if ($obj['token'] == null || !isset($obj['token'])) {
|
|
||||||
$this->response([
|
|
||||||
'state' => 'unsuccess',
|
|
||||||
'errorMSG' => "Missing Value Token in JSON payload",
|
|
||||||
], 401);
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
|
|
||||||
//Vstupní Checky
|
|
||||||
if (!DeviceManager::registeret($obj['token'])) {
|
|
||||||
//Notification data setup
|
|
||||||
$notificationMng = new NotificationManager;
|
|
||||||
$notificationData = [
|
|
||||||
'title' => 'Info',
|
|
||||||
'body' => 'New device Detected Found',
|
|
||||||
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
|
|
||||||
];
|
|
||||||
|
|
||||||
//Subdevice Registration
|
|
||||||
$device = DeviceManager::create($obj['token'], $obj['token']);
|
|
||||||
foreach ($obj['values'] as $key => $value) {
|
|
||||||
if (!SubDeviceManager::getSubDeviceByMaster($device['device_id'], $key)) {
|
|
||||||
SubDeviceManager::create($device['device_id'], $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'] . " ", LogRecordTypes::INFO);
|
|
||||||
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$logManager->write("[API] Registering Device", LogRecordTypes::INFO);
|
|
||||||
$this->response([
|
|
||||||
'state' => 'unsuccess',
|
|
||||||
'errorMSG' => "Device not registeret",
|
|
||||||
], 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!DeviceManager::approved($obj['token'])) {
|
|
||||||
$this->response([
|
|
||||||
'state' => 'unsuccess',
|
|
||||||
'errorMSG' => "Unaproved Device",
|
|
||||||
], 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
$device = DeviceManager::getDeviceByToken($obj['token']);
|
|
||||||
|
|
||||||
//Diagnostic
|
|
||||||
if (isset($obj['settings'])){
|
|
||||||
$data = ['mac' => $obj['settings']["network"]["mac"], 'ip_address' => $obj['settings']["network"]["ip"]];
|
|
||||||
if (array_key_exists("firmware_hash", $obj['settings'])) {
|
|
||||||
$data['firmware_hash'] = $obj['settings']["firmware_hash"];
|
|
||||||
}
|
|
||||||
DeviceManager::editByToken($obj['token'], $data);
|
|
||||||
$this->response([
|
|
||||||
'state' => 'succes',
|
|
||||||
'command' => $command,
|
|
||||||
], 200);
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
|
|
||||||
//Log Data Save
|
|
||||||
if (isset($obj['logs'])){
|
|
||||||
foreach ($obj['logs'] as $log) {
|
|
||||||
$deviceLogManager = new LogManager('../logs/devices/'. date("Y-m-d").'.log');
|
|
||||||
$deviceLogManager->setLevel(LOGLEVEL);
|
|
||||||
$deviceLogManager->write("[Device Log Msg] Device_ID " . $device['device_id'] . "->" . $log, LogRecordTypes::ERROR);
|
|
||||||
unset($deviceLogManager);
|
|
||||||
}
|
|
||||||
$this->response([
|
|
||||||
'state' => 'succes',
|
|
||||||
'command' => $command,
|
|
||||||
], 200);
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Issuing command
|
|
||||||
if ($command == "null"){
|
|
||||||
$deviceCommand = $device["command"];
|
|
||||||
if ($deviceCommand != '' && $deviceCommand != null && $deviceCommand != "null")
|
|
||||||
{
|
|
||||||
$command = $deviceCommand;
|
|
||||||
$data = [
|
|
||||||
'command'=>'null'
|
|
||||||
];
|
|
||||||
DeviceManager::editByToken($obj['token'], $data);
|
|
||||||
$logManager->write("[API] Device_ID " . $device['device_id'] . " executing command " . $command, LogRecordTypes::INFO);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$jsonAnswer = [];
|
|
||||||
$subDeviceLastReordValue = [];
|
|
||||||
|
|
||||||
if (isset($obj['values'])) {
|
|
||||||
//ZAPIS
|
|
||||||
foreach ($obj['values'] as $key => $value) {
|
|
||||||
if (!SubDeviceManager::getSubDeviceByMaster($device['device_id'], $key)) {
|
|
||||||
SubDeviceManager::create($device['device_id'], $key, UNITS[$key]);
|
|
||||||
}
|
|
||||||
$subDeviceLastReordValue[$key] = $value['value'];
|
|
||||||
RecordManager::create($device['device_id'], $key, round($value['value'],3));
|
|
||||||
$logManager->write("[API] Device_ID " . $device['device_id'] . " writed value " . $key . ' ' . $value['value'], LogRecordTypes::INFO);
|
|
||||||
|
|
||||||
//notification
|
|
||||||
if ($key == 'door' || $key == 'water') {
|
|
||||||
$notificationMng = new NotificationManager;
|
|
||||||
$notificationData = [];
|
|
||||||
|
|
||||||
switch ($key) {
|
|
||||||
case 'door':
|
|
||||||
$notificationData = [
|
|
||||||
'title' => 'Info',
|
|
||||||
'body' => 'Someone just open up '.$device['name'],
|
|
||||||
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
|
|
||||||
];
|
|
||||||
|
|
||||||
break;
|
|
||||||
case 'water':
|
|
||||||
$notificationData = [
|
|
||||||
'title' => 'Alert',
|
|
||||||
'body' => 'Wather leak detected by '.$device['name'],
|
|
||||||
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
|
|
||||||
];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (DEBUGMOD) $notificationData['body'] .= ' value='.$value['value'];
|
|
||||||
if ($notificationData != []) {
|
|
||||||
$subscribers = $notificationMng::getSubscription();
|
|
||||||
foreach ($subscribers as $key => $subscriber) {
|
|
||||||
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordTypes::INFO);
|
|
||||||
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
//upravit format na setings-> netvork etc
|
|
||||||
|
|
||||||
$subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($device['device_id']);
|
|
||||||
if (!in_array($subDevicesTypeList, ['on/off', 'door', 'water'])) {
|
|
||||||
$jsonAnswer['device']['sleepTime'] = $device['sleep_time'];
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (count(SubDeviceManager::getAllSubDevices($device['device_id'])) == 0) {
|
|
||||||
//SubDeviceManager::create($device['device_id'], 'on/off', UNITS[$key]);
|
|
||||||
//RecordManager::create($device['device_id'], 'on/off', 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
$subDevicesData = SubDeviceManager::getAllSubDevices($device['device_id']);
|
|
||||||
|
|
||||||
foreach ($subDevicesData as $key => $subDeviceData) {
|
|
||||||
$subDeviceId = $subDeviceData['subdevice_id'];
|
|
||||||
$subDeviceLastReord = RecordManager::getLastRecord($subDeviceId);
|
|
||||||
$subDeviceLastReordValue[$subDeviceData['type']] = $subDeviceLastReord['value'];
|
|
||||||
|
|
||||||
if ($subDeviceLastReord['execuded'] == 0){
|
|
||||||
$logManager->write("[API] subDevice_ID ".$subDeviceId . " executed comand with value " . json_encode($subDeviceLastReordValue) ." executed " . $subDeviceLastReord['execuded'], LogRecordTypes::INFO);
|
|
||||||
RecordManager::setExecuted($subDeviceLastReord['record_id']);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$hostname = "";
|
|
||||||
$hostname = strtolower($device['name']);
|
|
||||||
$hostname = str_replace(' ', '_', $hostname);
|
|
||||||
|
|
||||||
$jsonAnswer['device']['hostname'] = $hostname;
|
|
||||||
$jsonAnswer['state'] = 'succes';
|
|
||||||
$jsonAnswer['values'] = $subDeviceLastReordValue;
|
|
||||||
$jsonAnswer['command'] = $command;
|
|
||||||
|
|
||||||
$this->response($jsonAnswer);
|
|
||||||
// this method returns response as json
|
|
||||||
//unset($logManager); //TODO: Opravit
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,24 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
class ExampleApi extends ApiController{
|
|
||||||
|
|
||||||
public function example(){
|
|
||||||
// if this function should be accessible only for logged users uncomment next line
|
|
||||||
// $this->requireAuth();
|
|
||||||
// if user is logged in, next lines will be processed
|
|
||||||
// otherwise script get terminated with 401 UNAUTHORIZED
|
|
||||||
|
|
||||||
|
|
||||||
// input data are stored in $this->input
|
|
||||||
// in this example we just copy input to response
|
|
||||||
$response = $this->input;
|
|
||||||
|
|
||||||
|
|
||||||
// this method returns response as json
|
|
||||||
$this->response($response);
|
|
||||||
// you can specify returned http code by second optional parameter
|
|
||||||
// default value is 200
|
|
||||||
// $this->response($response, $httpCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@@ -1,56 +0,0 @@
|
|||||||
<?php
|
|
||||||
class GoogleHomeApi{
|
|
||||||
static function response(){
|
|
||||||
//$this->requireAuth();
|
|
||||||
$json = file_get_contents('php://input');
|
|
||||||
$obj = json_decode($json, true);
|
|
||||||
|
|
||||||
$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
|
|
||||||
$apiLogManager->setLevel(LOGLEVEL);
|
|
||||||
|
|
||||||
header('Content-Type: application/json');
|
|
||||||
|
|
||||||
switch ($obj['inputs'][0]['intent']) {
|
|
||||||
case 'action.devices.SYNC':
|
|
||||||
GoogleHome::sync($obj['requestId']);
|
|
||||||
$apiLogManager->write("[Google Home] action.devices.SYNC", LogRecordTypes::INFO);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.QUERY':
|
|
||||||
GoogleHome::query($obj['requestId'], $obj['inputs'][0]['payload']);
|
|
||||||
$apiLogManager->write("[Google Home] action.devices.QUERY", LogRecordTypes::INFO);
|
|
||||||
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.EXECUTE':
|
|
||||||
|
|
||||||
GoogleHome::execute($obj['requestId'], $obj['inputs'][0]['payload']);
|
|
||||||
$apiLogManager->write("[Google Home] action.devices.EXECUTE", LogRecordTypes::INFO);
|
|
||||||
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
unset($apiLogManager);
|
|
||||||
}
|
|
||||||
|
|
||||||
static function autorize(){
|
|
||||||
$json = file_get_contents('php://input');
|
|
||||||
$obj = json_decode($json, true);
|
|
||||||
|
|
||||||
$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
|
|
||||||
$apiLogManager->setLevel(LOGLEVEL);
|
|
||||||
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
|
|
||||||
$apiLogManager->write("[API] GET body\n" . json_encode($_GET, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
|
|
||||||
unset($apiLogManager);
|
|
||||||
|
|
||||||
$get = [
|
|
||||||
"access_token"=>"2222255888", //TODO: FIX
|
|
||||||
"token_type"=>"Bearer",
|
|
||||||
"state"=>$_GET["state"],
|
|
||||||
];
|
|
||||||
|
|
||||||
echo $_GET["redirect_uri"] . '#' . http_build_query($get) ;
|
|
||||||
echo '<a href="'.$_GET["redirect_uri"] . '#' . http_build_query($get) . '">FINISH</a>';
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,12 +0,0 @@
|
|||||||
<?php
|
|
||||||
class PluginsApi extends ApiController{
|
|
||||||
|
|
||||||
public function default(){
|
|
||||||
$this->requireAuth();
|
|
||||||
$response = [];
|
|
||||||
|
|
||||||
// TODO: process the request
|
|
||||||
|
|
||||||
$this->response($response);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,26 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
class RecordApi extends ApiController{
|
|
||||||
|
|
||||||
public function default(){
|
|
||||||
//$this->requireAuth();
|
|
||||||
$response = [];
|
|
||||||
$roomIds = [];
|
|
||||||
$roomsData = RoomManager::getRoomsDefault();
|
|
||||||
|
|
||||||
foreach ($roomsData as $roomKey => $room) {
|
|
||||||
$roomIds[] = $room['room_id'];
|
|
||||||
}
|
|
||||||
|
|
||||||
$subDevicesData = SubDeviceManager::getSubdevicesByRoomIds($roomIds);
|
|
||||||
|
|
||||||
foreach ($roomsData as $roomKey => $roomData) {
|
|
||||||
$response[] = [
|
|
||||||
'room_id' => $roomData['room_id'],
|
|
||||||
'name' => $roomData['name'],
|
|
||||||
'widgets' => isset($subDevicesData[$roomData['room_id']]) ? $subDevicesData[$roomData['room_id']] : [],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
$this->response($response);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,64 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
class RoomsApi extends ApiController
|
|
||||||
{
|
|
||||||
|
|
||||||
public function
|
|
||||||
default()
|
|
||||||
{
|
|
||||||
//$this->requireAuth();
|
|
||||||
$response = [];
|
|
||||||
$roomIds = [];
|
|
||||||
$roomsData = RoomManager::getRoomsDefault();
|
|
||||||
|
|
||||||
foreach ($roomsData as $roomKey => $room) {
|
|
||||||
$roomIds[] = $room['room_id'];
|
|
||||||
}
|
|
||||||
|
|
||||||
//Translation Of Numeric Walues
|
|
||||||
$subDevicesData = SubDeviceManager::getSubdevicesByRoomIds($roomIds);
|
|
||||||
foreach ($subDevicesData as $subDeviceKey => $subDevice) {
|
|
||||||
foreach ($subDevice as $key => $value) {
|
|
||||||
$type = null;
|
|
||||||
if (strpos($subDevicesData[$subDeviceKey][$key]['type'], '-') !== false) {
|
|
||||||
$type = $subDevicesData[$subDeviceKey][$key]['type'];
|
|
||||||
} else if (strpos(SubDeviceManager::getSubDeviceMaster($subDevicesData[$subDeviceKey][$key]['subdevice_id'])['type'], '-') !== false) {
|
|
||||||
$type = SubDeviceManager::getSubDeviceMaster($subDevicesData[$subDeviceKey][$key]['subdevice_id'])['type'];
|
|
||||||
} else {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$cammelCaseClass = "";
|
|
||||||
foreach (explode('-', $type) as $word) {
|
|
||||||
$cammelCaseClass .= ucfirst($word);
|
|
||||||
}
|
|
||||||
if (!class_exists($cammelCaseClass)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$deviceClass = new $cammelCaseClass;
|
|
||||||
if (!method_exists($deviceClass, 'translate')) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$subDevicesData[$subDeviceKey][$key]['value'] = $deviceClass->translate($subDevicesData[$subDeviceKey][$key]['value']);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ($roomsData as $roomKey => $roomData) {
|
|
||||||
if ($roomData['device_count'] == 0) continue;
|
|
||||||
$response[] = [
|
|
||||||
'room_id' => $roomData['room_id'],
|
|
||||||
'name' => $roomData['name'],
|
|
||||||
'widgets' => isset($subDevicesData[$roomData['room_id']]) ? $subDevicesData[$roomData['room_id']] : [],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
$this->response($response);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function update($roomId)
|
|
||||||
{
|
|
||||||
//$this->requireAuth();
|
|
||||||
|
|
||||||
$subDevicesData = SubDeviceManager::getSubdevicesByRoomIds([$roomId]);
|
|
||||||
$this->response($subDevicesData);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,35 +0,0 @@
|
|||||||
<?php
|
|
||||||
class ServerApi extends ApiController {
|
|
||||||
private function getSystemMemInfo()
|
|
||||||
{
|
|
||||||
$data = explode("\n", file_get_contents("/proc/meminfo"));
|
|
||||||
$meminfo = array();
|
|
||||||
foreach ($data as $line) {
|
|
||||||
$data = explode(":", $line);
|
|
||||||
if (count($data)!=2) continue;
|
|
||||||
$meminfo[$data[0]] = trim($data[1]);
|
|
||||||
}
|
|
||||||
return $meminfo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function default(){
|
|
||||||
//$this->requireAuth();
|
|
||||||
$response = [
|
|
||||||
"cpu_load" => sys_getloadavg()[0],
|
|
||||||
"uptime" => shell_exec('uptime -p'),
|
|
||||||
"ramFree" => $this->getSystemMemInfo()["MemFree"],
|
|
||||||
"ramTotal" => $this->getSystemMemInfo()["MemTotal"],
|
|
||||||
"diskFree" => disk_free_space("/"),
|
|
||||||
"diskTotal" => disk_total_space("/"),
|
|
||||||
"serverTime" => date('m. d. Y H:i:s - e'),
|
|
||||||
];
|
|
||||||
$this->response($response);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function logStatus()
|
|
||||||
{
|
|
||||||
$logKeeper = new LogMaintainer();
|
|
||||||
$response = $logKeeper::getStats();
|
|
||||||
$this->response($response);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,85 +0,0 @@
|
|||||||
<?php
|
|
||||||
class UpdatesApi {
|
|
||||||
private function sendFile($path) {
|
|
||||||
header($_SERVER["SERVER_PROTOCOL"] . ' 200 OK', true, 200);
|
|
||||||
header('Content-Type: application/octet-stream', true);
|
|
||||||
header('Content-Disposition: attachment; filename=' . basename($path));
|
|
||||||
header('Content-Length: ' . filesize($path), true);
|
|
||||||
header('x-MD5: ' . md5_file($path), true);
|
|
||||||
readfile($path);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function validateHeader($headers){
|
|
||||||
if (
|
|
||||||
isset($_SERVER['HTTP_X_ESP8266_STA_MAC']) &&
|
|
||||||
isset($_SERVER['HTTP_X_ESP8266_SKETCH_MD5'])
|
|
||||||
) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public function default(){
|
|
||||||
$logManager = new LogManager('../logs/ota/'. date("Y-m-d").'.log');
|
|
||||||
$logManager->setLevel(LOGLEVEL);
|
|
||||||
$logManager->write("[Updater] Client Connected", LogRecordTypes::INFO);
|
|
||||||
|
|
||||||
// if($this->validateHeader($_SERVER)){
|
|
||||||
// header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Header");
|
|
||||||
// die();
|
|
||||||
// }
|
|
||||||
|
|
||||||
header('Content-type: text/plain; charset=utf8', true);
|
|
||||||
|
|
||||||
// //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($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
|
|
||||||
// $logManager->write("[Updater] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordTypes::INFO);
|
|
||||||
// exit();
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
$macAddress = $_SERVER['HTTP_X_ESP8266_STA_MAC'];
|
|
||||||
$localBinary = "../updater/" . str_replace(':', '', $macAddress) . ".bin";
|
|
||||||
$logManager->write("[Updater] url: " . $localBinary, LogRecordTypes::INFO);
|
|
||||||
$logManager->write("[Updater] version: " . $_SERVER['HTTP_X_ESP8266_SKETCH_MD5'], LogRecordTypes::INFO);
|
|
||||||
if (file_exists($localBinary)) {
|
|
||||||
$logManager->write("[Updater] version PHP: " . md5_file($localBinary), LogRecordTypes::INFO);
|
|
||||||
if ($_SERVER['HTTP_X_ESP8266_SKETCH_MD5'] != md5_file($localBinary)) {
|
|
||||||
$this->sendFile($localBinary);
|
|
||||||
//get device data
|
|
||||||
$device = DeviceManager::getDeviceByMac($macAddress);
|
|
||||||
$deviceName = $device['name'];
|
|
||||||
$deviceId = $device['device_id'];
|
|
||||||
//logfile write
|
|
||||||
$logManager->write("[Device] device_ID " . $deviceId . " was just updated to new version", LogRecordTypes::INFO);
|
|
||||||
$logManager->write("[Device] version hash: " . md5_file($localBinary), LogRecordTypes::INFO);
|
|
||||||
//notification
|
|
||||||
$notificationMng = new NotificationManager;
|
|
||||||
$notificationData = [
|
|
||||||
'title' => 'Info',
|
|
||||||
'body' => $deviceName.' was just updated to new version',
|
|
||||||
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
|
|
||||||
];
|
|
||||||
if ($notificationData != []) {
|
|
||||||
$subscribers = $notificationMng->getSubscription();
|
|
||||||
foreach ($subscribers as $key => $subscriber) {
|
|
||||||
$logManager->write("[NOTIFICATION] SENDING TO " . $subscriber['id'] . " ", LogRecordTypes::INFO);
|
|
||||||
$answer = $notificationMng->sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
header($_SERVER["SERVER_PROTOCOL"].' 304 Not Modified', true, 304);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
|
|
||||||
}
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,37 +0,0 @@
|
|||||||
<?php
|
|
||||||
class UsersApi extends ApiController{
|
|
||||||
public function default(){
|
|
||||||
//$this->requireAuth();
|
|
||||||
$response = null;
|
|
||||||
|
|
||||||
$users = UserManager::getUsers(["user_id", "username", "at_home"]);
|
|
||||||
|
|
||||||
foreach ($users as $key => $user) {
|
|
||||||
$response[] = [
|
|
||||||
"userName" => $user['username'],
|
|
||||||
"homeStatus" => ($user['at_home'] == 'true') ? true : false,
|
|
||||||
"avatarUrl" => UserManager::getAvatarUrl($user['user_id']),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->response($response);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function status(){
|
|
||||||
//$this->requireAuth();
|
|
||||||
$response = null;
|
|
||||||
$obj = $this->input;
|
|
||||||
$atHome = $obj['atHome'];
|
|
||||||
|
|
||||||
$user = UserManager::getUser($obj['user']);
|
|
||||||
$userAtHome = $user['at_home'];
|
|
||||||
$userId = $user['user_id'];
|
|
||||||
|
|
||||||
if (!empty($user)) {
|
|
||||||
if($userAtHome != $atHome){
|
|
||||||
UserManager::atHome($userId, $atHome);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$this->response(['value'=>'OK']);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,136 +0,0 @@
|
|||||||
<?php
|
|
||||||
class WidgetApi extends ApiController
|
|
||||||
{
|
|
||||||
|
|
||||||
public function run($subDeviceId)
|
|
||||||
{
|
|
||||||
//$this->requireAuth();
|
|
||||||
|
|
||||||
$response = null;
|
|
||||||
if (RecordManager::getLastRecord($subDeviceId)['execuded'] === 0) {
|
|
||||||
throw new Exception("Unreachable", 409);
|
|
||||||
}
|
|
||||||
|
|
||||||
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
|
|
||||||
if ($subDeviceData['type'] == 'on/off') {
|
|
||||||
$lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'];
|
|
||||||
RecordManager::create($subDeviceData['device_id'], 'on/off', (int) !$lastValue);
|
|
||||||
$response = !$lastValue;
|
|
||||||
} else {
|
|
||||||
throw new Exception("Bad Request", 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$i = 0;
|
|
||||||
$timeout = 20;
|
|
||||||
while (RecordManager::getLastRecord($subDeviceId)['execuded'] == 0) {
|
|
||||||
if ($i == $timeout) {
|
|
||||||
throw new Exception("Timeout", 444);
|
|
||||||
}
|
|
||||||
$i++;
|
|
||||||
usleep(250000);
|
|
||||||
}
|
|
||||||
$this->response(['value' => $response]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function detail($subDeviceId)
|
|
||||||
{
|
|
||||||
//$this->requireAuth();
|
|
||||||
$response = null;
|
|
||||||
$connectionError = true;
|
|
||||||
|
|
||||||
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
|
|
||||||
$deviceData = DeviceManager::getDeviceById($subDeviceData['device_id']);
|
|
||||||
|
|
||||||
//TODO: zeptat se @Patrik Je Graf Dobře Seřazený na DESC ?
|
|
||||||
$events = RecordManager::getAllRecordForGraph($subDeviceId);
|
|
||||||
if ( count($events) == 0){
|
|
||||||
throw new Exception("No Records", 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$LastRecordTime = new DateTime(reset($events)['time']);
|
|
||||||
$niceTime = Utilities::ago($LastRecordTime);
|
|
||||||
|
|
||||||
$interval = $LastRecordTime->diff(new DateTime());
|
|
||||||
$hours = $interval->format('%h');
|
|
||||||
$minutes = $interval->format('%i');
|
|
||||||
$lastSeen = ($hours * 60 + $minutes);
|
|
||||||
|
|
||||||
if (
|
|
||||||
$lastSeen < $deviceData['sleep_time'] ||
|
|
||||||
$subDeviceData['type'] == "on/off" ||
|
|
||||||
$subDeviceData['type'] == "door" ||
|
|
||||||
$subDeviceData['type'] == "wather"
|
|
||||||
) {
|
|
||||||
$connectionError = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$labels = [];
|
|
||||||
$values = [];
|
|
||||||
foreach ($events as $key => $event) {
|
|
||||||
$recordDatetime = new DateTime($event['time']);
|
|
||||||
if ($key == 0){
|
|
||||||
$labels[] = 'now';
|
|
||||||
} else {
|
|
||||||
$labels[] = $recordDatetime->format('H:i');
|
|
||||||
}
|
|
||||||
$values[] = [
|
|
||||||
'y' => $event['value'],
|
|
||||||
't' => $recordDatetime->getTimestamp() * 1000,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$response = [
|
|
||||||
'records' => $events,
|
|
||||||
'graph' => [
|
|
||||||
'type' => $this->getDeviceConfig($subDeviceData['type'])['graph'],
|
|
||||||
'data' => [
|
|
||||||
'labels' => $labels,
|
|
||||||
'datasets' => [[
|
|
||||||
//'label' => 'FUCK you',
|
|
||||||
'data' => $values,
|
|
||||||
]],
|
|
||||||
],
|
|
||||||
'options' => [
|
|
||||||
'scales' => [
|
|
||||||
'xAxis' => [[
|
|
||||||
'type' => 'time',
|
|
||||||
'distribution' => 'linear',
|
|
||||||
]],
|
|
||||||
|
|
||||||
],
|
|
||||||
'legend' => [
|
|
||||||
'display' => false
|
|
||||||
],
|
|
||||||
'tooltips' => [
|
|
||||||
'enabled' => true
|
|
||||||
],
|
|
||||||
'hover' => [
|
|
||||||
'mode' => true
|
|
||||||
],
|
|
||||||
],
|
|
||||||
],
|
|
||||||
'comError' => $connectionError,
|
|
||||||
'lastConnectionTime' => (empty($niceTime) ? "00:00" : $niceTime),
|
|
||||||
];
|
|
||||||
|
|
||||||
//TODO: Make Cleaner
|
|
||||||
if (isset(RANGES[$subDeviceData['type']])){
|
|
||||||
$response['graph']['options']['options']['scales']['yAxes'] = [[
|
|
||||||
'ticks' => [
|
|
||||||
'min' => RANGES[$subDeviceData['type']]['min'],
|
|
||||||
'max' => RANGES[$subDeviceData['type']]['max'],
|
|
||||||
'steps' => RANGES[$subDeviceData['type']]['scale'],
|
|
||||||
]
|
|
||||||
]];
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->response($response);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function getDeviceConfig($type){
|
|
||||||
if (isset(RANGES[$type])){
|
|
||||||
return RANGES[$type];
|
|
||||||
}
|
|
||||||
return RANGES[''];
|
|
||||||
}
|
|
||||||
}
|
|
30
app/class/ApiManager.php
Normal file
30
app/class/ApiManager.php
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
class ApiManager {
|
||||||
|
public function generateToken($username, $password){
|
||||||
|
$userManager = new UserManager();
|
||||||
|
if ($username != '' || $password != ''){
|
||||||
|
$userLogedIn = $userManager->loginNew($username, $password);
|
||||||
|
|
||||||
|
if ($userLogedIn != false){
|
||||||
|
// Create token header as a JSON string
|
||||||
|
$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
|
||||||
|
// Create token payload as a JSON string
|
||||||
|
$payload = json_encode(['user_id' => $userLogedIn]);
|
||||||
|
// Encode Header to Base64Url String
|
||||||
|
$base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
|
||||||
|
// Encode Payload to Base64Url String
|
||||||
|
$base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
|
||||||
|
// Create Signature Hash
|
||||||
|
$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, 'abC123!', true);
|
||||||
|
// Encode Signature to Base64Url String
|
||||||
|
$base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
|
||||||
|
// Create JWT
|
||||||
|
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
|
||||||
|
|
||||||
|
return $jwt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
@@ -3,21 +3,21 @@
|
|||||||
class AutomationManager{
|
class AutomationManager{
|
||||||
public static $automation;
|
public static $automation;
|
||||||
|
|
||||||
public static function remove($automationId) {
|
public function remove($automationId) {
|
||||||
return Db::command ('DELETE FROM automation WHERE automation_id=?', array ($automationId));
|
return Db::command ('DELETE FROM automation WHERE automation_id=?', array ($automationId));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function deactive($automationId) {
|
public function deactive($automationId) {
|
||||||
$automation = Db::loadOne ("SELECT * FROM automation WHERE automation_id=?" , array ($automationId));
|
$automation = Db::loadOne ("SELECT * FROM automation WHERE automation_id=?" , array ($automationId));
|
||||||
$flipedValue = ($automation['active'] == 1 ? 0 : 1);
|
$flipedValue = ($automation['active'] == 1 ? 0 : 1);
|
||||||
return Db::command ('UPDATE automation SET active = ? WHERE automation_id=?', array ($flipedValue,$automationId));
|
return Db::command ('UPDATE automation SET active = ? WHERE automation_id=?', array ($flipedValue,$automationId));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function restart($automationId) {
|
public 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 function create ($name, $onDays, $doCode, $ifCode, $automationId = "") {
|
||||||
$userId = UserManager::getUserData('user_id');
|
$userId = UserManager::getUserData('user_id');
|
||||||
$scene = array (
|
$scene = array (
|
||||||
'name' => $name,
|
'name' => $name,
|
||||||
@@ -38,12 +38,12 @@ class AutomationManager{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getAll(){
|
public function getAll(){
|
||||||
return Db::loadAll ("SELECT * FROM automation");
|
return Db::loadAll ("SELECT * FROM automation");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function executeAll(){
|
public function executeAll(){
|
||||||
global $logManager;
|
global $logManager;
|
||||||
|
|
||||||
$automations = Db::loadAll ("SELECT * FROM automation");
|
$automations = Db::loadAll ("SELECT * FROM automation");
|
@@ -1,5 +1,4 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
class Db{
|
class Db{
|
||||||
private static $join;
|
private static $join;
|
||||||
private static $commandDatabase = array (
|
private static $commandDatabase = array (
|
||||||
@@ -58,41 +57,44 @@ class Db{
|
|||||||
public static function add ($table, $values = array()) {
|
public static function add ($table, $values = array()) {
|
||||||
return self::command (
|
return self::command (
|
||||||
"INSERT INTO `$table` (`" .
|
"INSERT INTO `$table` (`" .
|
||||||
implode('`, `', array_keys($values)) .
|
implode('`, `', array_keys($values)) .
|
||||||
"`) VALUES (" .
|
"`) VALUES (" .
|
||||||
str_repeat('?,', (count($values) > 0 ? count($values)-1 : 0)) .
|
str_repeat('?,', (count($values) > 0 ? count($values)-1 : 0)) .
|
||||||
"?)"
|
"?)"
|
||||||
, array_values ($values)
|
, array_values ($values));
|
||||||
);
|
}
|
||||||
}
|
// TODO: pokud vlozim prazdne pole tak chyba ??
|
||||||
// TODO: pokud vlozim prazdne pole tak chyba ??
|
public static function addAll ($table, $values = array ()) {
|
||||||
public static function addAll ($table, $values = array ()) {
|
try {
|
||||||
try {
|
foreach ($values as $value) {
|
||||||
foreach ($values as $value) {
|
self::add ($table, $value);
|
||||||
self::add ($table, $value);
|
}
|
||||||
}
|
} catch (PDOException $ex) {
|
||||||
} catch (PDOException $ex) {
|
throw new PDOException ($ex->getMessage());
|
||||||
throw new PDOException ($ex->getMessage());
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public static function edit ($table, $values = array(), $conditions, $values2 = array()) {
|
public static function edit (
|
||||||
return self::command (
|
$table,
|
||||||
"UPDATE `$table` SET `" .
|
$values = array(),
|
||||||
implode('` =?, `', array_keys($values)) .
|
$conditions,
|
||||||
"` =? " .
|
$values2 = array()
|
||||||
$conditions
|
) {
|
||||||
, array_merge (array_values ($values), $values2)
|
return self::command (
|
||||||
);
|
"UPDATE `$table` SET `" .
|
||||||
}
|
implode('` =?, `', array_keys($values)) .
|
||||||
|
"` =? " .
|
||||||
|
$conditions
|
||||||
|
, array_merge (array_values ($values), $values2));
|
||||||
|
}
|
||||||
|
|
||||||
public static function insertId () {
|
public static function insertId () {
|
||||||
return self::$join->lastInsertId ();
|
return self::$join->lastInsertId ();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function addId ($lastTable, $lastIdName) {
|
public static function addId ($lastTable, $lastIdName) {
|
||||||
$answer = self::$join->prepare ("SELECT `$lastIdName` FROM `$lastTable` ORDER BY `$lastIdName` DESC");
|
$answer = self::$join->prepare ("SELECT `$lastIdName` FROM `$lastTable` ORDER BY `$lastIdName` DESC");
|
||||||
$answer->execute ();
|
$answer->execute ();
|
||||||
return $answer->fetch (PDO::FETCH_NUM)[0];
|
return $answer->fetch (PDO::FETCH_NUM)[0];
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -3,19 +3,19 @@ class DashboardManager{
|
|||||||
public static $devices;
|
public static $devices;
|
||||||
|
|
||||||
|
|
||||||
static function getAllDashboards ($userId) {
|
function getAllDashboards ($userId) {
|
||||||
return Db::loadAll ("SELECT * FROM dashboard WHERE user_id=?", array($userId));
|
return Db::loadAll ("SELECT * FROM dashboard WHERE user_id=?", array($userId));
|
||||||
}
|
}
|
||||||
|
|
||||||
static function getAllSubDevices ($userId) {
|
function getAllSubDevices ($userId) {
|
||||||
return Db::loadAll ("SELECT * FROM subdevices WHERE subdevice_id IN (SELECT subdevice_id FROM dashboard WHERE user_id=?)", array($userId));
|
return Db::loadAll ("SELECT * FROM subdevices WHERE subdevice_id IN (SELECT subdevice_id FROM dashboard WHERE user_id=?)", array($userId));
|
||||||
}
|
}
|
||||||
|
|
||||||
static function getSubDevice ($userId, $subDeviceId) {
|
function getSubDevice ($userId, $subDeviceId) {
|
||||||
return Db::loadOne ("SELECT * FROM subdevices WHERE subdevice_id = (SELECT subdevice_id FROM dashboard WHERE user_id=? AND subdevice_id = ? )", array($userId, $subDeviceId));
|
return Db::loadOne ("SELECT * FROM subdevices WHERE subdevice_id = (SELECT subdevice_id FROM dashboard WHERE user_id=? AND subdevice_id = ? )", array($userId, $subDeviceId));
|
||||||
}
|
}
|
||||||
|
|
||||||
static function Add ($subDeviceId) {
|
function Add ($subDeviceId) {
|
||||||
if (self::getSubDevice(UserManager::getUserData('user_id'), $subDeviceId) == null){
|
if (self::getSubDevice(UserManager::getUserData('user_id'), $subDeviceId) == null){
|
||||||
|
|
||||||
// to do: pokud existuje nepridej
|
// to do: pokud existuje nepridej
|
||||||
@@ -34,7 +34,7 @@ class DashboardManager{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static function Remove ($subDeviceId){
|
function Remove ($subDeviceId){
|
||||||
$userId = UserManager::getUserData('user_id');
|
$userId = UserManager::getUserData('user_id');
|
||||||
Db::command ('DELETE FROM dashboard WHERE subdevice_id=? AND user_id = ?', array ($subDeviceId, $userId));
|
Db::command ('DELETE FROM dashboard WHERE subdevice_id=? AND user_id = ?', array ($subDeviceId, $userId));
|
||||||
}
|
}
|
@@ -2,47 +2,37 @@
|
|||||||
class DeviceManager{
|
class DeviceManager{
|
||||||
public static $devices;
|
public static $devices;
|
||||||
|
|
||||||
static function getAllDevices () {
|
function getAllDevices () {
|
||||||
return Db::loadAll ("SELECT devices.* FROM devices
|
return Db::loadAll ("SELECT * FROM devices WHERE approved != ?", Array(2));
|
||||||
WHERE approved != ?", Array(2));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static function getAllDevicesInRoom ($roomId = "") {
|
function getAllDevicesInRoom ($roomId = "") {
|
||||||
return Db::loadAll ("SELECT * FROM devices WHERE room_id = ? AND approved != ?", Array($roomId, 2));
|
return Db::loadAll ("SELECT * FROM devices WHERE room_id = ? AND approved != ?", Array($roomId, 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
static function getOtherDevices(){
|
function getOtherDevices(){
|
||||||
return Db::loadAll ("SELECT * FROM devices WHERE room_id IS NULL ");
|
return Db::loadAll ("SELECT * FROM devices WHERE room_id IS NULL ");
|
||||||
}
|
}
|
||||||
|
|
||||||
static function getDeviceByToken($deviceToken) {
|
function getDeviceByToken($deviceToken) {
|
||||||
return Db::loadOne("SELECT * FROM devices WHERE token = ?", array($deviceToken));
|
return Db::loadOne("SELECT * FROM devices WHERE token = ?", array($deviceToken));
|
||||||
}
|
}
|
||||||
|
|
||||||
static function getDeviceByMac($deviceMac) {
|
function getDeviceByMac($deviceMac) {
|
||||||
return Db::loadOne("SELECT * FROM devices WHERE mac = ?", array($deviceMac));
|
return Db::loadOne("SELECT * FROM devices WHERE mac = ?", array($deviceMac));
|
||||||
}
|
}
|
||||||
|
|
||||||
static function getDeviceById($deviceId) {
|
function getDeviceById($deviceId) {
|
||||||
return Db::loadOne("SELECT * FROM devices WHERE device_id = ?", array($deviceId));
|
return Db::loadOne("SELECT * FROM devices WHERE device_id = ?", array($deviceId));
|
||||||
}
|
}
|
||||||
|
|
||||||
static function getAllDevicesSorted ($sort, $sortType = "ASC") {
|
public function create ($name, $token) {
|
||||||
return Db::loadAll ("SELECT devices.* FROM devices
|
|
||||||
LEFT JOIN rooms ON (devices.room_id = rooms.room_id)
|
|
||||||
WHERE devices.approved != ? ORDER BY $sort $sortType", Array(2));
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function create ($name, $token, $type = "") {
|
|
||||||
$defaultRoom = RoomManager::getDefaultRoomId();
|
$defaultRoom = RoomManager::getDefaultRoomId();
|
||||||
$device = array (
|
$device = array (
|
||||||
'name' => $name,
|
'name' => $name,
|
||||||
'token' => $token,
|
'token' => $token,
|
||||||
'room_id' => $defaultRoom,
|
'room_id' => $defaultRoom,
|
||||||
);
|
);
|
||||||
if (!empty($type)) {
|
|
||||||
$device['type'] = $type;
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
Db::add ('devices', $device);
|
Db::add ('devices', $device);
|
||||||
return Db::loadOne("SELECT device_id FROM devices WHERE token = ?", array($token))['device_id'];
|
return Db::loadOne("SELECT device_id FROM devices WHERE token = ?", array($token))['device_id'];
|
||||||
@@ -52,7 +42,7 @@ class DeviceManager{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function edit ($deviceId, $values = []) {
|
public function edit ($deviceId, $values = []) {
|
||||||
try {
|
try {
|
||||||
Db::edit ('devices', $values, 'WHERE device_id = ?', array($deviceId));
|
Db::edit ('devices', $values, 'WHERE device_id = ?', array($deviceId));
|
||||||
} catch(PDOException $error) {
|
} catch(PDOException $error) {
|
||||||
@@ -61,7 +51,7 @@ class DeviceManager{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function editByToken ($token, $values = []) {
|
public function editByToken ($token, $values = []) {
|
||||||
try {
|
try {
|
||||||
Db::edit ('devices', $values, 'WHERE token = ?', array($token));
|
Db::edit ('devices', $values, 'WHERE token = ?', array($token));
|
||||||
} catch(PDOException $error) {
|
} catch(PDOException $error) {
|
||||||
@@ -75,7 +65,7 @@ class DeviceManager{
|
|||||||
* @param [type] $roomId [číslo místnosti do kter se má zařízení přiřadit]
|
* @param [type] $roomId [číslo místnosti do kter se má zařízení přiřadit]
|
||||||
* @param [type] $deviceId [Číslo zařízení které chcete přiřadit do místnosti]
|
* @param [type] $deviceId [Číslo zařízení které chcete přiřadit do místnosti]
|
||||||
*/
|
*/
|
||||||
public static function assignRoom ($roomId, $deviceId) {
|
public function assignRoom ($roomId, $deviceId) {
|
||||||
$device = array (
|
$device = array (
|
||||||
'room_id' => $roomId,
|
'room_id' => $roomId,
|
||||||
);
|
);
|
||||||
@@ -91,15 +81,15 @@ class DeviceManager{
|
|||||||
* [delete Smazání zařízení]
|
* [delete Smazání zařízení]
|
||||||
* @param [type] $deviceId [Id zařízení ke smazání]
|
* @param [type] $deviceId [Id zařízení ke smazání]
|
||||||
*/
|
*/
|
||||||
public static function delete ($deviceId) {
|
public function delete ($deviceId) {
|
||||||
Db::command ('DELETE FROM devices WHERE device_id=?', array ($deviceId));
|
Db::command ('DELETE FROM devices WHERE device_id=?', array ($deviceId));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function registeret ($deviceToken) {
|
public function registeret ($deviceToken) {
|
||||||
return (count(Db::loadAll ("SELECT * FROM devices WHERE token=?", array($deviceToken))) == 1 ? true : false);
|
return (count(Db::loadAll ("SELECT * FROM devices WHERE token=?", array($deviceToken))) == 1 ? true : false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function approved ($deviceToken) {
|
public function approved ($deviceToken) {
|
||||||
return (count(Db::loadAll ("SELECT * FROM devices WHERE token=? AND approved = ?", array($deviceToken, 1))) == 1 ? true : false);
|
return (count(Db::loadAll ("SELECT * FROM devices WHERE token=? AND approved = ?", array($deviceToken, 1))) == 1 ? true : false);
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -17,19 +17,18 @@ class LanguageManager
|
|||||||
|
|
||||||
function load()
|
function load()
|
||||||
{
|
{
|
||||||
$file = '../lang/en.php';
|
$file = './app/lang/en.php';
|
||||||
if (!file_exists($file)){
|
if (!file_exists($file)){
|
||||||
echo 'ERROR: en.php not found';
|
|
||||||
die();
|
die();
|
||||||
//TODO add lng EXEPTIONS
|
//TODO add lng EXEPTIONS
|
||||||
}
|
}
|
||||||
$arrayFirst = include($file);
|
$arrayFirst = include($file);
|
||||||
$file = '../lang/' . $this->lngCode . '.php';
|
$file = './app/lang/' . $this->lngCode . '.php';
|
||||||
$arraySecond = [];
|
$arraySecond = [];
|
||||||
if (file_exists($file)){
|
if (file_exists($file)){
|
||||||
$arraySecond = include($file);
|
$arraySecond = include($file);
|
||||||
}
|
}
|
||||||
$this->lngDatabase = array_merge($arrayFirst, $arraySecond);
|
$this->lngDatabase = array_merge($arrayFirst,$arraySecond);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
60
app/class/LogManager.php
Normal file
60
app/class/LogManager.php
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
class LogRecordType{
|
||||||
|
const WARNING = 'warning';
|
||||||
|
const ERROR = 'error';
|
||||||
|
const INFO = 'info';
|
||||||
|
}
|
||||||
|
|
||||||
|
class LogKeeper
|
||||||
|
{
|
||||||
|
function purge($days){
|
||||||
|
$todayFileName = date("Y-m-d").'.log';
|
||||||
|
$seconds = $days * 86400;
|
||||||
|
|
||||||
|
$logFiles = scandir('./app/logs/');
|
||||||
|
foreach ($logFiles as $key => $file) {
|
||||||
|
if (in_array($file,array(".","..", ".gitkeep", $todayFileName)))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (filemtime($file) > $seconds) {
|
||||||
|
unlink('./app/logs/'.$file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class LogManager
|
||||||
|
{
|
||||||
|
|
||||||
|
private $logFile;
|
||||||
|
function __construct($fileName = "")
|
||||||
|
{
|
||||||
|
if ($fileName == ""){
|
||||||
|
$fileName = './app/logs/'. date("Y-m-d").'.log';
|
||||||
|
}
|
||||||
|
if(!is_dir("./app/logs/"))
|
||||||
|
{
|
||||||
|
mkdir("./app/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";
|
||||||
|
if (strlen($record) > 65 ) {
|
||||||
|
$record = Utilities::stringInsert($record,"\n",65);
|
||||||
|
}
|
||||||
|
fwrite($this->logFile, $record);
|
||||||
|
}
|
||||||
|
|
||||||
|
function __destruct(){
|
||||||
|
if (isset($this->logFile)) {
|
||||||
|
fclose($this->logFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@@ -2,27 +2,25 @@
|
|||||||
/**
|
/**
|
||||||
* Notification Manager
|
* Notification Manager
|
||||||
*/
|
*/
|
||||||
//TODO: Working timestamp to $title
|
//TODO: Working timestamp to body or $title
|
||||||
class NotificationManager
|
class NotificationManager
|
||||||
{
|
{
|
||||||
public static function addSubscriber($userID, $token){
|
function addSubscriber($userID = '', $token = ''){
|
||||||
if (!empty($userID) && !empty($token)) {
|
$notificationSubscriber = $subDeviceId = Db::loadOne('SELECT id FROM notifications WHERE token = ?;', array($token));
|
||||||
$notificationSubscriber = $subDeviceId = Db::loadOne('SELECT id FROM notifications WHERE token = ?;', array($token));
|
if ($notificationSubscriber == ''){
|
||||||
if ($notificationSubscriber == ''){
|
$notification = array (
|
||||||
$notification = array (
|
'user_id' => $userID,
|
||||||
'user_id' => $userID,
|
'token' => $token,
|
||||||
'token' => $token,
|
);
|
||||||
);
|
Db::add ('notifications', $notification);
|
||||||
Db::add ('notifications', $notification);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getSubscription () {
|
function getSubscription () {
|
||||||
return Db::loadAll ("SELECT * FROM notifications");
|
return Db::loadAll ("SELECT * FROM notifications");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function sendSimpleNotification(string $serverKey, string $to, array $data, bool $timeStamp = false){
|
function sendSimpleNotification(string $serverKey, string $to, array $data, bool $timeStamp = false){
|
||||||
$dataTemplate = [
|
$dataTemplate = [
|
||||||
'title' => '',
|
'title' => '',
|
||||||
'body' => '',
|
'body' => '',
|
||||||
@@ -39,7 +37,7 @@ class NotificationManager
|
|||||||
|
|
||||||
$notification = new Notification($serverKey);
|
$notification = new Notification($serverKey);
|
||||||
$notification->to($to);
|
$notification->to($to);
|
||||||
$notification->notification($data['title'], date("h:i") . " - " . $data['body'], $data['icon'], '');
|
$notification->notification($data['title'], $data['body'], $data['icon'], '');
|
||||||
$answer = $notification->send();
|
$answer = $notification->send();
|
||||||
$notification = null;
|
$notification = null;
|
||||||
|
|
||||||
@@ -78,7 +76,7 @@ class Notification
|
|||||||
}
|
}
|
||||||
|
|
||||||
$this->jsonPayload["data"]["notification"]["title"] = $title;
|
$this->jsonPayload["data"]["notification"]["title"] = $title;
|
||||||
$this->jsonPayload["data"]["notification"]["body"] = $body;
|
$this->jsonPayload["data"]["notification"]["body"] = date("h:i") . " - " . $body;
|
||||||
$this->jsonPayload["data"]["notification"]["icon"] = $icon;
|
$this->jsonPayload["data"]["notification"]["icon"] = $icon;
|
||||||
$this->jsonPayload["data"]["notification"]["click_action"] = $action;
|
$this->jsonPayload["data"]["notification"]["click_action"] = $action;
|
||||||
}
|
}
|
@@ -1,13 +1,13 @@
|
|||||||
<?php
|
<?php
|
||||||
class Partial{
|
class Partial{
|
||||||
private $assignedValues = [];
|
var $assignedValues = [];
|
||||||
private $partBuffer;
|
var $partBuffer;
|
||||||
private $path;
|
var $path;
|
||||||
private $debug;
|
var $debug;
|
||||||
|
|
||||||
function __construct($path = "", $debug = false) {
|
function __construct($path = "", $debug = false) {
|
||||||
$this->debug = $debug;
|
$this->debug = $debug;
|
||||||
if (!empty('../app/views/templates/part/' . $path . '.phtml') && file_exists('../app/views/templates/part/' . $path . '.phtml')) {
|
if (!empty('app/templates/part/' . $path . '.phtml') && file_exists('app/templates/part/' . $path . '.phtml')) {
|
||||||
$this->path = $path;
|
$this->path = $path;
|
||||||
} else {
|
} else {
|
||||||
echo '<pre>';
|
echo '<pre>';
|
||||||
@@ -29,6 +29,6 @@ class Partial{
|
|||||||
extract($this->assignedValues);
|
extract($this->assignedValues);
|
||||||
}
|
}
|
||||||
|
|
||||||
require('../app/views/templates/part/' . $this->path . '.phtml');
|
require('app/templates/part/' . $this->path . '.phtml');
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -2,45 +2,16 @@
|
|||||||
class RecordManager{
|
class RecordManager{
|
||||||
public static $records;
|
public static $records;
|
||||||
|
|
||||||
public static function createWithSubId ($subDeviceId, $value) {
|
public function create ($deviceId, $type, $value) {
|
||||||
try {
|
|
||||||
$record = [
|
|
||||||
'execuded' => 1,
|
|
||||||
];
|
|
||||||
Db::edit ('records', $record, 'WHERE subdevice_id = ?', array ($subDeviceId));
|
|
||||||
$record = array (
|
|
||||||
'subdevice_id' => $subDeviceId,
|
|
||||||
'value' => $value,
|
|
||||||
);
|
|
||||||
return Db::add ('records', $record);
|
|
||||||
} catch(PDOException $error) {
|
|
||||||
echo $error->getMessage();
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function create ($deviceId, $type, $value) {
|
|
||||||
$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;
|
||||||
};
|
};
|
||||||
|
$record = array (
|
||||||
//Ochrana proti duplicitním hodnotám zapisují se jen změny
|
'subdevice_id' => $subDeviceId,
|
||||||
if (self::getLastRecord($subDeviceId, 1)['value'] === $value){
|
'value' => $value,
|
||||||
return false;
|
);
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$record = [
|
|
||||||
'execuded' => 1,
|
|
||||||
];
|
|
||||||
Db::edit ('records', $record, 'WHERE subdevice_id = ?', array ($subDeviceId));
|
|
||||||
|
|
||||||
$record = array (
|
|
||||||
'subdevice_id' => $subDeviceId,
|
|
||||||
'value' => $value,
|
|
||||||
);
|
|
||||||
return Db::add ('records', $record);
|
return Db::add ('records', $record);
|
||||||
} catch(PDOException $error) {
|
} catch(PDOException $error) {
|
||||||
echo $error->getMessage();
|
echo $error->getMessage();
|
||||||
@@ -71,20 +42,15 @@ class RecordManager{
|
|||||||
return Db::loadAll('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC LIMIT ?;', array($subDeviceId, 999, $num));
|
return Db::loadAll('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC LIMIT ?;', array($subDeviceId, 999, $num));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getLastRecordNotNull($subDeviceId) {
|
|
||||||
return Db::loadOne('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC;', array($subDeviceId, 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function getAllRecord($subDeviceId, $timeFrom, $timeTo) {
|
public static function getAllRecord($subDeviceId, $timeFrom, $timeTo) {
|
||||||
return Db::loadAll('SELECT * FROM records WHERE subdevice_id = ? AND time >= ? AND time <= ? AND value != ? ORDER BY time;', array($subDeviceId, $timeFrom, $timeTo, 999));
|
return Db::loadAll('SELECT * FROM records WHERE subdevice_id = ? AND time >= ? AND time <= ? AND value != ? ORDER BY time;', array($subDeviceId, $timeFrom, $timeTo, 999));
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO: Zeptat se @Patrik jestli je secure pak používat periodu přímo do SQL a pak pře url SQL Injection
|
|
||||||
public static function getAllRecordForGraph($subDeviceId, $period = "day", $groupBy = "hour") {
|
public static function getAllRecordForGraph($subDeviceId, $period = "day", $groupBy = "hour") {
|
||||||
$periodLocal = '- 1' . strtoupper($period);
|
$periodLocal = '- 1 ' . strtoupper($period);
|
||||||
$dateTime = new DateTime();
|
$dateTime = new DateTime();
|
||||||
$dateTime = $dateTime->modify($periodLocal);
|
$dateTime = $dateTime->modify($periodLocal);
|
||||||
$dateTime = $dateTime->format('Y-m-d H:i:s');
|
$dateTime = $dateTime->format('Y-m-d');
|
||||||
$groupBy = strtoupper($groupBy).'(time)';
|
$groupBy = strtoupper($groupBy).'(time)';
|
||||||
$sql = 'SELECT value, time FROM records
|
$sql = 'SELECT value, time FROM records
|
||||||
WHERE
|
WHERE
|
||||||
@@ -94,7 +60,7 @@ class RecordManager{
|
|||||||
AND
|
AND
|
||||||
time > ?
|
time > ?
|
||||||
GROUP BY '.$groupBy.'
|
GROUP BY '.$groupBy.'
|
||||||
ORDER BY time Desc';
|
ORDER BY time ASC';
|
||||||
//TODO: Prasárna Opravit
|
//TODO: Prasárna Opravit
|
||||||
return Db::loadAll($sql, array($subDeviceId, $dateTime));
|
return Db::loadAll($sql, array($subDeviceId, $dateTime));
|
||||||
}
|
}
|
||||||
@@ -105,6 +71,7 @@ class RecordManager{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//TODO: zkontrolovat jestli neco nezbilo po smazaní
|
//TODO: zkontrolovat jestli neco nezbilo po smazaní
|
||||||
public static function cleanSubdeviceRecords ($subDeviceId) {
|
public static function cleanSubdeviceRecords ($subDeviceId) {
|
||||||
Db::command ('DELETE FROM records WHERE subdevice_id = ?);', array($subDeviceId));
|
Db::command ('DELETE FROM records WHERE subdevice_id = ?);', array($subDeviceId));
|
31
app/class/RoomManager.php
Normal file
31
app/class/RoomManager.php
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
class RoomManager{
|
||||||
|
public static $rooms;
|
||||||
|
|
||||||
|
function getDefaultRoomId() {
|
||||||
|
$defaultRoom = Db::loadOne("SELECT room_id FROM rooms WHERE 'default' = 1");
|
||||||
|
return $defaultRoom['room_id'];
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAllRooms () {
|
||||||
|
$allRoom = Db::loadAll ("SELECT rooms.*, COUNT(devices.device_id) as device_count FROM rooms LEFT JOIN devices ON (devices.room_id=rooms.room_id) GROUP BY rooms.room_id");
|
||||||
|
return $allRoom;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function create ($name) {
|
||||||
|
$room = array (
|
||||||
|
'name' => $name,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
Db::add ('rooms', $room);
|
||||||
|
} catch(PDOException $error) {
|
||||||
|
echo $error->getMessage();
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function delete ($roomId) {
|
||||||
|
Db::command ('DELETE FROM rooms WHERE room_id=?', array ($roomId));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
30
app/class/Route.php
Normal file
30
app/class/Route.php
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
class Route{
|
||||||
|
private $urls = [];
|
||||||
|
private $views = [];
|
||||||
|
|
||||||
|
function __construct() {
|
||||||
|
// code...
|
||||||
|
}
|
||||||
|
|
||||||
|
function add($url, $view = "", $conrol = "") {
|
||||||
|
$this->urls[] = '/'.trim($url, '/');
|
||||||
|
if (!empty($view)) {
|
||||||
|
$this->views[] = $view;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function submit(){
|
||||||
|
$urlGetParam = isset($_GET['url']) ? '/' . $_GET['url'] : '/';
|
||||||
|
foreach ($this->urls as $urlKey => $urlValue) {
|
||||||
|
if ($urlValue === $urlGetParam) {
|
||||||
|
$useView = $this->views[$urlKey];
|
||||||
|
new $useView();
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
echo 'Not Fount 404';
|
||||||
|
die();
|
||||||
|
//TODO: 404 přidělat
|
||||||
|
}
|
||||||
|
}
|
@@ -2,7 +2,7 @@
|
|||||||
class SceneManager{
|
class SceneManager{
|
||||||
public static $scenes;
|
public static $scenes;
|
||||||
|
|
||||||
public static function create ($icon, $name, $doCode) {
|
public function create ($icon, $name, $doCode) {
|
||||||
$scene = array (
|
$scene = array (
|
||||||
'icon' => $icon,
|
'icon' => $icon,
|
||||||
'name' => $name,
|
'name' => $name,
|
||||||
@@ -16,15 +16,15 @@ class SceneManager{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getAllScenes () {
|
public function getAllScenes () {
|
||||||
return Db::loadAll ("SELECT * FROM scenes");
|
return Db::loadAll ("SELECT * FROM scenes");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getScene ($sceneId) {
|
public function getScene ($sceneId) {
|
||||||
return Db::loadOne("SELECT * FROM scenes WHERE scene_id = ?", array($sceneId));
|
return Db::loadOne("SELECT * FROM scenes WHERE scene_id = ?", array($sceneId));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function execScene ($sceneId) {
|
public function execScene ($sceneId) {
|
||||||
$sceneData = SceneManager::getScene($sceneId);
|
$sceneData = SceneManager::getScene($sceneId);
|
||||||
$sceneDoJson = $sceneData['do_something'];
|
$sceneDoJson = $sceneData['do_something'];
|
||||||
$sceneDoArray = json_decode($sceneDoJson);
|
$sceneDoArray = json_decode($sceneDoJson);
|
||||||
@@ -34,7 +34,7 @@ class SceneManager{
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function delete($sceneId){
|
public function delete($sceneId){
|
||||||
Db::command ('DELETE FROM scenes WHERE scene_id=?', array ($sceneId));
|
Db::command ('DELETE FROM scenes WHERE scene_id=?', array ($sceneId));
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -3,20 +3,17 @@ class SubDeviceManager
|
|||||||
{
|
{
|
||||||
public static $devices;
|
public static $devices;
|
||||||
|
|
||||||
public static function getAllSubDevices($deviceId = null)
|
public function getAllSubDevices($deviceId)
|
||||||
{
|
{
|
||||||
if ($deviceId == null){
|
|
||||||
return Db::loadAll("SELECT * FROM subdevices");
|
|
||||||
}
|
|
||||||
return Db::loadAll("SELECT * FROM subdevices WHERE device_id = ?", array($deviceId));
|
return Db::loadAll("SELECT * FROM subdevices WHERE device_id = ?", array($deviceId));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getSubDeviceMaster($subDeviceId)
|
public function getSubDeviceMaster($subDeviceId)
|
||||||
{
|
{
|
||||||
return Db::loadOne("SELECT * FROM devices WHERE device_id = (SELECT device_id FROM subdevices WHERE subdevice_id = ?)", array($subDeviceId));
|
return Db::loadOne("SELECT * FROM devices WHERE device_id = (SELECT device_id FROM subdevices WHERE subdevice_id = ?)", array($subDeviceId));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getSubDeviceByMaster($deviceId, $subDeviceType = null)
|
public function getSubDeviceByMaster($deviceId, $subDeviceType = null)
|
||||||
{
|
{
|
||||||
if ($subDeviceType == null) {
|
if ($subDeviceType == null) {
|
||||||
return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ?;", array($deviceId));
|
return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ?;", array($deviceId));
|
||||||
@@ -25,21 +22,21 @@ class SubDeviceManager
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getSubDeviceByMasterAndType($deviceId, $subDeviceType = '')
|
public function getSubDeviceByMasterAndType($deviceId, $subDeviceType = null)
|
||||||
{
|
{
|
||||||
if ($subDeviceType == '') {
|
if (!empty($subDeviceType)) {
|
||||||
return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ?;", array($deviceId));
|
return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ?;", array($deviceId));
|
||||||
} else {
|
} else {
|
||||||
return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ? AND type = ?;", array($deviceId, $subDeviceType));
|
return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ? AND type = ?;", array($deviceId, $subDeviceType));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getSubDevice($subDeviceId)
|
public function getSubDevice($subDeviceId)
|
||||||
{
|
{
|
||||||
return Db::loadOne("SELECT * FROM subdevices WHERE subdevice_id = ?;", array($subDeviceId));
|
return Db::loadOne("SELECT * FROM subdevices WHERE subdevice_id = ?;", array($subDeviceId));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getSubDevicesTypeForMater($deviceId)
|
public function getSubDevicesTypeForMater($deviceId)
|
||||||
{
|
{
|
||||||
$parsedTypes = [];
|
$parsedTypes = [];
|
||||||
$types = Db::loadAll("SELECT type FROM subdevices WHERE device_id = ?;", array($deviceId));
|
$types = Db::loadAll("SELECT type FROM subdevices WHERE device_id = ?;", array($deviceId));
|
||||||
@@ -51,7 +48,7 @@ class SubDeviceManager
|
|||||||
|
|
||||||
//check if dubdevice exist
|
//check if dubdevice exist
|
||||||
|
|
||||||
public static function create($deviceId, $type, $unit)
|
public function create($deviceId, $type, $unit)
|
||||||
{
|
{
|
||||||
$record = array(
|
$record = array(
|
||||||
'device_id' => $deviceId,
|
'device_id' => $deviceId,
|
||||||
@@ -66,35 +63,9 @@ class SubDeviceManager
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function remove($subDeviceId)
|
public function remove($subDeviceId)
|
||||||
{
|
{
|
||||||
RecordManager::cleanSubdeviceRecords($subDeviceId);
|
RecordManager::cleanSubdeviceRecords($subDeviceId);
|
||||||
return Db::loadAll("DELETE FROM subdevices WHERE subdevice_id = ?", array($subDeviceId));
|
return Db::loadAll("DELETE FROM subdevices WHERE subdevice_id = ?", array($subDeviceId));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getSubdevicesByRoomIds($roomIds = NULL) {
|
|
||||||
if(empty($roomIds)) return NULL;
|
|
||||||
|
|
||||||
//TODO: @Patrik Check line 89
|
|
||||||
$rows = Db::loadAll("
|
|
||||||
SELECT d.room_id, sd.subdevice_id, sd.device_id, d.name, sd.type, sd.unit, r.value FROM subdevices sd
|
|
||||||
JOIN devices d ON sd.device_id = d.device_id
|
|
||||||
JOIN records r ON r.subdevice_id = sd.subdevice_id
|
|
||||||
WHERE d.room_id IN (".str_repeat("?,", count($roomIds)-1)."?)
|
|
||||||
AND r.record_id IN (
|
|
||||||
SELECT MAX(record_id)
|
|
||||||
FROM records
|
|
||||||
GROUP BY subdevice_id
|
|
||||||
)
|
|
||||||
GROUP BY subdevice_id
|
|
||||||
ORDER BY d.name DESC
|
|
||||||
", $roomIds);
|
|
||||||
|
|
||||||
$ret = [];
|
|
||||||
foreach($rows as $row){
|
|
||||||
$ret[$row['room_id']][] = $row;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $ret;
|
|
||||||
}
|
|
||||||
}
|
}
|
34
app/class/Template.php
Normal file
34
app/class/Template.php
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
class Template extends Partial{
|
||||||
|
var $assignedValues = [];
|
||||||
|
var $partBuffer;
|
||||||
|
var $path;
|
||||||
|
var $debug;
|
||||||
|
|
||||||
|
function __construct($path = "", $debug = false) {
|
||||||
|
$this->debug = $debug;
|
||||||
|
if (!empty('app/templates/' . $path . '.phtml') && file_exists('app/templates/' . $path . '.phtml')) {
|
||||||
|
$this->path = $path;
|
||||||
|
} else {
|
||||||
|
echo '<pre>';
|
||||||
|
echo 'PHTML: Template File ' . $path . ' not found';
|
||||||
|
echo '</pre>';
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function prepare($searchS, $repleaceS) {
|
||||||
|
if (!empty($searchS)) {
|
||||||
|
$this->assignedValues[strtoupper($searchS)] = $repleaceS;
|
||||||
|
}
|
||||||
|
echo ($this->debug == true ? var_dump($this->assignedValues) : '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
extract($this->assignedValues);
|
||||||
|
if (!empty('app/controls/' . $this->path . '.php') && file_exists('app/controls/' . $this->path . '.php')) {
|
||||||
|
include('app/controls/' . $this->path . '.php');
|
||||||
|
}
|
||||||
|
require_once('app/templates/' . $this->path . '.phtml');
|
||||||
|
}
|
||||||
|
}
|
@@ -1,9 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
class UserManager
|
class UserManager
|
||||||
{
|
{
|
||||||
public static function getUsers ($filtr = ['*']) {
|
public function getUsers () {
|
||||||
try {
|
try {
|
||||||
$allUsers = Db::loadAll ("SELECT " . implode(",", $filtr) . " FROM users");
|
$allUsers = Db::loadAll ("SELECT user_id, username, at_home, ota FROM users");
|
||||||
return $allUsers;
|
return $allUsers;
|
||||||
} catch(PDOException $error) {
|
} catch(PDOException $error) {
|
||||||
echo $error->getMessage();
|
echo $error->getMessage();
|
||||||
@@ -11,7 +11,7 @@ class UserManager
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getUser ($userName) {
|
public function getUser ($userName) {
|
||||||
try {
|
try {
|
||||||
$user = Db::loadOne ("SELECT * FROM users WHERE username = ?", [$userName]);
|
$user = Db::loadOne ("SELECT * FROM users WHERE username = ?", [$userName]);
|
||||||
return $user;
|
return $user;
|
||||||
@@ -21,7 +21,7 @@ class UserManager
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getUserId ($userId) {
|
public function getUserId ($userId) {
|
||||||
try {
|
try {
|
||||||
$user = Db::loadOne ("SELECT * FROM users WHERE user_id = ?", [$userId]);
|
$user = Db::loadOne ("SELECT * FROM users WHERE user_id = ?", [$userId]);
|
||||||
return $user;
|
return $user;
|
||||||
@@ -31,26 +31,28 @@ class UserManager
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getAvatarUrl($userId = null){
|
public function getAvatarUrl($userId = null){
|
||||||
if ($userId == null) {
|
$email = self::getUserData('email');
|
||||||
$email = self::getUserData('email');
|
if ($userId != null){
|
||||||
}
|
|
||||||
else if ($userId != null){
|
|
||||||
$email = self::getUserData('email',$userId);
|
$email = self::getUserData('email',$userId);
|
||||||
}
|
}
|
||||||
return 'https://secure.gravatar.com/avatar/' . md5( strtolower( trim( $email ) ) );
|
return 'https://secure.gravatar.com/avatar/' . md5( strtolower( trim( $email ) ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function login ($username, $password, $rememberMe) {
|
public function login ($username, $password, $rememberMe) {
|
||||||
try {
|
try {
|
||||||
if ($user = Db::loadOne ('SELECT * FROM users WHERE (LOWER(username)=LOWER(?) OR LOWER(email)=LOWER(?))', array ($username, $username))) {
|
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($username))) {
|
||||||
if ($user['password'] == UserManager::getHashPassword($password)) {
|
if ($user['password'] == UserManager::getHashPassword($password)) {
|
||||||
if (isset($rememberMe) && $rememberMe == 'true') {
|
if (isset($rememberMe) && $rememberMe == 'true') {
|
||||||
setcookie ("rememberMe", self::setEncryptedCookie($user['username']), time () + (30 * 24 * 60 * 60 * 1000), BASEDIR, $_SERVER['HTTP_HOST'], 1);
|
setcookie ("rememberMe", $this->setEncryptedCookie($user['username']), time () + (30 * 24 * 60 * 60 * 1000), BASEDIR, $_SERVER['HTTP_HOST'], 1);
|
||||||
}
|
}
|
||||||
$_SESSION['user']['id'] = $user['user_id'];
|
$_SESSION['user']['id'] = $user['user_id'];
|
||||||
|
$page = "";
|
||||||
|
if ($user["startPage"] == 1) {
|
||||||
|
$page = "dashboard";
|
||||||
|
}
|
||||||
unset($_POST['login']);
|
unset($_POST['login']);
|
||||||
return "";
|
return $page;
|
||||||
} else {
|
} else {
|
||||||
throw new PDOException("Heslo není správné!");
|
throw new PDOException("Heslo není správné!");
|
||||||
}
|
}
|
||||||
@@ -58,17 +60,16 @@ class UserManager
|
|||||||
throw new PDOException("Uživatel s tím to jménem neexistuje!");
|
throw new PDOException("Uživatel s tím to jménem neexistuje!");
|
||||||
}
|
}
|
||||||
} catch(PDOException $error) {
|
} catch(PDOException $error) {
|
||||||
$_SESSION['msg'] = $error->getMessage();
|
echo $error->getMessage();
|
||||||
unset($_POST);
|
|
||||||
header('Location: ' . BASEURL . 'login');
|
|
||||||
die();
|
die();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function loginNew ($username, $password) {
|
public function loginNew ($username, $password) {
|
||||||
try {
|
try {
|
||||||
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?) OR LOWER(email)=LOWER(?)', array ($username, $username))) {
|
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($username))) {
|
||||||
if ($user['password'] == UserManager::getHashPassword($password)) {
|
if ($user['password'] == UserManager::getHashPassword($password)) {
|
||||||
|
echo "user loged in";
|
||||||
return $user['user_id'];
|
return $user['user_id'];
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
@@ -82,12 +83,12 @@ class UserManager
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function isLogin () {
|
public function isLogin () {
|
||||||
if (isset ($_SESSION['user']) && isset($_SESSION['user']['id'])) {
|
if (isset ($_SESSION['user']) && isset($_SESSION['user']['id'])) {
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
if (isset ($_COOKIE['rememberMe'])){
|
if (isset ($_COOKIE['rememberMe'])){
|
||||||
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array (self::getDecryptedCookie($_COOKIE['rememberMe'])))) {
|
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($this->getDecryptedCookie($_COOKIE['rememberMe'])))) {
|
||||||
$_SESSION['user']['id'] = $user['user_id'];
|
$_SESSION['user']['id'] = $user['user_id'];
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -96,14 +97,16 @@ class UserManager
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function logout () {
|
public function logout () {
|
||||||
unset($_SESSION['user']);
|
unset($_SESSION['user']);
|
||||||
unset($_COOKIE['rememberMe']);
|
|
||||||
setcookie("rememberMe", 'false', 0 - time(), BASEDIR, $_SERVER['HTTP_HOST']);
|
|
||||||
session_destroy();
|
session_destroy();
|
||||||
|
if (isset($_COOKIE['rememberMe'])){
|
||||||
|
unset($_COOKIE['rememberMe']);
|
||||||
|
setcookie("rememberMe", 'false', time(), BASEDIR, $_SERVER['HTTP_HOST']);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function setEncryptedCookie($value){
|
public function setEncryptedCookie($value){
|
||||||
$first_key = base64_decode(FIRSTKEY);
|
$first_key = base64_decode(FIRSTKEY);
|
||||||
$second_key = base64_decode(SECONDKEY);
|
$second_key = base64_decode(SECONDKEY);
|
||||||
|
|
||||||
@@ -116,7 +119,7 @@ class UserManager
|
|||||||
return $newvalue;
|
return $newvalue;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getDecryptedCookie($value){
|
public function getDecryptedCookie($value){
|
||||||
$first_key = base64_decode(FIRSTKEY);
|
$first_key = base64_decode(FIRSTKEY);
|
||||||
$second_key = base64_decode(SECONDKEY);
|
$second_key = base64_decode(SECONDKEY);
|
||||||
|
|
||||||
@@ -142,25 +145,19 @@ class UserManager
|
|||||||
return $user[$type];
|
return $user[$type];
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function setUserData ($type, $value) {
|
public function setUserData ($type, $value) {
|
||||||
if (isset ($_SESSION['user']['id'])) {
|
if (isset ($_SESSION['user']['id'])) {
|
||||||
Db::command ('UPDATE users SET ' . $type . '=? WHERE user_id=?', array ($value, $_SESSION['user']['id']));
|
Db::command ('UPDATE users SET ' . $type . '=? WHERE user_id=?', array ($value, $_SESSION['user']['id']));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function setUserDataAdmin ($type, $value, $id) {
|
public function getHashPassword ($password) {
|
||||||
if ($id) {
|
|
||||||
Db::command ('UPDATE users SET ' . $type . '=? WHERE user_id=?', array ($value, $id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function getHashPassword ($password) {
|
|
||||||
$salt = "s0mRIdlKvI";
|
$salt = "s0mRIdlKvI";
|
||||||
$hashPassword = hash('sha512', ($password . $salt));
|
$hashPassword = hash('sha512', ($password . $salt));
|
||||||
return $hashPassword;
|
return $hashPassword;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function atHome($userId, $atHome){
|
public function atHome($userId, $atHome){
|
||||||
try {
|
try {
|
||||||
Db::edit ('users', ['at_home' => $atHome], 'WHERE user_id = ?', array($userId));
|
Db::edit ('users', ['at_home' => $atHome], 'WHERE user_id = ?', array($userId));
|
||||||
} catch(PDOException $error) {
|
} catch(PDOException $error) {
|
||||||
@@ -169,7 +166,7 @@ class UserManager
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function changePassword($oldPassword, $newPassword, $newPassword2){
|
public function changePassword($oldPassword, $newPassword, $newPassword2){
|
||||||
if ($newPassword == $newPassword2) {
|
if ($newPassword == $newPassword2) {
|
||||||
//Password Criteria
|
//Password Criteria
|
||||||
$oldPasswordSaved = self::getUserData('password');
|
$oldPasswordSaved = self::getUserData('password');
|
||||||
@@ -183,9 +180,8 @@ class UserManager
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function createUser ($userName, $password, $email) {
|
public function createUser($userName, $password){
|
||||||
$email = strtolower ($email);
|
$userId = Db::loadOne('SELECT * FROM users WHERE username = ?;', array($userName))['user_id'];
|
||||||
$userId = Db::loadOne ('SELECT * FROM users WHERE LOWER (username) = LOWER (?) OR LOWER (email) = LOWER (?);', array ($userName, $email))['user_id'];
|
|
||||||
if ($userId != null) {
|
if ($userId != null) {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
@@ -193,7 +189,6 @@ class UserManager
|
|||||||
$user = [
|
$user = [
|
||||||
'username' => $userName,
|
'username' => $userName,
|
||||||
'password' => self::getHashPassword($password),
|
'password' => self::getHashPassword($password),
|
||||||
'email' => $email,
|
|
||||||
];
|
];
|
||||||
return Db::add ('users', $user);
|
return Db::add ('users', $user);
|
||||||
} catch(PDOException $error) {
|
} catch(PDOException $error) {
|
||||||
@@ -202,8 +197,8 @@ class UserManager
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function haveOtaEnabled($userName){
|
public function haveOtaEnabled($userName){
|
||||||
$ota = self::getUser($userName)['ota'];
|
$ota = $this->getUser($userName)['ota'];
|
||||||
|
|
||||||
if ($ota != ''){
|
if ($ota != ''){
|
||||||
return ($ota != '' ? $ota : false);
|
return ($ota != '' ? $ota : false);
|
||||||
@@ -211,15 +206,5 @@ class UserManager
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function setOta($otaCode, $otaSecret){
|
|
||||||
$ga = new PHPGangsta_GoogleAuthenticator();
|
|
||||||
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
|
|
||||||
if ($checkResult) {
|
|
||||||
self::setUserData('ota', $otaSecret);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
?>
|
?>
|
@@ -1,12 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
class Utilities
|
class Utilities
|
||||||
{
|
{
|
||||||
static function cleanString($text)
|
function cleanString($text) {
|
||||||
{
|
|
||||||
$utf8 = array(
|
$utf8 = array(
|
||||||
'/[áàâãªä]/u' => 'a',
|
'/[áàâãªä]/u' => 'a',
|
||||||
'/[ÁÀÂÃÄ]/u' => 'A',
|
'/[ÁÀÂÃÄ]/u' => 'A',
|
||||||
@@ -38,22 +36,21 @@ class Utilities
|
|||||||
return preg_replace(array_keys($utf8), array_values($utf8), $text);
|
return preg_replace(array_keys($utf8), array_values($utf8), $text);
|
||||||
}
|
}
|
||||||
|
|
||||||
static function stringInsert($str, $insertstr, $pos)
|
function stringInsert($str,$insertstr,$pos)
|
||||||
{
|
{
|
||||||
$str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
|
$str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
|
||||||
return $str;
|
return $str;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* [generateGraphJson description]
|
* [generateGraphJson description]
|
||||||
* @param string $type [line/bar]
|
* @param string $type [line/bar]
|
||||||
* @param array $data [description]
|
* @param array $data [description]
|
||||||
* @param array $options [description]
|
* @param array $options [description]
|
||||||
* @return [type] [description]
|
* @return [type] [description]
|
||||||
*/
|
*/
|
||||||
|
|
||||||
static function generateGraphJson(string $type = 'line', array $data = [], array $options = [])
|
function generateGraphJson(string $type = 'line', array $data = [], array $options = []){
|
||||||
{
|
|
||||||
$array = [
|
$array = [
|
||||||
'type' => $type,
|
'type' => $type,
|
||||||
'data' => [
|
'data' => [
|
||||||
@@ -97,85 +94,51 @@ class Utilities
|
|||||||
return json_encode($array, JSON_PRETTY_PRINT);
|
return json_encode($array, JSON_PRETTY_PRINT);
|
||||||
}
|
}
|
||||||
|
|
||||||
static function ago($datetime)
|
function ago( $datetime )
|
||||||
{
|
{
|
||||||
$interval = date_create('now')->diff($datetime);
|
$interval = date_create('now')->diff( $datetime );
|
||||||
$suffix = ($interval->invert ? ' ago' : '');
|
$suffix = ( $interval->invert ? ' ago' : '' );
|
||||||
if ($v = $interval->y >= 1) return self::pluralize($interval->m, 'month') . $suffix;
|
if ( $v = $interval->y >= 1 ) return self::pluralize( $interval->m, 'month' ) . $suffix;
|
||||||
if ($v = $interval->d >= 1) return self::pluralize($interval->d, 'day') . $suffix;
|
if ( $v = $interval->d >= 1 ) return self::pluralize( $interval->d, 'day' ) . $suffix;
|
||||||
if ($v = $interval->h >= 1) return self::pluralize($interval->h, 'hour') . $suffix;
|
if ( $v = $interval->h >= 1 ) return self::pluralize( $interval->h, 'hour' ) . $suffix;
|
||||||
if ($v = $interval->i >= 1) return self::pluralize($interval->i, 'minute') . $suffix;
|
if ( $v = $interval->i >= 1 ) return self::pluralize( $interval->i, 'minute' ) . $suffix;
|
||||||
return self::pluralize($interval->s, 'second') . $suffix;
|
return self::pluralize( $interval->s, 'second' ) . $suffix;
|
||||||
}
|
}
|
||||||
|
|
||||||
static function pluralize($count, $text)
|
function pluralize( $count, $text )
|
||||||
{
|
{
|
||||||
return $count . (($count == 1) ? (" $text") : (" ${text}s"));
|
return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
static function checkOperator($value1, $operator, $value2)
|
function checkOperator($value1, $operator, $value2) {
|
||||||
{
|
|
||||||
switch ($operator) {
|
switch ($operator) {
|
||||||
case '<': // Less than
|
case '<': // Less than
|
||||||
return $value1 < $value2;
|
return $value1 < $value2;
|
||||||
case '<=': // Less than or equal to
|
case '<=': // Less than or equal to
|
||||||
return $value1 <= $value2;
|
return $value1 <= $value2;
|
||||||
case '>': // Greater than
|
case '>': // Greater than
|
||||||
return $value1 > $value2;
|
return $value1 > $value2;
|
||||||
case '>=': // Greater than or equal to
|
case '>=': // Greater than or equal to
|
||||||
return $value1 >= $value2;
|
return $value1 >= $value2;
|
||||||
case '==': // Equal
|
case '==': // Equal
|
||||||
return ($value1 == $value2);
|
return ($value1 == $value2);
|
||||||
case '===': // Identical
|
case '===': // Identical
|
||||||
return $value1 === $value2;
|
return $value1 === $value2;
|
||||||
case '!==': // Not Identical
|
case '!==': // Not Identical
|
||||||
return $value1 !== $value2;
|
return $value1 !== $value2;
|
||||||
case '!=': // Not equal
|
case '!=': // Not equal
|
||||||
case '<>': // Not equal
|
case '<>': // Not equal
|
||||||
return $value1 != $value2;
|
return $value1 != $value2;
|
||||||
case '||': // Or
|
case '||': // Or
|
||||||
case 'or': // Or
|
case 'or': // Or
|
||||||
return $value1 || $value2;
|
return $value1 || $value2;
|
||||||
case '&&': // And
|
case '&&': // And
|
||||||
case 'and': // And
|
case 'and': // And
|
||||||
return $value1 && $value2;
|
return $value1 && $value2;
|
||||||
case 'xor': // Or
|
case 'xor': // Or
|
||||||
return $value1 xor $value2;
|
return $value1 xor $value2;
|
||||||
default:
|
default:
|
||||||
return FALSE;
|
return FALSE;
|
||||||
} // end switch
|
} // end switch
|
||||||
}
|
}
|
||||||
|
|
||||||
static function CallAPI($method, $url, $data = false)
|
|
||||||
{
|
|
||||||
$curl = curl_init();
|
|
||||||
|
|
||||||
switch ($method) {
|
|
||||||
case "POST":
|
|
||||||
curl_setopt($curl, CURLOPT_POST, 1);
|
|
||||||
|
|
||||||
if ($data)
|
|
||||||
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
|
|
||||||
break;
|
|
||||||
case "PUT":
|
|
||||||
curl_setopt($curl, CURLOPT_PUT, 1);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
if ($data)
|
|
||||||
$url = sprintf("%s?%s", $url, http_build_query($data));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Optional Authentication:
|
|
||||||
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
|
|
||||||
//curl_setopt($curl, CURLOPT_USERPWD, "username:password");
|
|
||||||
|
|
||||||
curl_setopt($curl, CURLOPT_URL, $url);
|
|
||||||
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
|
|
||||||
|
|
||||||
$result = curl_exec($curl);
|
|
||||||
|
|
||||||
curl_close($curl);
|
|
||||||
|
|
||||||
return $result;
|
|
||||||
}
|
|
||||||
}
|
}
|
@@ -1,14 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
class ExampleController extends Controller{
|
|
||||||
|
|
||||||
public function index(){
|
|
||||||
$this->view->title = 'Example title';
|
|
||||||
$this->view->render('example.phtml');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function subpage(){
|
|
||||||
echo 'subpage';
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@@ -1,32 +0,0 @@
|
|||||||
<?php
|
|
||||||
if (!empty ($_POST)){
|
|
||||||
$deviceManager = new DeviceManager ();
|
|
||||||
if (!empty ($_FILES['deviceFirmware']) && !empty ($_FILES['deviceFirmware']['tmp_name']) && !empty ($_POST['deviceId'])) {
|
|
||||||
$file = $_FILES['deviceFirmware'];
|
|
||||||
$deviceMac = $deviceManager->getDeviceById ($_POST['deviceId'])['mac'];
|
|
||||||
$fileName = (!empty ($deviceMac) ? str_replace (":", "", $deviceMac) . ".bin" : "");
|
|
||||||
|
|
||||||
if ($fileName != "" && file_exists ("../updater/" . $fileName)) {
|
|
||||||
unlink("../updater/" . $fileName);
|
|
||||||
}
|
|
||||||
if ($fileName != "") {
|
|
||||||
copy ($file['tmp_name'], "../updater/" . $fileName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (isset ($_POST['deviceCommand']) && !empty ($_POST['deviceId'])) {
|
|
||||||
$deviceManager->edit ($_POST['deviceId'], array ('command' => $_POST['deviceCommand']));
|
|
||||||
} else if (!empty ($_POST['deviceCommand'])) {
|
|
||||||
$devices = $deviceManager->getAllDevices();
|
|
||||||
foreach ($devices as $key => $device) {
|
|
||||||
$deviceManager->edit ($device['device_id'], array ('command' => $_POST['deviceCommand']));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!empty ($_POST['deviceRoomId']) && !empty ($_POST['deviceId'])) {
|
|
||||||
$deviceManager->edit ($_POST['deviceId'], array ('room_id' => $_POST['deviceRoomId']));
|
|
||||||
}
|
|
||||||
if (!empty ($_POST['deviceName']) && !empty ($_POST['deviceId'])) {
|
|
||||||
$deviceManager->edit ($_POST['deviceId'], array ('name' => $_POST['deviceName']));
|
|
||||||
}
|
|
||||||
header('Location: ./device');
|
|
||||||
die();
|
|
||||||
}
|
|
@@ -1,75 +0,0 @@
|
|||||||
<?php
|
|
||||||
$userManager = new UserManager();
|
|
||||||
|
|
||||||
if (
|
|
||||||
isset($_POST['username']) &&
|
|
||||||
$_POST['username'] != '' &&
|
|
||||||
isset($_POST['password']) &&
|
|
||||||
$_POST['password'] != ''
|
|
||||||
){
|
|
||||||
$ota = false;
|
|
||||||
$userName = $_POST['username'];
|
|
||||||
echo $_POST['username'];
|
|
||||||
$userPassword = $_POST['password'];
|
|
||||||
$state = $_POST["state"];
|
|
||||||
$clientId = $_POST["clientId"];
|
|
||||||
$ota = $userManager->haveOtaEnabled($userName);
|
|
||||||
if ($ota == "") {
|
|
||||||
$token = (new AuthManager)->getToken($userName,$userPassword, $clientId);
|
|
||||||
if (!$token) {
|
|
||||||
throw new Exception("Auth failed", 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
$get = [
|
|
||||||
"access_token"=>$token,
|
|
||||||
"token_type"=>"Bearer",
|
|
||||||
"state"=>$state,
|
|
||||||
];
|
|
||||||
|
|
||||||
header('Location: ' . $_POST["redirectUrl"] . '#' . http_build_query($get));
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
|
|
||||||
$_SESSION['USERNAME'] = $userName;
|
|
||||||
$_SESSION['PASSWORD'] = $userPassword;
|
|
||||||
$_SESSION['OTA'] = $ota;
|
|
||||||
$_SESSION['STATE'] = $state;
|
|
||||||
$_SESSION['REDIRECT'] = $_POST["redirectUrl"];
|
|
||||||
$_SESSION['CLIENT'] = $clientId;
|
|
||||||
|
|
||||||
|
|
||||||
} else if (
|
|
||||||
isset($_POST['otaCode']) &&
|
|
||||||
$_POST['otaCode'] != ''
|
|
||||||
) {
|
|
||||||
$otaCode = $_POST['otaCode'];
|
|
||||||
$otaSecret = $_POST['otaSecret'];
|
|
||||||
|
|
||||||
$userName = $_SESSION['USERNAME'];
|
|
||||||
$userPassword = $_SESSION['PASSWORD'];
|
|
||||||
$ota = $_SESSION['OTA'];
|
|
||||||
$oauthState = $_SESSION['STATE'];
|
|
||||||
$oauthRedirect = $_SESSION['REDIRECT'];
|
|
||||||
$oauthClientId = $_SESSION['CLIENT'];
|
|
||||||
|
|
||||||
$ga = new PHPGangsta_GoogleAuthenticator();
|
|
||||||
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
|
|
||||||
if ($checkResult) {
|
|
||||||
$token = (new AuthManager)->getToken($userName,$userPassword, $oauthClientId);
|
|
||||||
if (!$token) {
|
|
||||||
throw new Exception("Auth failed", 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
$get = [
|
|
||||||
"access_token"=>$token,
|
|
||||||
"token_type"=>"Bearer",
|
|
||||||
"state"=>$oauthState,
|
|
||||||
];
|
|
||||||
|
|
||||||
header('Location: ' . $oauthRedirect . '#' . http_build_query($get));
|
|
||||||
echo 'OK';
|
|
||||||
} else {
|
|
||||||
echo 'FAILED';
|
|
||||||
}
|
|
||||||
die();
|
|
||||||
}
|
|
@@ -1,28 +0,0 @@
|
|||||||
<?php
|
|
||||||
if (!empty ($_POST)){
|
|
||||||
if (
|
|
||||||
isset ($_POST['name']) &&
|
|
||||||
$_POST['name'] != '' &&
|
|
||||||
!isset ($_POST['remove'])
|
|
||||||
) {
|
|
||||||
if ($_POST['status'] == "true") {
|
|
||||||
if (file_exists ($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/!' . $_POST['name'] . ".php")) {
|
|
||||||
rename($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/!' . $_POST['name'] . ".php", $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/' . $_POST['name'] . ".php");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (file_exists ($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/' . $_POST['name'] . ".php")) {
|
|
||||||
rename($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/' . $_POST['name'] . ".php", $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/!' . $_POST['name'] . ".php");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
header('Location: ./plugins');
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
isset ($_POST['name']) &&
|
|
||||||
$_POST['name'] != '' &&
|
|
||||||
isset ($_POST['remove'])
|
|
||||||
) {
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
@@ -32,7 +32,7 @@ if (isset($_POST) && !empty($_POST)){
|
|||||||
|
|
||||||
AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode);
|
AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode);
|
||||||
|
|
||||||
header('Location: ' . BASEURL . strtolower(basename(__FILE__, '.php')));
|
header('Location: ' . BASEDIR . strtolower(basename(__FILE__, '.php')));
|
||||||
die();
|
die();
|
||||||
} else if (isset($_POST['modalFinal']) && $_POST['action'] == "edit") {
|
} else if (isset($_POST['modalFinal']) && $_POST['action'] == "edit") {
|
||||||
$doCode = json_encode($_POST['device'], JSON_PRETTY_PRINT);
|
$doCode = json_encode($_POST['device'], JSON_PRETTY_PRINT);
|
||||||
@@ -70,7 +70,7 @@ if (isset($_POST) && !empty($_POST)){
|
|||||||
|
|
||||||
AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode, (isset ($_POST['automation_id']) ? $_POST['automation_id'] : ""));
|
AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode, (isset ($_POST['automation_id']) ? $_POST['automation_id'] : ""));
|
||||||
|
|
||||||
header('Location: ' . BASEURL . strtolower(basename(__FILE__, '.php')));
|
header('Location: ' . BASEDIR . strtolower(basename(__FILE__, '.php')));
|
||||||
die();
|
die();
|
||||||
}
|
}
|
||||||
}
|
}
|
13
app/controls/dashboard.php
Normal file
13
app/controls/dashboard.php
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
if (isset($_POST) && !empty($_POST)){
|
||||||
|
|
||||||
|
if (isset($_POST['modalFinal']) && $_POST['modalFinal'] != "") {
|
||||||
|
$subDeviceIds = $_POST['devices'];
|
||||||
|
foreach ($subDeviceIds as $subDeviceId) {
|
||||||
|
DashboardManager::Add($subDeviceId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
header('Location: ' . BASEDIR . strtolower(basename(__FILE__, '.php')));
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
?>
|
87
app/controls/home.php
Normal file
87
app/controls/home.php
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
<?php
|
||||||
|
if (isset($_POST) && !empty($_POST)){
|
||||||
|
if (isset($_POST['saveDevice']) && $_POST['saveDevice'] != "") {
|
||||||
|
$deviceId = $_POST['deviceId'];
|
||||||
|
$deviceName = $_POST['deviceName'];
|
||||||
|
$deviceIcon = $_POST['deviceIcon'];
|
||||||
|
$sleepTime = 0;
|
||||||
|
if (isset($_FILES['deviceFirmware']) && isset($_FILES['deviceFirmware']['tmp_name']) && $_FILES['deviceFirmware']['tmp_name'] != "") {
|
||||||
|
$file = $_FILES['deviceFirmware'];
|
||||||
|
$deviceMac = DeviceManager::getDeviceById($deviceId)['mac'];
|
||||||
|
$fileName = (isset ($deviceMac) && $deviceMac != "" ? str_replace(":", "", $deviceMac) . ".bin" : "");
|
||||||
|
if ($fileName != "" && file_exists("./app/updater/" . $fileName)) {
|
||||||
|
unlink("./app/updater/" . $fileName);
|
||||||
|
}
|
||||||
|
if ($fileName != "") {
|
||||||
|
copy($file['tmp_name'], "./app/updater/" . $fileName);
|
||||||
|
} else {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($_POST['sleepTime'])) {
|
||||||
|
$sleepTime = $_POST['sleepTime'];
|
||||||
|
}
|
||||||
|
//TODO: if device isnt on off
|
||||||
|
$permissionsInJson = json_encode([
|
||||||
|
(int) $_POST['permissionOwner'],
|
||||||
|
(int) $_POST['permissionOther'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
|
||||||
|
$deviceOwnerUserId = $_POST['deviceOwnerUserId'];
|
||||||
|
$deviceOwnerRoomId = $_POST['deviceOwnerId'];
|
||||||
|
|
||||||
|
try {
|
||||||
|
$args = array(
|
||||||
|
'owner' => $deviceOwnerUserId,
|
||||||
|
'name' => $deviceName,
|
||||||
|
'icon' => $deviceIcon,
|
||||||
|
'permission' => $permissionsInJson,
|
||||||
|
'sleep_time' => $sleepTime,
|
||||||
|
'room_id' => $deviceOwnerRoomId,
|
||||||
|
);
|
||||||
|
DeviceManager::edit($deviceId, $args);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
echo $e->message();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//Debug
|
||||||
|
if (DEBUGMOD == 1) {
|
||||||
|
echo '<pre>';
|
||||||
|
echo $permissionsInJson;
|
||||||
|
echo $deviceId;
|
||||||
|
var_dump(json_decode ($permissionsInJson));
|
||||||
|
echo '</pre>';
|
||||||
|
echo '<a href="' . BASEDIR .'">CONTINUE</a>';
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
} else if (isset($_POST['approveDevice'])) {
|
||||||
|
$deviceId = $_POST['deviceId'];
|
||||||
|
$args = array(
|
||||||
|
'approved' => 1,
|
||||||
|
);
|
||||||
|
DeviceManager::edit($deviceId, $args);
|
||||||
|
} else if (isset($_POST['disableDevice'])) {
|
||||||
|
$deviceId = $_POST['deviceId'];
|
||||||
|
$args = array(
|
||||||
|
'approved' => 2,
|
||||||
|
);
|
||||||
|
DeviceManager::edit($deviceId, $args);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Debug
|
||||||
|
if (DEBUGMOD == 1) {
|
||||||
|
echo '<pre>';
|
||||||
|
var_dump($POST);
|
||||||
|
echo '</pre>';
|
||||||
|
echo '<a href="' . BASEDIR . '">CONTINUE</a>';
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
header('Location: ' . BASEDIR );
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
?>
|
@@ -1,5 +1,5 @@
|
|||||||
<?php
|
<?php
|
||||||
$userManager = new UserManager();
|
global $userManager;
|
||||||
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
@@ -15,7 +15,7 @@ if (
|
|||||||
$ota = $userManager->haveOtaEnabled($userName);
|
$ota = $userManager->haveOtaEnabled($userName);
|
||||||
if ($ota == "") {
|
if ($ota == "") {
|
||||||
$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
|
$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
|
||||||
header('Location: ' . BASEURL . $landingPage);
|
header('Location: ' . BASEDIR . $landingPage);
|
||||||
die();
|
die();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,6 +27,7 @@ if (
|
|||||||
isset($_POST['otaCode']) &&
|
isset($_POST['otaCode']) &&
|
||||||
$_POST['otaCode'] != ''
|
$_POST['otaCode'] != ''
|
||||||
) {
|
) {
|
||||||
|
|
||||||
$otaCode = $_POST['otaCode'];
|
$otaCode = $_POST['otaCode'];
|
||||||
$otaSecret = $_POST['otaSecret'];
|
$otaSecret = $_POST['otaSecret'];
|
||||||
|
|
||||||
@@ -39,7 +40,7 @@ if (
|
|||||||
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
|
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
|
||||||
if ($checkResult) {
|
if ($checkResult) {
|
||||||
$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
|
$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
|
||||||
header('Location: ' . BASEURL . '/');
|
header('Location: ' . BASEDIR . $landingPage);
|
||||||
echo 'OK';
|
echo 'OK';
|
||||||
} else {
|
} else {
|
||||||
echo 'FAILED';
|
echo 'FAILED';
|
18
app/controls/scene.php
Normal file
18
app/controls/scene.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
if (isset($_POST) && !empty($_POST)){
|
||||||
|
if (isset($_POST['submitFinal']) && $_POST['submitFinal'] != "") {
|
||||||
|
SceneManager::create($_POST['sceneIcon'], $_POST['sceneName'], json_encode($_POST['devices']));
|
||||||
|
header('Location: ' . BASEDIR . strtolower(basename(__FILE__, '.php')));
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
|
||||||
|
//Debug
|
||||||
|
if (DEBUGMOD == 1) {
|
||||||
|
echo '<pre>';
|
||||||
|
var_dump($_POST);
|
||||||
|
echo '</pre>';
|
||||||
|
echo '<a href="/' . BASEDIR . strtolower(basename(__FILE__, '.php')).'">CONTINUE</a>';
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
}
|
@@ -1,34 +1,34 @@
|
|||||||
<?php
|
<?php
|
||||||
if (isset($_POST) && !empty($_POST)){
|
if (isset($_POST) && !empty($_POST)){
|
||||||
$userManager = new UserManager();
|
|
||||||
if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") {
|
if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") {
|
||||||
$oldPassword = $_POST['oldPassword'];
|
$oldPassword = $_POST['oldPassword'];
|
||||||
$newPassword = $_POST['newPassword1'];
|
$newPassword = $_POST['newPassword1'];
|
||||||
$newPassword2 = $_POST['newPassword2'];
|
$newPassword2 = $_POST['newPassword2'];
|
||||||
$userManager->changePassword($oldPassword, $newPassword, $newPassword2);
|
UserManager::changePassword($oldPassword, $newPassword, $newPassword2);
|
||||||
header('Location: ' . BASEURL . 'logout');
|
header('Location: ' . BASEDIR . 'logout');
|
||||||
die();
|
die();
|
||||||
} else if (isset($_POST['submitCreateUser']) && $_POST['submitCreateUser'] != "") {
|
} else if (isset($_POST['submitCreateUser']) && $_POST['submitCreateUser'] != "") {
|
||||||
$userName = $_POST['userName'];
|
$userName = $_POST['userName'];
|
||||||
$password = $_POST['userPassword'];
|
$password = $_POST['userPassword'];
|
||||||
$email = $_POST['userEmail'];
|
UserManager::createUser($userName, $password);
|
||||||
$userManager->createUser($userName, $password, $email);
|
header('Location: ' . BASEDIR . 'setting');
|
||||||
header('Location: ' . BASEURL . 'setting');
|
die();
|
||||||
|
} else if (isset($_POST['submitCreateRoom']) && $_POST['submitCreateRoom'] != "") {
|
||||||
|
$roomName = $_POST['roomName'];
|
||||||
|
RoomManager::create($roomName);
|
||||||
|
header('Location: ' . BASEDIR . 'setting');
|
||||||
die();
|
die();
|
||||||
} else if (isset($_POST['submitEnableOta']) && $_POST['submitEnableOta'] != "") {
|
} else if (isset($_POST['submitEnableOta']) && $_POST['submitEnableOta'] != "") {
|
||||||
$otaCode = $_POST['otaCode'];
|
echo $otaCode = $_POST['otaCode'];
|
||||||
$otaSecret = $_POST['otaSecret'];
|
echo $otaSecret = $_POST['otaSecret'];
|
||||||
|
|
||||||
|
|
||||||
$ga = new PHPGangsta_GoogleAuthenticator();
|
$ga = new PHPGangsta_GoogleAuthenticator();
|
||||||
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
|
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
|
||||||
if ($checkResult) {
|
if ($checkResult) {
|
||||||
$userManager->setOta($otaCode, $otaSecret);
|
UserManager::setOta($otaCode, $otaSecret);
|
||||||
}
|
}
|
||||||
header('Location: ' . BASEURL . 'setting');
|
header('Location: ' . BASEDIR . 'setting');
|
||||||
die();
|
|
||||||
} else if (isset ($_POST['userPermission']) && !empty ($_POST['userID'])) {
|
|
||||||
$userManager->setUserDataAdmin("permission", $_POST['userPermission'], $_POST['userID']);
|
|
||||||
header('Location: ' . BASEURL . 'setting');
|
|
||||||
die();
|
die();
|
||||||
}
|
}
|
||||||
}
|
}
|
17
app/controls/settings.php
Normal file
17
app/controls/settings.php
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
if (isset($_POST) && !empty($_POST)){
|
||||||
|
if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") {
|
||||||
|
$oldPassword = $_POST['oldPassword'];
|
||||||
|
$newPassword = $_POST['newPassword1'];
|
||||||
|
$newPassword2 = $_POST['newPassword2'];
|
||||||
|
UserManager::changePassword($oldPassword, $newPassword, $newPassword2);
|
||||||
|
header('Location: ' . BASEDIR . 'logout');
|
||||||
|
die();
|
||||||
|
} else if (isset($_POST['submitCreateUser']) && $_POST['submitCreateUser'] != "") {
|
||||||
|
$userName = $_POST['userName'];
|
||||||
|
$password = $_POST['userPassword'];
|
||||||
|
UserManager::createUser($userName, $password);
|
||||||
|
header('Location: ' . BASEDIR . 'setting');
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
}
|
@@ -7,8 +7,6 @@ return $lang = [
|
|||||||
'm_automatization' => 'Automatizace',
|
'm_automatization' => 'Automatizace',
|
||||||
'm_scenes' => 'Scény',
|
'm_scenes' => 'Scény',
|
||||||
'm_log' => 'Log',
|
'm_log' => 'Log',
|
||||||
'm_devices' => 'Zařízení',
|
|
||||||
'm_plugins' => 'Pluginy',
|
|
||||||
|
|
||||||
//Buttons
|
//Buttons
|
||||||
'b_year' => 'Rok',
|
'b_year' => 'Rok',
|
||||||
@@ -58,7 +56,6 @@ return $lang = [
|
|||||||
'l_notificationStatus' => 'Notification status',
|
'l_notificationStatus' => 'Notification status',
|
||||||
'l_userName' => 'Uživatelské jméno',
|
'l_userName' => 'Uživatelské jméno',
|
||||||
'l_password' => 'Heslo',
|
'l_password' => 'Heslo',
|
||||||
'l_email' => 'Email',
|
|
||||||
'l_oldPassword' => 'Staré Heslo',
|
'l_oldPassword' => 'Staré Heslo',
|
||||||
'l_newPassword' => 'Nové Heslo',
|
'l_newPassword' => 'Nové Heslo',
|
||||||
'l_uploadFirmware' => 'Nahrát Firmware',
|
'l_uploadFirmware' => 'Nahrát Firmware',
|
||||||
@@ -81,15 +78,11 @@ return $lang = [
|
|||||||
't_networkSetting' => 'Nastavení Sítě',
|
't_networkSetting' => 'Nastavení Sítě',
|
||||||
't_deviceVersion' => 'Nastavení Verze',
|
't_deviceVersion' => 'Nastavení Verze',
|
||||||
't_ota' => 'OTA',
|
't_ota' => 'OTA',
|
||||||
't_permission' => 'Oprávnění',
|
|
||||||
't_permission_user' => 'Uživatel',
|
|
||||||
't_permission_admin' => 'Administrátor',
|
|
||||||
't_listUsers' => 'Seznam Uživatelů',
|
't_listUsers' => 'Seznam Uživatelů',
|
||||||
't_avatar' => 'Avatar',
|
't_avatar' => 'Avatar',
|
||||||
't_listRooms' => 'Seznam Místností',
|
't_listRooms' => 'Seznam Místností',
|
||||||
't_roomName' => 'Jméno Místnosti',
|
't_roomName' => 'Jméno Místnosti',
|
||||||
't_createRoom' => 'Vytvořit Místnost',
|
't_createRoom' => 'Vytvořit Místnost',
|
||||||
't_Plugins' => 'Pluginy',
|
|
||||||
|
|
||||||
//constants
|
//constants
|
||||||
'temp' => 'Teplota',
|
'temp' => 'Teplota',
|
@@ -7,8 +7,6 @@ return $lang = [
|
|||||||
'm_automatization' => 'Automatization',
|
'm_automatization' => 'Automatization',
|
||||||
'm_scenes' => 'Scenes',
|
'm_scenes' => 'Scenes',
|
||||||
'm_log' => 'Log',
|
'm_log' => 'Log',
|
||||||
'm_devices' => 'Devices',
|
|
||||||
'm_plugins' => 'Plugins',
|
|
||||||
|
|
||||||
//Buttons
|
//Buttons
|
||||||
'b_year' => 'Year',
|
'b_year' => 'Year',
|
||||||
@@ -58,7 +56,6 @@ return $lang = [
|
|||||||
'l_notificationStatus' => 'Notification status',
|
'l_notificationStatus' => 'Notification status',
|
||||||
'l_userName' => 'Username',
|
'l_userName' => 'Username',
|
||||||
'l_password' => 'Password',
|
'l_password' => 'Password',
|
||||||
'l_email' => 'Email',
|
|
||||||
'l_oldPassword' => 'Old Password',
|
'l_oldPassword' => 'Old Password',
|
||||||
'l_newPassword' => 'New Password',
|
'l_newPassword' => 'New Password',
|
||||||
'l_uploadFirmware' => 'Upload Firmware',
|
'l_uploadFirmware' => 'Upload Firmware',
|
||||||
@@ -81,15 +78,11 @@ return $lang = [
|
|||||||
't_networkSetting' => 'Network Setting',
|
't_networkSetting' => 'Network Setting',
|
||||||
't_deviceVersion' => 'Version Setting',
|
't_deviceVersion' => 'Version Setting',
|
||||||
't_ota' => 'OTA',
|
't_ota' => 'OTA',
|
||||||
't_permission' => 'Permission',
|
|
||||||
't_permission_user' => 'User',
|
|
||||||
't_permission_admin' => 'Admin',
|
|
||||||
't_listUsers' => 'User List',
|
't_listUsers' => 'User List',
|
||||||
't_avatar' => 'Avatar',
|
't_avatar' => 'Avatar',
|
||||||
't_listRooms' => 'Room List',
|
't_listRooms' => 'Room List',
|
||||||
't_roomName' => 'Room Name',
|
't_roomName' => 'Room Name',
|
||||||
't_createRoom' => 'Create Rom',
|
't_createRoom' => 'Create Rom',
|
||||||
't_Plugins' => 'Plugins',
|
|
||||||
|
|
||||||
//constants
|
//constants
|
||||||
'humi' => 'Humidity',
|
'humi' => 'Humidity',
|
@@ -7,7 +7,6 @@ return $lang = [
|
|||||||
'm_automatization' => 'Automatisatie',
|
'm_automatization' => 'Automatisatie',
|
||||||
'm_scenes' => 'Scénes',
|
'm_scenes' => 'Scénes',
|
||||||
'm_log' => 'Log',
|
'm_log' => 'Log',
|
||||||
'm_devices' => 'Apparaat',
|
|
||||||
|
|
||||||
//Buttons
|
//Buttons
|
||||||
'b_year' => 'Jaar',
|
'b_year' => 'Jaar',
|
||||||
@@ -52,7 +51,6 @@ return $lang = [
|
|||||||
'l_sleepTime' => 'Apparaat slaaptijd',
|
'l_sleepTime' => 'Apparaat slaaptijd',
|
||||||
'l_atHome' => 'Thuis',
|
'l_atHome' => 'Thuis',
|
||||||
'l_nameAt' => 'Naam',
|
'l_nameAt' => 'Naam',
|
||||||
'l_email' => 'Email',
|
|
||||||
'l_lastSeen' => 'Laatst gezien',
|
'l_lastSeen' => 'Laatst gezien',
|
||||||
'l_notificationStatus' => 'Notificatie status',
|
'l_notificationStatus' => 'Notificatie status',
|
||||||
|
|
@@ -7,7 +7,6 @@ return $lang = [
|
|||||||
'm_automatization' => 'Zaplanowane działania',
|
'm_automatization' => 'Zaplanowane działania',
|
||||||
'm_scenes' => 'Scenariusze',
|
'm_scenes' => 'Scenariusze',
|
||||||
'm_log' => 'Logi',
|
'm_log' => 'Logi',
|
||||||
'm_devices' => 'Urządzenie',
|
|
||||||
|
|
||||||
//Buttons
|
//Buttons
|
||||||
'b_year' => 'Rok',
|
'b_year' => 'Rok',
|
||||||
@@ -56,7 +55,6 @@ return $lang = [
|
|||||||
'l_notificationStatus' => 'Stan powiadomienia',
|
'l_notificationStatus' => 'Stan powiadomienia',
|
||||||
'l_userName' => 'Username', //newOne
|
'l_userName' => 'Username', //newOne
|
||||||
'l_password' => 'Password', //newOne
|
'l_password' => 'Password', //newOne
|
||||||
'l_email' => 'Email',
|
|
||||||
'l_oldPassword' => 'Old Password', //newOne
|
'l_oldPassword' => 'Old Password', //newOne
|
||||||
'l_newPassword' => 'New Password', //newOne
|
'l_newPassword' => 'New Password', //newOne
|
||||||
|
|
@@ -1,476 +0,0 @@
|
|||||||
<?php
|
|
||||||
class GoogleHome {
|
|
||||||
static function sync($requestId){
|
|
||||||
$devices = [];
|
|
||||||
$roomsData = RoomManager::getAllRooms();
|
|
||||||
foreach ($roomsData as $roomKey => $roomData) {
|
|
||||||
$devicesData = DeviceManager::getAllDevicesInRoom($roomData['room_id']);
|
|
||||||
foreach ($devicesData as $deviceKey => $deviceData) {
|
|
||||||
$traids = [];
|
|
||||||
$attributes = [];
|
|
||||||
|
|
||||||
//Google Compatibile Action Type
|
|
||||||
$actionType = GoogleHomeDeviceTypes::getAction($deviceData['type']);
|
|
||||||
if ($actionType == "") continue;
|
|
||||||
|
|
||||||
$subDevicesData = SubDeviceManager::getAllSubDevices($deviceData['device_id']);
|
|
||||||
foreach ($subDevicesData as $subDeviceKey => $subDeviceData) {
|
|
||||||
$deviceTraid = GoogleHomeDeviceTypes::getTraid($subDeviceData['type']);
|
|
||||||
if ($deviceTraid != "") {
|
|
||||||
$traids[] = $deviceTraid;
|
|
||||||
}
|
|
||||||
|
|
||||||
$deviceAttributes = GoogleHomeDeviceTypes::getAttribute($subDeviceData['type']);
|
|
||||||
if ($deviceAttributes != "") {
|
|
||||||
$attributes += $deviceAttributes;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$tempDevice = [
|
|
||||||
'id' => (string) $deviceData['device_id'],
|
|
||||||
'type' => $actionType,
|
|
||||||
'traits' => $traids,
|
|
||||||
'attributes' => $attributes,
|
|
||||||
'name' => [
|
|
||||||
'name' => $deviceData['name'],
|
|
||||||
],
|
|
||||||
|
|
||||||
'willReportState' => false,
|
|
||||||
'roomHint' => $roomData['name']
|
|
||||||
];
|
|
||||||
if ($tempDevice['attributes'] == null) unset($tempDevice['attributes']);
|
|
||||||
|
|
||||||
//traids & Attributes
|
|
||||||
$devices[] = $tempDevice;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
$response = [
|
|
||||||
'requestId' => $requestId,
|
|
||||||
'payload' => [
|
|
||||||
'agentUserId'=>'651351531531',
|
|
||||||
'devices' => array_values( $devices ),
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
|
|
||||||
$apiLogManager->setLevel(LOGLEVEL);
|
|
||||||
$apiLogManager->write("[API][$requestId] request response\n" . json_encode($response, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
|
|
||||||
echo json_encode($response);
|
|
||||||
}
|
|
||||||
|
|
||||||
static function query($requestId, $payload){
|
|
||||||
$devices = [];
|
|
||||||
$num = 0;
|
|
||||||
foreach ($payload['devices'] as $deviceId) {
|
|
||||||
$subDevicesData = SubDeviceManager::getAllSubDevices($deviceId['id']);
|
|
||||||
|
|
||||||
$tempDevice[$deviceId['id']] = [
|
|
||||||
'online' => false,
|
|
||||||
'status' => 'OFFLINE',
|
|
||||||
];
|
|
||||||
foreach ($subDevicesData as $key => $subDeviceData) {
|
|
||||||
$lastRecord = RecordManager::getLastRecord($subDeviceData['subdevice_id']);
|
|
||||||
if ($lastRecord['execuded'] == 1){
|
|
||||||
$tempDevice[$deviceId['id']]['online'] = true;
|
|
||||||
$tempDevice[$deviceId['id']]['status'] = "SUCCESS";
|
|
||||||
} else {
|
|
||||||
$executed = 0;
|
|
||||||
$waiting = 0;
|
|
||||||
foreach (RecordManager::getLastRecord($deviceId['id'], 6) as $key => $value) {
|
|
||||||
if ($value['execuded'] == 1){
|
|
||||||
$executed++;
|
|
||||||
} else {
|
|
||||||
$waiting++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($waiting < $executed){
|
|
||||||
$tempDevice[$deviceId['id']]['online'] = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch ($subDeviceData['type']) {
|
|
||||||
case 'temp_cont':
|
|
||||||
$tempDevice[$deviceId['id']]['thermostatMode'] = 'off';
|
|
||||||
if ($lastRecord['value'] != 0) {
|
|
||||||
$tempDevice[$deviceId['id']]['thermostatMode'] = 'heat';
|
|
||||||
}
|
|
||||||
$tempDevice[$deviceId['id']]['thermostatTemperatureAmbient'] = $lastRecord['value'];
|
|
||||||
$tempDevice[$deviceId['id']]['thermostatTemperatureSetpoint'] = $lastRecord['value'];
|
|
||||||
break;
|
|
||||||
case 'vol_cont':
|
|
||||||
$tempDevice[$deviceId['id']]['currentVolume'] = $lastRecord['value'];
|
|
||||||
break;
|
|
||||||
case 'media_apps':
|
|
||||||
$tempDevice[$deviceId['id']]['currentApplication'] = "kodi";
|
|
||||||
break;
|
|
||||||
case 'media_input':
|
|
||||||
$tempDevice[$deviceId['id']]['currentInput'] = "pc";
|
|
||||||
break;
|
|
||||||
case 'media_status':
|
|
||||||
$tempDevice[$deviceId['id']]['activityState'] = "ACTIVE";
|
|
||||||
$tempDevice[$deviceId['id']]['playbackState'] = "PLAYING";
|
|
||||||
break;
|
|
||||||
case 'on/off':
|
|
||||||
$tempDevice[$deviceId['id']]['on'] = ($lastRecord['value'] == 1 ? true : false);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lastRecord['execuded'] == 1){
|
|
||||||
$online = true;
|
|
||||||
$status = 'SUCCESS';
|
|
||||||
} else {
|
|
||||||
$executed = 0;
|
|
||||||
$waiting = 0;
|
|
||||||
foreach (RecordManager::getLastRecord($deviceId['id'], 6) as $key => $value) {
|
|
||||||
if ($value['execuded'] == 1){
|
|
||||||
$executed++;
|
|
||||||
} else {
|
|
||||||
$waiting++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($waiting < $executed){
|
|
||||||
$status = "PENDING";
|
|
||||||
$online = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$devices = $tempDevice;
|
|
||||||
/*if (count($devices)> 1){
|
|
||||||
$devices[] = $tempDevice;
|
|
||||||
}*/
|
|
||||||
}
|
|
||||||
$response = [
|
|
||||||
'requestId' => $requestId,
|
|
||||||
'payload' => [
|
|
||||||
'devices' => $devices,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
|
|
||||||
$apiLogManager->write("[API][$requestId] request response\n" . json_encode($response, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
|
|
||||||
$apiLogManager->setLevel(LOGLEVEL);
|
|
||||||
echo json_encode($response);
|
|
||||||
}
|
|
||||||
|
|
||||||
static function execute($requestId, $payload){
|
|
||||||
$commands = [];
|
|
||||||
foreach ($payload['commands'] as $key => $command) {
|
|
||||||
foreach ($command['devices'] as $key2 => $device) {
|
|
||||||
$executionCommand = $command['execution'][0];
|
|
||||||
if (isset($command['execution'][$key])) {
|
|
||||||
$executionCommand = $command['execution'][$key];
|
|
||||||
}
|
|
||||||
|
|
||||||
$deviceType = GoogleHomeDeviceTypes::getType($executionCommand['command']);
|
|
||||||
$subDeviceId = SubDeviceManager::getSubDeviceByMasterAndType($device['id'], $deviceType)['subdevice_id'];
|
|
||||||
switch ($executionCommand['command']) {
|
|
||||||
case 'action.devices.commands.OnOff':
|
|
||||||
$commands[] = self::executeSwitch($subDeviceId, $executionCommand);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.commands.ThermostatTemperatureSetpoint':
|
|
||||||
$commands[] = self::executeTermostatValue($subDeviceId, $executionCommand);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.commands.ThermostatSetMode':
|
|
||||||
$commands[] = self::executeTermostatMode($subDeviceId, $executionCommand);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.commands.setVolume':
|
|
||||||
$commands[] = self::executeVolume($subDeviceId, $executionCommand);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.commands.appSelect':
|
|
||||||
$commands[] = self::executeApp($subDeviceId, $executionCommand);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.commands.SetInput':
|
|
||||||
$commands[] = self::executeInput($subDeviceId, $executionCommand);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.commands.mediaNext':
|
|
||||||
$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.commands.mediaPrevious':
|
|
||||||
$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.commands.mediaPause':
|
|
||||||
$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.commands.mediaResume':
|
|
||||||
$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'action.devices.commands.mediaStop':
|
|
||||||
$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
|
|
||||||
break;
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$response = [
|
|
||||||
'requestId' => $requestId,
|
|
||||||
'payload' => [
|
|
||||||
'commands' => $commands,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
|
|
||||||
$apiLogManager->setLevel(LOGLEVEL);
|
|
||||||
$apiLogManager->write("[API][EXECUTE][$requestId]\n" . json_encode($response, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
|
|
||||||
|
|
||||||
echo json_encode($response);
|
|
||||||
}
|
|
||||||
|
|
||||||
static function executeSwitch($subDeviceId, $executionCommand){
|
|
||||||
$value = 0;
|
|
||||||
$status = 'OFFLINE';
|
|
||||||
$online = false;
|
|
||||||
|
|
||||||
if ($executionCommand['params']['on']) $value = 1;
|
|
||||||
|
|
||||||
RecordManager::createWithSubId($subDeviceId, $value);
|
|
||||||
|
|
||||||
$executed = 0;
|
|
||||||
$waiting = 0;
|
|
||||||
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
|
|
||||||
if ($value['execuded'] == 1){
|
|
||||||
$executed++;
|
|
||||||
} else {
|
|
||||||
$waiting++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($waiting < $executed){
|
|
||||||
$status = "PENDING";
|
|
||||||
$online = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
|
|
||||||
$commandTemp = [
|
|
||||||
'ids' => [(string) $deviceId],
|
|
||||||
'status' => $status,
|
|
||||||
'states' => [
|
|
||||||
'on' => $executionCommand['params']['on'],
|
|
||||||
'online' => $online,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
return $commandTemp;
|
|
||||||
}
|
|
||||||
|
|
||||||
static function executeTermostatValue($subDeviceId, $executionCommand){
|
|
||||||
$value = 0;
|
|
||||||
$status = 'OFFLINE';
|
|
||||||
$online = false;
|
|
||||||
|
|
||||||
if (isset($executionCommand['params']['thermostatTemperatureSetpoint'])) {
|
|
||||||
$value = $executionCommand['params']['thermostatTemperatureSetpoint'];
|
|
||||||
}
|
|
||||||
|
|
||||||
RecordManager::createWithSubId($subDeviceId, $value);
|
|
||||||
|
|
||||||
$executed = 0;
|
|
||||||
$waiting = 0;
|
|
||||||
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $lastValue) {
|
|
||||||
if ($lastValue['execuded'] == 1){
|
|
||||||
$executed++;
|
|
||||||
} else {
|
|
||||||
$waiting++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($waiting < $executed){
|
|
||||||
$status = "PENDING";
|
|
||||||
$online = true;;
|
|
||||||
}
|
|
||||||
|
|
||||||
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
|
|
||||||
$commandTemp = [
|
|
||||||
'ids' => [(string) $deviceId],
|
|
||||||
'status' => $status,
|
|
||||||
'states' => [
|
|
||||||
'thermostatMode' => 'heat',
|
|
||||||
'thermostatTemperatureSetpoint' => $value,
|
|
||||||
'thermostatTemperatureAmbient' => $value,
|
|
||||||
'online' => $online,
|
|
||||||
//ambient z dalšího zenzoru v roomu
|
|
||||||
],
|
|
||||||
];
|
|
||||||
return $commandTemp;
|
|
||||||
}
|
|
||||||
|
|
||||||
static function executeTermostatMode($subDeviceId, $executionCommand){
|
|
||||||
$mode = "off";
|
|
||||||
$value = 0;
|
|
||||||
$status = 'OFFLINE';
|
|
||||||
$online = false;
|
|
||||||
|
|
||||||
if (isset($executionCommand['params']['thermostatMode']) && $executionCommand['params']['thermostatMode'] != 'off') {
|
|
||||||
$mode = $executionCommand['params']['thermostatMode'];
|
|
||||||
$value = RecordManager::getLastRecordNotNull($subDeviceId)['value'];
|
|
||||||
}
|
|
||||||
|
|
||||||
RecordManager::createWithSubId($subDeviceId, $value);
|
|
||||||
|
|
||||||
$executed = 0;
|
|
||||||
$waiting = 0;
|
|
||||||
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
|
|
||||||
if ($value['execuded'] == 1){
|
|
||||||
$executed++;
|
|
||||||
} else {
|
|
||||||
$waiting++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($waiting < $executed){
|
|
||||||
$status = "PENDING";
|
|
||||||
$online = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
|
|
||||||
$commandTemp = [
|
|
||||||
'ids' => [(string) $deviceId],
|
|
||||||
'status' => $status,
|
|
||||||
'states' => [
|
|
||||||
'thermostatMode' => $mode,
|
|
||||||
'online' => $online,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
return $commandTemp;
|
|
||||||
}
|
|
||||||
|
|
||||||
static function executeVolume($subDeviceId, $executionCommand){
|
|
||||||
//echo $executionCommand['params']['volumeLevel'];
|
|
||||||
$status = 'OFFLINE';
|
|
||||||
$online = false;
|
|
||||||
|
|
||||||
$currentVolume = RecordManager::getLastRecord($subDeviceId)['value'];
|
|
||||||
|
|
||||||
if (isset($executionCommand['params']['volumeLevel'])) {
|
|
||||||
RecordManager::createWithSubId($subDeviceId, $executionCommand['params']['volumeLevel']);
|
|
||||||
$executed = 0;
|
|
||||||
$waiting = 0;
|
|
||||||
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
|
|
||||||
if ($value['execuded'] == 1){
|
|
||||||
$executed++;
|
|
||||||
} else {
|
|
||||||
$waiting++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($waiting < $executed){
|
|
||||||
$status = "PENDING";
|
|
||||||
$online = true;
|
|
||||||
$currentVolume = $executionCommand['params']['volumeLevel'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
|
|
||||||
$commandTemp = [
|
|
||||||
'ids' => [(string) $deviceId],
|
|
||||||
'status' => $status,
|
|
||||||
'states' => [
|
|
||||||
'currentVolume' => $currentVolume,
|
|
||||||
'online' => $online,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
return $commandTemp;
|
|
||||||
}
|
|
||||||
|
|
||||||
static function executeApp($subDeviceId, $executionCommand){
|
|
||||||
//echo $executionCommand['params']['newApplication'];
|
|
||||||
$status = 'OFFLINE';
|
|
||||||
$online = false;
|
|
||||||
|
|
||||||
$currentApplication = RecordManager::getLastRecord($subDeviceId)['value'];
|
|
||||||
|
|
||||||
if (isset($executionCommand['params']['newApplication'])) {
|
|
||||||
RecordManager::createWithSubId($subDeviceId, $executionCommand['params']['newApplication']);
|
|
||||||
$executed = 0;
|
|
||||||
$waiting = 0;
|
|
||||||
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
|
|
||||||
if ($value['execuded'] == 1){
|
|
||||||
$executed++;
|
|
||||||
} else {
|
|
||||||
$waiting++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($waiting < $executed){
|
|
||||||
$status = "PENDING";
|
|
||||||
$online = true;
|
|
||||||
$currentApplication = $executionCommand['params']['newApplication'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
|
|
||||||
$commandTemp = [
|
|
||||||
'ids' => [(string) $deviceId],
|
|
||||||
'status' => $status,
|
|
||||||
'states' => [
|
|
||||||
'currentApplication' => $currentApplication,
|
|
||||||
'online' => $online,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
return $commandTemp;
|
|
||||||
}
|
|
||||||
|
|
||||||
static function executeInput($subDeviceId, $executionCommand){
|
|
||||||
//echo $executionCommand['params']['newInput'];
|
|
||||||
$status = 'OFFLINE';
|
|
||||||
$online = false;
|
|
||||||
|
|
||||||
$currentInput = RecordManager::getLastRecord($subDeviceId)['value'];
|
|
||||||
|
|
||||||
if (isset($executionCommand['params']['newInput'])) {
|
|
||||||
RecordManager::createWithSubId($subDeviceId, $executionCommand['params']['newInput']);
|
|
||||||
$executed = 0;
|
|
||||||
$waiting = 0;
|
|
||||||
foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
|
|
||||||
if ($value['execuded'] == 1){
|
|
||||||
$executed++;
|
|
||||||
} else {
|
|
||||||
$waiting++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($waiting < $executed){
|
|
||||||
$status = "PENDING";
|
|
||||||
$online = true;
|
|
||||||
$currentInput = $executionCommand['params']['newInput'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
|
|
||||||
$commandTemp = [
|
|
||||||
'ids' => [(string) $deviceId],
|
|
||||||
'status' => $status,
|
|
||||||
'states' => [
|
|
||||||
'currentInput' => $currentInput,
|
|
||||||
'online' => $online,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
return $commandTemp;
|
|
||||||
}
|
|
||||||
|
|
||||||
static function executeMediaCont($subDeviceId, $executionCommand){
|
|
||||||
$status = 'SUCCESS';
|
|
||||||
$online = true;
|
|
||||||
|
|
||||||
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
|
|
||||||
$commandTemp = [
|
|
||||||
'ids' => [(string) $deviceId],
|
|
||||||
'status' => $status,
|
|
||||||
'states' => [
|
|
||||||
'online' => $online,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
return $commandTemp;
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,34 +0,0 @@
|
|||||||
<?php
|
|
||||||
class Partial{
|
|
||||||
private $assignedValues = [];
|
|
||||||
private $partBuffer;
|
|
||||||
private $path;
|
|
||||||
private $debug;
|
|
||||||
|
|
||||||
function __construct($path = "", $debug = false) {
|
|
||||||
$this->debug = $debug;
|
|
||||||
if (!empty('../app/views/templates/part/' . $path . '.phtml') && file_exists('../app/views/templates/part/' . $path . '.phtml')) {
|
|
||||||
$this->path = $path;
|
|
||||||
} else {
|
|
||||||
echo '<pre>';
|
|
||||||
echo 'PHTML: Parial File ' . $path . ' not found';
|
|
||||||
echo '</pre>';
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function prepare($searchS, $repleaceS) {
|
|
||||||
if (!empty($searchS)) {
|
|
||||||
$this->assignedValues[strtoupper($searchS)] = $repleaceS;
|
|
||||||
}
|
|
||||||
echo ($this->debug == true ? var_dump($this->assignedValues) : '');
|
|
||||||
}
|
|
||||||
|
|
||||||
function render() {
|
|
||||||
if (!empty($this->assignedValues)){
|
|
||||||
extract($this->assignedValues);
|
|
||||||
}
|
|
||||||
|
|
||||||
require('../app/views/templates/part/' . $this->path . '.phtml');
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,64 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
class AuthManager {
|
|
||||||
public function getToken($username, $password, $userAgent = null){
|
|
||||||
if ($userAgent == null) {
|
|
||||||
$userAgent = $_SERVER['HTTP_USER_AGENT'];
|
|
||||||
}
|
|
||||||
|
|
||||||
$userManager = new UserManager();
|
|
||||||
if ($username != '' || $password != ''){
|
|
||||||
$userLogedIn = $userManager->loginNew($username, $password);
|
|
||||||
|
|
||||||
if ($userLogedIn != false){
|
|
||||||
// Create token header as a JSON string
|
|
||||||
$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
|
|
||||||
// Create token payload as a JSON string
|
|
||||||
$payload = json_encode([
|
|
||||||
'user_id' => $userLogedIn,
|
|
||||||
'exp' => date('Y-m-d H:i:s',strtotime("+90 Days")),
|
|
||||||
'iat' => date('Y-m-d H:i:s',time()),
|
|
||||||
]);
|
|
||||||
// Encode Header to Base64Url String
|
|
||||||
$base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
|
|
||||||
// Encode Payload to Base64Url String
|
|
||||||
$base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
|
|
||||||
// Create Signature Hash
|
|
||||||
$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, 'abC123!', true);
|
|
||||||
// Encode Signature to Base64Url String
|
|
||||||
$base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
|
|
||||||
// Create JWT
|
|
||||||
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
|
|
||||||
|
|
||||||
|
|
||||||
$token = [
|
|
||||||
'user_id' => $userLogedIn,
|
|
||||||
'user_agent' => $userAgent,
|
|
||||||
'token' => $jwt,
|
|
||||||
'expire' => date('Y-m-d H:i:s',strtotime("+90 Days")),
|
|
||||||
'issued' => date('Y-m-d H:i:s',time()),
|
|
||||||
];
|
|
||||||
if (Db::add ('tokens', $token)){
|
|
||||||
return $jwt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function deleteToken($token){
|
|
||||||
Db::command ('DELETE FROM tokens WHERE token=?', array ($token));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function validateToken($token){
|
|
||||||
list($type, $hash) = explode(' ', $token);
|
|
||||||
$tokens = Db::loadAll('SELECT * FROM tokens WHERE token = ? AND expire >= CURRENT_TIMESTAMP AND blocked = 0;', array($hash));
|
|
||||||
if ($type == 'Bearer' && count($tokens) == 1) {
|
|
||||||
return true;
|
|
||||||
} else if (count($tokens) == 0) {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,129 +0,0 @@
|
|||||||
<?php
|
|
||||||
class ChartScale{
|
|
||||||
const HOUR = 'info';
|
|
||||||
const DAY = 'warning';
|
|
||||||
const MONTH = 'warning';
|
|
||||||
const YEAR = 'error';
|
|
||||||
}
|
|
||||||
class ChartManager{
|
|
||||||
function generateChart($data, $min = 0, $max = 100) {
|
|
||||||
|
|
||||||
echo '<br>Aktuální Hodnota: '.$data[0]['value'];
|
|
||||||
echo "<style>
|
|
||||||
.sloupec {
|
|
||||||
border-top: solid 2px red;
|
|
||||||
}
|
|
||||||
</style>";
|
|
||||||
echo '<div class=graph>';
|
|
||||||
echo '<div class="posuv " graf-max="'.$max.'" graf-min='.$min.'>';
|
|
||||||
for ($valuesRow = 0; $valuesRow < count($data); $valuesRow++) {
|
|
||||||
$row = $data[$valuesRow];
|
|
||||||
|
|
||||||
echo '<div class="sloupec " name="sloupec" value="' . $row['value'] . '" data-toggle="tooltip" title=""></div>';
|
|
||||||
}
|
|
||||||
echo '</div>';
|
|
||||||
echo '</div>';
|
|
||||||
echo '<script src="./include/js/chartDrwer.js"></script>';
|
|
||||||
echo 'Poslední Update: ';
|
|
||||||
|
|
||||||
echo '<style>
|
|
||||||
.graph {
|
|
||||||
width: 100%;
|
|
||||||
overflow: hidden;
|
|
||||||
|
|
||||||
margin-top: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
.posuv {
|
|
||||||
display: flex;
|
|
||||||
height: 200px;
|
|
||||||
background-image: url(./img/graph.png);
|
|
||||||
padding: 20px;
|
|
||||||
background-repeat: repeat;
|
|
||||||
border-bottom: 1px solid black;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sloupec {
|
|
||||||
border-top: solid 2px blue;
|
|
||||||
background-color: grey;
|
|
||||||
float: left;
|
|
||||||
margin: auto 0 0;
|
|
||||||
display: inline-block;
|
|
||||||
width: 1%;
|
|
||||||
}
|
|
||||||
|
|
||||||
</style>
|
|
||||||
<script>
|
|
||||||
var posuvList = document.getElementsByClassName("posuv");
|
|
||||||
var maxHeight = posuvList[0].clientHeight;
|
|
||||||
for (i = 0; i < posuvList.length; i++) {
|
|
||||||
var maxPx = 0;
|
|
||||||
var grafMax = Number(posuvList[i].getAttribute("graf-max")); //100%
|
|
||||||
var grafMin = Number(posuvList[i].getAttribute("graf-min")); //0%
|
|
||||||
if (grafMin == 0 && grafMax == 100) {
|
|
||||||
var onePercent = 1;
|
|
||||||
} else {
|
|
||||||
var stepsBetWene = grafMax;
|
|
||||||
if (grafMin !== 0) {
|
|
||||||
if (grafMin < 0) {
|
|
||||||
stepsBetWene = grafMax + Math.abs(grafMin);
|
|
||||||
}
|
|
||||||
if (grafMin > 0) {
|
|
||||||
stepsBetWene = grafMax - grafMin;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var onePercent = stepsBetWene / 100;
|
|
||||||
}
|
|
||||||
var sloupceList = posuvList[i].querySelectorAll(".sloupec");
|
|
||||||
for (ai = 0; ai < sloupceList.length; ai++) {
|
|
||||||
var onePxPercent = maxHeight / 100;
|
|
||||||
var heightInPercent =
|
|
||||||
Math.abs(sloupceList[ai].getAttribute("value")) / onePercent;
|
|
||||||
var outputPx = onePxPercent * heightInPercent;
|
|
||||||
|
|
||||||
sloupceList[ai].style.height = outputPx + "px";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>';
|
|
||||||
}
|
|
||||||
|
|
||||||
function generateChartData(int $subDeviceId, string $periode, string $groupBy) {
|
|
||||||
$chartData = [];
|
|
||||||
|
|
||||||
$subDevice = SubDeviceManager::getSubDevice($subDeviceId);
|
|
||||||
$records = RecordManager::getAllRecordForGraph($subDeviceId, $periode, $groupBy);
|
|
||||||
|
|
||||||
$array = array_column($records, 'value');
|
|
||||||
$arrayTime = array_column($records, 'time');
|
|
||||||
$output = [];
|
|
||||||
|
|
||||||
foreach ($array as $key => $value) {
|
|
||||||
$output[$key]['y'] = $value;
|
|
||||||
if ($subDevice['type'] == 'light'){
|
|
||||||
if ($value > 810){
|
|
||||||
$output[$key]['y'] = 1;
|
|
||||||
} else {
|
|
||||||
$output[$key]['y'] = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$timeStamp = new DateTime($arrayTime[$key]);
|
|
||||||
$output[$key]['t'] = $timeStamp->format("Y-m-d") . 'T' . $timeStamp->format("H:i:s") . 'Z';
|
|
||||||
}
|
|
||||||
|
|
||||||
$data = json_encode($output);
|
|
||||||
$data = $output;
|
|
||||||
$arrayTimeStamps = array_column($records, 'time');
|
|
||||||
foreach ($arrayTimeStamps as $key => $value) {
|
|
||||||
$arrayTimeStamps[$key] = (new DateTime($value))->format(TIMEFORMAT);
|
|
||||||
}
|
|
||||||
|
|
||||||
$chartData['graphRange'] = RANGES[$subDevice['type']];
|
|
||||||
$chartData['graphType'] = RANGES[$subDevice['type']]['graph'];
|
|
||||||
$chartData['graphData'] = $data;
|
|
||||||
|
|
||||||
return $chartData;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
?>
|
|
@@ -1,11 +0,0 @@
|
|||||||
<?php
|
|
||||||
class EmailManager {
|
|
||||||
public function SendTo ($pro, $predmet, $zprava) {
|
|
||||||
$email = "From: EnergyCounter@steelants.cz";
|
|
||||||
$email .= "\nMIME-Version: 1.0\n";
|
|
||||||
$email .= "Content-Type: text/html; charset=\"utf-8\"\n";
|
|
||||||
if (!mb_send_mail ($pro, $predmet, $zprava, $email)) {
|
|
||||||
throw new PDOException("!Email se nepodařilo odeslat!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,78 +0,0 @@
|
|||||||
<?php
|
|
||||||
class LogMaintainer
|
|
||||||
{
|
|
||||||
private function cleaningDir ($dir, $seconds) {
|
|
||||||
$todayFileName = date ("Y-m-d").'.log';
|
|
||||||
$logFiles = scandir ($dir);
|
|
||||||
foreach ($logFiles as $key => $file) {
|
|
||||||
if (in_array ($file,array (".", "..", ".gitkeep", $todayFileName)))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!is_dir($dir . $file)) {
|
|
||||||
if (strtotime(str_replace(".log", "", $file)) < (strtotime("now") - $seconds)) {
|
|
||||||
unlink ($dir . $file);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
$this->cleaningDir ($dir . $file . "/", $seconds);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function purge ($days) {
|
|
||||||
$seconds = $days * 86400;
|
|
||||||
$this->cleaningDir ('../logs/', $seconds);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function getStats(){
|
|
||||||
$stats = array(
|
|
||||||
'ERROR' => 0,
|
|
||||||
'WARNING' => 0,
|
|
||||||
'EXEPTION' => 0,
|
|
||||||
'INFO' => 0,
|
|
||||||
);
|
|
||||||
|
|
||||||
$result = array();
|
|
||||||
$result = self::logFinder ('../logs/', $result);
|
|
||||||
|
|
||||||
foreach ($result as $path => $files) {
|
|
||||||
foreach ($files as $file) {
|
|
||||||
|
|
||||||
# code...
|
|
||||||
$matches = array();
|
|
||||||
|
|
||||||
$re = '/\[(?:warning|error|info)\]/';
|
|
||||||
$str = file_get_contents($path . $file);
|
|
||||||
preg_match_all($re, $str, $matches);
|
|
||||||
if (count($matches[0]) == 0) continue;
|
|
||||||
|
|
||||||
foreach ($matches[0] as $match) {
|
|
||||||
switch($match){
|
|
||||||
case '[error]': $stats['ERROR']++; break;
|
|
||||||
case '[warning]': $stats['WARNING']++; break;
|
|
||||||
case '[exeption]': $stats['EXEPTION']++; break;
|
|
||||||
default: $stats['INFO']++; break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $stats;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static function logFinder ($dir, $result) {
|
|
||||||
$logFiles = scandir ($dir);
|
|
||||||
foreach ($logFiles as $key => $file) {
|
|
||||||
if (in_array ($file,array (".", "..", ".gitkeep")))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!is_dir($dir . $file)) {
|
|
||||||
$result[$dir][] = $file;
|
|
||||||
} else {
|
|
||||||
$result = self::logFinder ($dir . $file . "/", $result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return $result;
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,42 +0,0 @@
|
|||||||
<?php
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class LogManager
|
|
||||||
{
|
|
||||||
private $logFile;
|
|
||||||
private $logLevel = 1;
|
|
||||||
|
|
||||||
public 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!");
|
|
||||||
}
|
|
||||||
|
|
||||||
public function setLevel($type = LogRecordTypess::WARNING){
|
|
||||||
$this->logLevel = $type['level'];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function write($value, $type = LogRecordTypess::ERROR){
|
|
||||||
if ($type['level'] <= $this->logLevel) {
|
|
||||||
$record = "[".date("H:m:s")."][".$type['identifier']."]" . $value . "\n";
|
|
||||||
fwrite($this->logFile, $record);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function __destruct(){
|
|
||||||
if (isset($this->logFile) && $this->logFile != "Unable to open file!") {
|
|
||||||
fclose($this->logFile);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,38 +0,0 @@
|
|||||||
<?php
|
|
||||||
class RoomManager{
|
|
||||||
public static $rooms;
|
|
||||||
|
|
||||||
static function getDefaultRoomId() {
|
|
||||||
$defaultRoom = Db::loadOne("SELECT `room_id` FROM `rooms` WHERE `default` = 1");
|
|
||||||
return $defaultRoom['room_id'];
|
|
||||||
}
|
|
||||||
|
|
||||||
static function getAllRooms () {
|
|
||||||
//TODO: ignore Widgets withoud data
|
|
||||||
$allRoom = Db::loadAll ("SELECT rooms.*, COUNT(devices.device_id) as device_count FROM rooms LEFT JOIN devices ON (devices.room_id=rooms.room_id) GROUP BY rooms.room_id");
|
|
||||||
return $allRoom;
|
|
||||||
}
|
|
||||||
|
|
||||||
static function getRoomsDefault () {
|
|
||||||
//TODO: ignore Widgets withoud data
|
|
||||||
$allRoom = Db::loadAll ("SELECT rooms.room_id, rooms.name, COUNT(devices.device_id) as device_count FROM rooms LEFT JOIN devices ON (devices.room_id=rooms.room_id) GROUP BY rooms.room_id;");
|
|
||||||
return $allRoom;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function create ($name) {
|
|
||||||
$room = array (
|
|
||||||
'name' => $name,
|
|
||||||
);
|
|
||||||
try {
|
|
||||||
Db::add ('rooms', $room);
|
|
||||||
} catch(PDOException $error) {
|
|
||||||
echo $error->getMessage();
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function delete ($roomId) {
|
|
||||||
Db::command ('DELETE FROM rooms WHERE room_id=?', array ($roomId));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
?>
|
|
@@ -1,33 +0,0 @@
|
|||||||
<?php
|
|
||||||
class SettingsManager{
|
|
||||||
static function getAllValues () {
|
|
||||||
return Db::loadAll ("SELECT * FROM settings");
|
|
||||||
}
|
|
||||||
|
|
||||||
static function getByName($settingName) {
|
|
||||||
return Db::loadOne("SELECT * FROM settings WHERE name = ?", array($settingName));
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function create ($name, $value) {
|
|
||||||
$setting = array (
|
|
||||||
'name' => $name,
|
|
||||||
'value' => $value,
|
|
||||||
);
|
|
||||||
try {
|
|
||||||
Db::add ('settings', $setting);
|
|
||||||
} catch(PDOException $error) {
|
|
||||||
echo $error->getMessage();
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function update ($name, $value) {
|
|
||||||
try {
|
|
||||||
Db::edit ('settings', ['value' => $value], 'WHERE name = ?', array($name));
|
|
||||||
} catch(PDOException $error) {
|
|
||||||
echo $error->getMessage();
|
|
||||||
die();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
?>
|
|
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
class VirtualDeviceManager
|
|
||||||
{
|
|
||||||
public function fetchEnabled($deviceId = null, $subDeviceId = null){
|
|
||||||
$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;
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,185 +0,0 @@
|
|||||||
<?php
|
|
||||||
class GoogleHomeDeviceTypes {
|
|
||||||
/*const AirConditioningUnit = 'action.devices.types.AC_UNIT';
|
|
||||||
const AirFreshener = 'action.devices.types.AIRFRESHENER';
|
|
||||||
const AirPurifier = 'action.devices.types.AIRPURIFIER';
|
|
||||||
const Awning = 'action.devices.types.AWNING';
|
|
||||||
const Bathtub = 'action.devices.types.BATHTUB';
|
|
||||||
const Bed = 'action.devices.types.BED';
|
|
||||||
const Blender = 'action.devices.types.BLENDER';
|
|
||||||
const Blinds = 'action.devices.types.BLINDS';
|
|
||||||
const Boiler = 'action.devices.types.BOILER';
|
|
||||||
const Camera = 'action.devices.types.CAMERA';
|
|
||||||
const CarbonMonoxideDetector = 'action.devices.types.CARBON_MONOXIDE_DETECTOR';
|
|
||||||
const Charger = 'action.devices.types.CHARGER';
|
|
||||||
const Closet = 'action.devices.types.CLOSET';
|
|
||||||
const CoffeeMaker = 'action.devices.types.COFFEE_MAKER';
|
|
||||||
const Cooktop = 'action.devices.types.COOKTOP';
|
|
||||||
const Curtain = 'action.devices.types.CURTAIN';
|
|
||||||
const Dehumidifier = 'action.devices.types.DEHUMIDIFIER';
|
|
||||||
const Dehydrator = 'action.devices.types.DEHYDRATOR';
|
|
||||||
const Dishwasher = 'action.devices.types.DISHWASHER';
|
|
||||||
const Door = 'action.devices.types.DOOR';
|
|
||||||
const Drawer = 'action.devices.types.DRAWER';
|
|
||||||
const Dryer = 'action.devices.types.DRYER';
|
|
||||||
const Fan = 'action.devices.types.FAN';
|
|
||||||
const Faucet = 'action.devices.types.FAUCET';
|
|
||||||
const Fireplace = 'action.devices.types.FIREPLACE';
|
|
||||||
const Fryer = 'action.devices.types.FRYER';
|
|
||||||
const GarageDoor = 'action.devices.types.GARAGE';
|
|
||||||
const Gate = 'action.devices.types.GATE';
|
|
||||||
const Grill = 'action.devices.types.GRILL';
|
|
||||||
const Heater = 'action.devices.types.HEATER';
|
|
||||||
const Hood = 'action.devices.types.HOOD';
|
|
||||||
const Humidifier = 'action.devices.types.HUMIDIFIER';
|
|
||||||
const Kettle = 'action.devices.types.KETTLE';
|
|
||||||
const Light = 'action.devices.types.LIGHT';
|
|
||||||
const Lock = 'action.devices.types.LOCK';
|
|
||||||
const MediaRemote = 'action.devices.types.REMOTECONTROL';
|
|
||||||
const Mop = 'action.devices.types.MOP';
|
|
||||||
const Mower = 'action.devices.types.MOWER';
|
|
||||||
const Microwave = 'action.devices.types.MICROWAVE';
|
|
||||||
const Multicooker = 'action.devices.types.MULTICOOKER';
|
|
||||||
const Network = 'action.devices.types.NETWORK';
|
|
||||||
|
|
||||||
const Oven = 'action.devices.types.OVEN';
|
|
||||||
const Pergola = 'action.devices.types.PERGOLA';
|
|
||||||
const PetFeeder = 'action.devices.types.PETFEEDER';
|
|
||||||
const PressureCooker = 'action.devices.types.PRESSURECOOKER';
|
|
||||||
const Radiator = 'action.devices.types.RADIATOR';
|
|
||||||
const Refrigerator = 'action.devices.types.REFRIGERATOR';
|
|
||||||
const Router = 'action.devices.types.ROUTER';
|
|
||||||
const Scene = 'action.devices.types.SCENE';
|
|
||||||
const Sensor = 'action.devices.types.SENSOR';
|
|
||||||
const SecuritySystem = 'action.devices.types.SECURITYSYSTEM';
|
|
||||||
const SettopBox = 'action.devices.types.SETTOP';
|
|
||||||
const Shutter = 'action.devices.types.SHUTTER';
|
|
||||||
const Shower = 'action.devices.types.SHOWER';
|
|
||||||
const SmokeDetector = 'action.devices.types.SMOKE_DETECTOR';
|
|
||||||
const SousVide = 'action.devices.types.SOUSVIDE';
|
|
||||||
const Sprinkler = 'action.devices.types.SPRINKLER';
|
|
||||||
const StandMixer = 'action.devices.types.STANDMIXER';
|
|
||||||
const Switch = 'action.devices.types.SWITCH';
|
|
||||||
const Television = 'action.devices.types.TV';
|
|
||||||
const Thermostat = 'action.devices.types.THERMOSTAT';
|
|
||||||
const Vacuum = 'action.devices.types.VACUUM';
|
|
||||||
const Valve = 'action.devices.types.VALVE';
|
|
||||||
const Washer = 'action.devices.types.WASHER';
|
|
||||||
const WaterHeater = 'action.devices.types.WATERHEATER';
|
|
||||||
const WaterPurifier = 'action.devices.types.WATERPURIFIER';
|
|
||||||
const WaterSoftener = 'action.devices.types.WATERSOFTENER';
|
|
||||||
const Window = 'action.devices.types.WINDOW';
|
|
||||||
const YogurtMaker = 'action.devices.types.YOGURTMAKER';*/
|
|
||||||
|
|
||||||
private static $actionWordBook = [
|
|
||||||
'control-light' => 'action.devices.types.LIGHT',
|
|
||||||
'control-socket' => 'action.devices.types.OUTLET',
|
|
||||||
'control-temp' => 'action.devices.types.THERMOSTAT',
|
|
||||||
'control-media' => 'action.devices.types.REMOTECONTROL',
|
|
||||||
];
|
|
||||||
|
|
||||||
private static $traidWordBook = [
|
|
||||||
'on/off' => 'action.devices.traits.OnOff',
|
|
||||||
'temp_cont' => 'action.devices.traits.TemperatureSetting',
|
|
||||||
'vol_cont' => 'action.devices.traits.Volume',
|
|
||||||
'media_cont' => 'action.devices.traits.TransportControl',
|
|
||||||
'media_status' => 'action.devices.traits.MediaState',
|
|
||||||
'media_apps' => 'action.devices.traits.AppSelector',
|
|
||||||
'media_input' => 'action.devices.traits.InputSelector',
|
|
||||||
];
|
|
||||||
|
|
||||||
private static $commandWordBook = [
|
|
||||||
'action.devices.commands.OnOff' => 'on/off',
|
|
||||||
'action.devices.commands.ThermostatTemperatureSetpoint' => 'temp_cont',
|
|
||||||
'action.devices.commands.ThermostatSetMode' => 'temp_cont',
|
|
||||||
'action.devices.commands.setVolume' => 'vol_cont',
|
|
||||||
'action.devices.commands.mediaNext' => 'media_status',
|
|
||||||
'action.devices.commands.mediaPause' => 'media_status',
|
|
||||||
'action.devices.commands.mediaPrevious' => 'media_status',
|
|
||||||
'action.devices.commands.mediaResume' => 'media_status',
|
|
||||||
'action.devices.commands.mediaStop' => 'media_status',
|
|
||||||
'action.devices.commands.appSelect' => 'media_apps',
|
|
||||||
'action.devices.commands.SetInput' => 'media_input',
|
|
||||||
];
|
|
||||||
|
|
||||||
private static $attributeWordBook = [
|
|
||||||
'on/off' => [
|
|
||||||
'commandOnlyOnOff' => false,
|
|
||||||
],
|
|
||||||
'temp_cont' => [
|
|
||||||
'availableThermostatModes' => 'off,heat',
|
|
||||||
'thermostatTemperatureUnit' => 'C',
|
|
||||||
],
|
|
||||||
'vol_cont' => [
|
|
||||||
'volumeCanMuteAndUnmute' => false,
|
|
||||||
'volumeDefaultPercentage' => 6,
|
|
||||||
'volumeMaxLevel' => 100,
|
|
||||||
'levelStepSize' => 2,
|
|
||||||
'commandOnlyVolume' => false,
|
|
||||||
],
|
|
||||||
'media_cont'=> [
|
|
||||||
'transportControlSupportedCommands' => [
|
|
||||||
"NEXT",
|
|
||||||
"PREVIOUS",
|
|
||||||
"PAUSE",
|
|
||||||
"STOP",
|
|
||||||
"RESUME",
|
|
||||||
"CAPTION_CONTROL"
|
|
||||||
],
|
|
||||||
],
|
|
||||||
'media_status'=> [
|
|
||||||
'supportActivityState' => true,
|
|
||||||
'supportPlaybackState' => true,
|
|
||||||
],
|
|
||||||
'media_apps' => [
|
|
||||||
"availableApplications" => [
|
|
||||||
[
|
|
||||||
"key" => "kodi",
|
|
||||||
"names" => [
|
|
||||||
"name_synonym" => [
|
|
||||||
"Kodi",
|
|
||||||
],
|
|
||||||
"lang" => "en",
|
|
||||||
],
|
|
||||||
],
|
|
||||||
],
|
|
||||||
],
|
|
||||||
'media_input' => [
|
|
||||||
"availableInputs" => [
|
|
||||||
[
|
|
||||||
"key" => "pc",
|
|
||||||
"names" => [
|
|
||||||
"name_synonym" => [
|
|
||||||
"PC",
|
|
||||||
],
|
|
||||||
"lang" => "en",
|
|
||||||
],
|
|
||||||
],
|
|
||||||
]
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
static function getAction($deviceType){
|
|
||||||
if (!isset(self::$actionWordBook[$deviceType])) return;
|
|
||||||
return self::$actionWordBook[$deviceType];
|
|
||||||
}
|
|
||||||
|
|
||||||
static function getTraid($subDeviceType){
|
|
||||||
if (!isset(self::$traidWordBook[$subDeviceType])) return;
|
|
||||||
return self::$traidWordBook[$subDeviceType];
|
|
||||||
}
|
|
||||||
|
|
||||||
static function getType($subDeviceCommand){
|
|
||||||
if (!isset(self::$commandWordBook[$subDeviceCommand])) return;
|
|
||||||
return self::$commandWordBook[$subDeviceCommand];
|
|
||||||
}
|
|
||||||
|
|
||||||
static function getAttribute($subDeviceType){
|
|
||||||
if (!isset(self::$attributeWordBook[$subDeviceType])) return;
|
|
||||||
return self::$attributeWordBook[$subDeviceType];
|
|
||||||
}
|
|
||||||
|
|
||||||
static function getQueryJson($deviceType, $type){
|
|
||||||
return self::$wordBook[$type];
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
class LogRecordTypes{
|
|
||||||
const ERROR = [
|
|
||||||
'level' => 0,
|
|
||||||
'identifier' => 'error',
|
|
||||||
];
|
|
||||||
const WARNING = [
|
|
||||||
'level' => 1,
|
|
||||||
'identifier' =>'warning',
|
|
||||||
];
|
|
||||||
const EXEPTION = [
|
|
||||||
'level' => 2,
|
|
||||||
'identifier' => 'exeption',
|
|
||||||
];
|
|
||||||
const INFO = [
|
|
||||||
'level' => 3,
|
|
||||||
'identifier' => 'info',
|
|
||||||
];
|
|
||||||
}
|
|
@@ -1,45 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
class WidgetTypes {
|
|
||||||
const VALUE = 0;
|
|
||||||
const ICON = 1;
|
|
||||||
const BUTTON = 2;
|
|
||||||
const SWITH = 3;
|
|
||||||
const RANGE = 4;
|
|
||||||
const CUSTOM = 5;
|
|
||||||
|
|
||||||
private $types = [
|
|
||||||
self::VALUE => [
|
|
||||||
'name' => 'value',
|
|
||||||
'active' => false
|
|
||||||
],
|
|
||||||
self::ICON => [
|
|
||||||
'name' => 'icon',
|
|
||||||
'active' => false
|
|
||||||
],
|
|
||||||
self::BUTTON => [
|
|
||||||
'name' => 'button',
|
|
||||||
'active' => true
|
|
||||||
],
|
|
||||||
self::SWITH => [
|
|
||||||
'name' => 'switch',
|
|
||||||
'active' => true
|
|
||||||
],
|
|
||||||
self::RANGE => [
|
|
||||||
'name' => 'range',
|
|
||||||
'active' => true
|
|
||||||
],
|
|
||||||
self::CUSTOM => [
|
|
||||||
'name' => 'custom',
|
|
||||||
'active' => true
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
public static function getName($type){
|
|
||||||
return self::$types[$type];
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function isActive($type){
|
|
||||||
return isset(self::$types[$type]) && self::$types[$type]['active'];
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,52 +0,0 @@
|
|||||||
<?php
|
|
||||||
class AirQuality extends VirtualDeviceManager
|
|
||||||
{
|
|
||||||
private $city_sluig = "prague";
|
|
||||||
private $app_id = "53ccbc353bb0bd0b05515169a593b96c38d57c48";
|
|
||||||
private $api_uri = 'http://api.waqi.info/feed/%s/?token=%s'; // Your redirect uri
|
|
||||||
private $virtual_device_name = "Air Quality";
|
|
||||||
private $subdevice_type = "air-quality";
|
|
||||||
|
|
||||||
function make()
|
|
||||||
{
|
|
||||||
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();
|
|
||||||
|
|
||||||
$finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id);
|
|
||||||
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
|
|
||||||
RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi']);
|
|
||||||
} 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 < 50) {
|
|
||||||
return 'Good';
|
|
||||||
} else if ($value > 51 && $value < 100) {
|
|
||||||
return 'Moderate';
|
|
||||||
} else if ($value > 101 && $value < 150) {
|
|
||||||
return 'Normal';
|
|
||||||
} else if ($value > 151 && $value < 200) {
|
|
||||||
return 'Unhealthy';
|
|
||||||
} else if ($value > 201 && $value < 300) {
|
|
||||||
return 'Very Unhealthy';
|
|
||||||
} else if ($value > 301 ) {
|
|
||||||
return 'Hazardous';
|
|
||||||
}
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,52 +0,0 @@
|
|||||||
<?php
|
|
||||||
class AirQuality extends VirtualDeviceManager
|
|
||||||
{
|
|
||||||
private $city_sluig = "prague";
|
|
||||||
private $app_id = "53ccbc353bb0bd0b05515169a593b96c38d57c48";
|
|
||||||
private $api_uri = 'http://api.waqi.info/feed/%s/?token=%s'; // Your redirect uri
|
|
||||||
private $virtual_device_name = "Air Quality";
|
|
||||||
private $subdevice_type = "air-quality";
|
|
||||||
|
|
||||||
function make()
|
|
||||||
{
|
|
||||||
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();
|
|
||||||
|
|
||||||
$finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id);
|
|
||||||
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
|
|
||||||
RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi']);
|
|
||||||
} 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 < 50) {
|
|
||||||
return 'Good';
|
|
||||||
} else if ($value > 51 && $value < 100) {
|
|
||||||
return 'Moderate';
|
|
||||||
} else if ($value > 101 && $value < 150) {
|
|
||||||
return 'Normal';
|
|
||||||
} else if ($value > 151 && $value < 200) {
|
|
||||||
return 'Unhealthy';
|
|
||||||
} else if ($value > 201 && $value < 300) {
|
|
||||||
return 'Very Unhealthy';
|
|
||||||
} else if ($value > 301 ) {
|
|
||||||
return 'Hazardous';
|
|
||||||
}
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,53 +0,0 @@
|
|||||||
<?php
|
|
||||||
class CovidV2 extends VirtualDeviceManager
|
|
||||||
{
|
|
||||||
private $api_uri = 'https://onemocneni-aktualne.mzcr.cz/api/v2/covid-19/nakazeni-vyleceni-umrti-testy.json'; // Your redirect uri
|
|
||||||
private $virtual_device_name = "Covid-V2";
|
|
||||||
private $name_index = [
|
|
||||||
"Active" => "kumulativni_pocet_nakazenych",
|
|
||||||
"Recovered" => "kumulativni_pocet_vylecenych",
|
|
||||||
"Tested" => "kumulativni_pocet_testu",
|
|
||||||
"Deaths" => "kumulativni_pocet_umrti",
|
|
||||||
|
|
||||||
];
|
|
||||||
|
|
||||||
public function make()
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
if (DeviceManager::registeret($this->virtual_device_name)) {
|
|
||||||
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
|
|
||||||
$dataItems = ['Tested', '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 = $this->api_uri;
|
|
||||||
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true)['data'];
|
|
||||||
|
|
||||||
foreach ($dataItems as $dataItem) {
|
|
||||||
RecordManager::create($deviceId, strtolower($dataItem), end($json)[$this->name_index[$dataItem]]);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, strtolower($this->virtual_device_name));
|
|
||||||
DeviceManager::approved($this->virtual_device_name);
|
|
||||||
}
|
|
||||||
return 'sucessful';
|
|
||||||
} catch (Exception $e) {
|
|
||||||
return 'exception: ' . $e->getMessage();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function translate($value){
|
|
||||||
$outcome = $value / 1000;
|
|
||||||
if ($outcome < 1){
|
|
||||||
return $value;
|
|
||||||
}
|
|
||||||
return round($outcome) . 'K';
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,78 +0,0 @@
|
|||||||
<?php
|
|
||||||
class DatabaseBackup
|
|
||||||
{
|
|
||||||
public function make()
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
$filenames = [];
|
|
||||||
$backupWorker = new DatabaseBackup;
|
|
||||||
$filenames[] = $backupWorker->scheme(); //Backup Database scheme
|
|
||||||
$filenames[] = $backupWorker->data(); //Backup Database Data
|
|
||||||
$filenames[] = $_SERVER['DOCUMENT_ROOT'] . '/config/config.php'; //Backup Configuration File
|
|
||||||
$backupWorker->compress($_SERVER['DOCUMENT_ROOT'] . BASEDIR . '/backup/' . date("Y-m-d", time()) . '.zip', $filenames);
|
|
||||||
return 'sucessful';
|
|
||||||
} catch (Exception $e) {
|
|
||||||
return 'exception: ' . $e->getMessage();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function scheme()
|
|
||||||
{
|
|
||||||
$backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . "/backup/" . DBNAME . '_scheme_' . date("Y-m-d", time()) . '.sql';
|
|
||||||
$command = "mysqldump --skip-comments --no-create-info -h localhost -u " . DBUSER . " -p" . DBPASS . " " . DBNAME . " -r $backupfile 2>&1";
|
|
||||||
$this->executeCommand($command);
|
|
||||||
return $backupfile;
|
|
||||||
}
|
|
||||||
|
|
||||||
private function data()
|
|
||||||
{
|
|
||||||
$backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . "/backup/" . DBNAME . '_data_' . date("Y-m-d", time()) . '.sql';
|
|
||||||
$command = "mysqldump --skip-comments --no-data -h localhost -u " . DBUSER . " -p" . DBPASS . " " . DBNAME . " -r $backupfile 2>&1";
|
|
||||||
$this->executeCommand($command);
|
|
||||||
return $backupfile;
|
|
||||||
}
|
|
||||||
|
|
||||||
private function executeCommand($command)
|
|
||||||
{
|
|
||||||
ini_set('date.timezone', 'Europe/Prague');
|
|
||||||
exec($command);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function compress($filename, $files = [])
|
|
||||||
{
|
|
||||||
$zip = new ZipArchive();
|
|
||||||
if ($zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
|
|
||||||
foreach ($files as $file) {
|
|
||||||
$zip->addFile($file);
|
|
||||||
}
|
|
||||||
$zip->close();
|
|
||||||
foreach ($files as $file) {
|
|
||||||
unlink($file);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function cleaningDir($dir, $seconds)
|
|
||||||
{
|
|
||||||
$todayFileName = date("Y-m-d") . '.zip';
|
|
||||||
$logFiles = scandir($dir);
|
|
||||||
foreach ($logFiles as $key => $file) {
|
|
||||||
if (in_array($file, array(".", "..", ".gitkeep", $todayFileName))) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!is_dir($dir . $file)) {
|
|
||||||
if (strtotime(str_replace(".zip", "", $file)) < (strtotime("now") - $seconds)) {
|
|
||||||
unlink($dir . $file);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
$this->cleaningDir($dir . $file . "/", $seconds);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function purge($days)
|
|
||||||
{
|
|
||||||
$seconds = $days * 86400;
|
|
||||||
$this->cleaningDir('../backup/', $seconds);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,11 +0,0 @@
|
|||||||
<?php
|
|
||||||
class ExamplePlugin extends VirtualDeviceManager
|
|
||||||
{
|
|
||||||
function make(){
|
|
||||||
//Getting Data
|
|
||||||
}
|
|
||||||
|
|
||||||
function translate($value){
|
|
||||||
//Translation of numeric values
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,36 +0,0 @@
|
|||||||
<?php
|
|
||||||
class OpenWeatherMap extends VirtualDeviceManager
|
|
||||||
{
|
|
||||||
private $city_sluig = "prague";
|
|
||||||
private $app_id = "1ee609f2fcf8048e84f1d2fb1d1d72b5";
|
|
||||||
private $api_uri = 'api.openweathermap.org/data/2.5/weather?q=%s&appid=%s'; // Your redirect uri
|
|
||||||
private $virtual_device_name = "Weather";
|
|
||||||
private $subdevice_type = "weather";
|
|
||||||
|
|
||||||
function make()
|
|
||||||
{
|
|
||||||
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();
|
|
||||||
|
|
||||||
$finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id);
|
|
||||||
$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
|
|
||||||
|
|
||||||
RecordManager::create($deviceId, $this->subdevice_type, $json['weather'][0]['id']);
|
|
||||||
} 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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,66 +0,0 @@
|
|||||||
<?php
|
|
||||||
class Spotify extends VirtualDeviceManager
|
|
||||||
{
|
|
||||||
private $token = "";
|
|
||||||
private $client_id = '76840e2199e34dcd903d19877bd726dd'; // Your client id
|
|
||||||
private $redirect_uri = 'https://dev.steelants.cz/vasek/home-update/plugins/spotify/callback'; // Your redirect uri
|
|
||||||
|
|
||||||
public function oAuth()
|
|
||||||
{
|
|
||||||
$client_secret = 'CLIENT_SECRET'; // Your secret
|
|
||||||
$scopes = 'user-read-private user-read-email';
|
|
||||||
|
|
||||||
header('Location: https://accounts.spotify.com/authorize?client_id=' . $this->client_id . '&response_type=token&redirect_uri=' . urlencode($this->redirect_uri) . '&scope=user-read-playback-state');
|
|
||||||
}
|
|
||||||
|
|
||||||
private function setToken($token)
|
|
||||||
{
|
|
||||||
$this->token = $token;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function callback()
|
|
||||||
{
|
|
||||||
var_dump($_REQUEST);
|
|
||||||
(new SettingsManager)->create('spotify_token', $token);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function autorize()
|
|
||||||
{
|
|
||||||
|
|
||||||
$client_secret = '0f94ed2c0bd64bf791ea13b7e6310ba3';
|
|
||||||
|
|
||||||
$ch = curl_init();
|
|
||||||
curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/api/token');
|
|
||||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
|
|
||||||
curl_setopt($ch, CURLOPT_POST, 1);
|
|
||||||
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials&scope=user-read-playback-state');
|
|
||||||
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . base64_encode($this->client_id . ':' . $client_secret)));
|
|
||||||
|
|
||||||
$result = curl_exec($ch);
|
|
||||||
|
|
||||||
$this->setToken(json_decode($result, true)['access_token']);
|
|
||||||
echo $result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private function getPlayerData()
|
|
||||||
{
|
|
||||||
$ch = curl_init();
|
|
||||||
curl_setopt($ch, CURLOPT_URL, 'https://api.spotify.com/v1/me/player');
|
|
||||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
|
|
||||||
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . (new SettingsManager)->getByName('spotify_token')['value']));
|
|
||||||
|
|
||||||
$result = curl_exec($ch);
|
|
||||||
echo $result;
|
|
||||||
}
|
|
||||||
|
|
||||||
// function make()
|
|
||||||
// {
|
|
||||||
// try {
|
|
||||||
// //$this->autorize();d
|
|
||||||
// //$this->getPlayerData();
|
|
||||||
// return 'sucessful';
|
|
||||||
// } catch (Exception $e) {
|
|
||||||
// return 'exception: ' . $e->getMessage();
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
}
|
|
@@ -1,66 +0,0 @@
|
|||||||
<?php
|
|
||||||
class UsaElection extends VirtualDeviceManager
|
|
||||||
{
|
|
||||||
private $api_uri = 'https://ft-ig-content-prod.s3.eu-west-1.amazonaws.com/v2/Financial-Times/ig-rcp-polls-backend/2020-presidential/latest/presidential-races.json'; // Your redirect uri
|
|
||||||
private $virtual_device_name = "Election";
|
|
||||||
private $subdevice_type = "election";
|
|
||||||
|
|
||||||
function make()
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
if (DeviceManager::registeret($this->virtual_device_name)) {
|
|
||||||
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
|
|
||||||
$dataItems = ['Trump', 'Biden', 'Unknown'];
|
|
||||||
foreach ($dataItems as $dataItem) {
|
|
||||||
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) {
|
|
||||||
SubDeviceManager::create($deviceId, strtolower($dataItem), '% ' . $dataItem);
|
|
||||||
sleep(1);
|
|
||||||
$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($this->subdevice_type));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die();
|
|
||||||
|
|
||||||
$finalUrl = $this->api_uri;
|
|
||||||
$json = json_decode(Utilities::CallAPI('GET', $finalUrl), true);
|
|
||||||
|
|
||||||
$voteSpectrum = [
|
|
||||||
'republican' => [
|
|
||||||
'solid' => 0,
|
|
||||||
'leaning' => 0,
|
|
||||||
],
|
|
||||||
'democrat' => [
|
|
||||||
'solid' => 0,
|
|
||||||
'leaning' => 0,
|
|
||||||
],
|
|
||||||
'tossup' => 0
|
|
||||||
];
|
|
||||||
|
|
||||||
foreach ($json as $state) {
|
|
||||||
if ($state['raceCategory'] != 'tossup') {
|
|
||||||
$raceCategory = explode('-', $state['raceCategory']);
|
|
||||||
$voteSpectrum[$raceCategory[0]][$raceCategory[1]] = $voteSpectrum[$raceCategory[0]][$raceCategory[1]] + $state['raceDelegates'];
|
|
||||||
} else {
|
|
||||||
$voteSpectrum['tossup'] = $voteSpectrum['tossup'] + $state['raceDelegates'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$Trump = $voteSpectrum['republican']['solid'] + $voteSpectrum['republican']['leaning'];
|
|
||||||
$Biden = $voteSpectrum['democrat']['solid'] + $voteSpectrum['democrat']['leaning'];
|
|
||||||
$Unknown = $voteSpectrum['tossup'];
|
|
||||||
|
|
||||||
$OnePercent = ($Trump + $Biden + $Unknown) / 100;
|
|
||||||
|
|
||||||
foreach ($dataItems as $Category) {
|
|
||||||
RecordManager::create($deviceId, strtolower($Category), round(($$Category / $OnePercent)));
|
|
||||||
}
|
|
||||||
} 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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,39 +0,0 @@
|
|||||||
<?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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@@ -60,7 +60,6 @@
|
|||||||
<script src="./app/templates/js/automation.js"></script>
|
<script src="./app/templates/js/automation.js"></script>
|
||||||
<?php
|
<?php
|
||||||
$partial = new Partial('footer');
|
$partial = new Partial('footer');
|
||||||
$partial->prepare('baseDir', $BASEDIR);
|
|
||||||
$partial->render();
|
$partial->render();
|
||||||
?>
|
?>
|
||||||
</body>
|
</body>
|
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user