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 _INSTALATION
_README_IMG _README_IMG
README.md README.md
.todo

6
.gitignore vendored
View File

@ -1,13 +1,7 @@
.ftpconfig .ftpconfig
.ftpconfig2
config.php config.php
_nemazat/index.html _nemazat/index.html
_nemazat/css/main.css.map _nemazat/css/main.css.map
_nemazat/css/main.css _nemazat/css/main.css
_nemazat/css/font-awesome.min.css _nemazat/css/font-awesome.min.css
app/logs/*.log 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 %{HTTPS} off
RewriteCond %{REQUEST_FILENAME} !api.php RewriteCond %{REQUEST_FILENAME} !api.php
RewriteCond %{REQUEST_FILENAME} !apiFront.php
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
AddType application/x-httpd-php .php .phtml AddType application/x-httpd-php .php .phtml

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 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal 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', 'Ajax.php',
)); ));
foreach($files as $file) { foreach($files as $file) {
include './app/class/'. $file; include './app/class/'. $file;
} }
//Allow acces only wia Curl, Ajax ETC //Allow acces only wia Curl, Ajax ETC
/*$restAcess = 'XMLHttpRequest' == ( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' ); $restAcess = 'XMLHttpRequest' == ( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );
if (!$restAcess){ if (!$restAcess){
header('Location: ./'); header('Location: ./');
}*/ }
//Log //Log
$logManager = new LogManager(); $logManager = new LogManager();
$apiLogManager = new LogManager('./app/logs/api/'. date("Y-m-d").'.log');
//DB Conector //DB Conector
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME); Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
@ -42,25 +39,17 @@ Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
$json = file_get_contents('php://input'); $json = file_get_contents('php://input');
$obj = json_decode($json, true); $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 //zabespecit proti Ddosu
if (isset($obj['user']) && $obj['user'] != ''){ if (isset($obj['user']) && $obj['user'] != ''){
//user at home //user at home
$user = UserManager::getUser($obj['user']); $user = UserManager::getUser($obj['user']);
$userAtHome = $user['at_home'];
if (!empty($user)) { if (!empty($user)) {
$userId = $user['user_id']; $userId = $user['user_id'];
$atHome = $obj['atHome']; $atHome = $obj['atHome'];
if($userAtHome != $atHome){ UserManager::atHome($userId, $atHome);
UserManager::atHome($userId, $atHome); $logManager->write("[Record] user " . $userId . "changet his home state to " . $atHome . RECORDTIMOUT , LogRecordType::WARNING);
$logManager->write("[USER] user " . $userId . " changet his home state to " . $atHome , LogRecordType::INFO);
}
echo 'Saved: ' . $atHome; echo 'Saved: ' . $atHome;
header($_SERVER["SERVER_PROTOCOL"]." 200 OK"); header("HTTP/1.1 200 OK");
die(); die();
} }
} }
@ -71,8 +60,8 @@ if (DEBUGMOD != 1) {
echo json_encode(array( echo json_encode(array(
'state' => 'unsuccess', 'state' => 'unsuccess',
'errorMSG' => "Using API from your IP insnt alowed!", '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); $logManager->write("[API] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING);
exit(); exit();
} }
@ -81,9 +70,6 @@ if (DEBUGMOD != 1) {
//automationExecution //automationExecution
try { try {
AutomationManager::executeAll(); AutomationManager::executeAll();
$fallbackManager = new FallbackManager(RANGES);
$fallbackManager->check();
//LogKeeper::purge(LOGTIMOUT);
} catch (\Exception $e) { } catch (\Exception $e) {
$logManager->write("[Automation] Something happen during automation execution", LogRecordType::ERROR); $logManager->write("[Automation] Something happen during automation execution", LogRecordType::ERROR);
} }
@ -93,50 +79,33 @@ try {
RecordManager::clean(RECORDTIMOUT); RecordManager::clean(RECORDTIMOUT);
} catch (\Exception $e) { } catch (\Exception $e) {
$logManager->write("[Record] cleaning record older that " . RECORDTIMOUT , LogRecordType::ERROR); $logManager->write("[Record] cleaning record older that " . RECORDTIMOUT , LogRecordType::ERROR);
}
}
//Variables //Variables
$token = $obj['token']; $token = $obj['token'];
$values = null; $values = null;
$settings = null;
$deviceLogs = null;
$command = "null";
if (isset($obj['values'])) { if (isset($obj['values'])) {
$values = $obj['values']; $values = $obj['values'];
} }
if (isset($obj['settings'])) {
$settings = $obj['settings'];
}
if (isset($obj['logs'])) {
$deviceLogs = $obj['logs'];
}
//Checks //Checks
if ($token == null || $token == "") { if ($token == null || $token == "") {
echo json_encode(array( echo json_encode(array(
'state' => 'unsuccess', 'state' => 'unsuccess',
'errorMSG' => "Missing Value Token in JSON payload", 'errorMSG' => "Missing Value Token in JSON payload",
), JSON_PRETTY_PRINT); ));
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); header("HTTP/1.1 401 Unauthorized");
die(); die();
} }
//Vstupní Checky //Vstupní Checky
if (!DeviceManager::registeret($token)) { if (!DeviceManager::registeret($token)) {
//Notification data setup
$notificationMng = new NotificationManager;
$notificationData = [ $notificationData = [
'title' => 'Info', 'title' => 'Info',
'body' => 'New device Detected Found', 'body' => 'New device Detected',
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', 'icon' => '',
]; ];
//Subdevice Registration
$deviceId = DeviceManager::create($token, $token); $deviceId = DeviceManager::create($token, $token);
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) { if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) {
@ -145,85 +114,32 @@ if (!DeviceManager::registeret($token)) {
} }
//Notification for newly added Device //Notification for newly added Device
if ($notificationData != []) { $subscribers = $notificationMng::getSubscription();
$subscribers = $notificationMng::getSubscription(); foreach ($subscribers as $key => $subscriber) {
foreach ($subscribers as $key => $subscriber) { $logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ");
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO); $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
} }
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); header("HTTP/1.1 401 Unauthorized");
echo json_encode(array( echo json_encode(array(
'state' => 'unsuccess', 'state' => 'unsuccess',
'errorMSG' => "Device not registeret", 'errorMSG' => "Device not registeret",
), JSON_PRETTY_PRINT); ));
$logManager->write("[API] Registering Device", LogRecordType::INFO); $logManager->write("[API] Registering Device", LogRecordType::INFO);
exit(); exit();
} }
if (!DeviceManager::approved($token)) { if (!DeviceManager::approved($token)) {
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); header("HTTP/1.1 401 Unauthorized");
echo json_encode(array( echo json_encode(array(
'state' => 'unsuccess', 'state' => 'unsuccess',
'errorMSG' => "Unaproved Device", 'errorMSG' => "Unaproved Device",
), JSON_PRETTY_PRINT); ));
exit(); 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! // Subdevices first data!
if ($values != null && $values != "") { if ($values != null || $values != "") {
//ZAPIS //ZAPIS
$device = DeviceManager::getDeviceByToken($token); $device = DeviceManager::getDeviceByToken($token);
@ -232,7 +148,7 @@ if ($values != null && $values != "") {
if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) { if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) {
SubDeviceManager::create($deviceId, $key, UNITS[$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); $logManager->write("[API] Device_ID " . $deviceId . " writed value " . $key . ' ' . $value['value'], LogRecordType::INFO);
//notification //notification
@ -242,26 +158,25 @@ if ($values != null && $values != "") {
switch ($key) { switch ($key) {
case 'door': case 'door':
$notificationData = [ $notificationData = [
'title' => 'Info', 'title' => 'Info',
'body' => 'Someone just open up '.$device['name'], 'body' => 'Someone just open up '.$device['name'],
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', 'icon' => '',
]; ];
break; break;
case 'water': case 'water':
$notificationData = [ $notificationData = [
'title' => 'Alert', 'title' => 'Alert',
'body' => 'Wather leak detected by '.$device['name'], 'body' => 'Wather leak detected by '.$device['name'],
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', 'icon' => '',
]; ];
break; break;
} }
if (DEBUGMOD) $notificationData['body'] .= ' value='.$value['value']; if (DEBUGMOD) $notificationData['body'] .= ' value='.$value['value'];
if ($notificationData != []) { if ($notificationData != []) {
$subscribers = $notificationMng::getSubscription(); $subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) { 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); $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
} }
} }
@ -270,26 +185,22 @@ if ($values != null && $values != "") {
$hostname = strtolower($device['name']); $hostname = strtolower($device['name']);
$hostname = str_replace(' ', '_', $hostname); $hostname = str_replace(' ', '_', $hostname);
//upravit format na setings-> netvork etc
$jsonAnswer = [ $jsonAnswer = [
'device' => [ 'device' => [
'hostname' => $hostname, 'hostname' => $hostname,
'ipAddress' => $device['ip_address'],
'subnet' => $device['subnet'],
'gateway' => $device['gateway'],
], ],
'state' => 'succes', 'state' => 'succes',
'command' => $command,
]; ];
$subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($deviceId); $subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($deviceId);
if (!in_array($subDevicesTypeList, ['on/off', 'door', 'water'])) { 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); echo json_encode($jsonAnswer);
header($_SERVER["SERVER_PROTOCOL"]." 200 OK"); header("HTTP/1.1 200 OK");
} else { } else {
//Vypis //Vypis
//TODO: doděla uložení výpisu jinými slovy zda li byl comman vykonán
$device = DeviceManager::getDeviceByToken($token); $device = DeviceManager::getDeviceByToken($token);
$deviceId = $device['device_id']; $deviceId = $device['device_id'];
@ -303,24 +214,21 @@ if ($values != null && $values != "") {
$subDeviceLastReordValue = $subDeviceLastReord['value']; $subDeviceLastReordValue = $subDeviceLastReord['value'];
if ($subDeviceLastReord['execuded'] == 0){ 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']); RecordManager::setExecuted($subDeviceLastReord['record_id']);
} }
echo json_encode(array( echo json_encode(array(
'device' => [ 'device' => [
'hostname' => $device['name'], 'hostname' => $device['name'],
'ipAddress' => $device['ip_address'], 'sleepTime' => $device['sleep_time'],
'subnet' => $device['subnet'], ],
'gateway' => $device['gateway'], 'state' => 'succes',
], 'value' => $subDeviceLastReordValue
'state' => 'succes', ));
'value' => $subDeviceLastReordValue, header("HTTP/1.1 200 OK");
'command' => $command, }
), JSON_PRETTY_PRINT);
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
}
unset($logManager); unset($logManager);
Db::disconect(); Db::disconect();
die(); 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 = "") { public function create ($name, $onDays, $doCode, $ifCode, $automationId = "") {
$userId = UserManager::getUserData('user_id');
$scene = array ( $scene = array (
'name' => $name, 'name' => $name,
'owner_id' => $userId,
'on_days' => $onDays, 'on_days' => $onDays,
'if_something' => $ifCode, 'if_something' => $ifCode,
'do_something' => $doCode, 'do_something' => $doCode,
@ -79,21 +77,9 @@ class AutomationManager{
} }
} else if ($onValue['type'] == 'outHome') { } 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') { } 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') { } else if ($onValue['type'] == 'noOneHome') {
$users = UserManager::getUsers(); $users = UserManager::getUsers();
$membersHome = 0; $membersHome = 0;
@ -120,18 +106,6 @@ class AutomationManager{
} else if ($membersHome > 0 && $automation['executed'] == 0){ } else if ($membersHome > 0 && $automation['executed'] == 0){
$run = true; $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 //finalization
@ -146,23 +120,18 @@ class AutomationManager{
$subscribers = NotificationManager::getSubscription(); $subscribers = NotificationManager::getSubscription();
$i = 0; $i = 0;
$notificationMng = new NotificationManager; foreach ($subscribers as $key => $subscriber) {
$notificationData = [ $logManager->write("[NOTIFICATION] SENDING NOTIFICATION TO" . $subscriber['id'] . " was executed" . $i);
'title' => 'Automatization', $title = 'Automatization '.$automation['name']." was just executed";
'body' => 'Automatization '.$automation['name']." was just executed", $notification = new Notification(SERVERKEY);
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', $notification->to($subscriber['token']);
]; $notification->notification($title, '' , '', '');
$notification->send();
if ($notificationData != []) { $notification = null;
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {
$logManager->write("[NOTIFICATION/AUTOOMATION] SENDING TO" . $subscriber['id'] . " ");
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
}
} }
$logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was executed"); $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) { } else if ($restart) {
$logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was restarted"); $logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was restarted");
Db::edit('automation', array('executed' => 0), 'WHERE automation_id = ?', array($automation['automation_id'])); Db::edit('automation', array('executed' => 0), 'WHERE automation_id = ?', array($automation['automation_id']));

View File

@ -18,20 +18,14 @@ class DeviceManager{
return Db::loadOne("SELECT * FROM devices WHERE token = ?", array($deviceToken)); 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) { function getDeviceById($deviceId) {
return Db::loadOne("SELECT * FROM devices WHERE device_id = ?", array($deviceId)); return Db::loadOne("SELECT * FROM devices WHERE device_id = ?", array($deviceId));
} }
public function create ($name, $token) { public function create ($name, $token) {
$defaultRoom = RoomManager::getDefaultRoomId();
$device = array ( $device = array (
'name' => $name, 'name' => $name,
'token' => $token, 'token' => $token,
'room_id' => $defaultRoom,
); );
try { try {
Db::add ('devices', $device); 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] * [assignRoom Přiřazení zařízení do třídy]
* @param [type] $roomId [číslo místnosti do kter se zařízení přiřadit] * @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'; 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 class LogManager
{ {
@ -46,9 +27,7 @@ class LogManager
function write($value, $type = LogRecordType::ERROR){ function write($value, $type = LogRecordType::ERROR){
$record = "[".date("H:m:s")."][".$type."]" . $value . "\n"; $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); 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 * Notification Manager
*/ */
//TODO: Working timestamp to body or $title
class NotificationManager class NotificationManager
{ {
function addSubscriber($userID = '', $token = ''){ function addSubscriber($userID = '', $token = ''){
@ -16,11 +15,11 @@ class NotificationManager
} }
} }
function getSubscription () { function getSubscription(){
return Db::loadAll ("SELECT * FROM notifications"); 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 = [ $dataTemplate = [
'title' => '', 'title' => '',
'body' => '', 'body' => '',
@ -31,10 +30,6 @@ class NotificationManager
return; return;
} }
if ($timeStamp) {
$data['title'] = $data['title'] . date();
}
$notification = new Notification($serverKey); $notification = new Notification($serverKey);
$notification->to($to); $notification->to($to);
$notification->notification($data['title'], $data['body'], $data['icon'], ''); $notification->notification($data['title'], $data['body'], $data['icon'], '');
@ -69,14 +64,10 @@ class Notification
$this->jsonPayload["to"] = $to; $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"]["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"]["icon"] = $icon;
$this->jsonPayload["data"]["notification"]["click_action"] = $action; $this->jsonPayload["data"]["notification"]["click_action"] = $action;
} }

View File

@ -67,7 +67,7 @@ class RecordManager{
public static function clean ($day) { public static function clean ($day) {
if (isset($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{ class RoomManager{
public static $rooms; public static $rooms;
function getDefaultRoomId() {
$defaultRoom = Db::loadOne("SELECT room_id FROM rooms WHERE 'default' = 1");
return $defaultRoom['room_id'];
}
function getAllRooms () { 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"); $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; return $allRoom;

View File

@ -27,7 +27,7 @@ class Template extends Partial{
function render() { function render() {
extract($this->assignedValues); extract($this->assignedValues);
if (!empty('app/controls/' . $this->path . '.php') && file_exists('app/controls/' . $this->path . '.php')) { 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'); 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) { public function login ($username, $password, $rememberMe) {
try { try {
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($username))) { 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 () { public function isLogin () {
if (isset ($_SESSION['user']) && isset($_SESSION['user']['id'])) { if (isset ($_SESSION['user']) && isset($_SESSION['user']['id'])) {
return true; return true;
@ -138,8 +102,10 @@ class UserManager
} }
public static function getUserData ($type, $userId = '') { public static function getUserData ($type, $userId = '') {
if ($userId == '') { if (isset($_SESSION['user']['id'])) {
$userId = $_SESSION['user']['id']; $userId = $_SESSION['user']['id'];
} else {
return "";
} }
$user = Db::loadOne ('SELECT ' . $type . ' FROM users WHERE user_id=?', array ($userId)); $user = Db::loadOne ('SELECT ' . $type . ' FROM users WHERE user_id=?', array ($userId));
return $user[$type]; return $user[$type];

View File

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

View File

@ -2,33 +2,22 @@
if (isset($_POST) && !empty($_POST)){ if (isset($_POST) && !empty($_POST)){
if (isset($_POST['modalFinal']) && $_POST['action'] == "add") { if (isset($_POST['modalFinal']) && $_POST['action'] == "add") {
$doCode = json_encode($_POST['device'], JSON_PRETTY_PRINT); $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([ $ifCode = json_encode([
"type" => $_POST['atSelector'], "type" => $_POST['atSelector'],
"value" => $value, "value" => $_POST['atSelectorValue'],
], JSON_PRETTY_PRINT); ], JSON_PRETTY_PRINT);
$onDays = $_POST['atDays']; $onDays = $_POST['atDays'];
//Debug //Debug
// if (DEBUGMOD == 1) { if (DEBUGMOD == 1) {
// echo '<pre>'; echo '<pre>';
// echo $permissionsInJson; echo $permissionsInJson;
// echo $deviceId; echo $deviceId;
// var_dump(json_decode ($permissionsInJson)); var_dump(json_decode ($permissionsInJson));
// echo '</pre>'; echo '</pre>';
// echo '<a href="' . BASEDIR .'">CONTINUE</a>'; echo '<a href="' . BASEDIR .'">CONTINUE</a>';
// die(); die();
// } }
AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode); AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode);
@ -43,28 +32,18 @@ if (isset($_POST) && !empty($_POST)){
$subDevice = SubDeviceManager::getSubDevice($subDeviceId); $subDevice = SubDeviceManager::getSubDevice($subDeviceId);
$subDeviceMaster = SubDeviceManager::getSubDeviceMaster($subDeviceId,$subDevice['type']); $subDeviceMaster = SubDeviceManager::getSubDeviceMaster($subDeviceId,$subDevice['type']);
$device = [ $json = json_encode([
'deviceID' => $subDeviceMaster['device_id'], 'deviceID' => $subDeviceMaster['device_id'],
'type'=> $subDevice['type'], 'type'=> $subDevice['type'],
'value'=> $subDeviceValue, 'value'=> $subDeviceValue,
]; ]);
} }
$value = $_POST['atSelector']; $_POST['atSelectorValue'] = (isset($_POST['atTime']) ? $_POST['atTime'] : (isset($_POST['atDeviceValue']) ? $json : $_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']));
$ifCode = json_encode([ $ifCode = json_encode([
"type" => $_POST['atSelector'], "type" => $_POST['atSelector'],
"value" => $value, "value" => $_POST['atSelectorValue'],
], JSON_PRETTY_PRINT); ], JSON_PRETTY_PRINT);
$onDays = ($_POST['day'] != '' ? json_encode($_POST['day']) : ''); $onDays = ($_POST['day'] != '' ? json_encode($_POST['day']) : '');

View File

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

View File

@ -13,11 +13,6 @@ if (isset($_POST) && !empty($_POST)){
UserManager::createUser($userName, $password); UserManager::createUser($userName, $password);
header('Location: ' . BASEDIR . 'setting'); header('Location: ' . BASEDIR . 'setting');
die(); 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'] != "") { } else if (isset($_POST['submitEnableOta']) && $_POST['submitEnableOta'] != "") {
echo $otaCode = $_POST['otaCode']; echo $otaCode = $_POST['otaCode'];
echo $otaSecret = $_POST['otaSecret']; echo $otaSecret = $_POST['otaSecret'];

View File

@ -28,7 +28,6 @@ return $lang = [
'b_restart' => 'Restart', 'b_restart' => 'Restart',
'b_disable' => 'Deaktivovat', 'b_disable' => 'Deaktivovat',
'b_select' => 'Zvolit', 'b_select' => 'Zvolit',
'b_ota' => 'ota',
//labels //labels
'l_choseDevice' => 'Zvolte zařízení:', 'l_choseDevice' => 'Zvolte zařízení:',
@ -58,10 +57,6 @@ return $lang = [
'l_password' => 'Heslo', 'l_password' => 'Heslo',
'l_oldPassword' => 'Staré Heslo', 'l_oldPassword' => 'Staré Heslo',
'l_newPassword' => 'Nové Heslo', 'l_newPassword' => 'Nové Heslo',
'l_uploadFirmware' => 'Nahrát Firmware',
'l_userAvatar' => 'Avatar',
'l_userEmail' => 'Email',
'l_roomName' => 'Jméno Místnosti',
//Title //Title
't_createScene' => 'Vytvořit scénu', 't_createScene' => 'Vytvořit scénu',
@ -75,14 +70,6 @@ return $lang = [
't_experimental' => 'Experimental', 't_experimental' => 'Experimental',
't_createuser' => 'Vytvořit Uživatele', 't_createuser' => 'Vytvořit Uživatele',
't_changePassword' => 'Změnit Heslo', '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 //constants
'temp' => 'Teplota', 'temp' => 'Teplota',

View File

@ -28,7 +28,6 @@ return $lang = [
'b_restart' => 'Restart', 'b_restart' => 'Restart',
'b_disable' => 'disabele', 'b_disable' => 'disabele',
'b_select' => 'Select', 'b_select' => 'Select',
'b_ota' => 'ota',
//labels //labels
'l_choseDevice' => 'Chose device:', 'l_choseDevice' => 'Chose device:',
@ -58,10 +57,6 @@ return $lang = [
'l_password' => 'Password', 'l_password' => 'Password',
'l_oldPassword' => 'Old Password', 'l_oldPassword' => 'Old Password',
'l_newPassword' => 'New Password', 'l_newPassword' => 'New Password',
'l_uploadFirmware' => 'Upload Firmware',
'l_userAvatar' => 'Avatar',
'l_userEmail' => 'Email',
'l_roomName' => 'Room Name',
//Title //Title
't_createScene' => 'Create Scene', 't_createScene' => 'Create Scene',
@ -75,14 +70,6 @@ return $lang = [
't_experimental' => 'Experimental', 't_experimental' => 'Experimental',
't_createuser' => 'Create User', 't_createuser' => 'Create User',
't_changePassword' => 'Change Password', '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 //constants
'humi' => 'Humidity', 'humi' => 'Humidity',

View File

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

View File

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

View File

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

View File

@ -16,7 +16,6 @@
$partial = new Partial('menu'); $partial = new Partial('menu');
$partial->prepare('item', 'home'); $partial->prepare('item', 'home');
$partial->prepare('langMng',$LANGMNG); $partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->render(); $partial->render();
?> ?>
</div> </div>
@ -85,23 +84,5 @@
$partial = new Partial('footer'); $partial = new Partial('footer');
$partial->render(); $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> </body>
</html> </html>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -21,12 +21,9 @@
'value'=> $subDeviceValue, 'value'=> $subDeviceValue,
]); ]);
echo htmlspecialchars($json); echo htmlspecialchars($json);
} else { }
if ($_POST['atSelector'] == "inHome" || $_POST['atSelector'] == "outHome") { else {
echo $USERMANAGER->getUserData('user_id'); echo $_POST['atSelector'];
} else {
echo $_POST['atSelector'];
}
} ?>" required/> } ?>" required/>
<input type="hidden" name="atDays" value="<?php echo htmlspecialchars(($_POST['day'] != '' ? json_encode($_POST['day']) : '')); ?>" required/> <input type="hidden" name="atDays" value="<?php echo htmlspecialchars(($_POST['day'] != '' ? json_encode($_POST['day']) : '')); ?>" required/>
<?php foreach ($_POST['devices'] as $value) { ?> <?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> <h5 unselectable="on" class="fa">&#x<?php echo $DEVICE['icon'] ?></h5>
</div> </div>
<div class="col"> <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> <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> </div>
<div class="row"> <div class="row">

View File

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

View File

@ -4,7 +4,7 @@
<i class="fa fa-times"></i> <i class="fa fa-times"></i>
</div> </div>
<h4 class="mb-4"><?php $LANGMNG->echo('t_editDevice'); ?></h4> <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; ?>"> <input class="input" type="hidden" name="deviceId" value="<?php echo $DEVICEID; ?>">
<?php if ($DEVICE['approved'] != 0) { ?> <?php if ($DEVICE['approved'] != 0) { ?>
<?php if ($DEVICE['userIsAdmin']) { ?> <?php if ($DEVICE['userIsAdmin']) { ?>
@ -62,34 +62,6 @@
<div class="label">Token:</div> <div class="label">Token:</div>
<input class="input" type="text" name="deviceToken" value="<?php echo $DEVICE['token']; ?>" disabled> <input class="input" type="text" name="deviceToken" value="<?php echo $DEVICE['token']; ?>" disabled>
</div> </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 ($DEVICE['userIsAdmin']) { ?>
<?php if (!in_array($SUBDEVICE['type'], ['on/off', 'door', 'water'])) { ?> <?php if (!in_array($SUBDEVICE['type'], ['on/off', 'door', 'water'])) { ?>
<div class="field"> <div class="field">
@ -129,19 +101,19 @@
<div class="label"><?php $LANGMNG->echo('w_moduls'); ?></div> <div class="label"><?php $LANGMNG->echo('w_moduls'); ?></div>
<div class="row no-gutters"> <div class="row no-gutters">
<?php foreach ($DEVICE['subDevices'] as $subDeviceKey => $subDevice) { ?> <?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">
<div class="square-content"> <div class="square-content">
<div class="row no-gutters"> <div class="row">
<div class="col"> <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>
<div class="col"> <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> </div>
<div class="row"> <div class="row">
<div class="col button-text" unselectable="on" > <div class="col">
<?php echo $DEVICE['name']; ?> <?php echo $DEVICE['name']; ?>
</div> </div>
</div> </div>
@ -158,13 +130,22 @@
<div class="label"><?php $LANGMNG->echo('w_moduls'); ?></div> <div class="label"><?php $LANGMNG->echo('w_moduls'); ?></div>
<div class="row no-gutters"> <div class="row no-gutters">
<?php foreach ($DEVICE['subDevices'] as $subDeviceKey => $subDevice) { ?> <?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">
<div class="square-content"> <div class="square-content">
<div class="row">
<?php echo $DEVICE['name']; ?> <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> </div>
</div> </div>

View File

@ -32,11 +32,7 @@
'path' => 'log', 'path' => 'log',
], ],
]; ];
foreach ( $menuItems as $key => $value) { foreach ( $menuItems as $key => $value) { ?>
if ($DEBUGMOD == 0 && $value['path'] == 'log') {
continue;
}
?>
<div class="nav-item <?php echo ($ITEM == $value ? 'is-active' : ''); ?>"> <div class="nav-item <?php echo ($ITEM == $value ? 'is-active' : ''); ?>">
<a href="<?php echo $value['path']?>"> <a href="<?php echo $value['path']?>">
<i class="fa <?php echo $key ?>"></i> <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="col-12 col-md-6 col-xl-4 square-wrap noselect">
<div class="rectangle-2"> <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="row">
<div class="col-1"> <div class="col-1">
<h5 class="fa noselect"> <h5 class="fa noselect">

View File

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

View File

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

View File

@ -16,14 +16,12 @@
$partial = new Partial('menu'); $partial = new Partial('menu');
$partial->prepare('item', 'setting'); $partial->prepare('item', 'setting');
$partial->prepare('langMng',$LANGMNG); $partial->prepare('langMng',$LANGMNG);
$partial->prepare('debugMod',$DEBUGMOD);
$partial->render(); $partial->render();
?> ?>
</div> </div>
<div class="col-md-9 main-body"> <div class="col-md-9 main-body">
<div class="col-12 col-sm-9 mx-auto mt-4"> <div class="col-12 col-sm-9 mx-auto mt-4">
<h4 class="mb-4"> <h4 class="mb-4">
<?php $LANGMNG->echo('t_pageAfterLogIn') ?> <?php $LANGMNG->echo('t_pageAfterLogIn') ?>
</h4> </h4>
<form method="post" enctype="multipart/form-data"> <form method="post" enctype="multipart/form-data">
@ -40,19 +38,6 @@
</form> </form>
<div class="col-12 col-sm-9 mx-auto mt-4"> <div class="col-12 col-sm-9 mx-auto mt-4">
<h4 class="mb-4"><?php $LANGMNG->echo('t_profile') ?></h4> <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"> <div class="field">
<a href="logout" class="button is-primary"><?php $LANGMNG->echo('b_logOut') ?></a> <a href="logout" class="button is-primary"><?php $LANGMNG->echo('b_logOut') ?></a>
</div> </div>
@ -115,7 +100,6 @@
<table class="table is-fluid"> <table class="table is-fluid">
<thead> <thead>
<tr> <tr>
<th><?php $LANGMNG->echo('t_avatar');?></th>
<th><?php $LANGMNG->echo('t_userName');?></th> <th><?php $LANGMNG->echo('t_userName');?></th>
<th><?php $LANGMNG->echo('t_ota');?></th> <th><?php $LANGMNG->echo('t_ota');?></th>
<th><?php $LANGMNG->echo('t_action');?></th> <th><?php $LANGMNG->echo('t_action');?></th>
@ -124,7 +108,6 @@
<tbody> <tbody>
<?php foreach ($USERS as $key => $user) { ?> <?php foreach ($USERS as $key => $user) { ?>
<tr> <tr>
<td><img src="<?php echo $user['gavatar_url']; ?>" /></td>
<td><?php echo $user['username']; ?></td> <td><?php echo $user['username']; ?></td>
<td><?php echo ($user['ota'] ? '<span class="fa">&#xf00c;</span>' : ''); ?></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> <td><button name="deleteUser" type="button" class="button is-danger fa">&#xf1f8;</button></td>
@ -138,57 +121,17 @@
<form method="post"> <form method="post">
<div class="field"> <div class="field">
<div class="label"><?php $LANGMNG->echo('l_userName') ?>:</div> <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>
<div class="field"> <div class="field">
<div class="label"><?php $LANGMNG->echo('l_password') ?>:</div> <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>
<div class="field"> <div class="field">
<input type="submit" name="submitCreateUser" class="button" value="Uložit"> <input type="submit" name="submitCreateUser" class="button" value="Uložit">
</div> </div>
</form> </form>
</div> </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> </div>

View File

View File

@ -26,27 +26,27 @@ class Ajax extends Template
$_POST['automation_id'] != '' && $_POST['automation_id'] != '' &&
isset($_POST['action']) && isset($_POST['action']) &&
$_POST['action'] != '' $_POST['action'] != ''
) { ) {
$automationId = $_POST['automation_id']; $automationId = $_POST['automation_id'];
//Automation Editation of Automations from Buttons/Details //Automation Editation of Automations from Buttons/Details
switch ($_POST['action']) { switch ($_POST['action']) {
case 'delete': case 'delete':
AutomationManager::remove($automationId); AutomationManager::remove($automationId);
die(); die();
break; break;
case 'deactive': case 'deactive':
AutomationManager::deactive($automationId); AutomationManager::deactive($automationId);
die(); die();
break; break;
case 'restart': case 'restart':
AutomationManager::restart($automationId); AutomationManager::restart($automationId);
die(); die();
break; break;
default: default:
echo 'no action detected'; echo 'no action detected';
break; break;
} }
} else if ( } else if (
@ -54,46 +54,38 @@ class Ajax extends Template
$_POST['subDevice_id'] != '' && $_POST['subDevice_id'] != '' &&
isset($_POST['action']) && isset($_POST['action']) &&
$_POST['action'] != '' $_POST['action'] != ''
) { ) {
$subDeviceId = $_POST['subDevice_id']; $subDeviceId = $_POST['subDevice_id'];
switch ($_POST['action']) { switch ($_POST['action']) {
case 'chart': case 'chart':
$period = $_POST['period']; $period = $_POST['period'];
$groupBy = $_POST['group']; $groupBy = $_POST['group'];
header('Content-Type: application/json'); header('Content-Type: application/json');
$graphData = ChartManager::generateChartData($subDeviceId, $period, $groupBy); $graphData = ChartManager::generateChartData($subDeviceId, $period, $groupBy);
echo Utilities::generateGraphJson($graphData['graphType'], $graphData['graphData'], $graphData['graphRange']); echo Utilities::generateGraphJson($graphData['graphType'], $graphData['graphData'], $graphData['graphRange']);
die(); die();
break; break;
//Change On/Off Device State of Device Button //Change On/Off Device State of Device Button
case 'change': case 'change':
$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId); $subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id']; $deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
if ($subDeviceData['type'] == 'on/off'){ if ($subDeviceData['type'] == 'on/off'){
$lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value']; $lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'];
RecordManager::create($deviceId, 'on/off', !$lastValue); RecordManager::create($deviceId, 'on/off', !$lastValue);
echo (!$lastValue ? 'ON' : 'OFF'); echo (!$lastValue ? 'ON' : 'OFF');
} }
die(); die();
break; break;
//Waitin for execution of Changet walue for Device Button //Waitin for execution of Changet walue for Device Button
case 'executed': case 'executed':
echo RecordManager::getLastRecord($subDeviceId)['execuded']; echo RecordManager::getLastRecord($subDeviceId)['execuded'];
die(); die();
break; break;
case 'set': default:
$value = $_POST['value']; echo 'no action detected';
$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';
break; break;
} }
} else if ( } else if (
@ -101,21 +93,21 @@ class Ajax extends Template
$_POST['scene_id'] != '' && $_POST['scene_id'] != '' &&
isset($_POST['action']) && isset($_POST['action']) &&
$_POST['action'] != '' $_POST['action'] != ''
) { ) {
$sceneId = $_POST['scene_id']; $sceneId = $_POST['scene_id'];
switch ($_POST['action']) { switch ($_POST['action']) {
case 'delete': case 'delete':
SceneManager::delete($sceneId); SceneManager::delete($sceneId);
die(); die();
break; break;
case 'execute': case 'execute':
echo SceneManager::execScene($sceneId); echo SceneManager::execScene($sceneId);
die(); die();
break; break;
default: default:
echo 'no action detected'; echo 'no action detected';
break; break;
} }
} else if ( } else if (
@ -123,106 +115,36 @@ class Ajax extends Template
$_POST['notification'] != '' && $_POST['notification'] != '' &&
isset($_POST['action']) && isset($_POST['action']) &&
$_POST['action'] != '' $_POST['action'] != ''
) { ) {
switch ($_POST['action']) { switch ($_POST['action']) {
//add suscription to database //add suscription to database
case 'subscribe': case 'subscribe':
$subscriptionToken = $_POST['token']; $subscriptionToken = $_POST['token'];
NotificationManager::addSubscriber($_SESSION['user']['id'], $subscriptionToken); NotificationManager::addSubscriber($_SESSION['user']['id'], $subscriptionToken);
die(); die();
break; break;
case 'sendTest': case 'sendTest':
$notificationData = [ echo "test";
'title' => 'Alert', $notificationData = [
'body' => 'test notification', 'title' => 'Alert',
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', 'body' => 'test notification',
]; 'icon' => '',
$notificationMng = new NotificationManager; ];
$subscribers = $notificationMng::getSubscription(); $notificationMng = new NotificationManager;
foreach ($subscribers as $key => $subscriber) { $subscribers = $notificationMng::getSubscription();
echo $subscriber['user_id']; foreach ($subscribers as $key => $subscriber) {
if ($subscriber['user_id'] != $_SESSION['user']['id']) continue; echo $subscriber['user_id'];
echo $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData); if ($subscriber['user_id'] != $_SESSION['user']['id']) continue;
} echo $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
die(); }
break; die();
break;
default: default:
echo 'no action detected'; echo 'no action detected';
break; 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, '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']] = [ $automations[$automationData['automation_id']] = [
'name' => $automationData['name'], 'name' => $automationData['name'],
'owner_name' => $userManager->getUserId($automationData['owner_id'])['username'],
'onDays' => json_decode($automationData['on_days']), 'onDays' => json_decode($automationData['on_days']),
'ifSomething' => $automationData['if_something'], 'ifSomething' => $automationData['if_something'],
'doSomething' => $doSomething, 'doSomething' => $doSomething,
'active' => $automationData['active'], 'active' => $automationData['active'],
'execution_time' => $executionTime,
]; ];
} }
@ -59,11 +52,8 @@ class Automation extends Template
$template = new Template('automation'); $template = new Template('automation');
$template->prepare('baseDir', BASEDIR); $template->prepare('baseDir', BASEDIR);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Automation'); $template->prepare('title', 'Automation');
$template->prepare('langMng', $langMng); $template->prepare('langMng', $langMng);
$template->prepare('userManager', $userManager);
$template->prepare('automations', $automations); $template->prepare('automations', $automations);
$template->prepare('subDevices', $approvedSubDevices); $template->prepare('subDevices', $approvedSubDevices);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -24,21 +24,13 @@ class Setting extends Template
$template = new Template('setting'); $template = new Template('setting');
$template->prepare('baseDir', BASEDIR); $template->prepare('baseDir', BASEDIR);
$template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Automation'); $template->prepare('title', 'Automation');
$template->prepare('langMng', $langMng); $template->prepare('langMng', $langMng);
$template->prepare('automations', $automations); $template->prepare('automations', $automations);
$users = $userManager->getUsers(); $users = $userManager->getUsers();
foreach ($users as $key => $value) {
$users[$key]['gavatar_url'] = $userManager->getAvatarUrl($value['user_id']);
}
$template->prepare('users', $users); $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') == ''){ if ($userManager->getUserData('ota') == ''){
$ga = new PHPGangsta_GoogleAuthenticator(); $ga = new PHPGangsta_GoogleAuthenticator();
$otaSecret = $ga->createSecret(); $otaSecret = $ga->createSecret();
@ -53,9 +45,6 @@ class Setting extends Template
// echo "Checking Code '$oneCode' and Secret '$otaSecret':\n"; // echo "Checking Code '$oneCode' and Secret '$otaSecret':\n";
} }
$rooms = RoomManager::getAllRooms();
$template->prepare('rooms', $rooms);
$template->render(); $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> <pre>
<?php <?php
var_dump($_POST); var_dump($_POST);
var_dump(file_exists("./app/updater/" . "3C71BF22FDCF" . ".bin"));
?> ?>
</pre> </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();