Browse Source

History Clean Up

pull/10/head
JonatanRek 2 years ago
commit
8cf912993d
112 changed files with 11395 additions and 0 deletions
  1. +31
    -0
      .editorconfig
  2. +6
    -0
      .gitignore
  3. +12
    -0
      .htaccess
  4. +21
    -0
      LICENSE
  5. +67
    -0
      README.md
  6. BIN
      _FIRMWARE/drivers/CH341SER/CH341PT.DLL
  7. BIN
      _FIRMWARE/drivers/CH341SER/CH341S64.SYS
  8. BIN
      _FIRMWARE/drivers/CH341SER/CH341S98.SYS
  9. +213
    -0
      _FIRMWARE/drivers/CH341SER/CH341SER.INF
  10. BIN
      _FIRMWARE/drivers/CH341SER/CH341SER.SYS
  11. BIN
      _FIRMWARE/drivers/CH341SER/CH341SER.VXD
  12. BIN
      _FIRMWARE/drivers/CH341SER/DRVSETUP64/DRVSETUP64.exe
  13. BIN
      _FIRMWARE/drivers/CH341SER/SETUP.EXE
  14. BIN
      _FIRMWARE/drivers/CH341SER/ch341SER.CAT
  15. BIN
      _FIRMWARE/drivers/PL2303/PL2303_Prolific_GPS_1013_20090319.exe
  16. BIN
      nsor/ESP_OS_NODE_STABLE/ESP_OS_NODE_STABLE.ino
  17. +346
    -0
      nsor/ESP_OS_NODE_V2.ino/ESP_OS_NODE_V2.ino.ino
  18. +92
    -0
      iginal/ESP_END_POINT.ino
  19. +94
    -0
      _FIRMWARE/firmwares/Sonoff_Basic/ESP_END_POINT.ino
  20. +94
    -0
      _FIRMWARE/firmwares/Sonoff_S20/ESP_END_POINT.ino
  21. BIN
      _FIRMWARE/libs/libraries.zip
  22. +268
    -0
      _INSTALATION/_SQL_TABLES.sql
  23. BIN
      _README_IMG/1.png
  24. BIN
      _README_IMG/10.png
  25. BIN
      _README_IMG/2.png
  26. BIN
      _README_IMG/3.png
  27. BIN
      _README_IMG/4.png
  28. BIN
      _README_IMG/5.png
  29. BIN
      _README_IMG/6.png
  30. BIN
      _README_IMG/7.png
  31. BIN
      _README_IMG/8.png
  32. BIN
      _README_IMG/9.png
  33. +149
    -0
      api.php
  34. +79
    -0
      class/AutomationManager.php
  35. +194
    -0
      class/ChartJS.php
  36. +21
    -0
      class/ChartJS_Line.php
  37. +86
    -0
      class/ChartManager.php
  38. +96
    -0
      class/DB.php
  39. +41
    -0
      class/DashboardManager.php
  40. +80
    -0
      class/DeviceManager.php
  41. +1
    -0
      class/Form.php
  42. +34
    -0
      class/Partial.php
  43. +74
    -0
      class/RecordManager.php
  44. +26
    -0
      class/RoomManager.php
  45. +26
    -0
      class/Route.php
  46. +41
    -0
      class/SceneManager.php
  47. +55
    -0
      class/SubDeviceManager.php
  48. +34
    -0
      class/Template.php
  49. +180
    -0
      class/UserManager.php
  50. +38
    -0
      class/Utilities.php
  51. +59
    -0
      config_sample.php
  52. +14
    -0
      controls/automation.php
  53. +14
    -0
      controls/dashboard.php
  54. +67
    -0
      controls/home.php
  55. +18
    -0
      controls/scene.php
  56. +75
    -0
      index.php
  57. +71
    -0
      lang/cs.php
  58. +71
    -0
      lang/en.php
  59. +22
    -0
      manifest.json
  60. +78
    -0
      serviceWorker.js
  61. +69
    -0
      templates/Elementum/scss/elements/_buttons.scss
  62. +185
    -0
      templates/automation.phtml
  63. +6
    -0
      templates/css/font-awesome.min.css
  64. +19
    -0
      templates/css/loading.css
  65. +2956
    -0
      templates/css/main.css
  66. +44
    -0
      templates/css/main.css.map
  67. +28
    -0
      templates/css/modal.css
  68. +17
    -0
      templates/css/pre.css
  69. +75
    -0
      templates/dashboard.phtml
  70. BIN
      templates/fonts/FontAwesome.otf
  71. BIN
      templates/fonts/Metropolis-Medium.otf
  72. BIN
      templates/fonts/Metropolis-Regular.otf
  73. BIN
      templates/fonts/Metropolis-SemiBold.otf
  74. BIN
      templates/fonts/fontawesome-webfont.eot
  75. +2671
    -0
      templates/fonts/fontawesome-webfont.svg
  76. BIN
      templates/fonts/fontawesome-webfont.ttf
  77. BIN
      templates/fonts/fontawesome-webfont.woff
  78. BIN
      templates/fonts/fontawesome-webfont.woff2
  79. +100
    -0
      templates/home.phtml
  80. BIN
      templates/images/icon-192x192.png
  81. BIN
      templates/images/icon-512x512.png
  82. +2
    -0
      templates/js/jquery.js
  83. +182
    -0
      templates/js/jquery.redirect.js
  84. +54
    -0
      templates/js/post.js
  85. +226
    -0
      templates/js/script.js
  86. +20
    -0
      templates/loading.css
  87. +37
    -0
      templates/login.phtml
  88. +85
    -0
      templates/part/automationCreate.phtml
  89. +38
    -0
      templates/part/automationCreateFinal.phtml
  90. +97
    -0
      templates/part/automationEdit.phtml
  91. +22
    -0
      templates/part/dashboardButton.phtml
  92. +29
    -0
      templates/part/deviceButton.phtml
  93. +80
    -0
      templates/part/deviceDetail.phtml
  94. +160
    -0
      templates/part/deviceEdit.phtml
  95. +3
    -0
      templates/part/footer.phtml
  96. +25
    -0
      templates/part/head.phtml
  97. +40
    -0
      templates/part/sceneCreate.phtml
  98. +26
    -0
      templates/part/sceneCreateOptions.phtml
  99. +48
    -0
      templates/part/sceneEdit.phtml
  100. +3
    -0
      templates/part/test.phtml

+ 31
- 0
.editorconfig View File

@ -0,0 +1,31 @@
# https://editorconfig.org/
root = true
[*]
tab_width = 4
[*.{php,phpt,inc}]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = tab
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
charset = utf-8
end_of_line = lf
indent_style = tab
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 80
[COMMIT_EDITMSG]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = tab
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 80

+ 6
- 0
.gitignore View File

@ -0,0 +1,6 @@
.ftpconfig
config.php
_nemazat/index.html
_nemazat/css/main.css.map
_nemazat/css/main.css
_nemazat/css/font-awesome.min.css

+ 12
- 0
.htaccess View File

@ -0,0 +1,12 @@
RewriteEngine On
RewriteBase /vasek/home/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !.css
RewriteCond %{REQUEST_FILENAME} !.js
RewriteRule (.*) index.php?url=$1 [QSA,L]
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_FILENAME} !api.php
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

+ 21
- 0
LICENSE View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 JonatanRek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

+ 67
- 0
README.md View File

@ -0,0 +1,67 @@
<img src="./templates/images/icon-512x512.png" height="20" width="20">
# Smart_Home
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Discord](https://img.shields.io/discord/601817042475286540.svg?color=Blue&label=Discord&logo=Discord)](https://discord.gg/nMe5evu)
PHP, JS, HTML - Supports PWA
# Installation
default user is Admin and his password id ESP
# Discord
https://discord.gg/nMe5evu
## Browser (Desktop PWA)
<img src="./_README_IMG/1.png" height="500" width="1000">
<img src="./_README_IMG/2.png" height="500" width="1000">
<img src="./_README_IMG/3.png" height="500" width="1000">
<img src="./_README_IMG/4.png" height="500" width="1000">
<img src="./_README_IMG/5.png" height="500" width="1000">
## Mobile (PWA)
<img src="./_README_IMG/6.png" height="500" width="250">
<img src="./_README_IMG/7.png" height="500" width="250">
<img src="./_README_IMG/8.png" height="500" width="250">
<img src="./_README_IMG/9.png" height="500" width="250">
<img src="./_README_IMG/10.png" height="500" width="250">
API
POST Message (Spínač)
```
{
"token":"2"
}
```
Answer (Spínač)
```
{
"device":{
"hostname":"2",
"sleepTime":0
},
"state":"succes",
"value":"0"
}
}
```
POST Message (Sensor)
```
{
"token":"4",
"values":{
"door":{
"value":1
}
}
}
```
Answer (Sensor)
```
{
}
```

BIN
_FIRMWARE/drivers/CH341SER/CH341PT.DLL View File


BIN
_FIRMWARE/drivers/CH341SER/CH341S64.SYS View File


BIN
_FIRMWARE/drivers/CH341SER/CH341S98.SYS View File


+ 213
- 0
_FIRMWARE/drivers/CH341SER/CH341SER.INF View File

@ -0,0 +1,213 @@
; CH341SER.INF
; Driver for CH341 (USB=>SERIAL chip) V3.4
; WDM&VXD for Windows 98/Me/2000/XP/Server2003/Vista/64bit Vista/Server2008/Win7/64bit Win7
; Copyright (C) W.ch 2001-2014
;
[Version]
Signature = "$Chicago$"
Class = Ports
ClassGuid = {4D36E978-E325-11CE-BFC1-08002BE10318}
Provider = %WinChipHead%
DriverVer = 08/08/2014, 3.4.2014.08
CatalogFile = CH341SER.CAT
[ControlFlags]
ExcludeFromSelect = USB\VID_1A86&PID_7523
ExcludeFromSelect = USB\VID_1A86&PID_5523
ExcludeFromSelect = USB\VID_4348&PID_5523
ExcludeFromSelect = USB\VID_4348&PID_5523&REV_0250
ExcludeFromSelect = USBSERPORT\SER5523
ExcludeFromSelect = CH341PORT\SER5523
[Manufacturer]
%WinChipHead% = WinChipHead,NT,NTamd64,NTia64
[WinChipHead]
%CH340SER.DeviceDesc% = CH341SER_Install, USB\VID_1A86&PID_7523
%CH341ASER.DeviceDesc% = CH341SER_Install, USB\VID_1A86&PID_5523
%CH341SER.DeviceDesc% = CH341SER_Install, USB\VID_4348&PID_5523
%CH340SER.DeviceDesc% = CH341SER_Install, USB\VID_4348&PID_5523&REV_0250
%CH341S98.DeviceDesc% = CH341S98_Install, USBSERPORT\SER5523
%CH341S98.DeviceDesc% = CH341S98_Install, CH341PORT\SER5523
[WinChipHead.NT]
%CH340SER.DeviceDesc% = CH341SER_Install.NT, USB\VID_1A86&PID_7523
%CH341ASER.DeviceDesc% = CH341SER_Install.NT, USB\VID_1A86&PID_5523
%CH341SER.DeviceDesc% = CH341SER_Install.NT, USB\VID_4348&PID_5523
%CH340SER.DeviceDesc% = CH341SER_Install.NT, USB\VID_4348&PID_5523&REV_0250
[WinChipHead.NTamd64]
%CH340SER.DeviceDesc% = CH341SER_Inst.NTamd64, USB\VID_1A86&PID_7523
%CH341ASER.DeviceDesc% = CH341SER_Inst.NTamd64, USB\VID_1A86&PID_5523
%CH341SER.DeviceDesc% = CH341SER_Inst.NTamd64, USB\VID_4348&PID_5523
%CH340SER.DeviceDesc% = CH341SER_Inst.NTamd64, USB\VID_4348&PID_5523&REV_0250
[WinChipHead.NTia64]
%CH340SER.DeviceDesc% = CH341SER_Inst.NTia64, USB\VID_1A86&PID_7523
%CH341ASER.DeviceDesc% = CH341SER_Inst.NTia64, USB\VID_1A86&PID_5523
%CH341SER.DeviceDesc% = CH341SER_Inst.NTia64, USB\VID_4348&PID_5523
%CH340SER.DeviceDesc% = CH341SER_Inst.NTia64, USB\VID_4348&PID_5523&REV_0250
[CH341SER_Install]
DelFiles = CH341S98.DelFiles.SYS
CopyFiles = CH341SER.CopyFiles.SYS, CH341SER.CopyFiles.DLL
AddReg = CH341SER.9X.AddReg, CH341SER.AddReg
[CH341SER_Install.NT]
CopyFiles = CH341SER.NT.CopyFiles.SYS, CH341SER.CopyFiles.DLL
AddReg = CH341SER.NT.AddReg, CH341SER.AddReg
[CH341SER_Install.NT.HW]
AddReg = CH341SER.NT.HW.AddReg
[CH341SER_Inst.NTamd64]
CopyFiles = CH341SER.NT.CopyFiles.SYSA64
AddReg = CH341SER.NT.AddReg, CH341SER.AddReg
[CH341SER_Inst.NTamd64.HW]
AddReg = CH341SER.NT.HW.AddReg
[CH341SER_Inst.NTia64]
CopyFiles = CH341SER.NT.CopyFiles.SYSI64
AddReg = CH341SER.NT.AddReg, CH341SER.AddReg
[CH341SER_Inst.NTia64.HW]
AddReg = CH341SER.NT.HW.AddReg
[CH341S98_Install]
DelFiles = CH341S98.DelFiles.SYS
CopyFiles = CH341S98.CopyFiles.VXD, CH341SER.CopyFiles.SYS
AddReg = CH341S98.9X.AddReg, CH341S98.AddReg
;[CH341S98_Install.NT]
[CH341S98.DelFiles.SYS]
CH341S98.SYS, , , 1
[CH341SER.CopyFiles.SYS]
CH341S98.SYS, , , 2
[CH341SER.NT.CopyFiles.SYS]
CH341SER.SYS, , , 2
[CH341SER.NT.CopyFiles.SYSA64]
CH341S64.SYS, , , 2
[CH341SER.NT.CopyFiles.SYSI64]
;CH341I64.SYS, , , 2
[CH341S98.CopyFiles.VXD]
CH341SER.VXD, , , 2
[CH341SER.CopyFiles.DLL]
CH341PT.DLL, , , 2
;安装DLL是可选的,DLL可以用于识别CH341端口和监视CH341端口的插拔事件
[CH341SER.9X.AddReg]
HKR, , DevLoader, , *NTKERN
HKR, , NTMPDriver, , CH341S98.SYS
[CH341SER.NT.AddReg]
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"
[CH341SER.NT.HW.AddReg]
HKR,,"UpperFilters",0x00010000,"serenum"
;上面这行用于枚举接在串口的即插即用设备,启动时将产生DTR和RTS信号,如果需要枚举,请将上面这行的分号去掉
[CH341S98.9X.AddReg]
HKR, , DevLoader, , *vcomm
HKR, , PortDriver, , CH341SER.VXD
HKR, , Contention, , *vcd
HKR, , ConfigDialog, , serialui.dll
HKR, , DCB, 3, 1C,00,00,00, 80,25,00,00, 11,00,00,00, 00,00,0A,00, 0A,00,08,00, 00,11,13,00, 00,00,00,00
HKR, , PortSubClass, 1, 01
HKR, , EnumPropPages, , "serialui.dll,EnumPropPages"
HKR, , Enumerator, , serenum.vxd
;上面这行用于枚举接在串口的即插即用设备,启动时将产生DTR和RTS信号,如果需要枚举,请将上面这行的分号去掉
[CH341SER.AddReg]
HKLM, SOFTWARE\WinChipHead\IC\CH341SER, WDM, 0x00010001, 0x00000034
HKLM, SOFTWARE\WinChipHead\IC\CH341PORT, DLL, 0x00010001, 0x00000010
HKLM, SOFTWARE\WinChipHead\IC\CH341SER, Function, , "USB=>Serial"
;HKLM, SYSTEM\CurrentControlSet\Services\CH341SER, UserRemoval, 0x00010001, 0x00000001
;上面这行用于在系统托盘中显示“安全删除USB转SERIAL硬件设备”,便于用户手工删除硬件
[CH341S98.AddReg]
HKLM, SOFTWARE\WinChipHead\IC\CH341SER, VXD, 0x00010001, 0x00000023
[CH341SER_Install.NT.Services]
AddService = CH341SER, 2, CH341SER.Service
AddService = Serenum, , Serenum_Service_Inst
[CH341SER_Inst.NTamd64.Services]
AddService = CH341SER_A64, 2, CH341SER.ServiceA64
AddService = Serenum, , Serenum_Service_Inst
[CH341SER_Inst.NTia64.Services]
AddService = CH341SER_I64, 2, CH341SER.ServiceI64
AddService = Serenum, , Serenum_Service_Inst
[CH341SER.Service]
DisplayName = "CH341SER"
ServiceType = 1
StartType = 3
ErrorControl = 1
ServiceBinary = %10%\System32\Drivers\CH341SER.SYS
[CH341SER.ServiceA64]
DisplayName = "CH341SER_A64"
ServiceType = 1
StartType = 3
ErrorControl = 1
ServiceBinary = %10%\System32\Drivers\CH341S64.SYS
[CH341SER.ServiceI64]
DisplayName = "CH341SER_I64"
ServiceType = 1
StartType = 3
ErrorControl = 1
ServiceBinary = %10%\System32\Drivers\CH341I64.SYS
[Serenum_Service_Inst]
DisplayName = "SerEnum"
ServiceType = 1
StartType = 3
ErrorControl = 1
ServiceBinary = %12%\serenum.sys
LoadOrderGroup = PNP Filter
[DestinationDirs]
DefaultDestDir = 10, System32\Drivers
CH341S98.DelFiles.SYS = 11
CH341SER.CopyFiles.SYS = 10, System32\Drivers
CH341SER.NT.CopyFiles.SYS = 10, System32\Drivers
CH341S98.CopyFiles.VXD = 11
CH341SER.CopyFiles.DLL = 11
CH341SER.NT.CopyFiles.SYSA64 = 10, System32\Drivers
;CH341SER.NT.CopyFiles.SYSI64 = 10, System32\Drivers
[SourceDisksFiles]
CH341SER.SYS = 1
CH341S98.SYS = 1
CH341SER.VXD = 1
CH341PT.DLL = 1
CH341S64.SYS = 1
;CH341I64.SYS = 1
[SourceDisksNames]
1 = %DISK_NAME%, , ,
[SourceDisksNames.amd64]
1 = %DISK_NAME%, , ,
[SourceDisksNames.ia64]
1 = %DISK_NAME%, , ,
[Strings]
WinChipHead = "wch.cn"
CH341SER.DeviceDesc = "USB-SERIAL CH341"
CH341S98.DeviceDesc = "USB-SERIAL CH341"
CH340SER.DeviceDesc = "USB-SERIAL CH340"
CH341ASER.DeviceDesc = "USB-SERIAL CH341A"
DISK_NAME = "CH341 Serial Installation Disk"

BIN
_FIRMWARE/drivers/CH341SER/CH341SER.SYS View File


BIN
_FIRMWARE/drivers/CH341SER/CH341SER.VXD View File


BIN
_FIRMWARE/drivers/CH341SER/DRVSETUP64/DRVSETUP64.exe View File


BIN
_FIRMWARE/drivers/CH341SER/SETUP.EXE View File


BIN
_FIRMWARE/drivers/CH341SER/ch341SER.CAT View File


BIN
_FIRMWARE/drivers/PL2303/PL2303_Prolific_GPS_1013_20090319.exe View File


BIN
_FIRMWARE/firmwares/NodeMCU → nsor/ESP_OS_NODE_STABLE/ESP_OS_NODE_STABLE.ino View File


_FIRMWARE/firmwares/NodeMCU → nsor/ESP_OS_NODE_V2.ino/ESP_OS_NODE_V2.ino.ino View File

@ -0,0 +1,346 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include "DHT.h"
String ssid = "";
String pasw = "";
String hwId = "";
String url = "";
//Pins
#define LIGHTPIN 13
#define DHTPIN 4
#define DHTTYPE DHT11
#define LED_BUILTIN 16
//Settings
bool deepSleepOn = true;
long sleepTime = 4; //in minutes
bool lightSensor = true;
bool humiditySensor = true;
bool temperatureSensor = true;
ESP8266WebServer server(80);
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.setDebugOutput(true);
EEPROM.begin(512);
Serial.println("");
}
void loop() {
restorSetting();
if (!checkConnection()) {
settingMode();
while (true){
Serial.println("CONECTION SETTING LOOP");
server.handleClient();
}
} else {
httpRequest();
sleep();
}
}
//webpages
void handleRoot() {
String s = "<!DOCTYPE html><html><head>";
s += "<meta name=\"viewport\" content=\"width=device-width,user-scalable=0\">";
s += "<title>";
s += "Main";
s += "</title>";
s += "</head>";
s += "<body>";
s += "<a href=\"/restart\"><p>Restartovat</p><a/>";
s += "<a href=\"/setting\"><p>Refrest WIFI Networks</p><a/>";
s += "</body>";
s += "</html>";
server.send(200, "text/html", s);
}
void handleSetting() {
String wifiList = "";
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0) {
Serial.println("no networks found");
} else {
for (int i = 0; i < n; ++i) {
//Serial.println("SSID: " + WiFi.SSID(i));
wifiList = wifiList + String("<option value=\"");
wifiList = wifiList + String(WiFi.SSID(i));
wifiList = wifiList + String("\">");
wifiList = wifiList + String(WiFi.SSID(i) + "(" + WiFi.RSSI() + ")");
wifiList = wifiList + String("</option>");
}
}
String s = "<!DOCTYPE html><html><head>";
s += "<meta name=\"viewport\" content=\"width=device-width,user-scalable=0\">";
s += "<title>";
s += "Main";
s += "</title>";
s += "</head>";
s += "<body>";
s += "<form method=\"get\" action=\"set\">";
s += "<br>SSID: <select name=\"ssid\">";
s += wifiList;
s += "</select>";
s += "<br>Password: <input name=\"pasw\" length=64 type=\"password\">";
s += "<br>Token: <input name=\"token\" length=64 type=\"text\">";
s += "<br>Api Url: <input name=\"url\" length=64 type=\"url\">";
s += "<input type=\"submit\">";
s += "</form>";
s += "</body>";
s += "</html>";
server.send(200, "text/html", s);
}
//functions
bool restorSetting() {
Serial.println("Reading EEPROM");
ssid = "";
pasw = "";
hwId = "";
url = "";
if (EEPROM.read(0) != 0) {
Serial.println("Reading EEPROM");
for (int i = 0; i < 64; ++i) {
ssid += char(EEPROM.read(i));
}
Serial.println("SSID: " + String(ssid));
for (int i = 64; i < 128; ++i) {
pasw += char(EEPROM.read(i));
}
Serial.println("PASS: " + String(pasw));
for (int i = 128; i < 192; ++i) {
hwId += char(EEPROM.read(i));
}
Serial.println("TOKEN: " + String(hwId));
for (int i = 192; i < 256; ++i) {
url += char(EEPROM.read(i));
}
Serial.println("URL: " + String(url));
return true;
} else {
return false;
}
}
String urlDecode(String input) {
String s = input;
s.replace("%20", " ");
s.replace("+", " ");
s.replace("%21", "!");
s.replace("%22", "\"");
s.replace("%23", "#");
s.replace("%24", "$");
s.replace("%25", "%");
s.replace("%26", "&");
s.replace("%27", "\'");
s.replace("%28", "(");
s.replace("%29", ")");
s.replace("%30", "*");
s.replace("%31", "+");
s.replace("%2C", ",");
s.replace("%2E", ".");
s.replace("%2F", "/");
s.replace("%2C", ",");
s.replace("%3A", ":");
s.replace("%3A", ";");
s.replace("%3C", "<");
s.replace("%3D", "=");
s.replace("%3E", ">");
s.replace("%3F", "?");
s.replace("%40", "@");
s.replace("%5B", "[");
s.replace("%5C", "\\");
s.replace("%5D", "]");
s.replace("%5E", "^");
s.replace("%5F", "-");
s.replace("%60", "`");
return s;
}
bool checkConnection() {
int count = 0;
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.forceSleepWake();
WiFi.begin(ssid, pasw);
Serial.print("Waiting for Wi-Fi connection");
while ( count < 30 ) {
if (WiFi.status() == WL_CONNECTED) {
Serial.println();
Serial.println("Connected!");
return (true);
}
delay(500);
Serial.print(".");
count++;
}
Serial.println("Timed out.");
return false;
}
void settingMode(){
WiFi.mode(WIFI_AP);
WiFi.softAP("NodeMeter");
IPAddress myIP = WiFi.softAPIP();
Serial.print("HotSpt IP:");
Serial.println(myIP);
server.on("/", handleRoot);
server.on("/restart", []() {
ESP.restart();
});
server.on("/setting", handleSetting);
server.on("/set", []() {
for (int i = 0; i < 96; ++i) {
EEPROM.write(i, 'e');
}
EEPROM.commit();
ssid = server.arg("ssid");
pasw = server.arg("pasw");
hwId = server.arg("token");
url = server.arg("url");
for (int i = 0; i < 256; ++i) {
EEPROM.write(i, 0);
}
Serial.println("Writing EEPROM...");
Serial.println("SSID:" + ssid);
for (int i = 0; i < ssid.length(); ++i) {
EEPROM.write(i,ssid[i]);
}
Serial.println("PASW:" + pasw);
for (int i = 0; i < pasw.length(); ++i) {
EEPROM.write(64 + i, pasw[i]);
}
Serial.println("TOKEN:" + hwId);
for (int i = 0; i < hwId.length(); ++i) {
EEPROM.write(128 + i, hwId[i]);
}
Serial.println("URL:" + url);
for (int i = 0; i < url.length(); ++i) {
EEPROM.write(192 + i, url[i]);
}
EEPROM.commit();
Serial.println("Write EEPROM done!");
String s = "<h1>Setup complete.</h1><p>device will be connected to \"";
s += ssid;
s += "\" after the restart.";
server.send(200, "text/html", s);
ESP.restart();
});
server.begin();
Serial.println("HTTP server started");
}
bool httpRequest(){
StaticJsonDocument<1024> sendContent;
sendContent["token"] = hwId;
if (temperatureSensor){
sendContent["values"]["temp"]["value"] = String(getTemperature());
sendContent["values"]["temp"]["unit"] = "C";
}
if (humiditySensor){
sendContent["values"]["humi"]["value"] = String(getHumidity());
sendContent["values"]["humi"]["unit"] = "%";
}
if (lightSensor){
sendContent["values"]["light"]["value"] = String(getLight());
sendContent["values"]["light"]["unit"] = "";
}
String requestJson = "";
serializeJson(sendContent, requestJson);
Serial.println("JSON: " + requestJson);
HTTPClient http;
http.begin(String(url));
http.addHeader("Content-Type", "application/json"); //Specify content-type header
int httpCode = http.POST(requestJson);
String payload = http.getString(); //Get the response payload
http.end();
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
String hostname = doc["device"]["hostname"];
sleepTime = doc["device"]["sleepTime"];
WiFi.hostname(hostname);
Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
Serial.println("HTTP BODY: " + String(payload) + ""); //Print request response payload
http.end(); //Close connection
}
void sleep(){
Serial.println("DISCONECTED FROM WIFI");
WiFi.disconnect();
if (deepSleepOn) {
Serial.println("GOING TO SLEEP FOR " + String(sleepTime));
ESP.deepSleep((sleepTime * 60) * 1000000, RF_DEFAULT); // 20e6 is 20 microseconds
delay(1000);
} else {
delay(1000);
delay(sleepTime);
}
}
//ReadTemperatures
float getTemperature() {
float t = dht.readTemperature();
//Serial.print(dht.readTemperature());
//Serial.println(t);
if (isnan(t)) {
Serial.println( "Failed to read temperature from sensor!") ;
return 999;
}
return t;
}
float getHumidity() {
float h = dht.readHumidity();
//Serial.println(h);
if (isnan(h)) {
Serial.println("Failed to read humidity from sensor!");
return 999;
}
return h;
}
int getLight() {
int l = analogRead(LIGHTPIN);
if (l > 1000) {
return 1;
} else {
return 0;
}
Serial.println("Failed to read light from sensor!");
return 999;
}

_FIRMWARE/firmwares/Sonoff → iginal/ESP_END_POINT.ino View File

@ -0,0 +1,92 @@
//Includes
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
//Variables
const char* ssid = "";
const char* pasw = "";
const char* server = "http://ESP:ESP@dev.steelants.cz/projekty/rest_vasek/api/out.php";
const char* hwId = "";
int lastState = 0;
//Constant
#define SONOFF 12
#define SONOFF_LED 13
#define SONOFF_BUT 0
void setup() {
Serial.begin(9600);
Serial.println("HW: " + String(hwId));
pinMode(SONOFF, OUTPUT);
pinMode(SONOFF_LED, OUTPUT);
pinMode(SONOFF_BUT, OUTPUT);
pinMode(SONOFF_BUT, INPUT);
// WI-FI CONECTING
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pasw);
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, pasw);
while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
digitalWrite(SONOFF_LED, LOW); // LOW will turn on the LED
delay(1000);
digitalWrite(SONOFF_LED, HIGH); // HIGH will turn off the LED
delay(1000);
}
Serial.println("\nCONECTED TO WIFI");
Serial.println("IP: " + String(WiFi.localIP()));
}
bool buttonState = digitalRead(SONOFF_BUT);
HTTPClient http;
http.begin(server);
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
String requestJson = "{";
requestJson += "\"tocken\":\"" + String(hwId) + "\"";
if (buttonState == true) {
requestJson += ",";
requestJson += "\"on/off\":{";
requestJson += "\"value\":\"" + String(~lastState) + "\",";
requestJson += "\"unit\":\"\"";
requestJson += "}";
}
while(buttonState == true) {
delay(50); // keeps a small delay
}
requestJson += "}";
Serial.println("JSON: " + requestJson);
int httpCode = http.POST(requestJson);
String payload = http.getString(); //Get the response payload
Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
Serial.println("HTTP BODY: " + String(payload) + ""); //Print request response payload
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
string hostname = doc["hostname"];
WiFi.hostname(hostname);
int state = doc["state"];
if (state == 1 && lastState == 0) {
Serial.println("ON");
digitalWrite(SONOFF, HIGH); // Turn the LED on by making the voltage LOW
digitalWrite(SONOFF_LED, LOW); // Turn the LED on by making the voltage LOW
} else {
Serial.println("OFF");
digitalWrite(SONOFF, LOW); // Turn the LED on by making the voltage LOW
digitalWrite(SONOFF_LED, HIGH); // Turn the LED on by making the voltage LOW
}
lastState = state;
delay(1000);
}

+ 94
- 0
_FIRMWARE/firmwares/Sonoff_Basic/ESP_END_POINT.ino View File

@ -0,0 +1,94 @@
//Includes
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
//Variables
const char* ssid = "";
const char* pasw = "";
const char* server = "http://ESP:ESP@dev.steelants.cz/projekty/rest_vasek/api/out.php";
const char* hwId = "";
int lastState = 0;
//Constant
#define SONOFF 12
#define SONOFF_LED 13
#define SONOFF_BUT 0
void setup() {
Serial.begin(9600);
Serial.println("HW: " + String(hwId));
pinMode(SONOFF, OUTPUT);
pinMode(SONOFF_LED, OUTPUT);
pinMode(SONOFF_BUT, OUTPUT);
pinMode(SONOFF_BUT, INPUT);
// WI-FI CONECTING
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pasw);
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, pasw);
while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
digitalWrite(SONOFF_LED, LOW); // LOW will turn on the LED
delay(1000);
digitalWrite(SONOFF_LED, HIGH); // HIGH will turn off the LED
delay(1000);
}
Serial.println("\nCONECTED TO WIFI");
Serial.println("IP: " + String(WiFi.localIP()));
}
bool buttonState = digitalRead(SONOFF_BUT);
HTTPClient http;
http.begin(server);
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
String requestJson = "{";
requestJson += "\"tocken\":\"" + String(hwId) + "\"";
if (buttonState == true) {
requestJson += ",";
requestJson += "\"on/off\":{";
requestJson += "\"value\":\"" + String(~lastState) + "\",";
requestJson += "\"unit\":\"\"";
requestJson += "}";
}
while(buttonState == true) {
delay(50); // keeps a small delay
}
requestJson += "}";
Serial.println("JSON: " + requestJson);
int httpCode = http.POST(requestJson);
String payload = http.getString(); //Get the response payload
Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
Serial.println("HTTP BODY: " + String(payload) + ""); //Print request response payload
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
string hostname = doc["device"]["hostname"];
sleepTime = doc["device"]["sleepTime"];
WiFi.hostname(hostname);
int state = doc["state"];
if (state == 1 && lastState == 0) {
Serial.println("ON");
digitalWrite(SONOFF, HIGH); // Turn the LED on by making the voltage LOW
digitalWrite(SONOFF_LED, LOW); // Turn the LED on by making the voltage LOW
} else {
Serial.println("OFF");
digitalWrite(SONOFF, LOW); // Turn the LED on by making the voltage LOW
digitalWrite(SONOFF_LED, HIGH); // Turn the LED on by making the voltage LOW
}
lastState = state;
delay(1000);
}

+ 94
- 0
_FIRMWARE/firmwares/Sonoff_S20/ESP_END_POINT.ino View File

@ -0,0 +1,94 @@
//Includes
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
//Variables
const char* ssid = "";
const char* pasw = "";
const char* server = "httpa://dev.steelants.cz/vasek/home/api.php";
const char* hwId = "";
int lastState = 0;
int reconectAtemptsMax = 10; //time to wait before restart
//Constant
#define SONOFF 12
#define SONOFF_LED 13
#define SONOFF_BUT 0
HTTPClient http;
void setup() {
Serial.begin(9600);
Serial.println("HW: " + String(hwId));
pinMode(SONOFF, OUTPUT);
pinMode(SONOFF_LED, OUTPUT);
pinMode(SONOFF_BUT, OUTPUT);
pinMode(SONOFF_BUT, INPUT);
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.setAutoConnect (true);
WiFi.setAutoReconnect (true);
WiFi.begin(ssid, pasw);
http.begin(server);
}
void loop() {
int reconectAtempts = 0;
while(WiFi.status() != WL_CONNECTED){
if (reconectAtemptsMax == reconectAtempts) {
ESP.restart();
}
WiFi.begin(ssid, pasw);
delay(1000);
}
bool buttonState = digitalRead(SONOFF_BUT);
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
StaticJsonBuffer<1024> jsonContent;
jsonContent["token"] = hwId;
if (buttonState){
jsonContent["values"]["on/off"]["value"] = lastState;
jsonContent["values"]["on/off"]["unit"] = '';
while(buttonState) {
delay(100);
}
}
String requestJson = "";
serializeJson(jsonContent, requestJson);
jsonContent.clean();
Serial.println("JSON: " + requestJson);
int httpCode = http.POST(jsonContent);
String payload = http.getString(); //Get the response payload
Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
Serial.println("HTTP BODY: " + String(payload) + ""); //Print request response payload
deserializeJson(doc, payload);
string hostname = doc["device"]["hostname"];
WiFi.hostname(hostname);
int state = doc["state"];
if (state == 1 && lastState == 0) {
Serial.println("ON");
digitalWrite(SONOFF, HIGH); // Turn the LED on by making the voltage LOW
digitalWrite(SONOFF_LED, LOW); // Turn the LED on by making the voltage LOW
} else {
Serial.println("OFF");
digitalWrite(SONOFF, LOW); // Turn the LED on by making the voltage LOW
digitalWrite(SONOFF_LED, HIGH); // Turn the LED on by making the voltage LOW
}
lastState = state;
delay(1000);
}

BIN
_FIRMWARE/libs/libraries.zip View File


+ 268
- 0
_INSTALATION/_SQL_TABLES.sql View File

@ -0,0 +1,268 @@
-- phpMyAdmin SQL Dump
-- version 4.6.6deb4
-- https://www.phpmyadmin.net/
--
-- Počítač: localhost:3306
-- Vytvořeno: Pát 28. čen 2019, 10:05
-- Verze serveru: 10.1.38-MariaDB-0+deb9u1
-- Verze PHP: 7.0.33-0+deb9u3
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` int(11) 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'
) 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,
`approved` int(11) NOT NULL,
`icon` 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` varchar(255) NOT NULL,
`time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) 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
) 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 `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=10;
--
-- AUTO_INCREMENT pro tabulku `dashboard`
--
ALTER TABLE `dashboard`
MODIFY `dashboard_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT pro tabulku `devices`
--
ALTER TABLE `devices`
MODIFY `device_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT pro tabulku `records`
--
ALTER TABLE `records`
MODIFY `record_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26310;
--
-- AUTO_INCREMENT pro tabulku `rooms`
--
ALTER TABLE `rooms`
MODIFY `room_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
--
-- AUTO_INCREMENT pro tabulku `scenes`
--
ALTER TABLE `scenes`
MODIFY `scene_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pro tabulku `subdevices`
--
ALTER TABLE `subdevices`
MODIFY `subdevice_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT pro tabulku `users`
--
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- 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 CASCADE ON UPDATE CASCADE;
--
-- 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/1.png View File

Before After
Width: 1680  |  Height: 907  |  Size: 256 KiB

BIN
_README_IMG/10.png View File

Before After
Width: 360  |  Height: 640  |  Size: 18 KiB

BIN
_README_IMG/2.png View File

Before After
Width: 1680  |  Height: 907  |  Size: 196 KiB

BIN
_README_IMG/3.png View File

Before After
Width: 1680  |  Height: 907  |  Size: 196 KiB

BIN
_README_IMG/4.png View File

Before After
Width: 1680  |  Height: 907  |  Size: 67 KiB

BIN
_README_IMG/5.png View File

Before After
Width: 1680  |  Height: 907  |  Size: 103 KiB

BIN
_README_IMG/6.png View File

Before After
Width: 360  |  Height: 640  |  Size: 74 KiB

BIN
_README_IMG/7.png View File

Before After
Width: 360  |  Height: 640  |  Size: 44 KiB

BIN
_README_IMG/8.png View File

Before After
Width: 360  |  Height: 640  |  Size: 17 KiB

BIN
_README_IMG/9.png View File

Before After
Width: 360  |  Height: 640  |  Size: 22 KiB

+ 149
- 0
api.php View File

@ -0,0 +1,149 @@
<?php
/** Includes **/
include_once('./config.php');
//Autoloader
foreach (["class", "views"] as $dir) {
$files = scandir('./'.$dir.'/');
$files = array_diff($files, array('.', '..'));
foreach ($files as $file) {
include_once './'.$dir.'/'. $file;
}
}
//DB Conector
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
//Filtrování IP adress
if (DEBUGMOD != 1) {
if (!in_array($_SERVER['REMOTE_ADDR'], HOMEIP)) {
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Using API from your IP insn´t alowed!",
));
header("HTTP/1.1 401 Unauthorized");
exit();
}
}
//Read API data
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
if (isset($obj['user']) && $obj['user'] != ''){
//user at home
$user = UserManager::getUser($obj['user']);
$userId = $user['user_id'];
UserManager::atHome($userId, $obj['location']);
die();
}
//automationExecution
AutomationManager::executeAll();
//Record Cleaning
RecordManager::clean(RECORDTIMOUT);
//Variables
$token = $obj['token'];
$values = null;
if (isset($obj['values'])) {
$values = $obj['values'];
}
//Checks
if ($token == null || $token == "") {
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Missing Value Token in JSON payload",
));
header("HTTP/1.1 401 Unauthorized");
die();
}
//Vstupní Checky
if (!DeviceManager::registeret($token)) {
DeviceManager::create($token, $token);
header("HTTP/1.1 401 Unauthorized");
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Device not registeret",
));
exit();
}
if (!DeviceManager::approved($token)) {
header("HTTP/1.1 401 Unauthorized");
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Unaproved Device",
));
exit();
}
if (!DeviceManager::approved($token)) {
header("HTTP/1.1 401 Unauthorized");
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Unaproved Device",
));
exit();
}
// 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'],2));
}
$hostname = strtolower($device['name']);
$hostname = str_replace(' ', '_', $hostname);
echo json_encode(array(
'device' => [
'hostname' => $hostname,
'sleepTime' => $device['sleep_time'],
],
'state' => 'succes',
));
header("HTTP/1.1 200 OK");
die();
} else {
//Vypis
//TODO: doděla uložení výpisu jinými slovy zda li byl comman vykonán
$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'];
RecordManager::setExecuted($subDeviceLastReord['record_id']);
echo json_encode(array(
'device' => [
'hostname' => $device['name'],
'sleepTime' => $device['sleep_time'],
],
'state' => 'succes',
'value' => $subDeviceLastReordValue
));
header("HTTP/1.1 200 OK");
die();
}

+ 79
- 0
class/AutomationManager.php View File

@ -0,0 +1,79 @@
<?php
class AutomationManager{
public static $automation;
public function remove($automationId) {
return Db::command ('DELETE FROM automation WHERE automation_id=?', array ($automationId));
}
public function deactive($automationId) {
$automation = Db::loadOne ("SELECT * FROM automation WHERE automation_id=?" , array ($automationId));
$flipedValue = ($automation['active'] == 1 ? 0 : 1);
return Db::command ('UPDATE automation SET active = ? WHERE automation_id=?', array ($flipedValue,$automationId));
}
public function create ($name, $onDays, $doCode, $ifCode) {
$scene = array (
'name' => $name,
'on_days' => $onDays,
'if_something' => $doCode,
'do_something' => $ifCode,
);
try {
Db::add ('automation', $scene);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public function getAll(){
return Db::loadAll ("SELECT * FROM automation");
}
public function executeAll(){
global $dateTimeOffset;
$automations = Db::loadAll ("SELECT * FROM automation");
$dayNameNow = strtolower (date('D', time()));
foreach ($automations as $automation) {
$onValue = $automation['if_something'];
$sceneDoJson = $automation['do_something'];
$actionDays = json_decode($automation['on_days'], true);
$value = time();
if ($automation['active'] != 0){
if (in_array($dayNameNow, $actionDays)){
switch ($onValue) {
case 'sunSet':
$value = date_sunset($value, SUNFUNCS_RET_TIMESTAMP, 50.0755381 , 14.4378005, 90, $dateTimeOffset);
break;
case 'sunRise':
$value = date_sunrise($value, SUNFUNCS_RET_TIMESTAMP, 50.0755381 , 14.4378005, 90, $dateTimeOffset);
break;
case 'time':
$onValue = explode(':',$onValue);
$today = date_create('now');
$onValue = $today->setTime($onValue[0], $onValue[1]);
$value = $today->getTimestamp();
break;
default:
break;
}
if (time() > $value){
if ($automation['executed'] == 0){
$sceneDoArray = json_decode($sceneDoJson);
foreach ($sceneDoArray as $deviceId => $deviceState) {
RecordManager::create($deviceId, 'on/off', $deviceState);
}
Db::edit('automation', array('executed' => 1), 'WHERE automation_id = ?', array($automation['automation_id']));
}
} elseif (time() < $value && $automation['executed'] = 1) { //recovery realowing of automation
Db::edit('automation', array('executed' => 0), 'WHERE automation_id = ?', array($automation['automation_id']));
}
}
}
}
}
}

+ 194
- 0
class/ChartJS.php View File

@ -0,0 +1,194 @@
<?php
abstract class ChartJS
{
/**
* @var array chart data
*/
protected $_datasets = array();
/**
* @var array chart labels
*/
protected $_labels = array();
/**
* The chart type
* @var string
*/
protected $_type = '';
/**
* @var array Specific options for chart
*/
protected $_options = array();
/**
* @var string Chartjs canvas' ID
*/
protected $_id;
/**
* @var string Canvas width
*/
protected $_width;
/**
* @var string Canvas height
*/
protected $_height;
/**
* @var array Canvas attributes (class,
*/
protected $_attributes = array();
/**
* @var array Default colors
*/
protected static $_defaultColors = array('fill' => 'rgba(220,220,220,0.2)', 'stroke' => 'rgba(220,220,220,1)', 'point' => 'rgba(220,220,220,1)', 'pointStroke' => '#fff');
/**
* Add label(s)
* @param array $labels
* @param bool $reset
*/
public function addLabels(array $labels, $reset = false)
{
if ($reset) {
$this->_labels = array();
}
$this->_labels = $this->_labels + $labels;
}
/**
* Add dataset
* @param $dataset
* @param $reset
*/
public function addDataset($dataset, $reset)
{
if ($reset) {
$this->_datasets = array();
}
$this->_datasets += $dataset;
}
public function __construct($id = null, $width = '', $height = '', $otherAttributes = array())
{
if (!$id) {
$id = uniqid('chartjs_', true);
}
$this->_id = $id;
$this->_width = $width;
$this->_height = $height;
// Always save otherAttributes as array
if ($otherAttributes && !is_array($otherAttributes)) {
$otherAttributes = array($otherAttributes);
}
$this->_attributes = $otherAttributes;
}
/**
* This method allows to echo ChartJS object and directly renders canvas (instead of using ChartJS->render())
*/
public function __toString()
{
return $this->renderCanvas();
}
public function renderCanvas()
{
$data = $this->_renderData();
$options = $this->_renderOptions();