Compare commits

..

No commits in common. "master" and "alfa" have entirely different histories.
master ... alfa

73 changed files with 1211 additions and 1412 deletions

View File

@ -3,4 +3,3 @@ _FIRMWARE
_INSTALATION
_README_IMG
README.md
.todo

6
.gitignore vendored
View File

@ -1,13 +1,7 @@
.ftpconfig
.ftpconfig2
config.php
_nemazat/index.html
_nemazat/css/main.css.map
_nemazat/css/main.css
_nemazat/css/font-awesome.min.css
app/logs/*.log
.vscode/
.vscode/sftp.json
app/updater/*.bin
logs/*

View File

@ -12,7 +12,6 @@ RewriteRule (.*) index.php?url=$1 [QSA,L]
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_FILENAME} !api.php
RewriteCond %{REQUEST_FILENAME} !apiFront.php
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
AddType application/x-httpd-php .php .phtml

13
.todo
View File

@ -1,13 +0,0 @@
//TODO: Automation last Run Time
//TODO: Check if every automation type Works
//TODO: Add Switch to Setting For debug mode
//TODO: hide menu item Debug When Debug mode is disabled
//TODO: Check if every setting works
//TODO: Add slector to automation execute all To execute only utomation whitch contain same day (as actual to speed up process)
//TODO: Check and fix time based automation
//TODO: 404 same like in ENergo COunter Project
//TODO: @FILIP Fix Editation of all Automations
//TODO: @FILIP test if registration work without an isuu even with notification
//TODO: Fix Default Room selection
//TODO: Fix User Delete button
//TODO: Fix new add email form

View File

@ -1,4 +0,0 @@
Login
https://dev.steelants.cz/vasek/home/apiFront.php
```json
{"username":"username","password":"password"}```

View File

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2019 JonatanRek<gamerclassn7@gamil.com> :)
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

Binary file not shown.

Binary file not shown.

Binary file not shown.

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"

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

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;
}

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);
}

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);
}

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://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
void setup() {
Serial.begin(9600);
delay(10);
Serial.println('\n');
Serial.println("HW: " + String(hwId));
pinMode(SONOFF, OUTPUT);
pinMode(SONOFF_LED, OUTPUT);
pinMode(SONOFF_BUT, INPUT);
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pasw);
Serial.print("Connecting to ");
Serial.print(ssid); Serial.println(" ...");
int i = 0;
while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++i); Serial.print(' ');
}
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());
}
void loop() {
StaticJsonDocument<200> jsonContent;
jsonContent["token"] = hwId;
if (!digitalRead(SONOFF_BUT)){
jsonContent["values"]["on/off"]["value"] = (int) !lastState;
if (!lastState == 1) {
digitalWrite(SONOFF, HIGH)
} else if (!lastState == 0){
digitalWrite(SONOFF, LOW)
}
while(!digitalRead(SONOFF_BUT)) {
delay(100);
}
}
String requestJson = "";
serializeJson(jsonContent, requestJson);
Serial.println("JSON: " + requestJson);
HTTPClient http;
http.begin(server);
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
int httpCode = http.POST(requestJson);
String payload = http.getString(); //Get the response payload
http.end();
Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
Serial.println("HTTP BODY: " + String(payload) + ""); //Print request response payload
deserializeJson(jsonContent, payload);
String hostname = jsonContent["device"]["hostname"];
int state = jsonContent["value"];
WiFi.hostname(hostname);
if (state != lastState){
if (state == 1 && lastState == 0) {
Serial.println("ON");
digitalWrite(SONOFF, HIGH); // 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
}
}
lastState = state;
}

Binary file not shown.

188
api.php
View File

@ -19,21 +19,18 @@ $files = array_diff($files, array(
'Ajax.php',
));
foreach($files as $file) {
include './app/class/'. $file;
}
//Allow acces only wia Curl, Ajax ETC
/*$restAcess = 'XMLHttpRequest' == ( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );
$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);
@ -42,25 +39,17 @@ Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
$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);
}
UserManager::atHome($userId, $atHome);
$logManager->write("[Record] user " . $userId . "changet his home state to " . $atHome . RECORDTIMOUT , LogRecordType::WARNING);
echo 'Saved: ' . $atHome;
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
header("HTTP/1.1 200 OK");
die();
}
}
@ -71,8 +60,8 @@ if (DEBUGMOD != 1) {
echo json_encode(array(
'state' => 'unsuccess',
'errorMSG' => "Using API from your IP insnt alowed!",
), JSON_PRETTY_PRINT);
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
));
header("HTTP/1.1 401 Unauthorized");
$logManager->write("[API] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING);
exit();
}
@ -81,9 +70,6 @@ if (DEBUGMOD != 1) {
//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);
}
@ -93,50 +79,33 @@ 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");
));
header("HTTP/1.1 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',
'body' => 'New device Detected',
'icon' => '',
];
//Subdevice Registration
$deviceId = DeviceManager::create($token, $token);
foreach ($values as $key => $value) {
if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) {
@ -145,85 +114,32 @@ if (!DeviceManager::registeret($token)) {
}
//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);
}
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ");
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
header("HTTP/1.1 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");
header("HTTP/1.1 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 != "") {
if ($values != null || $values != "") {
//ZAPIS
$device = DeviceManager::getDeviceByToken($token);
@ -232,7 +148,7 @@ if ($values != null && $values != "") {
if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) {
SubDeviceManager::create($deviceId, $key, UNITS[$key]);
}
RecordManager::create($deviceId, $key, round($value['value'],3));
RecordManager::create($deviceId, $key, round($value['value'],2));
$logManager->write("[API] Device_ID " . $deviceId . " writed value " . $key . ' ' . $value['value'], LogRecordType::INFO);
//notification
@ -242,26 +158,25 @@ if ($values != null && $values != "") {
switch ($key) {
case 'door':
$notificationData = [
'title' => 'Info',
'body' => 'Someone just open up '.$device['name'],
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
$notificationData = [
'title' => 'Info',
'body' => 'Someone just open up '.$device['name'],
'icon' => '',
];
break;
case 'water':
$notificationData = [
'title' => 'Alert',
'body' => 'Wather leak detected by '.$device['name'],
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
$notificationData = [
'title' => 'Alert',
'body' => 'Wather leak detected by '.$device['name'],
'icon' => '',
];
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);
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ");
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
}
@ -270,26 +185,22 @@ if ($values != null && $values != "") {
$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'];
$jsonAnswer['sleepTime'] = $device['sleep_time'];
}
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
echo json_encode($jsonAnswer);
header("HTTP/1.1 200 OK");
} 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'];
@ -303,24 +214,21 @@ if ($values != null && $values != "") {
$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);
$logManager->write("[API] subDevice id ".$subDeviceId . " executed comand with value " .$subDeviceLastReordValue . " record id " . $subDeviceLastReord['record_id'] . " executed " . $subDeviceLastReord['execuded']);
RecordManager::setExecuted($subDeviceLastReord['record_id']);
}
echo json_encode(array(
'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");
}
'sleepTime' => $device['sleep_time'],
],
'state' => 'succes',
'value' => $subDeviceLastReordValue
));
header("HTTP/1.1 200 OK");
}
unset($logManager);
Db::disconect();
die();
unset($logManager);
Db::disconect();
die();

View File

@ -1,98 +0,0 @@
<?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();*/

View File

@ -1,30 +0,0 @@
<?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;
}
}

View File

@ -18,10 +18,8 @@ class AutomationManager{
}
public function create ($name, $onDays, $doCode, $ifCode, $automationId = "") {
$userId = UserManager::getUserData('user_id');
$scene = array (
'name' => $name,
'owner_id' => $userId,
'on_days' => $onDays,
'if_something' => $ifCode,
'do_something' => $doCode,
@ -79,21 +77,9 @@ class AutomationManager{
}
} else if ($onValue['type'] == 'outHome') {
//TODO: Add Ovner to automation
$userHomeStatus = UserManager::getUserData('at_home', $onValue['value']);
if ($userHomeStatus == 'false' && $automation['executed'] == 0) {
$run = true;
} else if ($userHomeStatus == 'true' && $automation['executed'] == 1) {
$restart = true;
}
} else if ($onValue['type'] == 'inHome') {
//TODO: Add Ovner to automation
$userHomeStatus = UserManager::getUserData('at_home', $onValue['value']);
if ($userHomeStatus == 'true' && $automation['executed'] == 0) {
$run = true;
} else if ($userHomeStatus == 'false' && $automation['executed'] == 1) {
$restart = true;
}
} else if ($onValue['type'] == 'noOneHome') {
$users = UserManager::getUsers();
$membersHome = 0;
@ -120,18 +106,6 @@ class AutomationManager{
} else if ($membersHome > 0 && $automation['executed'] == 0){
$run = true;
}
} else if ($onValue['type'] == 'atDeviceValue') {
$subDeviceId = SubDeviceManager::getSubDeviceByMaster($onValue['value']['deviceID'], $onValue['value']['type'])["subdevice_id"];
$lastValue = RecordManager::getLastRecord($subDeviceId);
if ($lastValue['value'] == $onValue['value']['value'] && $automation['executed'] == 0) {
$run = true;
} else if ($lastValue['value'] != $onValue['value']['value'] && $automation['executed'] == 1){
$restart = true;
}
}
//finalization
@ -146,23 +120,18 @@ class AutomationManager{
$subscribers = NotificationManager::getSubscription();
$i = 0;
$notificationMng = new NotificationManager;
$notificationData = [
'title' => 'Automatization',
'body' => 'Automatization '.$automation['name']." was just executed",
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
if ($notificationData != []) {
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
$logManager->write("[NOTIFICATION/AUTOOMATION] SENDING TO" . $subscriber['id'] . " ");
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
foreach ($subscribers as $key => $subscriber) {
$logManager->write("[NOTIFICATION] SENDING NOTIFICATION TO" . $subscriber['id'] . " was executed" . $i);
$title = 'Automatization '.$automation['name']." was just executed";
$notification = new Notification(SERVERKEY);
$notification->to($subscriber['token']);
$notification->notification($title, '' , '', '');
$notification->send();
$notification = null;
}
$logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was executed");
Db::edit('automation', array('executed' => 1, 'execution_time' => date("Y-m-d H:i:s")), 'WHERE automation_id = ?', array($automation['automation_id']));
Db::edit('automation', array('executed' => 1), 'WHERE automation_id = ?', array($automation['automation_id']));
} else if ($restart) {
$logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was restarted");
Db::edit('automation', array('executed' => 0), 'WHERE automation_id = ?', array($automation['automation_id']));

View File

@ -18,20 +18,14 @@ class DeviceManager{
return Db::loadOne("SELECT * FROM devices WHERE token = ?", array($deviceToken));
}
function getDeviceByMac($deviceMac) {
return Db::loadOne("SELECT * FROM devices WHERE mac = ?", array($deviceMac));
}
function getDeviceById($deviceId) {
return Db::loadOne("SELECT * FROM devices WHERE device_id = ?", array($deviceId));
}
public function create ($name, $token) {
$defaultRoom = RoomManager::getDefaultRoomId();
$device = array (
'name' => $name,
'token' => $token,
'room_id' => $defaultRoom,
);
try {
Db::add ('devices', $device);
@ -51,15 +45,6 @@ class DeviceManager{
}
}
public function editByToken ($token, $values = []) {
try {
Db::edit ('devices', $values, 'WHERE token = ?', array($token));
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
/**
* [assignRoom Přiřazení zařízení do třídy]
* @param [type] $roomId [číslo místnosti do kter se zařízení přiřadit]

View File

@ -1,44 +0,0 @@
<?php
/**
*
*/
class FallbackManager
{
public $deviceDefinitions = "";
function __construct($deviceDefinition)
{
$this->deviceDefinitions = $deviceDefinition;
}
function check(){
//TODO: FIX IT
$allDevicesData = DeviceManager::getAllDevices();
foreach ($allDevicesData as $deviceKey => $deviceValue) {
$allSubDevicesData = SubDeviceManager::getAllSubDevices($deviceValue['device_id']);
foreach ($allSubDevicesData as $subDeviceKey => $subDeviceValue) {
if (!isset($this->deviceDefinitions[$subDeviceValue['type']]["fallBack"])) {
continue;
}
if (!isset($this->deviceDefinitions[$subDeviceValue['type']]["fallBackTime"])) {
continue;
}
$lastRecord = RecordManager::getLastRecord($subDeviceValue['subdevice_id']);
if ($lastRecord["value"] == $this->deviceDefinitions[$subDeviceValue['type']]["fallBack"]) {
continue;
}
$minutes = (time() - strtotime($lastRecord['time'])) / 60;
if ( $minutes > $this->deviceDefinitions[$subDeviceValue['type']]["fallBackTime"]){
RecordManager::create($deviceValue['device_id'], $subDeviceValue['type'], $this->deviceDefinitions[$subDeviceValue['type']]["fallBack"]);
}
}
}
}
}

View File

@ -9,25 +9,6 @@ class LogRecordType{
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
{
@ -46,9 +27,7 @@ class LogManager
function write($value, $type = LogRecordType::ERROR){
$record = "[".date("H:m:s")."][".$type."]" . $value . "\n";
if (strlen($record) > 65 ) {
$record = Utilities::stringInsert($record,"\n",65);
}
$record = Utilities::stringInsert($record,"\n",65);
fwrite($this->logFile, $record);
}

View File

@ -1,18 +0,0 @@
<?php
/**
*
*/
class NetvorkManager
{
function __construct()
{
// code...
}
function validateIp($ip = '0.0.0.0'){
if (!filter_var($ip, FILTER_VALIDATE_IP)){
return false;
}
}
}

View File

@ -2,7 +2,6 @@
/**
* Notification Manager
*/
//TODO: Working timestamp to body or $title
class NotificationManager
{
function addSubscriber($userID = '', $token = ''){
@ -16,11 +15,11 @@ class NotificationManager
}
}
function getSubscription () {
return Db::loadAll ("SELECT * FROM notifications");
function getSubscription(){
return Db::loadAll('SELECT * FROM notifications;', array());
}
function sendSimpleNotification(string $serverKey, string $to, array $data, bool $timeStamp = false){
function sendSimpleNotification(string $serverKey, string $to, array $data){
$dataTemplate = [
'title' => '',
'body' => '',
@ -31,10 +30,6 @@ class NotificationManager
return;
}
if ($timeStamp) {
$data['title'] = $data['title'] . date();
}
$notification = new Notification($serverKey);
$notification->to($to);
$notification->notification($data['title'], $data['body'], $data['icon'], '');
@ -69,14 +64,10 @@ class Notification
$this->jsonPayload["to"] = $to;
}
function notification($title = '', $body = '', $icon = '', $action = '', bool $timeStamp = false)
function notification($title = '', $body = '', $icon = '', $action = '')
{
if ($timeStamp) {
$data['title'] = $data['title'] . date();
}
$this->jsonPayload["data"]["notification"]["title"] = $title;
$this->jsonPayload["data"]["notification"]["body"] = date("h:i") . " - " . $body;
$this->jsonPayload["data"]["notification"]["body"] = $body;
$this->jsonPayload["data"]["notification"]["icon"] = $icon;
$this->jsonPayload["data"]["notification"]["click_action"] = $action;
}

View File

@ -67,7 +67,7 @@ class RecordManager{
public static function clean ($day) {
if (isset($day)) {
Db::command ('DELETE FROM records WHERE `time` < ADDDATE(NOW(), INTERVAL -? DAY);', array($day));
Db::command ('DELETE FROM records WHERE time < ADDDATE(NOW(), INTERVAL -? DAY);', array($day));
}
}

View File

@ -2,11 +2,6 @@
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;

View File

@ -27,7 +27,7 @@ class Template extends Partial{
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/controls/' . $this->path . '.php');
}
require_once('app/templates/' . $this->path . '.phtml');
}

View File

@ -21,24 +21,6 @@ class UserManager
}
}
public function getUserId ($userId) {
try {
$user = Db::loadOne ("SELECT * FROM users WHERE user_id = ?", [$userId]);
return $user;
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public function getAvatarUrl($userId = null){
$email = self::getUserData('email');
if ($userId != null){
$email = self::getUserData('email',$userId);
}
return 'https://secure.gravatar.com/avatar/' . md5( strtolower( trim( $email ) ) );
}
public function login ($username, $password, $rememberMe) {
try {
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($username))) {
@ -65,24 +47,6 @@ class UserManager
}
}
public function loginNew ($username, $password) {
try {
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($username))) {
if ($user['password'] == UserManager::getHashPassword($password)) {
echo "user loged in";
return $user['user_id'];
} else {
return false;
}
} else {
return false;
}
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public function isLogin () {
if (isset ($_SESSION['user']) && isset($_SESSION['user']['id'])) {
return true;
@ -138,8 +102,10 @@ class UserManager
}
public static function getUserData ($type, $userId = '') {
if ($userId == '') {
if (isset($_SESSION['user']['id'])) {
$userId = $_SESSION['user']['id'];
} else {
return "";
}
$user = Db::loadOne ('SELECT ' . $type . ' FROM users WHERE user_id=?', array ($userId));
return $user[$type];

View File

@ -56,9 +56,7 @@ class Utilities
'data' => [
'datasets' => [
[
'data' => $data,
'borderColor' => "#d4def7",
'backgroundColor' => "#d4def7"
'data' => $data
]
]
],
@ -121,7 +119,7 @@ class Utilities
case '>=': // Greater than or equal to
return $value1 >= $value2;
case '==': // Equal
return ($value1 == $value2);
return $value1 == $value2;
case '===': // Identical
return $value1 === $value2;
case '!==': // Not Identical

View File

@ -2,33 +2,22 @@
if (isset($_POST) && !empty($_POST)){
if (isset($_POST['modalFinal']) && $_POST['action'] == "add") {
$doCode = json_encode($_POST['device'], JSON_PRETTY_PRINT);
$value = $_POST['atSelector'];
if ($_POST['atSelector'] == 'time'){
$value = $_POST['atSelectorValue'];
} else if ($_POST['atSelector'] == 'atDeviceValue') {
$value = json_decode($_POST['atSelectorValue']);
} else if ($_POST['atSelector'] == 'inHome' || $_POST['atSelector'] == 'outHome') {
$value = UserManager::getUserData('user_id');
}
$ifCode = json_encode([
"type" => $_POST['atSelector'],
"value" => $value,
"value" => $_POST['atSelectorValue'],
], JSON_PRETTY_PRINT);
$onDays = $_POST['atDays'];
//Debug
// if (DEBUGMOD == 1) {
// echo '<pre>';
// echo $permissionsInJson;
// echo $deviceId;
// var_dump(json_decode ($permissionsInJson));
// echo '</pre>';
// echo '<a href="' . BASEDIR .'">CONTINUE</a>';
// die();
// }
if (DEBUGMOD == 1) {
echo '<pre>';
echo $permissionsInJson;
echo $deviceId;
var_dump(json_decode ($permissionsInJson));
echo '</pre>';
echo '<a href="' . BASEDIR .'">CONTINUE</a>';
die();
}
AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode);
@ -43,28 +32,18 @@ if (isset($_POST) && !empty($_POST)){
$subDevice = SubDeviceManager::getSubDevice($subDeviceId);
$subDeviceMaster = SubDeviceManager::getSubDeviceMaster($subDeviceId,$subDevice['type']);
$device = [
$json = json_encode([
'deviceID' => $subDeviceMaster['device_id'],
'type'=> $subDevice['type'],
'value'=> $subDeviceValue,
];
]);
}
$value = $_POST['atSelector'];
if (isset($_POST['atTime'])){
$value = $_POST['atTime'];
} else if (isset($_POST['atDeviceValue'])) {
$value = $device;
} else if ($_POST['atSelector'] == 'inHome' || $_POST['atSelector'] == 'outHome') {
//TODO: opravit edit aby vkládal id původního uživatele
$value = UserManager::getUserData('user_id');
}
$value = (isset($_POST['atTime']) ? $_POST['atTime'] : (isset($_POST['atDeviceValue']) ? $device : $_POST['atSelector']));
$_POST['atSelectorValue'] = (isset($_POST['atTime']) ? $_POST['atTime'] : (isset($_POST['atDeviceValue']) ? $json : $_POST['atSelector']));
$ifCode = json_encode([
"type" => $_POST['atSelector'],
"value" => $value,
"value" => $_POST['atSelectorValue'],
], JSON_PRETTY_PRINT);
$onDays = ($_POST['day'] != '' ? json_encode($_POST['day']) : '');

View File

@ -5,20 +5,6 @@ if (isset($_POST) && !empty($_POST)){
$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'];
}

View File

@ -13,11 +13,6 @@ if (isset($_POST) && !empty($_POST)){
UserManager::createUser($userName, $password);
header('Location: ' . BASEDIR . 'setting');
die();
} else if (isset($_POST['submitCreateRoom']) && $_POST['submitCreateRoom'] != "") {
$roomName = $_POST['roomName'];
RoomManager::create($roomName);
header('Location: ' . BASEDIR . 'setting');
die();
} else if (isset($_POST['submitEnableOta']) && $_POST['submitEnableOta'] != "") {
echo $otaCode = $_POST['otaCode'];
echo $otaSecret = $_POST['otaSecret'];

View File

@ -28,7 +28,6 @@ return $lang = [
'b_restart' => 'Restart',
'b_disable' => 'Deaktivovat',
'b_select' => 'Zvolit',
'b_ota' => 'ota',
//labels
'l_choseDevice' => 'Zvolte zařízení:',
@ -58,10 +57,6 @@ return $lang = [
'l_password' => 'Heslo',
'l_oldPassword' => 'Staré Heslo',
'l_newPassword' => 'Nové Heslo',
'l_uploadFirmware' => 'Nahrát Firmware',
'l_userAvatar' => 'Avatar',
'l_userEmail' => 'Email',
'l_roomName' => 'Jméno Místnosti',
//Title
't_createScene' => 'Vytvořit scénu',
@ -75,14 +70,6 @@ return $lang = [
't_experimental' => 'Experimental',
't_createuser' => 'Vytvořit Uživatele',
't_changePassword' => 'Změnit Heslo',
't_networkSetting' => 'Nastavení Sítě',
't_deviceVersion' => 'Nastavení Verze',
't_ota' => 'OTA',
't_listUsers' => 'Seznam Uživatelů',
't_avatar' => 'Avatar',
't_listRooms' => 'Seznam Místností',
't_roomName' => 'Jméno Místnosti',
't_createRoom' => 'Vytvořit Místnost',
//constants
'temp' => 'Teplota',

View File

@ -28,7 +28,6 @@ return $lang = [
'b_restart' => 'Restart',
'b_disable' => 'disabele',
'b_select' => 'Select',
'b_ota' => 'ota',
//labels
'l_choseDevice' => 'Chose device:',
@ -58,10 +57,6 @@ return $lang = [
'l_password' => 'Password',
'l_oldPassword' => 'Old Password',
'l_newPassword' => 'New Password',
'l_uploadFirmware' => 'Upload Firmware',
'l_userAvatar' => 'Avatar',
'l_userEmail' => 'Email',
'l_roomName' => 'Room Name',
//Title
't_createScene' => 'Create Scene',
@ -75,14 +70,6 @@ return $lang = [
't_experimental' => 'Experimental',
't_createuser' => 'Create User',
't_changePassword' => 'Change Password',
't_networkSetting' => 'Network Setting',
't_deviceVersion' => 'Version Setting',
't_ota' => 'OTA',
't_listUsers' => 'User List',
't_avatar' => 'Avatar',
't_listRooms' => 'Room List',
't_roomName' => 'Room Name',
't_createRoom' => 'Create Rom',
//constants
'humi' => 'Humidity',

View File

@ -16,7 +16,6 @@
$partial = new Partial('menu');
$partial->prepare('item','automation');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->render();
?>
</div>
@ -34,7 +33,6 @@
//EDIT
$partial = new Partial('automationEdit');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('userManager',$USERMANAGER);
$partial->prepare('automationId',$automationId);
$partial->prepare('automation',$automationData);
$partial->prepare('subDevices',$SUBDEVICES);
@ -47,13 +45,11 @@
if (isset($_POST['modalNext'])) {
$partial = new Partial('automationCreateFinal');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('userManager',$USERMANAGER);
$partial->prepare('subDevices',$SUBDEVICES);
$partial->render();
} else {
$partial = new Partial('automationCreate');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('subDevices',$SUBDEVICES);
$partial->render();
}?>

View File

@ -14,8 +14,3 @@ table.table th {
background-color: #121a2b;
color: white;
}
button:disabled,
button[disabled] {
opacity: .4;
}

View File

@ -16,7 +16,6 @@
$partial = new Partial('menu');
$partial->prepare('item', 'dashboard');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->render();
?>
</div>

View File

@ -16,7 +16,6 @@
$partial = new Partial('menu');
$partial->prepare('item', 'home');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->render();
?>
</div>
@ -85,23 +84,5 @@
$partial = new Partial('footer');
$partial->render();
?>
<script>
$(document).on('keyup mouseup', '#value_control', function(event) {
$.ajax({
url: 'ajax',
type: 'POST',
//TODO: GET Attribute from ID
data: { subDevice_id : '13', action : 'set', value: this.value},
success: function(msg){
console.log("message");
console.log(msg);
},
error: function (request, status, error) {
console.log('0');
}
});
console.log(this.value);
});
</script>
</body>
</html>

View File

@ -5,7 +5,6 @@ function ajaxPostSimple(path, params, reload = false) {
type: 'POST',
data: params,
success: function(msg){
console.log("message");
console.log(msg);
if (reload){
location.reload();

View File

@ -17,24 +17,23 @@ if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('serviceWorker.js')
.then(registration => {
console.log('Service Worker is registered', registration);
messaging.useServiceWorker(registration);
messaging.usePublicVapidKey('BDYQ7X7J7PX0aOFNqB-CivQeqLq4-SqCxQJlDfJ6yNnQeYRoK8H2KOqxHRh47fLrbUhC8O3tve67MqJAIqox7Ng');
messaging.requestPermission().then(function () {
console.log("Notification permission granted.");
return messaging.getToken()
})
.then(function (token) {
.then(function(token) {
console.log("token is : " + token);
$.ajax({
url: 'ajax',
type: 'POST',
data: {
"notification": 'X',
"notification" : 'X',
"action": 'subscribe',
"token": token
},
success: function (data) {
success: function(data){
console.log('saved', data);
},
error: function (request, status, error) {
@ -45,6 +44,15 @@ if ('serviceWorker' in navigator) {
.catch(function (err) {
console.log("Unable to get permission to notify.", err);
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
var notification = new Notification('hello', {
body: "Hey there!",
});
notification.onclick = function () {
window.open("http://google.com");
};
});
})
.catch(err => {
console.error('Registration failed:', err);
@ -53,27 +61,27 @@ if ('serviceWorker' in navigator) {
}
$('select[name="atSelector"]').change(function (e) {
$('select[name="atSelector"]').change(function(e) {
console.log($(this).val());
if ($(this).val() == 'time') {
if( $(this).val() == 'time') {
$('input[name="atTime"]').prop("disabled", false);
$('input[name="atTime"]').prop( "disabled", false );
$('select[name="atDeviceValueInt"]').prop("disabled", true);
$('input[name="atDeviceValue"]').prop("disabled", true);
} else if ($(this).val() == 'atDeviceValue') {
$('select[name="atDeviceValueInt"]').prop( "disabled", true );
$('input[name="atDeviceValue"]').prop( "disabled", true );
} else if( $(this).val() == 'atDeviceValue') {
$('select[name="atDeviceValue"]').prop("disabled", false);
$('input[name="atDeviceValueInt"]').prop("disabled", false);
$('select[name="atDeviceValue"]').prop( "disabled", false );
$('input[name="atDeviceValueInt"]').prop( "disabled", false );
$('input[name="atTime"]').prop("disabled", true);
$('input[name="atTime"]').prop( "disabled", true );
}
});
var pressTimer;
var touch = 0;
var touchSubId = "";
$("div.square-content").on('touchend', function (e) {
$("div.square-content").on('touchend', function (e){
clearTimeout(pressTimer);
});
@ -95,10 +103,10 @@ $("div.square-content").on('touchstart', function (eTarget) {
var subId = $(this).attr('data-sub-device-id');
touch++;
if (touch == 2 && touchSubId == subId) {
if(touch == 2 && touchSubId == subId){
console.log("Detail");
if (windowLoc == "/") {
$("#modal-detail-" + subId).removeClass('modal-container-hiden').show();
$("#modal-detail-"+subId).removeClass('modal-container-hiden').show();
ajaxChart(subId);
} else if (windowLoc == "/scene") {
@ -112,12 +120,12 @@ $("div.square-content").on('touchstart', function (eTarget) {
pressTimer = window.setTimeout(function (e) {
console.log("Setting");
$("#modal-setting-" + id).removeClass('modal-container-hiden').show();
$("#modal-setting-"+id).removeClass('modal-container-hiden').show();
touch = 0;
}, 500);
});
$("div.square-content").mousedown(function (e) {
$("div.square-content").mousedown(function(e) {
if (event.which == 3) {
var windowLoc = $(location).attr('pathname');
windowLoc = windowLoc.substring(windowLoc.lastIndexOf("/"));
@ -130,7 +138,7 @@ $("div.square-content").mousedown(function (e) {
} else if (windowLoc == "/automation") {
id = $(this).attr('id').replace('automation-', '');
}
$("#modal-setting-" + id).removeClass('modal-container-hiden').show();
$("#modal-setting-"+id).removeClass('modal-container-hiden').show();
console.log("Setting");
console.log("modal" + id);
}
@ -141,7 +149,7 @@ $(".close").on('click', function (e) {
a.hide();
});
$(this).bind("contextmenu", function (e) {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
});
@ -151,11 +159,11 @@ $("div.square-content").on('dblclick', function (eTarget) {
console.log("Detail");
var subId = $(this).attr('data-sub-device-id');
ajaxChart(subId);
$("#modal-detail-" + subId).removeClass('modal-container-hiden').show();
$("#modal-detail-"+subId).removeClass('modal-container-hiden').show();
}
});
$("input#sleepTime").change(function () {
$("input#sleepTime").change(function() {
console.log("Input text changed!");
});
@ -167,7 +175,7 @@ $("a#remove").on('click', function (e) {
element.toggle();
});
function ajaxChart(id, period = 'day', group = 'hour') {
function ajaxChart(id, period = 'day', group = 'hour'){
$.ajax({
url: 'ajax',
type: 'POST',
@ -178,9 +186,9 @@ function ajaxChart(id, period = 'day', group = 'hour') {
"period": period,
"group": group
},
success: function (data) {
console.log('ID: ', id, 'DATA: ', data);
var ctx = document.getElementById('canvas-' + id).getContext('2d');
success: function(data){
console.log('ID: ',id, 'DATA: ', data);
var ctx = document.getElementById('canvas-'+id).getContext('2d');
var myChart = new Chart(ctx, data);
},
error: function (request, status, error) {
@ -202,11 +210,11 @@ if (windowLoc == "/") {
}
console.log('Saved Selected Room ID ' + selectRoomId);
console.log('Saved Selected Room ID '+ selectRoomId);
$('[name="room"]').val(selectRoomId);
$('.device-button').each(function () {
if (selectRoomId != 'all') {
if ($(this).data('room-id') != selectRoomId) {
$('.device-button').each(function(){
if (selectRoomId != 'all'){
if($(this).data('room-id') != selectRoomId){
$(this).hide();
} else {
$(this).show();
@ -218,62 +226,58 @@ if (windowLoc == "/") {
}
//Room selector
$('[name="room"]').change(function (e) {
$( '[name="room"]' ).change(function (e) {
console.log('Selected Room ID ' + this.value)
var roomId = this.value;
localStorage.setItem("selectedRoomId", roomId);
$('.device-button').show();
if (roomId != 'all') {
$('.device-button').each(function () {
if ($(this).data('room-id') != roomId) {
if (roomId != 'all'){
$('.device-button').each(function(){
if($(this).data('room-id') != roomId){
$(this).hide();
}
});
}
});
/*
var windowLoc = $(location).attr('pathname');
windowLoc = windowLoc.substring(windowLoc.lastIndexOf("/"));
console.log();
if (windowLoc == "/") {
var autoUpdate = setInterval(function(){
if (pending == false) {
pending = true;
$.ajax({
url: 'ajax',
type: 'POST',
dataType: 'json',
data: {
"action": 'getState'
},
success: function(data){
console.log(data);
for (const key in data) {
if (data.hasOwnProperty(key)) {
const device = data[key];
$('[data-sub-device-id="'+key+'"]')
.find('.device-button-value')
.text(device['value'])
.attr('title',device['time'])
}
}
},
error: function (request, status, error) {
console.log("ERROR ajaxChart():", request, error);
},
complete: function (){
pending = false;
}
});
}
},4000);
var autoUpdate = setInterval(function(){
if (pending == false) {
pending = true;
$.ajax({
url: 'ajax',
type: 'POST',
dataType: 'json',
data: {
"action": 'getState'
},
success: function(data){
console.log(data);
for (const key in data) {
if (data.hasOwnProperty(key)) {
const device = data[key];
$('[data-sub-device-id="'+key+'"]')
.find('.device-button-value')
.text(device['value'])
.attr('title',device['time'])
}
}
},
error: function (request, status, error) {
console.log("ERROR ajaxChart():", request, error);
},
complete: function (){
pending = false;
}
});
}
},4000);
}*/
//Graphs
$('.graph-period').on('click', function (e) {
var subId = $(this).attr('data-sub-device-id');
@ -283,7 +287,7 @@ $('.graph-period').on('click', function (e) {
ajaxChart(subId, period, groupBy);
});
$("button[name=remove]").click(function (e) {
$( "button[name=remove]" ).click(function(e) {
if (confirm('Are you shure ?')) {
var windowLoc = $(location).attr('pathname');
windowLoc = windowLoc.substring(windowLoc.lastIndexOf("/"));
@ -291,7 +295,7 @@ $("button[name=remove]").click(function (e) {
var id = null;
if (windowLoc == "/scene") {
id = $(this).data('scene-id');
$("#scene-" + id + "-content").remove();
$("#scene-"+id+"-content").remove();
} else if (windowLoc == "/automation") {
$(this).parent().remove();
}

View File

@ -16,13 +16,11 @@
$partial = new Partial('menu');
$partial->prepare('item', 'log');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->render();
?>
</div>
<div class="col-md-9 main-body">
<div class="col-12 col-sm-9 mx-auto mt-4">
<label><?php echo $LANGMNG->get('l_logMaxLiveTime') . " " . $LOGTOLIVETIME . " days";?></label>
<form method="post" action="">
<div class="field">
<select class="input" name="LogFile">

View File

@ -50,12 +50,6 @@
<div class="col">
<?php echo implode(', ',$AUTOMATIONDATA['onDays']);?>
</div>
<div class="col">
<?php echo $AUTOMATIONDATA['owner_name'];?>
</div>
<div class="col">
<?php echo $AUTOMATIONDATA['execution_time'];?>
</div>
</div>
<div class="row">
<div class="col">

View File

@ -2,7 +2,7 @@
<div class="modal">
<a href=""><i class="fa fa-times close"></i></a>
<h4 class="mb-4"><?php $LANGMNG->echo('t_createAutomation')?></h4>
<form method="post" action="" >
<form method="post">
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_nameAt')?></div>
<div class="field">

View File

@ -21,12 +21,9 @@
'value'=> $subDeviceValue,
]);
echo htmlspecialchars($json);
} else {
if ($_POST['atSelector'] == "inHome" || $_POST['atSelector'] == "outHome") {
echo $USERMANAGER->getUserData('user_id');
} else {
echo $_POST['atSelector'];
}
}
else {
echo $_POST['atSelector'];
} ?>" required/>
<input type="hidden" name="atDays" value="<?php echo htmlspecialchars(($_POST['day'] != '' ? json_encode($_POST['day']) : '')); ?>" required/>
<?php foreach ($_POST['devices'] as $value) { ?>

View File

@ -15,17 +15,7 @@ if ($SUBDEVICE['type'] == 'on/off') {
<h5 unselectable="on" class="fa">&#x<?php echo $DEVICE['icon'] ?></h5>
</div>
<div class="col">
<?php if ($SUBDEVICE['type'] == 'temp_cont') { ?>
<input type="number" step="5" class="device-button-value text-right" id="value_control" value="<?php echo $SUBDEVICE['lastRecort']['value'] ?>"><?php echo $SUBDEVICE['unit']?>
<style>
input.device-button-value.text-right {
width: inherit;
}
</style>
<?php } else { ?>
<h5 unselectable="on" class="device-button-value text-right" title="<?php echo $SUBDEVICE['lastRecort']['time']; ?>"><?php echo $SUBDEVICE['lastRecort']['value'] . $SUBDEVICE['unit']?></h5>
<?php } ?>
</div>
</div>
<div class="row">

View File

@ -62,6 +62,9 @@
<thead>
<tr>
<th><?php $LANGMNG->echo('t_time');?></th>
<?php if (DEBUGMOD) { ?>
<th><?php $LANGMNG->echo('t_raw');?></th>
<?php } ?>
<th><?php $LANGMNG->echo('t_state');?></th>
</tr>
</thead>
@ -69,12 +72,10 @@
<?php foreach ($SUBDEVICE['events'] as $key => $value) { ?>
<tr>
<td><?php echo (new DateTime($value['time']))->format(DATEFORMAT); ?></td>
<td title="test"><?php
echo $value['value'] . $SUBDEVICE['unit'];
if (DEBUGMOD) {
echo ' (' . $SUBDEVICE['eventsRaw'][$key]['value'] . ')';
}
?></td>
<?php if (DEBUGMOD) { ?>
<td><?php echo $SUBDEVICE['eventsRaw'][$key]['value']; ?></td>
<?php } ?>
<td title="test"><?php echo $value['value'] . $SUBDEVICE['unit'];?></td>
<?php //TODO: P5IDAT TOOLTIP PRO RAW VALUE?>
</tr>
<?php } ?>

View File

@ -4,7 +4,7 @@
<i class="fa fa-times"></i>
</div>
<h4 class="mb-4"><?php $LANGMNG->echo('t_editDevice'); ?></h4>
<form method="post" action="" enctype="multipart/form-data">
<form method="post" action="">
<input class="input" type="hidden" name="deviceId" value="<?php echo $DEVICEID; ?>">
<?php if ($DEVICE['approved'] != 0) { ?>
<?php if ($DEVICE['userIsAdmin']) { ?>
@ -62,34 +62,6 @@
<div class="label">Token:</div>
<input class="input" type="text" name="deviceToken" value="<?php echo $DEVICE['token']; ?>" disabled>
</div>
<h4 class="mb-4"><?php $LANGMNG->echo('t_networkSetting'); ?></h4>
<div class="field">
<div class="label">Type:</div>
<input class="input" type="text" name="deviceToken" value="<?php echo $DEVICE['type']; ?>" disabled>
</div>
<div class="field">
<div class="label">Mac Address:</div>
<input class="input" type="text" name="deviceMac" value="<?php echo $DEVICE['mac']; ?>" disabled>
</div>
<div class="field">
<div class="label">IP:</div>
<input class="input" type="text" name="deviceIp" value="<?php echo $DEVICE['ip']; ?>" minlength="7" maxlength="15" size="15" pattern="^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$" disabled>
</div>
<div class="field">
<div class="label">Subnet:</div>
<input class="input" type="text" name="deviceSubnet" value="<?php echo $DEVICE['subnet']; ?>" minlength="7" maxlength="15" size="15" pattern="^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$" disabled>
</div>
<div class="field">
<div class="label">Gateway:</div>
<input class="input" type="text" name="deviceGateway" value="<?php echo $DEVICE['gateway']; ?>" minlength="7" maxlength="15" size="15" pattern="^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$" disabled>
</div>
<h4 class="mb-4"><?php $LANGMNG->echo('t_deviceVersion'); ?></h4>
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_uploadFirmware'); ?></div>
<input class="input" type="file" name="deviceFirmware" value="">
</div>
<?php if ($DEVICE['userIsAdmin']) { ?>
<?php if (!in_array($SUBDEVICE['type'], ['on/off', 'door', 'water'])) { ?>
<div class="field">
@ -129,19 +101,19 @@
<div class="label"><?php $LANGMNG->echo('w_moduls'); ?></div>
<div class="row no-gutters">
<?php foreach ($DEVICE['subDevices'] as $subDeviceKey => $subDevice) { ?>
<div class="device-button col-4 col-sm-3 col-xl-2 square-wrap">
<div class="col-4 col-sm-3 col-xl-2 square-wrap">
<div class="square">
<div class="square-content">
<div class="row no-gutters">
<div class="row">
<div class="col">
<h5 unselectable="on" class="fa">&#x<?php echo $DEVICE['icon'] ?></h5>
<h3 class="fa">&#x<?php echo $DEVICE['icon']; ?></h3>
</div>
<div class="col">
<h5 unselectable="on" class="device-button-value text-right" title="<?php echo $subDevice['lastRecort']['time']; ?>"><?php echo $subDevice['lastRecort']['value'] . $subDevice['unit']?></h5>
<h3><?php echo $subDevice['unit']; ?></h3>
</div>
</div>
<div class="row">
<div class="col button-text" unselectable="on" >
<div class="col">
<?php echo $DEVICE['name']; ?>
</div>
</div>
@ -158,13 +130,22 @@
<div class="label"><?php $LANGMNG->echo('w_moduls'); ?></div>
<div class="row no-gutters">
<?php foreach ($DEVICE['subDevices'] as $subDeviceKey => $subDevice) { ?>
<div class="device-button col-4 col-sm-3 col-xl-2 square-wrap">
<div class="col-4 col-sm-3 col-xl-2 square-wrap">
<div class="square">
<div class="square-content">
<?php echo $DEVICE['name']; ?>
<div class="row">
<div class="col">
<h3 class="fa">&#x<?php echo $DEVICE['icon']; ?></h3>
</div>
<div class="col">
<h3><?php echo $subDevice['unit']; ?></h3>
</div>
</div>
<div class="row">
<div class="col">
<?php echo $DEVICE['name']; ?>
</div>
</div>
</div>
</div>
</div>

View File

@ -32,11 +32,7 @@
'path' => 'log',
],
];
foreach ( $menuItems as $key => $value) {
if ($DEBUGMOD == 0 && $value['path'] == 'log') {
continue;
}
?>
foreach ( $menuItems as $key => $value) { ?>
<div class="nav-item <?php echo ($ITEM == $value ? 'is-active' : ''); ?>">
<a href="<?php echo $value['path']?>">
<i class="fa <?php echo $key ?>"></i>

View File

@ -1,6 +1,6 @@
<div class="col-12 col-md-6 col-xl-4 square-wrap noselect">
<div class="rectangle-2">
<div class="square-content double" id="scene-<?php echo $SCENEID ?>" onClick="ajaxPost('ajax',{scene_id:'<?php echo $SCENEID; ?>',action:'execute'}, this);" >
<div class="square-content double" id="scene-<?php echo $SCENEID ?>" onClick="ajaxPost('ajax',{scene_id:'<?php echo $SCENEID; ?>'}, this);" >
<div class="row">
<div class="col-1">
<h5 class="fa noselect">

View File

@ -15,8 +15,7 @@
<?php
$partial = new Partial('menu');
$partial->prepare('item', 'rooms');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->prepare('lang',$LANG);
$partial->render();
?>
</div>
@ -30,7 +29,7 @@
<div class="">
<h1><?php echo $room['name']; ?></h1>
<?php foreach ($room['reading'] as $key => $value) { ?>
<?php echo $LANGMNG->get($key) .": ". $value; ?></br>
<?php echo $LANG[$key] .": ". $value; ?></br>
<?php } ?>
<?php if (DEBUGMOD == 1) { ?>
<pre>

View File

@ -16,7 +16,6 @@
$partial = new Partial('menu');
$partial->prepare('item', 'scene');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->render();
?>
</div>

View File

@ -16,14 +16,12 @@
$partial = new Partial('menu');
$partial->prepare('item', 'setting');
$partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->render();
?>
</div>
<div class="col-md-9 main-body">
<div class="col-12 col-sm-9 mx-auto mt-4">
<h4 class="mb-4">
<?php $LANGMNG->echo('t_pageAfterLogIn') ?>
</h4>
<form method="post" enctype="multipart/form-data">
@ -40,19 +38,6 @@
</form>
<div class="col-12 col-sm-9 mx-auto mt-4">
<h4 class="mb-4"><?php $LANGMNG->echo('t_profile') ?></h4>
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_userAvatar') ?>:</div>
<img src="<?php echo $USERAVATARURL; ?>" />
<div class="label">* providet by Gavatar</div>
</div>
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_userName') ?>:</div>
<input class="input" value="<?php echo $USERNAME; ?>" disabled>
</div>
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_userEmail') ?>:</div>
<input class="input" value="<?php echo $USEREMAIL; ?>" disabled>
</div>
<div class="field">
<a href="logout" class="button is-primary"><?php $LANGMNG->echo('b_logOut') ?></a>
</div>
@ -115,7 +100,6 @@
<table class="table is-fluid">
<thead>
<tr>
<th><?php $LANGMNG->echo('t_avatar');?></th>
<th><?php $LANGMNG->echo('t_userName');?></th>
<th><?php $LANGMNG->echo('t_ota');?></th>
<th><?php $LANGMNG->echo('t_action');?></th>
@ -124,7 +108,6 @@
<tbody>
<?php foreach ($USERS as $key => $user) { ?>
<tr>
<td><img src="<?php echo $user['gavatar_url']; ?>" /></td>
<td><?php echo $user['username']; ?></td>
<td><?php echo ($user['ota'] ? '<span class="fa">&#xf00c;</span>' : ''); ?></td>
<td><button name="deleteUser" type="button" class="button is-danger fa">&#xf1f8;</button></td>
@ -138,57 +121,17 @@
<form method="post">
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_userName') ?>:</div>
<input type="text" class="input" name="userName" value="">
<input type="text" class="input" name="userName" value="" data-cip-id="cIPJQ342845639">
</div>
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_password') ?>:</div>
<input type="password" class="input" name="userPassword" value="">
<input type="password" class="input" name="userPassword" value="" data-cip-id="cIPJQ342845639">
</div>
<div class="field">
<input type="submit" name="submitCreateUser" class="button" value="Uložit">
</div>
</form>
</div>
<!--Room Managment-->
<div class="col-12 col-sm-9 mx-auto mt-4">
<h4 class="mb-4"><?php $LANGMNG->echo('t_listRooms') ?></h4>
<table class="table is-fluid">
<thead>
<tr>
<th><?php $LANGMNG->echo('t_roomName');?></th>
<th><?php $LANGMNG->echo('t_action');?></th>
</tr>
</thead>
<tbody>
<?php foreach ($ROOMS as $key => $room) { ?>
<tr>
<td><?php echo $room['name']; ?></td>
<td>
<button name="deleteRoom" type="button" class="button is-danger fa">&#xf1f8;</button>
<button name="defaultRoom" type="button" class="button fa" <?php echo ($room['default'] ? 'disabled' : ''); ?>>&#xf140;</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<!--Room Creation-->
<div class="col-12 col-sm-9 mx-auto mt-4">
<h4 class="mb-4"><?php $LANGMNG->echo('t_createRoom') ?></h4>
<form method="post">
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_roomName') ?>:</div>
<input type="text" class="input" name="roomName" value="">
</div>
<div class="field">
<input type="submit" name="submitCreateRoom" class="button" value="<?php $LANGMNG->echo('b_create') ?>">
</div>
</form>
</div>
</div>

View File

View File

@ -26,27 +26,27 @@ class Ajax extends Template
$_POST['automation_id'] != '' &&
isset($_POST['action']) &&
$_POST['action'] != ''
) {
$automationId = $_POST['automation_id'];
//Automation Editation of Automations from Buttons/Details
switch ($_POST['action']) {
case 'delete':
AutomationManager::remove($automationId);
die();
break;
) {
$automationId = $_POST['automation_id'];
//Automation Editation of Automations from Buttons/Details
switch ($_POST['action']) {
case 'delete':
AutomationManager::remove($automationId);
die();
break;
case 'deactive':
AutomationManager::deactive($automationId);
die();
break;
case 'deactive':
AutomationManager::deactive($automationId);
die();
break;
case 'restart':
AutomationManager::restart($automationId);
die();
break;
case 'restart':
AutomationManager::restart($automationId);
die();
break;
default:
echo 'no action detected';
default:
echo 'no action detected';
break;
}
} else if (
@ -54,46 +54,38 @@ class Ajax extends Template
$_POST['subDevice_id'] != '' &&
isset($_POST['action']) &&
$_POST['action'] != ''
) {
$subDeviceId = $_POST['subDevice_id'];
switch ($_POST['action']) {
case 'chart':
$period = $_POST['period'];
$groupBy = $_POST['group'];
header('Content-Type: application/json');
$graphData = ChartManager::generateChartData($subDeviceId, $period, $groupBy);
echo Utilities::generateGraphJson($graphData['graphType'], $graphData['graphData'], $graphData['graphRange']);
die();
break;
) {
$subDeviceId = $_POST['subDevice_id'];
switch ($_POST['action']) {
case 'chart':
$period = $_POST['period'];
$groupBy = $_POST['group'];
header('Content-Type: application/json');
$graphData = ChartManager::generateChartData($subDeviceId, $period, $groupBy);
echo Utilities::generateGraphJson($graphData['graphType'], $graphData['graphData'], $graphData['graphRange']);
die();
break;
//Change On/Off Device State of Device Button
case 'change':
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
if ($subDeviceData['type'] == 'on/off'){
$lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'];
RecordManager::create($deviceId, 'on/off', !$lastValue);
echo (!$lastValue ? 'ON' : 'OFF');
}
die();
break;
//Change On/Off Device State of Device Button
case 'change':
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
if ($subDeviceData['type'] == 'on/off'){
$lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'];
RecordManager::create($deviceId, 'on/off', !$lastValue);
echo (!$lastValue ? 'ON' : 'OFF');
}
die();
break;
//Waitin for execution of Changet walue for Device Button
case 'executed':
echo RecordManager::getLastRecord($subDeviceId)['execuded'];
die();
break;
//Waitin for execution of Changet walue for Device Button
case 'executed':
echo RecordManager::getLastRecord($subDeviceId)['execuded'];
die();
break;
case 'set':
$value = $_POST['value'];
$subDevice = SubDeviceManager::getSubDevice($subDeviceId);
RecordManager::create($subDevice['device_id'], $subDevice['type'], $value);
echo 'test id' . $subDevice['device_id'] .$subDevice['type'] . $value ;
die();
break;
default:
echo 'no action detected';
default:
echo 'no action detected';
break;
}
} else if (
@ -101,21 +93,21 @@ class Ajax extends Template
$_POST['scene_id'] != '' &&
isset($_POST['action']) &&
$_POST['action'] != ''
) {
$sceneId = $_POST['scene_id'];
switch ($_POST['action']) {
case 'delete':
SceneManager::delete($sceneId);
die();
break;
) {
$sceneId = $_POST['scene_id'];
switch ($_POST['action']) {
case 'delete':
SceneManager::delete($sceneId);
die();
break;
case 'execute':
echo SceneManager::execScene($sceneId);
die();
break;
case 'execute':
echo SceneManager::execScene($sceneId);
die();
break;
default:
echo 'no action detected';
default:
echo 'no action detected';
break;
}
} else if (
@ -123,106 +115,36 @@ class Ajax extends Template
$_POST['notification'] != '' &&
isset($_POST['action']) &&
$_POST['action'] != ''
) {
switch ($_POST['action']) {
//add suscription to database
case 'subscribe':
$subscriptionToken = $_POST['token'];
NotificationManager::addSubscriber($_SESSION['user']['id'], $subscriptionToken);
die();
break;
) {
switch ($_POST['action']) {
//add suscription to database
case 'subscribe':
$subscriptionToken = $_POST['token'];
NotificationManager::addSubscriber($_SESSION['user']['id'], $subscriptionToken);
die();
break;
case 'sendTest':
$notificationData = [
'title' => 'Alert',
'body' => 'test notification',
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
];
$notificationMng = new NotificationManager;
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
echo $subscriber['user_id'];
if ($subscriber['user_id'] != $_SESSION['user']['id']) continue;
echo $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
die();
break;
case 'sendTest':
echo "test";
$notificationData = [
'title' => 'Alert',
'body' => 'test notification',
'icon' => '',
];
$notificationMng = new NotificationManager;
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
echo $subscriber['user_id'];
if ($subscriber['user_id'] != $_SESSION['user']['id']) continue;
echo $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
die();
break;
default:
echo 'no action detected';
default:
echo 'no action detected';
break;
}
} else if (
isset($_POST['action']) &&
$_POST['action'] != ''
) {
$updateData = [];
$allDevicesData = DeviceManager::getAllDevices();
foreach ($allDevicesData as $deviceKey => $deviceValue) {
$allSubDevices = SubDeviceManager::getAllSubDevices($deviceValue['device_id']);
foreach ($allSubDevices as $key => $subDevicesData) {
$lastRecord = RecordManager::getLastRecord($subDevicesData['subdevice_id']);
$parsedValue = $lastRecord['value'] . $subDevicesData['unit'];
//TODO: udělat parser a ten použít jak v houmu tak zde
switch ($subDevicesData['type']) {
case 'on/off':
$replacementTrue = 'On';
$replacementFalse = 'Off';
$operator = '==';
$breakValue = 1;
break;
case 'door':
$replacementTrue = 'Closed';
$replacementFalse = 'Open';
$operator = '==';
$breakValue = 1;
break;
case 'light':
$replacementTrue = 'Light';
$replacementFalse = 'Dark';
$operator = '==';
$breakValue = 1;
if ($lastRecord['value'] != 1 && $lastRecord['value'] != 0) { //Digital Light Senzor
$operator = '<';
$breakValue = 810;
}
break;
case 'water':
$replacementTrue = 'Wet';
$replacementFalse = 'Dry';
$operator = '==';
$breakValue = 1;
break;
default:
$replacementTrue = '';
$replacementFalse = '';
break;
}
if ($replacementTrue != '' && $replacementFalse != '') {
//parsing last values
$parsedValue = $replacementFalse;
if (Utilities::checkOperator($lastRecord['value'], $operator, $breakValue)) {
$parsedValue = $replacementTrue;
}
}
$updateData[$subDevicesData['subdevice_id']] = [
'time' => $lastRecord['time'],
'value' => $parsedValue,
];
}
}
//TODO: PRO JS VRACET DATA
echo json_encode($updateData, JSON_PRETTY_PRINT);
}
}
}

View File

@ -27,19 +27,12 @@ class Automation extends Template
'state' => $subDeviceState,
];
}
//TODO: Transaltion add
$executionTime = 'never';
if ($automationData['execution_time'] != '0000-00-00 00:00:00') {
$executionTime = date(DATEFORMAT,strtotime($automationData['execution_time']));
}
$automations[$automationData['automation_id']] = [
'name' => $automationData['name'],
'owner_name' => $userManager->getUserId($automationData['owner_id'])['username'],
'onDays' => json_decode($automationData['on_days']),
'ifSomething' => $automationData['if_something'],
'doSomething' => $doSomething,
'active' => $automationData['active'],
'execution_time' => $executionTime,
];
}
@ -59,11 +52,8 @@ class Automation extends Template
$template = new Template('automation');
$template->prepare('baseDir', BASEDIR);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Automation');
$template->prepare('langMng', $langMng);
$template->prepare('userManager', $userManager);
$template->prepare('automations', $automations);
$template->prepare('subDevices', $approvedSubDevices);

View File

@ -81,7 +81,6 @@ class Dashboard extends Template
}
$template->prepare('baseDir', BASEDIR);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Nástěnka');
$template->prepare('langMng', $langMng);
$template->prepare('dashboard', $dashboard);

View File

@ -77,8 +77,8 @@ class Home extends Template
$replacementFalse = 'Dark';
$operator = '==';
$breakValue = 1;
if ($lastValue != 1 && $lastValue != 0) { //Digital Light Senzor
$operator = '<';
if ($lastValue != 1 || $lastValue != 0) { //Digital Light Senzor
$operator = '<=';
$breakValue = 810;
}
break;
@ -108,7 +108,7 @@ class Home extends Template
//parsing last events values
foreach ($events as $key => $value) {
$events[$key]['value'] = $replacementFalse;
if (Utilities::checkOperator($value['value'], $operator, $breakValue)) {
if (Utilities::checkOperator($lastValue, $operator, $breakValue)) {
$events[$key]['value'] = $replacementTrue;
}
}
@ -122,11 +122,7 @@ class Home extends Template
$minutes = $interval->format('%i');
$lastSeen = ($hours * 60 + $minutes);
if (
$lastSeen < $deviceData['sleep_time'] ||
$subDeviceData['type'] == "on/off" ||
$subDeviceData['type'] == "door"
) {
if ($lastSeen < $deviceData['sleep_time'] || $subDeviceData['type'] == "on/off") {
$connectionError = false;
}
}
@ -160,11 +156,6 @@ class Home extends Template
'icon' => $deviceData['icon'],
'room' => $deviceData['room_id'],
'token' => $deviceData['token'],
'type' => $deviceData['type'],
'mac' => $deviceData['mac'],
'ip' => $deviceData['ip_address'],
'subnet' => $deviceData['subnet'],
'gateway' => $deviceData['gateway'],
'sleepTime' => $deviceData['sleep_time'],
'approved' => $deviceData['approved'],
'permission' => $permissionArray,
@ -182,7 +173,6 @@ class Home extends Template
$rooms = RoomManager::getAllRooms();
$template->prepare('baseDir', BASEDIR);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Home');
$template->prepare('rooms', $rooms);
$template->prepare('langMng', $langMng);

View File

@ -26,8 +26,6 @@ class Log extends Template
}
$template->prepare('baseDir', BASEDIR);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('logToLiveTime', LOGTIMOUT);
$template->prepare('title', 'Logy');
$template->prepare('logsFiles', $result);
$template->prepare('langMng', $langMng);

View File

@ -15,8 +15,6 @@ class Login extends Template
$template->prepare('title', 'Home');
$template->prepare('lang', $lang);
$template->render();
}
}

View File

@ -6,7 +6,7 @@ class Rooms extends Template
function __construct()
{
global $userManager;
global $langMng;
global $lang;
if (!$userManager->isLogin()){
header('Location: ' . BASEDIR . 'login');
@ -15,9 +15,8 @@ class Rooms extends Template
$template = new Template('rooms');
$template->prepare('baseDir', BASEDIR);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Rooms');
$template->prepare('langMng', $langMng);
$template->prepare('lang', $lang);
$roomsItems = [];
$roomsData = RoomManager::getAllRooms();

View File

@ -12,7 +12,6 @@ class Scene extends Template
$template = new Template('scene');
$template->prepare('baseDir', BASEDIR);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Scény');
$template->prepare('langMng', $langMng);

View File

@ -24,21 +24,13 @@ class Setting extends Template
$template = new Template('setting');
$template->prepare('baseDir', BASEDIR);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Automation');
$template->prepare('langMng', $langMng);
$template->prepare('automations', $automations);
$users = $userManager->getUsers();
foreach ($users as $key => $value) {
$users[$key]['gavatar_url'] = $userManager->getAvatarUrl($value['user_id']);
}
$template->prepare('users', $users);
$template->prepare('userName', $userManager->getUserData('username'));
$template->prepare('userEmail', $userManager->getUserData('email'));
$template->prepare('userAvatarUrl', $userManager->getAvatarUrl());
if ($userManager->getUserData('ota') == ''){
$ga = new PHPGangsta_GoogleAuthenticator();
$otaSecret = $ga->createSecret();
@ -53,9 +45,6 @@ class Setting extends Template
// echo "Checking Code '$oneCode' and Secret '$otaSecret':\n";
}
$rooms = RoomManager::getAllRooms();
$template->prepare('rooms', $rooms);
$template->render();
}

34
make.sh
View File

@ -1,34 +0,0 @@
#! /bin/sh
apt install dialog;
#dialog --stdout --title "Smart-Home" \
#--backtitle "Select update chanel :)" \
#--yesno "DEV: Experimental Version, STABLE: Stable version" 7 60
#dialog_status=$?
# Do something
dialog --menu "The best tortilla is:" 0 0 0 1 "with onions" 2 "without onion" 3 "with piminetos"
echo "answer $?";
#if [ "$dialo_status" -eq 'DEV' ]; then
# The previous dialog was answered Yes
#git checkout dev;
#else
# The previous dialog was answered No or interrupted with <C-c>
#git checkout master;
#fi
#clear;
#git reset --hard HEAD
#git pull
#rm ./.gitignore
#rm ./.ftpignore
#rm ./.todo
#rm ./LICENCE
#rm ./README.md
#rm -rf ./_FIRMWARE/*
#rm -rf ./_INSTALATION/*
#rm -rf ./_README_IMG/*
echo "Done";

180
old.home
View File

@ -1,180 +0,0 @@
<!-- <?php
//
// class Home extends Template
// {
// function __construct()
// {
// global $userManager;
// global $lang;
//
// if (!$userManager->isLogin()){
// header('Location: ./login');
// }
//
// $template = new Template('home');
//
// //users instantialize
// $users = UserManager::getUsers();
// $template->prepare('users', $users);
//
// //Users at home Info
// $usersAtHome = '';
// $i = 0;
// foreach ($users as $user) {
// $i++;
// if ($user['at_home'] == 'true') {
// $usersAtHome .= $user['username'];
// if ($usersAtHome != "" && isset($users[$i + 1])){
// $usersAtHome .= ', ';
// }
// }
// }
// $template->prepare('usersAtHome', $usersAtHome);
//
// $roomsItems = [];
// $roomsData = RoomManager::getAllRooms();
// foreach ($roomsData as $roomKey => $roomsData) {
// $devices = [];
// $devicesData = DeviceManager::getAllDevicesInRoom($roomsData['room_id']);
// foreach ($devicesData as $deviceKey => $deviceData) {
// $subDevices = [];
// $subDevicesData = SubDeviceManager::getAllSubDevices($deviceData['device_id']);
// foreach ($subDevicesData as $subDeviceKey => $subDeviceData) {
//
// $events = RecordManager::getLastRecord($subDeviceData['subdevice_id'], 5);
//
// $connectionError = false;
// $parsedValue = "";
// $niceTime = "";
//
// if (sizeof($events) > 1) {
//
// //TODO: skontrolovat zdali se jedná o poslední (opravdu nejaktuálnější) záznam
// $lastRecord = $events[0];
//
// $parsedValue = round($lastRecord['value']);
//
// /*Value Parsing*/
// if ($subDeviceData['type'] == "on/off") {
// $parsedValue = ($parsedValue == 1 ? 'ON' : 'OFF');
// }
//
// if ($subDeviceData['type'] == "door") {
// $replacementTrue = 'Closed';
// $replacementFalse = 'Opened';
// foreach ($events as $key => $value) {
// $events[$key]['value'] = ($value['value'] == 1 ? $replacementTrue : $replacementFalse);
// }
// $parsedValue = ($parsedValue == 1 ? $replacementTrue : $replacementFalse);
// }
//
// if ($subDeviceData['type'] == "light") {
// $replacementTrue = 'Light';
// $replacementFalse = 'Dark';
// foreach ($events as $key => $value) {
// if ($parsedValue != 1){
// //Analog Reading
// $events[$key]['value'] = ($value['value'] <= 810 ? $replacementTrue : $replacementFalse);
// } else {
// //Digital Reading
// $events[$key]['value'] = ($value['value'] == 0 ? $replacementTrue : $replacementFalse);
// }
// }
// if ($parsedValue != 1){
// //Analog Reading
// $parsedValue = ($parsedValue <= 810 ? $replacementTrue : $replacementFalse);
// } else {
// //Digital Reading
// $parsedValue = ($parsedValue == 0 ? $replacementTrue : $replacementFalse);
// }
// }
//
// $date2 = new DateTime($lastRecord['time']);
//
// $niceTime = $this->ago($date2);
//
//
// $startDate = date_create($lastRecord['time']);
// $interval = $startDate->diff(new DateTime());
// $hours = $interval->format('%h');
// $minutes = $interval->format('%i');
// $lastSeen = ($hours * 60 + $minutes);
//
// if ($lastSeen > $deviceData['sleep_time'] && $subDeviceData['type'] != "on/off") {
// $connectionError = true;
// }
// } else {
// $connectionError = true;
// }
//
// $subDevices[$subDeviceData['subdevice_id']] = [
// 'events'=> $events,
// 'type' => $subDeviceData['type'],
// 'unit' => $subDeviceData['unit'],
// 'comError' => $connectionError,
// 'lastRecort' => [
// 'value' => (empty($parsedValue) ? 0 : $parsedValue),
// 'time' => (empty($lastRecord['time']) ? "00:00" : $lastRecord['time']),
// 'niceTime' => (empty($niceTime) ? "00:00" : $niceTime),
// ],
// ];
// }
//
// $permissionArray = json_decode($deviceData['permission']);
//
// $userIsDeviceAdmin = false;
// if($permissionArray[1] == 3) {
// $userIsDeviceAdmin = true;
// } else if ($permissionArray[0] == 3) {
// if ( $deviceData['owner'] == $userManager->getUserData('user_id')) {
// $userIsDeviceAdmin = true;
// }
// }
//
// $devices[$deviceData['device_id']] = [
// 'name' => $deviceData['name'],
// 'icon' => $deviceData['icon'],
// 'room' => $deviceData['room_id'],
// 'token' => $deviceData['token'],
// 'sleepTime' => $deviceData['sleep_time'],
// 'approved' => $deviceData['approved'],
// 'permission' => $permissionArray,
// 'owner' => $deviceData['owner'],
// 'userIsAdmin' => $userIsDeviceAdmin,
// 'subDevices' => $subDevices,
// ];
// }
// $roomsItems[$roomsData['room_id']] = [
// 'name' => $roomsData['name'],
// 'deviceCount' => $roomsData['device_count'],
// 'devices' => $devices,
// ];
// }
//
// $rooms = RoomManager::getAllRooms();
// $template->prepare('rooms', $rooms);
// $template->prepare('title', 'Home');
// $template->prepare('lang', $lang);
// $template->prepare('data', $roomsItems);
//
// $template->render();
//
// }
//
// function ago( $datetime )
// {
// $interval = date_create('now')->diff( $datetime );
// $suffix = ( $interval->invert ? ' ago' : '' );
// if ( $v = $interval->y >= 1 ) return $this->pluralize( $interval->m, 'month' ) . $suffix;
// if ( $v = $interval->d >= 1 ) return $this->pluralize( $interval->d, 'day' ) . $suffix;
// if ( $v = $interval->h >= 1 ) return $this->pluralize( $interval->h, 'hour' ) . $suffix;
// if ( $v = $interval->i >= 1 ) return $this->pluralize( $interval->i, 'minute' ) . $suffix;
// return $this->pluralize( $interval->s, 'second' ) . $suffix;
// }
//
// function pluralize( $count, $text )
// {
// return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
// }
// }

View File

@ -1,7 +1,6 @@
<pre>
<?php
var_dump($_POST);
var_dump(file_exists("./app/updater/" . "3C71BF22FDCF" . ".bin"));
?>
</pre>

View File

@ -1,91 +0,0 @@
<?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;
}
//DB Conector
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
$logManager = new LogManager();
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'], LogRecordType::WARNING);
exit();
}
}
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);
}
$macAddress = $_SERVER['HTTP_X_ESP8266_STA_MAC'];
$localBinary = "./app/updater/" . str_replace(':', '', $macAddress) . ".bin";
$logManager->write("[Updater] url: " . $localBinary, LogRecordType::INFO);
$logManager->write("[Updater] version: " . $_SERVER['HTTP_X_ESP8266_SKETCH_MD5'], LogRecordType::INFO);
if (file_exists($localBinary)) {
$logManager->write("[Updater] version PHP: \n" . md5_file($localBinary), LogRecordType::INFO);
if ($_SERVER['HTTP_X_ESP8266_SKETCH_MD5'] != md5_file($localBinary)) {
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", LogRecordType::WARNING);
$logManager->write("[Device] version hash: \n" . md5_file($localBinary), LogRecordType::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'] . " ", LogRecordType::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();