some fix and new firmware for shelly1

This commit is contained in:
unknown 2020-02-18 21:30:44 +01:00
parent e76b3127f3
commit 5a06a6c85a
20 changed files with 626 additions and 96 deletions

1
.gitignore vendored
View File

@ -1,4 +1,5 @@
.ftpconfig .ftpconfig
.ftpconfig2
config.php config.php
_nemazat/index.html _nemazat/index.html
_nemazat/css/main.css.map _nemazat/css/main.css.map

View File

@ -2,7 +2,7 @@ Options -Indexes
Options -MultiViews -Indexes Options -MultiViews -Indexes
RewriteEngine On RewriteEngine On
RewriteBase / RewriteBase /vasek/home/
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-d
@ -10,8 +10,8 @@ RewriteCond %{REQUEST_FILENAME} !.css
RewriteCond %{REQUEST_FILENAME} !.js RewriteCond %{REQUEST_FILENAME} !.js
RewriteRule (.*) index.php?url=$1 [QSA,L] RewriteRule (.*) index.php?url=$1 [QSA,L]
#RewriteCond %{HTTPS} off RewriteCond %{HTTPS} off
#RewriteCond %{REQUEST_FILENAME} !api.php RewriteCond %{REQUEST_FILENAME} !api.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

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@ -0,0 +1,210 @@
//Includes
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <EEPROM.h>
//Variables
const char* ssid = "Smart-Home";
const char* pasw = "S1pjg3684dcCPTUQ";
const char* hwId = "55f4g8d6ggh";
const char* server = "http://dev.steelants.cz/vasek/home/api.php";
int unsuccessfulRounds = 0; //Unsucesful atmpt counter
StaticJsonDocument<250> jsonContent;
bool buttonActive = false;
int interuptCount = 0;
int realState = 1;
int state = 0;
String requestJson = "";
//Pins
#define RELAY 4 //12
#define SWITCH 5 //0
void ICACHE_RAM_ATTR handleInterrupt ();
void setup() {
Serial.begin(9600);
EEPROM.begin(1);
while (!Serial) continue;
delay(10);
Serial.println('\n');
Serial.println("HW: " + String(hwId));
pinMode(SWITCH, INPUT);
pinMode(RELAY, OUTPUT);
state = EEPROM.read(0);
digitalWrite(RELAY, state);
realState = state;
attachInterrupt(digitalPinToInterrupt(SWITCH), handleInterrupt, CHANGE);
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pasw);
checkConnection();
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:");
Serial.println(WiFi.localIP());
Serial.print("MAC address:");
Serial.println(WiFi.macAddress());
jsonContent = {};
jsonContent["token"] = hwId;
jsonContent["values"]["on/off"]["value"] = (String)realState;
serializeJson(jsonContent, requestJson);
Serial.println("JSON: " + requestJson);
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
}
void loop() {
if(unsuccessfulRounds >= 5) {
Serial.println("RESTARTING ESP");
ESP.restart();
}
jsonContent = {};
jsonContent["token"] = hwId;
requestJson = "";
if (buttonActive){
int realStateLocal = digitalRead(SWITCH);
jsonContent["values"]["on/off"]["value"] = (String)realStateLocal;
digitalWrite(RELAY, realStateLocal);
realState = realStateLocal;
EEPROM.write(0, realState);
EEPROM.commit();
serializeJson(jsonContent, requestJson);
Serial.println("JSON: " + requestJson);
//HTTP CLIENT
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
buttonActive = false;
}
jsonContent = {};
jsonContent["token"] = hwId;
requestJson = "";
serializeJson(jsonContent, requestJson);
Serial.println("JSON: " + requestJson);
//HTTP CLIENT
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
if (error) {
Serial.println(error.c_str());
unsuccessfulRounds++;
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
return;
}
//configuration setup
String hostName = jsonContent["device"]["hostname"];
String ipAddress = jsonContent["device"]["ipAddress"];
String gateway = jsonContent["device"]["gateway"];
String subnet = jsonContent["device"]["subnet"];
String requestState = jsonContent["state"];
JsonObject object = jsonContent.as<JsonObject>();
if (!object["value"].isNull()) {
state = (int)jsonContent["value"];
}
if (requestState != "succes") {
unsuccessfulRounds++;
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
} else if (requestState == "succes") {
unsuccessfulRounds = 0;
}
//Set static ip
setStaticIp(ipAddress, gateway, subnet);
WiFi.hostname(hostName);
Serial.println("state: " + (String)state + ", realState: " + (String)realState);
if (state != realState){
if (state == 1 && realState == 0) {
Serial.println("ON state: " + (String)state + ", realState: " + (String)realState);
digitalWrite(RELAY, HIGH); // Turn the LED on by making the voltage LOW
realState = 1;
} else {
Serial.println("OFF");
digitalWrite(RELAY, LOW); // Turn the LED on by making the voltage LOW
realState = 0;
}
EEPROM.write(0, realState);
EEPROM.commit();
}
}
void handleInterrupt() {
interuptCount++;
buttonActive = true;
}
String sendHttpRequest (String requestJson) {
HTTPClient http;
http.setReuse(true);
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
if (httpCode == -1) {
unsuccessfulRounds++;
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
return "";
}
return payload;
}
bool checkConnection() {
int count = 0;
Serial.print("Waiting for Wi-Fi connection");
while ( count < 30 ) {
if (buttonActive){
if (!realState == 1) {
digitalWrite(RELAY, HIGH);
realState = 1;
} else if (!realState == 0){
digitalWrite(RELAY, LOW);
realState = 0;
}
EEPROM.write(0, realState);
EEPROM.commit();
buttonActive = false;
}
delay(250);
if (WiFi.status() == WL_CONNECTED) {
Serial.println();
Serial.println("Connected!");
return (true);
}
Serial.print(".");
count++;
}
Serial.println("Timed out.");
return false;
}
void setStaticIp(String ipAddress, String subnet, String gateway){
//Set static ip
IPAddress staticIpAddress;
IPAddress subnetIpAddress;
IPAddress gatewayIpAddress;
if (
staticIpAddress.fromString(ipAddress) &&
subnetIpAddress.fromString(subnet) &&
gatewayIpAddress.fromString(gateway) &&
WiFi.localIP() != staticIpAddress
) {
WiFi.config(staticIpAddress, subnetIpAddress, gatewayIpAddress);
Serial.print("STATIC IP address:");
Serial.println(WiFi.localIP());
}
}

View File

@ -5,9 +5,9 @@
#include <EEPROM.h> #include <EEPROM.h>
//Variables //Variables
const char* ssid = "ssid"; const char* ssid = "Smart-Home";
const char* pasw = "pasw"; const char* pasw = "S1pjg3684dcCPTUQ";
const char* hwId = "hwId"; const char* hwId = "452r5s8dad";
const char* server = "http://dev.steelants.cz/vasek/home/api.php"; const char* server = "http://dev.steelants.cz/vasek/home/api.php";
int unsuccessfulRounds = 0; //Unsucesful atmpt counter int unsuccessfulRounds = 0; //Unsucesful atmpt counter
StaticJsonDocument<250> jsonContent; StaticJsonDocument<250> jsonContent;

View File

@ -38,6 +38,7 @@ Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
//Read API data //Read API data
$json = file_get_contents('php://input'); $json = file_get_contents('php://input');
$obj = json_decode($json, true); $obj = json_decode($json, true);
$logManager->write("[API] Rest API request body -> decodet to json \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'] != ''){
@ -69,9 +70,10 @@ if (DEBUGMOD != 1) {
//automationExecution //automationExecution
try { try {
AutomationManager::executeAll();
$fallbackManager = new FallbackManager(RANGES); $fallbackManager = new FallbackManager(RANGES);
$fallbackManager->check(); $fallbackManager->check();
AutomationManager::executeAll(); //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);
} }

View File

@ -2,6 +2,9 @@
/** /**
* *
*/ */
class FallbackManager class FallbackManager
{ {
public $deviceDefinitions = ""; public $deviceDefinitions = "";
@ -13,7 +16,7 @@ class FallbackManager
function check(){ function check(){
//TODO: FIX IT //TODO: FIX IT
/*$allDevicesData = DeviceManager::getAllDevices(); $allDevicesData = DeviceManager::getAllDevices();
foreach ($allDevicesData as $deviceKey => $deviceValue) { foreach ($allDevicesData as $deviceKey => $deviceValue) {
$allSubDevicesData = SubDeviceManager::getAllSubDevices($deviceValue['device_id']); $allSubDevicesData = SubDeviceManager::getAllSubDevices($deviceValue['device_id']);
foreach ($allSubDevicesData as $subDeviceKey => $subDeviceValue) { foreach ($allSubDevicesData as $subDeviceKey => $subDeviceValue) {
@ -21,13 +24,21 @@ class FallbackManager
continue; continue;
} }
if (!isset($this->deviceDefinitions[$subDeviceValue['type']]["fallBackTime"])) {
continue;
}
$lastRecord = RecordManager::getLastRecord($subDeviceValue['subdevice_id']); $lastRecord = RecordManager::getLastRecord($subDeviceValue['subdevice_id']);
$minutes = (time() - $lastRecord['time']) / 60; if ($lastRecord["value"] == $this->deviceDefinitions[$subDeviceValue['type']]["fallBack"]) {
echo $minutes; continue;
if ( $minutes > 2){ }
$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"]); RecordManager::create($deviceValue['device_id'], $subDeviceValue['type'], $this->deviceDefinitions[$subDeviceValue['type']]["fallBack"]);
} }
} }
}*/ }
} }
} }

View File

@ -9,6 +9,25 @@ 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
{ {

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

@ -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')) {
require_once('app/controls/' . $this->path . '.php'); include('app/controls/' . $this->path . '.php');
} }
require_once('app/templates/' . $this->path . '.phtml'); require_once('app/templates/' . $this->path . '.phtml');
} }

View File

@ -9,15 +9,15 @@ if (isset($_POST) && !empty($_POST)){
$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);

View File

@ -64,16 +64,16 @@ 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 );
} }
}); });
@ -88,7 +88,7 @@ $("div.square-content").on('touchend', function (e){
$("div.square-content").on('touchstart', function (eTarget) { $("div.square-content").on('touchstart', function (eTarget) {
navigator.vibrate([500]); navigator.vibrate([500]);
var id = ''; var id = '';
var windowLoc = $(location).attr('pathname'); var windowLoc = $(location).attr('pathname');
windowLoc = windowLoc.substring(windowLoc.lastIndexOf("/")); windowLoc = windowLoc.substring(windowLoc.lastIndexOf("/"));
console.log(windowLoc); console.log(windowLoc);
@ -99,9 +99,9 @@ $("div.square-content").on('touchstart', function (eTarget) {
} else if (windowLoc == "/automation") { } else if (windowLoc == "/automation") {
id = $(this).attr('id').replace('automation-', ''); id = $(this).attr('id').replace('automation-', '');
} }
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");
@ -109,7 +109,7 @@ $("div.square-content").on('touchstart', function (eTarget) {
$("#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") {
} else if (windowLoc == "/automation") { } else if (windowLoc == "/automation") {
} }
touch = 0; touch = 0;
@ -117,7 +117,7 @@ $("div.square-content").on('touchstart', function (eTarget) {
return; return;
} }
touchSubId = subId; touchSubId = subId;
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();
@ -202,14 +202,14 @@ var windowLoc = $(location).attr('pathname');
windowLoc = windowLoc.substring(windowLoc.lastIndexOf("/")); windowLoc = windowLoc.substring(windowLoc.lastIndexOf("/"));
console.log(); console.log();
if (windowLoc == "/") { if (windowLoc == "/") {
var selectRoomId = localStorage.getItem("selectedRoomId"); var selectRoomId = localStorage.getItem("selectedRoomId");
if (selectRoomId == null) { if (selectRoomId == null) {
selectRoomId = 'all'; selectRoomId = 'all';
} }
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(){
@ -221,8 +221,8 @@ if (windowLoc == "/") {
} }
} }
}); });
} }
//Room selector //Room selector
@ -239,51 +239,55 @@ $( '[name="room"]' ).change(function (e) {
}); });
} }
}); });
/* /*
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');
var period = $(this).attr('data-period'); var period = $(this).attr('data-period');
var groupBy = $(this).attr('data-group'); var groupBy = $(this).attr('data-group');
ajaxChart(subId, period, groupBy); ajaxChart(subId, period, groupBy);
}); });

View File

@ -22,6 +22,7 @@
</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

@ -22,11 +22,11 @@
</div> </div>
<div class="label"><?php $LANGMNG->echo('l_permission'); ?></div> <div class="label"><?php $LANGMNG->echo('l_permission'); ?></div>
<div class="row"> <div class="row">
<div class="col-6"> <div class="col-6">
<div class="label"> - <?php $LANGMNG->echo('l_owner'); ?></div> <div class="label"> - <?php $LANGMNG->echo('l_owner'); ?></div>
</div> </div>
<div class="col-6"> <div class="col-6">
<?php <?php
$permissions = $DEVICE['permission']; $permissions = $DEVICE['permission'];
@ -40,7 +40,7 @@
<input type="radio" name="permissionOwner" value=1 <?php ECHO ($permissions[0] == 1 ? 'checked' : ''); ?>/><?php $LANGMNG->echo('l_read'); ?> <input type="radio" name="permissionOwner" value=1 <?php ECHO ($permissions[0] == 1 ? 'checked' : ''); ?>/><?php $LANGMNG->echo('l_read'); ?>
<input type="radio" name="permissionOwner" value=2 <?php ECHO ($permissions[0] == 2 ? 'checked' : ''); ?>/><?php $LANGMNG->echo('l_use'); ?> <input type="radio" name="permissionOwner" value=2 <?php ECHO ($permissions[0] == 2 ? 'checked' : ''); ?>/><?php $LANGMNG->echo('l_use'); ?>
<input type="radio" name="permissionOwner" value=3 <?php ECHO ($permissions[0] == 3 ? 'checked' : ''); ?>/><?php $LANGMNG->echo('l_edit'); ?> <input type="radio" name="permissionOwner" value=3 <?php ECHO ($permissions[0] == 3 ? 'checked' : ''); ?>/><?php $LANGMNG->echo('l_edit'); ?>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
@ -156,10 +156,10 @@
<div class="device-button col-4 col-sm-3 col-xl-2 square-wrap"> <div class="device-button col-4 col-sm-3 col-xl-2 square-wrap">
<div class="square"> <div class="square">
<div class="square-content"> <div class="square-content">
<?php echo $DEVICE['name']; ?> <?php echo $DEVICE['name']; ?>
</div> </div>
</div> </div>
</div> </div>

View File

@ -145,6 +145,77 @@ class Ajax extends Template
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

@ -7,11 +7,6 @@ class Home extends Template
{ {
global $userManager; global $userManager;
global $langMng; global $langMng;
$roomManager = new RoomManager();
$deviceManager = new DeviceManager();
$subDeviceManager = new SubDeviceManager();
$recordManager = new RecordManager();
$utilities = new Utilities();
if (!$userManager->isLogin()){ if (!$userManager->isLogin()){
header('Location: ' . BASEDIR . 'login'); header('Location: ' . BASEDIR . 'login');
@ -20,7 +15,7 @@ class Home extends Template
$template = new Template('home'); $template = new Template('home');
//users instantialize //users instantialize
$users = $userManager->getUsers(); $users = UserManager::getUsers();
$template->prepare('users', $users); $template->prepare('users', $users);
//Users at home Info //Users at home Info
@ -39,16 +34,16 @@ class Home extends Template
$roomsItems = []; $roomsItems = [];
$roomsData = $roomManager->getAllRooms(); $roomsData = RoomManager::getAllRooms();
foreach ($roomsData as $roomKey => $roomsData) { foreach ($roomsData as $roomKey => $roomsData) {
$devices = []; $devices = [];
$devicesData = $deviceManager->getAllDevicesInRoom($roomsData['room_id']); $devicesData = DeviceManager::getAllDevicesInRoom($roomsData['room_id']);
foreach ($devicesData as $deviceKey => $deviceData) { foreach ($devicesData as $deviceKey => $deviceData) {
$subDevices = []; $subDevices = [];
$subDevicesData = $subDeviceManager->getAllSubDevices($deviceData['device_id']); $subDevicesData = SubDeviceManager::getAllSubDevices($deviceData['device_id']);
foreach ($subDevicesData as $subDeviceKey => $subDeviceData) { foreach ($subDevicesData as $subDeviceKey => $subDeviceData) {
$events = $recordManager->getLastRecord($subDeviceData['subdevice_id'], 5); $events = RecordManager::getLastRecord($subDeviceData['subdevice_id'], 5);
$eventsRaw = $events; $eventsRaw = $events;
$connectionError = true; $connectionError = true;
@ -105,7 +100,7 @@ class Home extends Template
//parsing last values //parsing last values
$parsedValue = $replacementFalse; $parsedValue = $replacementFalse;
if ($utilities->checkOperator($lastValue, $operator, $breakValue)) { if (Utilities::checkOperator($lastValue, $operator, $breakValue)) {
$parsedValue = $replacementTrue; $parsedValue = $replacementTrue;
} }
@ -113,14 +108,14 @@ 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($value['value'], $operator, $breakValue)) {
$events[$key]['value'] = $replacementTrue; $events[$key]['value'] = $replacementTrue;
} }
} }
} }
$LastRecordTime = new DateTime($lastRecord['time']); $LastRecordTime = new DateTime($lastRecord['time']);
$niceTime = $utilities->ago($LastRecordTime); $niceTime = Utilities::ago($LastRecordTime);
$interval = $LastRecordTime->diff(new DateTime()); $interval = $LastRecordTime->diff(new DateTime());
$hours = $interval->format('%h'); $hours = $interval->format('%h');
@ -180,7 +175,7 @@ class Home extends Template
]; ];
} }
$rooms = $roomManager->getAllRooms(); $rooms = RoomManager::getAllRooms();
$template->prepare('baseDir', BASEDIR); $template->prepare('baseDir', BASEDIR);
$template->prepare('debugMod', DEBUGMOD); $template->prepare('debugMod', DEBUGMOD);
$template->prepare('title', 'Home'); $template->prepare('title', 'Home');

View File

@ -26,6 +26,8 @@ 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);

34
make.sh Normal file
View File

@ -0,0 +1,34 @@
#! /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";

View File

@ -3,20 +3,20 @@
"short_name": "Home", "short_name": "Home",
"description": "Smart Home interface in PWA", "description": "Smart Home interface in PWA",
"lang": "cs-CZ", "lang": "cs-CZ",
"start_url": "/", "start_url": "/vasek/home/",
"scope": "/", "scope": "/vasek/home/",
"display": "fullscreen", "display": "fullscreen",
"orientation": "portrait", "orientation": "portrait",
"theme_color": "#182239", "theme_color": "#182239",
"icons": [ "icons": [
{ {
"src": "/app/templates/images/icon-192x192.png", "src": "/vasek/home/app/templates/images/icon-192x192.png",
"sizes": "192x192" "sizes": "192x192"
}, },
{ {
"src": "/app/templates/images/icon-512x512.png", "src": "/vasek/home/app/templates/images/icon-512x512.png",
"sizes": "512x512" "sizes": "512x512"
} }
], ],
"background_color": "#182239" "background_color": "#182239"
} }

180
old.home Normal file
View File

@ -0,0 +1,180 @@
<!-- <?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" ) );
// }
// }