1
0

a lot of debug

This commit is contained in:
daniel Tartavel 2022-04-23 02:00:52 +02:00
parent f8fc3f63ec
commit d1f1065e44
21 changed files with 544 additions and 217 deletions

View File

@ -47,8 +47,11 @@ function htmlSend($socket, $text, $meta="")
function apiServer($read) function apiServer($read)
{ {
global $topics, $indexDevices, $devices; global $topics, $indexDevices, $devices;
logger(DEBUG, "Function apiServer", __FILE__ . ":" . __LINE__);
$array = array(); $array = array();
$argList =array(); $argList =array();
//logger(DEBUG, _("askWebserver function starting"), __FILE__ . ":" . __LINE__); //logger(DEBUG, _("askWebserver function starting"), __FILE__ . ":" . __LINE__);
if ( stream_select( $read, $array, $array, 0 )) if ( stream_select( $read, $array, $array, 0 ))
{ {
@ -88,41 +91,54 @@ function apiServer($read)
switch($command) switch($command)
{ {
case "dashboard": case "dashboard":
webDashboard($spawn, $argList["dashboard"]); apiDashboard($spawn, $argList["dashboard"]);
break; break;
case "browse": case "browse":
logger(DEBUG, _("Browsing"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("Browsing"), __FILE__ . ":" . __LINE__);
webBrowse($spawn, $argList); apiBrowse($spawn, $argList);
//return true; //return true;
break; break;
case "get": case "get":
logger(DEBUG, _("GET reached"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("GET reached"), __FILE__ . ":" . __LINE__);
htmlSend($spawn, webGet($argList)); htmlSend($spawn, apiGet($argList));
break; break;
case "set": case "set":
logger(DEBUG, _("SET reached"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("SET reached"), __FILE__ . ":" . __LINE__);
htmlSend($spawn, webSet($argList)); htmlSend($spawn, apiSet($argList));
break; break;
case "dump": case "dump":
case "print": case "print":
logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__); logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__);
htmlSend($spawn, webPrint($argList, $command)); htmlSend($spawn, apiPrint($argList, $command));
break; break;
case "notify": case "notify":
logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__); logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__);
htmlSend($spawn, webNotify($argList)); htmlSend($spawn, apiNotify($argList));
logger(DEBUG, print_r($monitored, true), __FILE__ . ":" . __LINE__); logger(DEBUG, print_r($monitored, true), __FILE__ . ":" . __LINE__);
break; break;
case "type": case "type":
logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__); logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__);
//htmlSend($spawn, webDisplayByType($argList)); //htmlSend($spawn, apiDisplayByType($argList));
/*case "stats": /*case "stats":
logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__); logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__);
displayStats($spawn, $argList);*/ displayStats($spawn, $argList);*/
break;
case "verbose":
logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__);
htmlSend($spawn, apiVerbose($argList));
break;
case "friendlyname":
logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__);
htmlSend($spawn, getFn($argList));
break;
case "property":
logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__);
htmlSend($spawn, PropertiesDashboard($argList));
break;
default: default:
if (is_numeric(array_key_first($argList))) if (is_numeric(array_key_first($argList)))
{ {
webDashboard($spawn, $argList[0]); apiDashboard($spawn, $argList[0]);
}else }else
{ {
logger(DEBUG, $command . _(" so default action"), __FILE__ . ":" . __LINE__); logger(DEBUG, $command . _(" so default action"), __FILE__ . ":" . __LINE__);
@ -141,11 +157,11 @@ function apiServer($read)
} }
}else }else
{ {
webDashboard($spawn); apiDashboard($spawn);
} }
}else }else
{ {
webDashboard($spawn); apiDashboard($spawn);
} }
} }
} }

View File

@ -1,11 +1,11 @@
<?php <?php
require_once "events.php"; require_once "events.php";
function webDashboard($socket, $n="Général") function apiDashboard($socket, $n="Général")
{ {
global $dashboards, $indexDevices; global $dashboards, $indexDevices;
require_once "apiserver/javascript.php"; require_once "apiserver/javascript.php";
logger(DEBUG, _("webDashboard function"), __FILE__ . ":" . __LINE__); logger(INFO, _("apiDashboard function"), __FILE__ . ":" . __LINE__);
$response = insertJavascript(); $response = insertJavascript();
if(array_key_exists($n, $dashboards)) if(array_key_exists($n, $dashboards))
@ -20,7 +20,7 @@ function webDashboard($socket, $n="Général")
{ {
$propertyObject = $device->properties[$property]; $propertyObject = $device->properties[$property];
$value = $propertyObject["value"]; $value = $propertyObject["value"];
logger(DEBUG, $device->friendlyName . " => " . bool2string(_($value))); logger(DEBUG, $device->friendlyName . " => " . bool2string(_($value)), __FILE__ . ":" . __LINE__);
$response .= $device->friendlyName . aliases($device->friendlyName, $property) . ' => '; $response .= $device->friendlyName . aliases($device->friendlyName, $property) . ' => ';
if (array_key_exists("access", $propertyObject)) if (array_key_exists("access", $propertyObject))
{ {
@ -130,7 +130,7 @@ function displayChoice($device, $propertyName, $value)
function mkHTML($device, $propertyName, $choice) function mkHTML($device, $propertyName, $choice)
{ {
$html = ""; $html = "";
logger(DEBUG, "function mkHTML", __FILE__ . ":" . __LINE__); logger(INFO, "function mkHTML", __FILE__ . ":" . __LINE__);
foreach ($choice as $key => $value) foreach ($choice as $key => $value)
{ {
$html .= '<input type="button" id="' . $device->topic ."/" . $device->friendlyName . "/" . $propertyName . "/" . strtolower($value) . '" value="' . $value . "\" onmouseup=\"setPropertyValue('" . $device->topic . "', '" . $device->friendlyName . "', '" . $value . "', '" . $propertyName . "')\">"; $html .= '<input type="button" id="' . $device->topic ."/" . $device->friendlyName . "/" . $propertyName . "/" . strtolower($value) . '" value="' . $value . "\" onmouseup=\"setPropertyValue('" . $device->topic . "', '" . $device->friendlyName . "', '" . $value . "', '" . $propertyName . "')\">";
@ -138,10 +138,10 @@ function mkHTML($device, $propertyName, $choice)
return $html; return $html;
} }
function webBrowse($socket, $argList, $page="/browse") function apiBrowse($socket, $argList, $page="/browse")
{ {
global $topics, $devices, $listenPort,$indexDevices; global $topics, $devices, $listenPort,$indexDevices;
logger(DEBUG, _("Generic response to choose device and property"), __FILE__ . ":" . __LINE__); logger(INFO, _("Generic response to choose device and property"), __FILE__ . ":" . __LINE__);
//$response = "<html><header></header><body>" . _("unknown command") . "</body></html>"; //$response = "<html><header></header><body>" . _("unknown command") . "</body></html>";
$response = ""; $response = "";
$flag = false; $flag = false;
@ -220,11 +220,11 @@ function webBrowse($socket, $argList, $page="/browse")
} }
}else }else
{ {
$response = webListTopics(); $response = apiListTopics();
} }
}else }else
{ {
$response = webListTopics(); $response = apiListTopics();
} }
htmlSend($socket, $response); htmlSend($socket, $response);
} }
@ -279,10 +279,10 @@ function iterateProperty($device, $property, $value, &$response, $tab="")
} }
} }
function webListTopics() function apiListTopics()
{ {
global $topics; global $topics;
logger(DEBUG, _("webListTopics function")); logger(INFO, _("apiListTopics function"), __FILE__ . ":" . __LINE__);
$response = ""; $response = "";
foreach ($topics as $name => $topic) foreach ($topics as $name => $topic)
{ {
@ -291,7 +291,7 @@ function webListTopics()
return $response; return $response;
} }
function webGet($argList) function apiGet($argList)
{ {
if(!array_key_exists("topic", $argList) or !array_key_exists("fn", $argList) or !array_key_exists("property", $argList)) if(!array_key_exists("topic", $argList) or !array_key_exists("fn", $argList) or !array_key_exists("property", $argList))
{ {
@ -313,7 +313,7 @@ function webGet($argList)
return $response; return $response;
} }
function webSet($argList) function apiSet($argList)
{ {
global $indexFriendlyName; global $indexFriendlyName;
if(!array_key_exists("topic", $argList) or !array_key_exists("fn", $argList) or !array_key_exists("property", $argList) or !array_key_exists("value", $argList)) if(!array_key_exists("topic", $argList) or !array_key_exists("fn", $argList) or !array_key_exists("property", $argList) or !array_key_exists("value", $argList))
@ -331,13 +331,13 @@ function webSet($argList)
{ {
$response = "setting property " . $argList["property"] . " of " . $argList["fn"] . " to value: " . $argList["value"]; $response = "setting property " . $argList["property"] . " of " . $argList["fn"] . " to value: " . $argList["value"];
$payload = array($argList["property"] => $argList["value"]); $payload = array($argList["property"] => $argList["value"]);
publish($argList["topic"] . "/" . $argList["fn"], $payload); publish($argList["topic"] . "/" . $argList["fn"], $payload, "set");
//removeEvent($indexFriendlyName($argList["fn"]), $argList["property"], "OFF"); //removeEvent($indexFriendlyName($argList["fn"]), $argList["property"], "OFF");
} }
return $response; return $response;
} }
function webPrint($argList, $command) function apiPrint($argList, $command)
{ {
global $GLOBALS, $topics; global $GLOBALS, $topics;
if (array_key_exists($argList["object"], $GLOBALS)) if (array_key_exists($argList["object"], $GLOBALS))
@ -386,7 +386,7 @@ function webPrint($argList, $command)
return $response; return $response;
} }
function webNotify($argList) function apiNotify($argList)
{ {
if (!array_key_exists("topic", $argList) or !array_key_exists("fn", $argList) or !array_key_exists("property", $argList) or !array_key_exists("condition", $argList) or !array_key_exists("value", $argList)) if (!array_key_exists("topic", $argList) or !array_key_exists("fn", $argList) or !array_key_exists("property", $argList) or !array_key_exists("condition", $argList) or !array_key_exists("value", $argList))
{ {
@ -398,8 +398,118 @@ function webNotify($argList)
} }
return $response; return $response;
} }
function apiVerbose($argList)
{
global $logLevel, $logLevels;
logger(INFO, _("apiVerbose function"), __FILE__ . ":" . __LINE__);
$response = "";
//print_r($argList);
foreach ($logLevels as $value => $level)
{
//print $level . " => " . $value . " ==>" . strtoupper(trim($argList["cmd"])) . EOL;
if (strtoupper(trim($argList["verbose"])) == $level)
{
print "change of " . $level . EOL;
$logLevel ^= $value;
}
if ($logLevel & $value)
{
$response .= $level . _(" is active") . EOLH;
}else
{
$response .= $level . _(" is inactive") . EOLH;
}
}
return $response;
}
function getFn($argList)
{
global $indexDevices;
$jsonArray = array();
logger(INFO, _("getFn function"), __FILE__ . ":" . __LINE__);
if (array_key_exists("ieeeAddress", $argList))
{
logger(DEBUG, "ieeeAddress = " . $argList["ieeeAddress"], __FILE__ . ":" . __LINE__);
if (array_key_exists($argList["ieeeAddress"], $indexDevices))
{
logger(DEBUG, "FriendlyName is " . $indexDevices[$argList["ieeeAddress"]]->friendlyName, __FILE__ . ":" . __LINE__);
$response = '["' . $argList["ieeeAddress"] . '":"' . $indexDevices[$argList["ieeeAddress"]]->friendlyName . '"]';
}
}else
{
$flag = false;
//$response = "{";
foreach($indexDevices as $ieeeAddress => $device)
{
/*if ($flag == false)
{
$flag = true;
}else
{
$response .= ', ';
}
*/
//$response .= '"' . $ieeeAddress . '" : "' . $indexDevices[$ieeeAddress]->friendlyName . '"';
$jsonArray[$ieeeAddress] = $indexDevices[$ieeeAddress]->friendlyName;
array_multisort($jsonArray);
}
$response = json_encode($jsonArray, JSON_UNESCAPED_SLASHES);
print $response;
//print_r(json_decode($response));
}
logger(DEBUG, "response = " . $response, __FILE__ . ":" . __LINE__);
return $response;
}
function PropertiesDashboard($argList)
{
global $indexProperties;
require_once "apiserver/javascript.php";
logger(INFO, _("propertiesDashboard function"), __FILE__ . ":" . __LINE__);
$response = insertJavascript();
$property = $argList["property"];
foreach ($indexProperties[$property] as $device)
{
$propertyObject = $device->properties[$property];
$value = $propertyObject["value"];
logger(DEBUG, $device->friendlyName . " => " . bool2string(_($value)), __FILE__ . ":" . __LINE__);
$response .= $device->friendlyName . aliases($device->friendlyName, $property) . ' => ';
if (array_key_exists("access", $propertyObject))
{
logger(DEBUG, _("Access = ") . $propertyObject["access"], __FILE__ . ":" . __LINE__);
if(($propertyObject["access"] & 2))
{
logger(DEBUG, _("Write Access OK ") . ($propertyObject["access"] & 2), __FILE__ . ":" . __LINE__);
$response .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . displayChoice($device, $property, $value);
}
if(($propertyObject["access"] & 4))
{
logger(DEBUG, _("can get value") . ($propertyObject["access"] & 4), __FILE__ . ":" . __LINE__);
$response .= '<input type="button" id="' . $device->topic ."/" . $device->friendlyName . "/" . $propertyObject["name"] . '" value="' . _("Update") . "\" onmouseup=\"getPropertyValue('" . $device->topic . "','" . $device->friendlyName . "','" . $propertyObject["name"] . "')\">";
}else
{
$response .= $value;
}
$response .= EOLH;
}else
{
$response .= bool2string(_($value));
if(array_key_exists("unit", $propertyObject))
{
$response .= $propertyObject["unit"];
logger(DEBUG, _("unit = ") . $unit, __FILE__ . ":" . __LINE__);
}
$response .= EOLH;
}
}
return "json=" . $response;
}
/* /*
function webDisplayByType($argList) function apiDisplayByType($argList)
{ {
global $indexTypes, $config; global $indexTypes, $config;
require_once $config . "porpertiesbytype.php"; require_once $config . "porpertiesbytype.php";

View File

@ -24,23 +24,25 @@ class hook
function installHooks(&$indexDevices) function installHooks(&$indexDevices)
{ {
global $devices; global $devices, $devicesRequest;
static $requestflag = 0;
$result = true; $result = true;
// assigne the function to the sensors devices // assigne the function to the sensors devices
if ($this->active === true) if ($this->active === true)
{ {
foreach ($this->devicelist as $ieeeAddress => $property) foreach ($this->devicelist as $ieeeAddress => $property)
{ {
if (array_key_exists($ieeeAddress, $devices)) if (array_key_exists($ieeeAddress, $indexDevices))
{ {
logger(DEBUG, _("Device: ") . $ieeeAddress, __FILE__ . ":" . __LINE__); logger(DEBUG, _("Device: ") . $ieeeAddress, __FILE__ . ":" . __LINE__);
if ($this->propertyInitialized[$ieeeAddress][$property] === false) if (!array_key_exists($this->hookName, $indexDevices[$ieeeAddress]->properties[$property]["functions"]))
{
if (array_key_exists($property, $indexDevices[$ieeeAddress]->properties))
{ {
logger(DEBUG, _("Trying to store callback"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("Trying to store callback"), __FILE__ . ":" . __LINE__);
if (array_key_exists("functions", $indexDevices[$ieeeAddress]->properties[$property])) if (array_key_exists("functions", $indexDevices[$ieeeAddress]->properties[$property]))
{ {
$indexDevices[$ieeeAddress]->properties[$property]["functions"][$this->hookName] = array($this,"callback"); $indexDevices[$ieeeAddress]->properties[$property]["functions"][$this->hookName] = array($this,"callback");
$this->propertyInitialized[$ieeeAddress][$property] = true;
logger(DEBUG, sprintf(_("Property '%s' of %s is initialized with callback"), $property, $indexDevices[$ieeeAddress]->friendlyName), __FILE__ . ":" . __LINE__); logger(DEBUG, sprintf(_("Property '%s' of %s is initialized with callback"), $property, $indexDevices[$ieeeAddress]->friendlyName), __FILE__ . ":" . __LINE__);
}else }else
@ -49,12 +51,27 @@ class hook
$result = false; $result = false;
} }
}else }else
{
logger(WARNING, sprintf(_("Hook %s can not initialize Property '%s' of device %s : property does not exists"), $this->hookName, $property, $indexDevices[$ieeeAddress]->friendlyName), __FILE__ . ":" . __LINE__);
$result = false;
}
}else
{ {
logger(DEBUG, _("Callback already installed"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("Callback already installed"), __FILE__ . ":" . __LINE__);
} }
}else }else
{ {
logger(ERROR, $ieeeAddress . (" does not exists"), __FILE__ . ":" . __LINE__); logger(ERROR, $ieeeAddress . (" does not exists"), __FILE__ . ":" . __LINE__);
if ($devicesRequest === false)
{
publish("zigbee2mqtt", array("bridge/devices" => ""), "get");
$devicesRequest = true;
}elseif ($requestflag++ > 30)
{
$requestflag = 0;
}
$result = false;
mkIndexes(); mkIndexes();
} }

View File

@ -15,7 +15,8 @@
array(METEO, "rainin"), array(METEO, "rainin"),
array(METEO, "barominmb"), array(METEO, "barominmb"),
array(METEO, "UV"), array(METEO, "UV"),
array(METEO, "solarradiation") array(METEO, "solarradiation"),
array(RDC_STORE, "position")
); );
$dashboards["etage"] = array( $dashboards["etage"] = array(
array(ETAGE_SALON_RADIATEUR,"current_heating_setpoint"), array(ETAGE_SALON_RADIATEUR,"current_heating_setpoint"),

View File

@ -27,4 +27,5 @@ foreach ($logLevels as $key => $string)
$logLevels[6] = "NOTICE & WARNING"; $logLevels[6] = "NOTICE & WARNING";
define( "ALL", DEBUG | INFO | NOTICE | WARNING | ERROR | ALERT); define( "ALL", DEBUG | INFO | NOTICE | WARNING | ERROR | ALERT);
define("NOTIF_DEFAULT_DEST", "daniel");
?> ?>

View File

@ -9,7 +9,7 @@ function storeDB($db, $filepath)
$data = serialize($db); $data = serialize($db);
if (file_put_contents($filepath, $data) === false) if (file_put_contents($filepath, $data) === false)
{ {
logger(DEBUG,_("Failed storing database ") . $filepath , __FILE__ . ":" . __LINE__); logger(ALERT,_("Failed storing database ") . $filepath , __FILE__ . ":" . __LINE__);
return false; return false;
}else }else
{ {
@ -23,20 +23,24 @@ function loadDB($filepath)
$data = file_get_contents($filepath); $data = file_get_contents($filepath);
if ($data === false) if ($data === false)
{ {
logger(DEBUG,_("Failed loading database ") . $filepath , __FILE__ . ":" . __LINE__); logger(ALERT,_("Failed loading database ") . $filepath , __FILE__ . ":" . __LINE__);
return false; return false;
} }
$db = unserialize($data); if (($db = unserialize($data)) === false)
{
logger(ALERT,_("Failed unserializing database ") . $filepath , __FILE__ . ":" . __LINE__);
}
return $db; return $db;
} }
function mkDevicesDB($topic, $json, $group=false) function mkDevicesDB($topic, $json, $group=false)
{ {
global $devices, $listProperties, $listPropertiesKeys, $indexDevices, $dbInit, $logFh, $hooks, $indexFriendlyNames; global $devices, $listProperties, $listPropertiesKeys, $indexDevices, $dbInit, $logFh, $hooks, $indexFriendlyNames;
if (!isset($devices[$topic])) if (!array_key_exists($topic, $devices))
{ {
$devices[$topic]= array(); $devices[$topic]= array();
} }
//fwrite($logFh, var_export($json, true));
//print_r($json); //print_r($json);
foreach ($json as $jsonDevice) foreach ($json as $jsonDevice)
{ {
@ -57,7 +61,7 @@ function addDevice($topic, $fn, $jsonDevice, $group=false )
global $devices, $listProperties, $listPropertiesKeys, $hooks, $indexDevices, $indexFriendlyNames; global $devices, $listProperties, $listPropertiesKeys, $hooks, $indexDevices, $indexFriendlyNames;
$fnTree = explode("/", $fn); $fnTree = explode("/", $fn);
$device = & $devices[$topic]; $device = & $devices[$topic];
print_r($jsonDevice); //print_r($jsonDevice);
foreach($fnTree as $fnPart) foreach($fnTree as $fnPart)
{ {
if (!array_key_exists($fnPart, $device)) if (!array_key_exists($fnPart, $device))
@ -108,13 +112,13 @@ function searchPropertyKey($fn, &$device, $inputObject, $listPropertiesKeys)
{ {
//foreach($listPropertiesKeys as $propertyKey) //foreach($listPropertiesKeys as $propertyKey)
//{ //{
logger(DEBUG, _("searching for property"), __FILE__ . ":" . __LINE__ ); //logger(DEBUG, _("searching for property"), __FILE__ . ":" . __LINE__ );
//if (is_object($inputObject)) //if (is_object($inputObject))
//{ //{
//print_r($inputObject); //print_r($inputObject);
if (array_key_exists("property", $inputObject)) if (array_key_exists("property", $inputObject))
{ {
logger(DEBUG, _("property Key exists filling properties"), __FILE__ . ":" . __LINE__ ); //logger(DEBUG, _("property Key exists filling properties"), __FILE__ . ":" . __LINE__ );
$string = $inputObject["property"]; $string = $inputObject["property"];
if (!array_key_exists($string, $device->properties)) if (!array_key_exists($string, $device->properties))
{ {
@ -136,11 +140,14 @@ function searchPropertyKey($fn, &$device, $inputObject, $listPropertiesKeys)
{ {
$device->type = $inputObject["type"]; $device->type = $inputObject["type"];
} }
/*foreach($inputObject as $key => $value) foreach($inputObject as $key => $value)
{
//logger(DEBUG, sprintf(_("key = %s"), $key), __FILE__ . ":" . __LINE__ );
if (is_array($value))
{ {
logger(DEBUG, sprintf(_("key = %s"), $key), __FILE__ . ":" . __LINE__ );
searchPropertyKey($fn, $device, $value, $listPropertiesKeys); searchPropertyKey($fn, $device, $value, $listPropertiesKeys);
}*/ }
}
} }
//print_r($device); //print_r($device);
//} //}
@ -247,12 +254,16 @@ function getDevicesValues($topic)
if ($value["access"] & 4) if ($value["access"] & 4)
{ {
$device->payload[$property] = ""; $device->payload[$property] = "";
$flag = true;
break; break;
} }
} }
} }
//logger(DEBUG, print_r($device->payload, true), __FILE__ . ":" . __LINE__ ); //logger(DEBUG, print_r($device->payload, true), __FILE__ . ":" . __LINE__ );
if ($flag === true)
{
$device->get(); $device->get();
}
}else }else
{ {
logger(DEBUG, _("no properties to get for device: " . $device->friendlyName ), __FILE__ . ":" . __LINE__ ); logger(DEBUG, _("no properties to get for device: " . $device->friendlyName ), __FILE__ . ":" . __LINE__ );
@ -302,24 +313,32 @@ function mkIndexes()
function iterate2device(&$object) function iterate2device(&$object)
{ {
global $indexDevices, $indexFriendlyNames, $indexTypes; global $indexDevices, $indexFriendlyNames, $indexTypes, $indexProperties;
foreach ($object as $key => &$device) foreach ($object as $key => &$device)
{ {
if (is_a($device, "device")) if (is_a($device, "device"))
{ {
$object = &$device; //$object = &$device;
//print("=============" . $device->friendlyName); //print("=============" . $device->friendlyName);
//if (!array_key_exists($object->ieeeAddress, $indexDevices)) //if (!array_key_exists($object->ieeeAddress, $indexDevices))
//{ //{
//print("============>"); //print("============>");
$indexDevices[$object->ieeeAddress] = &$object; $indexDevices[$device->ieeeAddress] = &$device;
$indexFriendlyNames[$object->friendlyName] = &$object; $indexFriendlyNames[$device->friendlyName] = &$device;
if (property_exists($object, "type")) if (property_exists($device, "type"))
{ {
$indexTypes[$object->type][] = &$object; $indexTypes[$device->type][] = &$object;
}
$properties = array_keys($device->properties);
foreach($properties as $property)
{
$indexProperties[$property][$device->ieeeAddress] = &$device;
} }
//} //}
//return true;
}elseif (empty($device))
{
return true; return true;
}else }else
{ {

View File

@ -8,7 +8,7 @@ function checkEvents()
{ {
global $logLevel, $events; global $logLevel, $events;
$oldLevel = $logLevel; $oldLevel = $logLevel;
$logLevel = DEBUG; //$logLevel = DEBUG;
$exception = false; $exception = false;
if ($events === null) if ($events === null)
{ {
@ -68,10 +68,12 @@ function checkEvents()
} }
} }
//print_r($events); //print_r($events);
$logLevel = $oldLevel; //$logLevel = $oldLevel;
} }
function setOneshotEvent(&$deviceObject, $datetime, $property, $value, $replace=false, $method=null) // datetime format : "yyyy-mm-dd hh:mm:ss"
function setOneshotEvent(device &$deviceObject, string $datetime, $property, $value, $replace=false, $method=null)
{ {
global $events; global $events;
$events[] = new event; $events[] = new event;
@ -85,18 +87,20 @@ function setOneshotEvent(&$deviceObject, $datetime, $property, $value, $replace=
if ($method !==null) $events[$key]->method =$method; if ($method !==null) $events[$key]->method =$method;
} }
function setRecurrentEvent(&$deviceObject, $property, $value, $startDatetime, $stopDatetime, $hours, $minutes, $seconds, $days, $weeks, $months, $years, $method = null) // startDatetime and stopDatetime format : "yyyy-mm-dd hh:mm:ss"
function setRecurrentEvent(device &$deviceObject, string $property, $value, string $startDatetime, string $stopDatetime, int $hours, int $minutes, int $seconds, int $days, int $weeks, int $months, int $years, int $method = null)
{ {
global $events; global $events;
$string = "P"; $string = "P";
if (!empty($years)) $string .= $days . "Y"; if (!empty($years)) $string .= $years . "Y";
if (!empty($months)) $string .= $days . "M"; if (!empty($months)) $string .= $months . "M";
if (!empty($week)) $string .= $week . "W"; if (!empty($week)) $string .= $week . "W";
if (!empty($days)) $string .= $days . "D"; if (!empty($days)) $string .= $days . "D";
$string .= "T"; $string .= "T";
if (!empty($hours)) $string .= $days . "H"; if (!empty($hours)) $string .= $hours . "H";
if (!empty($months)) $string .= $days . "M"; if (!empty($months)) $string .= $months . "M";
if (!empty($seconds)) $string .= $days . "S"; if (!empty($seconds)) $string .= $seconds . "S";
$event = new event; $event = new event;
@ -117,7 +121,7 @@ function setRecurrentEvent(&$deviceObject, $property, $value, $startDatetime, $s
if ($method !== null) $event->method = $method; if ($method !== null) $event->method = $method;
} }
function setDelay(&$deviceObject, $delay, $unit, $property, $value, $replace=false, $method = null) function setDelay(device &$deviceObject, float $delay, string $unit, string $property, $value, bool $replace=false, int $method = null)
{ {
global $events, $logLevel; global $events, $logLevel;
$oldLevel = $logLevel; $oldLevel = $logLevel;
@ -160,7 +164,7 @@ function setDelay(&$deviceObject, $delay, $unit, $property, $value, $replace=fal
if ($replace) if ($replace)
{ {
$eventKey = searchEvent($deviceObject, $property, $value); $eventKey = searchEvent($deviceObject, $property, $value);
if ($eventKey !== false) deleteEvent($events[$eventKey]); if ($eventKey !== false) deleteEvent($eventKey);
} }
//$dt = $datetime->format("Y-m-d\TH:i:s\Z"); //$dt = $datetime->format("Y-m-d\TH:i:s\Z");
$events[] = new event; $events[] = new event;
@ -177,7 +181,7 @@ function setDelay(&$deviceObject, $delay, $unit, $property, $value, $replace=fal
$logLevel = $oldLevel; $logLevel = $oldLevel;
} }
function removeEvent($deviceObject, $property , $value, $method = null) function removeEvent(device $deviceObject, string $property , $value, int $method = null)
{ {
global $events; global $events;
$eventKey = searchEvent($deviceObject, $property , $value); $eventKey = searchEvent($deviceObject, $property , $value);
@ -188,7 +192,7 @@ function removeEvent($deviceObject, $property , $value, $method = null)
} }
} }
function searchEvent($deviceObject, $property , $value) function searchEvent(device $deviceObject, string $property , $value)
{ {
global $events; global $events;
logger(DEBUG, sprintf(_("searching event for device %s, property %s and value %s"), $deviceObject->friendlyName, $property, bool2string($value)), __FILE__ . ":" . __LINE__); logger(DEBUG, sprintf(_("searching event for device %s, property %s and value %s"), $deviceObject->friendlyName, $property, bool2string($value)), __FILE__ . ":" . __LINE__);
@ -205,7 +209,7 @@ function searchEvent($deviceObject, $property , $value)
} }
// warning delete event does not manage method of the device (IDLE, ) // warning delete event does not manage method of the device (IDLE, )
function deleteEvent($eventKey) function deleteEvent(int $eventKey)
{ {
global $events; global $events;
if ($eventKey !== false) if ($eventKey !== false)

View File

@ -6,7 +6,7 @@ class notificationFreemobile
public $active = true; public $active = true;
public $level; public $level;
private $dest = array( private $dest = array(
"32886706&pass=JTGUY6l5OG73zX", //daniel "daniel" => "32886706&pass=JTGUY6l5OG73zX",
); );
function __construct() function __construct()
@ -14,7 +14,7 @@ class notificationFreemobile
$this->level = ALERT | ERROR; $this->level = ALERT | ERROR;
} }
function send($message, $destinataire=0) function send($message, $destinataire=NOTIF_DEFAULT_DEST)
{ {
global $curlErr; global $curlErr;
$result = false; $result = false;
@ -22,7 +22,7 @@ class notificationFreemobile
{ {
$ch = curl_init(); $ch = curl_init();
// set url // set url
curl_setopt($ch, CURLOPT_URL, $this->url . $this->dest["destinataire"] . "&msg=" . urlencode(trim($message))); curl_setopt($ch, CURLOPT_URL, $this->url . $this->dest[$destinataire] . "&msg=" . urlencode(trim($message)));
echo $this->url . urlencode(trim($message)) . EOL; echo $this->url . urlencode(trim($message)) . EOL;
//return the transfer as a string //return the transfer as a string
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

View File

@ -26,8 +26,9 @@ class rdc_salon_eclairage extends hook
$lux = $indexDevices[RDC_SALON_LUMINOSITE]; $lux = $indexDevices[RDC_SALON_LUMINOSITE];
$mvmt = $indexDevices[RDC_SALON_MVMT]; $mvmt = $indexDevices[RDC_SALON_MVMT];
$mvmt2 = $indexDevices[RDC_SALON_MVMT2]; $mvmt2 = $indexDevices[RDC_SALON_MVMT2];
logger (INFO, _("property => ") . $param . _("value =>") . bool2string($value), __FILE__ . ":" . __LINE__); $illuminance = getValue(RDC_SALON_LUMINOSITE, "illuminance_lux");
logger (INFO, _("property => ") . $param . _("value =>") . bool2string($value), __FILE__ . ":" . __LINE__);
switch($param) switch($param)
{ {
case "occupancy": case "occupancy":
@ -35,7 +36,6 @@ class rdc_salon_eclairage extends hook
//print_r(getValue(RDC_SALON_LUMINOSITE, "illuminance_lux")); //print_r(getValue(RDC_SALON_LUMINOSITE, "illuminance_lux"));
if ($value == ON) if ($value == ON)
{ {
$illuminance = getValue(RDC_SALON_LUMINOSITE, "illuminance_lux");
logger(INFO, _("illuminance value : ") . $illuminance, __FILE__ . ":" . __LINE__); logger(INFO, _("illuminance value : ") . $illuminance, __FILE__ . ":" . __LINE__);
if ($illuminance <= $this->luminance_min) if ($illuminance <= $this->luminance_min)
{ {
@ -49,14 +49,14 @@ class rdc_salon_eclairage extends hook
if (getValue(RDC_SALON_MVMT, "occupancy") == OFF and (getValue(RDC_SALON_MVMT2, "occupancy") == OFF)) if (getValue(RDC_SALON_MVMT, "occupancy") == OFF and (getValue(RDC_SALON_MVMT2, "occupancy") == OFF))
{ {
logger(INFO, _("Setting to OFF"), __FILE__ . ":" . __LINE__); logger(INFO, _("Setting to OFF"), __FILE__ . ":" . __LINE__);
//setDelay($deviceTarget, $this->delay, $this->timeUnit, "state", "OFF", true); setDelay($deviceTarget, $this->delay, $this->timeUnit, "state", "OFF", true);
$this->send($deviceTarget, "OFF", false, IDLE); //$this->send($deviceTarget, "OFF", false, IDLE);
} }
} }
break; break;
case "contact": case "contact":
logger(INFO, _("CASE: Contact Door"), __FILE__ . ":" . __LINE__); logger(INFO, _("CASE: Contact Door"), __FILE__ . ":" . __LINE__);
if ($value == false and getValue(RDC_SALON_LUMINOSITE, "illuminance_lux") <= $this->luminance_min) if ($value == false and $illuminance <= $this->luminance_min)
{ {
logger(INFO, _("Door is open and illumance < min"), __FILE__ . ":" . __LINE__); logger(INFO, _("Door is open and illumance < min"), __FILE__ . ":" . __LINE__);
if ($deviceTarget->properties["state"]["method"] !== MANUAL) if ($deviceTarget->properties["state"]["method"] !== MANUAL)

View File

@ -14,8 +14,9 @@ class rdc_store extends hook
protected $propertyInitialized =array(); protected $propertyInitialized =array();
protected $devicelist = array( protected $devicelist = array(
RDC_EXTERIEUR_LUMINOSITE => "illuminance_lux", RDC_EXTERIEUR_LUMINOSITE => "illuminance_lux",
RDC_SALON_LUMINOSITE => "illuminance_lux",
METEO => "rainin", METEO => "rainin",
//METEO => "solarradiation", METEO => "solarradiation",
METEO => "windspeedkmh", METEO => "windspeedkmh",
METEO => "windgustkmh" METEO => "windgustkmh"
); );
@ -35,7 +36,7 @@ class rdc_store extends hook
$rafale = 0; $rafale = 0;
$soleil = 0; $soleil = 0;
$storeDevice = $indexDevices[RDC_STORE]; $storeDevice = $indexDevices[RDC_STORE];
$maxLevel = 100; $this->maxLevel = 100;
$r = 100; $r = 100;
if (array_key_exists("position", $storeDevice->properties)) if (array_key_exists("position", $storeDevice->properties))
@ -50,11 +51,19 @@ class rdc_store extends hook
if (array_key_exists("illuminance_lux", $indexDevices[RDC_EXTERIEUR_LUMINOSITE]->properties)) if (array_key_exists("illuminance_lux", $indexDevices[RDC_EXTERIEUR_LUMINOSITE]->properties))
{ {
$exterieur_lux = $mohaDB->moyenne($indexDevices[RDC_EXTERIEUR_LUMINOSITE], "illuminance_lux", 15); $exterieur_lux = $mohaDB->moyenne($indexDevices[RDC_EXTERIEUR_LUMINOSITE], "illuminance_lux", 15);
if ($exterieur_lux == 0)
{
$exterieur_lux = $indexDevices[RDC_EXTERIEUR_LUMINOSITE]->properties["illuminance_lux"]["value"];
}
logger(DEBUG, "exterieur_lux=" . $exterieur_lux, __FILE__ . ":" . __LINE__); logger(DEBUG, "exterieur_lux=" . $exterieur_lux, __FILE__ . ":" . __LINE__);
} }
if (array_key_exists("illuminance_lux", $indexDevices[RDC_SALON_LUMINOSITE]->properties)) if (array_key_exists("illuminance_lux", $indexDevices[RDC_SALON_LUMINOSITE]->properties))
{ {
$salon_lux = $mohaDB->moyenne($indexDevices[RDC_SALON_LUMINOSITE], "illuminance_lux", 10); $salon_lux = $mohaDB->moyenne($indexDevices[RDC_SALON_LUMINOSITE], "illuminance_lux", 10);
if ($salon_lux == 0)
{
$salon_lux = $indexDevices[RDC_SALON_LUMINOSITE]->properties["illuminance_lux"]["value"];
}
logger(DEBUG, "salon_lux=" . $salon_lux, __FILE__ . ":" . __LINE__); logger(DEBUG, "salon_lux=" . $salon_lux, __FILE__ . ":" . __LINE__);
} }
if (array_key_exists(METEO, $indexDevices)) if (array_key_exists(METEO, $indexDevices))
@ -66,13 +75,17 @@ class rdc_store extends hook
} }
if (array_key_exists("windgustkmh", $indexDevices[METEO]->properties)) if (array_key_exists("windgustkmh", $indexDevices[METEO]->properties))
{ {
$rafale = $mohaDB->moyenne($indexDevices[METEO], "windgustkmh", 12); if ($indexDevices[METEO]->properties["windgustkmh"]["value"] > 50)
{
logger(ALERT, "Vent fort :" . $indexDevices[METEO]->properties["windgustkmh"]["value"], __FILE__ . ":" . __LINE__);
}
$rafale = $mohaDB->moyenne($indexDevices[METEO], "windgustkmh", 7);
logger(DEBUG, "rafale=" . $rafale, __FILE__ . ":" . __LINE__); logger(DEBUG, "rafale=" . $rafale, __FILE__ . ":" . __LINE__);
} }
if (array_key_exists("solarradiation", $indexDevices[METEO]->properties)) if (array_key_exists("solarradiation", $indexDevices[METEO]->properties))
{ {
$soleil = $mohaDB->moyenne($indexDevices[METEO], "solarradiation", 12); $soleil = $mohaDB->moyenne($indexDevices[METEO], "solarradiation", 12);
logger(DEBUG, "soleil=" . $exterieur_lux, __FILE__ . ":" . __LINE__); logger(DEBUG, "soleil=" . $soleil, __FILE__ . ":" . __LINE__);
} }
} }
logger(DEBUG, sprintf(_("property=%s, value=%s"), $property, $value), __FILE__ . ":" . __LINE__); logger(DEBUG, sprintf(_("property=%s, value=%s"), $property, $value), __FILE__ . ":" . __LINE__);
@ -94,10 +107,10 @@ class rdc_store extends hook
{ {
case "illuminance_lux": case "illuminance_lux":
logger(DEBUG, "CASE: illuminance_lux:" . $value, __FILE__ . ":" . __LINE__); logger(DEBUG, "CASE: illuminance_lux:" . $value, __FILE__ . ":" . __LINE__);
if ($exterieur_lux > 40000) if ($exterieur_lux > 30000)
{ {
logger(DEBUG, "exterieur_lux > 40000", __FILE__ . ":" . __LINE__); logger(DEBUG, "exterieur_lux > 30000", __FILE__ . ":" . __LINE__);
if ($this->maxLevel != 0 and $salon_lux > 150) if ($this->maxLevel != 0 and $salon_lux > 100)
{ {
$store2level = $this->storeLevel + 15; $store2level = $this->storeLevel + 15;
if ( $store2level > $this->maxLevel ) if ( $store2level > $this->maxLevel )
@ -110,9 +123,9 @@ class rdc_store extends hook
$this->set($store2level); $this->set($store2level);
} }
} }
}elseif ($exterieur_lux < 35000) }elseif ($exterieur_lux < 15000 and $salon_lux < 300)
{ {
logger(DEBUG, "exterieur_lux < 35000", __FILE__ . ":" . __LINE__); logger(DEBUG, "exterieur_lux < 15000", __FILE__ . ":" . __LINE__);
$this->close("Luminosité faible"); $this->close("Luminosité faible");
} }
break; break;
@ -141,11 +154,16 @@ class rdc_store extends hook
private function set ($level) private function set ($level)
{ {
if ($this->storeLevel < $level) logger(DEBUG, "function 'set' to level : " . $level, __FILE__ . ":" . __LINE__);
{ //if ($this->storeLevel < $level)
//{
logger(DEBUG, "Open store :" . $level, __FILE__ . ":" . __LINE__); logger(DEBUG, "Open store :" . $level, __FILE__ . ":" . __LINE__);
$this->send(100 - $level); $this->send(100 - $level);
} //}else
/*{
logger(DEBUG, "store is already at level" . $this->storeLevel . " so < at " . $level, __FILE__ . ":" . __LINE__);
}*/
} }
private function close ($reason) private function close ($reason)

View File

@ -4,7 +4,7 @@ cli_set_process_title($title);
file_put_contents("/proc/".getmypid()."/comm",$title); file_put_contents("/proc/".getmypid()."/comm",$title);
declare(ticks = 1); declare(ticks = 1);
$testMode = true; $testMode = false;
$webServerIsActive = true; $webServerIsActive = true;
require "constants.php"; require "constants.php";
@ -14,15 +14,17 @@ $listPropertiesKeys = array("expose");
//global variables //global variables
$notificationLevel = ALERT | ERROR; $notificationLevel = ALERT;
$topics = array(); // list of topics $topics = array(); // list of topics
$mids = array(); // list of message IDs $mids = array(); // list of message IDs
$devices = array(); // array of device objetcs $devices = array(); // array of device objetcs
$indexDevices = array(); // index of devices by ieee_address $indexDevices = array(); // index of devices by ieee_address
$indexFriendlyNames = array(); // index of devices by freindly name $indexFriendlyNames = array(); // index of devices by friendly name
$indexTypes = array(); // index of devices by type $indexTypes = array();
$indexProperties = array(); // index of properties
$hooksList = array(); // list of hooks to be included $hooksList = array(); // list of hooks to be included
$hooks = array(); // array of hooks $hooks = array(); // array of hooks
$topicsCallbacks = array(); // array of topics's callbacks
$notificationMethods = array(); // array of notification methods objects $notificationMethods = array(); // array of notification methods objects
$events = array(); // list of event objects $events = array(); // list of event objects
$monitored = array(); // list of device to watch $monitored = array(); // list of device to watch
@ -36,7 +38,7 @@ $curlErr = 0; // Number of errors returned by curl
$configDir = "./config"; // default config dir (production value is /etc/moha/) $configDir = "./config"; // default config dir (production value is /etc/moha/)
$hooksInitialized = 0; // are all hooks initialized ? false/true $hooksInitialized = 0; // are all hooks initialized ? false/true
$flagHooks = false; $flagHooks = false;
$devicesRequest = false; //say to true when publishing device request to zigbee2mqtt
if ($testMode) if ($testMode)
{ {
@ -199,10 +201,10 @@ require "db_functions.php";
require "apiserver/apiserver.php"; require "apiserver/apiserver.php";
// topics definition // topics definition
listHooks("./topics_callbacks", $hooksList); listHooks("./topics_callbacks", $topicsCallbacks);
if (!empty($hooksList)) if (!empty($topicsCallbacks))
{ {
foreach ($hooksList as $callback) foreach ($topicsCallbacks as $callback)
{ {
logger(INFO, _("Including ") . $callback, __FILE__ . ":" . __LINE__); logger(INFO, _("Including ") . $callback, __FILE__ . ":" . __LINE__);
include $callback; include $callback;
@ -211,7 +213,7 @@ if (!empty($hooksList))
// making the list of hooks to include // making the list of hooks to include
listHooks("./hooks", $hooksList); listHooks("./hooks", $hooksList);
if (!empty($hooksList)) // some hooks to include if hooklist is not empty if (!empty($hooksList)) // hooks to include if hooklist is not empty
{ {
foreach ($hooksList as $hookFile) // loop to include hooks in hookslist foreach ($hooksList as $hookFile) // loop to include hooks in hookslist
{ {
@ -268,7 +270,6 @@ if (file_exists($dataPath . "events.db"))
logger(DEBUG, _("Program start"), __FILE__ . ":" . __LINE__, false); logger(DEBUG, _("Program start"), __FILE__ . ":" . __LINE__, false);
$client = new Mosquitto\Client(); $client = new Mosquitto\Client();
// defining callback functions
try try
{ {
@ -298,6 +299,8 @@ foreach($topics as $name => &$topic)
$topic->status = false; $topic->status = false;
} }
// starting main loop // starting main loop
logger(INFO, _("Starting loop"), __FILE__ . ":" . __LINE__, false); logger(INFO, _("Starting loop"), __FILE__ . ":" . __LINE__, false);
$oneshot = false; $oneshot = false;
@ -305,28 +308,11 @@ $oneshot = false;
while (true) while (true)
{ {
$client->loop(); // mqtt server loop() $client->loop(); // mqtt server loop()
/*if (! $included) // hooks not already included
{
logger(DEBUG, _("Loading hooks list"), __FILE__ . ":" . __LINE__, false);
if (!empty($hooksList)) // some hooks to include if hooklist is not empty
{
foreach ($hooksList as $hookFile) // loop to include hooks in hookslist
{
logger(INFO, _("Including ") . $hookFile, __FILE__ . ":" . __LINE__, false);
include_once $hookFile;
}
if ($logLevel & DEBUG)
{
file_put_contents($dataPath . "moha.devices", var_export($devices, true)); // debugging : save device list
}
$included = true;
}
}else
{*/
if ($oneshot === false) // execute while the first loop :WARNING hooks can to be not initialized if ($oneshot === false) // execute while the first loop :WARNING hooks can to be not initialized
{ {
logger(DEBUG, _("Oneshot part of loop"), __FILE__ . ":" . __LINE__, false); logger(DEBUG, _("Oneshot part of loop"), __FILE__ . ":" . __LINE__, false);
pws2mqttGetList();
$oneshot = true; $oneshot = true;
} }
@ -350,11 +336,9 @@ while (true)
}else // executed when hooks initialization finished but database init not finished }else // executed when hooks initialization finished but database init not finished
{ {
//logger(DEBUG, _("looping"), __FILE__ . ":" . __LINE__); //logger(DEBUG, _("looping"), __FILE__ . ":" . __LINE__);
} }
checkEvents(); checkEvents();
apiServer($read); apiServer($read);
//}
} }
endMoha(); endMoha();

View File

@ -1,9 +1,7 @@
#!/usr/bin/bash #!/usr/bin/bash
rsync -aP --exclude "*~" --exclude *kate-swp $1/config/ /etc/moha/ rsync -aP --exclude "*~" --exclude *kate-swp $1/config/ /etc/moha/
chmod 0500 /etc/moha chmod a+rX -R /etc/moha
chmod 0400 /etc/moha/*
chown domotique:domotique -R /etc/moha chown domotique:domotique -R /etc/moha
rsync -aP --exclude "*~" --exclude *kate-swp $1/webserver/ /var/www/html/moha/ rsync -aP --exclude "*~" --exclude *kate-swp $1/webserver/ /var/www/html/moha/
chmod 0400 -R /var/www/html/moha/ chmod u+rX -R /var/www/html/moha/
chmod 0500 /var/www/html/moha
chown apache:apache -R /var/www/html/moha chown apache:apache -R /var/www/html/moha

View File

@ -1,6 +1,5 @@
<?php <?php
//TODO to test and debug //TODO to test and debug
var_dump($topics);
if (!array_key_exists("linky2mqtt", $topics)) $topics["linky2mqtt"] = new topic; if (!array_key_exists("linky2mqtt", $topics)) $topics["linky2mqtt"] = new topic;
if (!array_key_exists("linky2mqtt", $devices)) $devices["linky2mqtt"] = array(); if (!array_key_exists("linky2mqtt", $devices)) $devices["linky2mqtt"] = array();

View File

@ -11,6 +11,8 @@ function pws2mqttCallback($topic, $message)
$device = & $devices[$topicName]; $device = & $devices[$topicName];
$payloadArray = json_decode($message->payload, true); $payloadArray = json_decode($message->payload, true);
// friendlyname // friendlyname
if ( $fn != "get")
{
if (!array_key_exists($fn, $device)) if (!array_key_exists($fn, $device))
{ {
echo "initializing $fn"; echo "initializing $fn";
@ -55,6 +57,7 @@ function pws2mqttCallback($topic, $message)
{ {
changeDevice($topicName, $fn, $device["device"], $payloadArray); changeDevice($topicName, $fn, $device["device"], $payloadArray);
} }
}
}; };
$topics["pws2mqtt"]->callback = "pws2mqttCallback"; $topics["pws2mqtt"]->callback = "pws2mqttCallback";
@ -66,5 +69,4 @@ if (!is_callable("pws2mqttGetList"))
} }
} }
pws2mqttGetList();
?> ?>

View File

@ -5,7 +5,7 @@ if (!array_key_exists("zigbee2mqtt", $devices)) $devices["zigbee2mqtt"] = array
function zigbee2mqttCallback($topic, $message) function zigbee2mqttCallback($topic, $message)
{ {
global $topics, $devices, $included, $logFh, $indexFriendlyNames; global $topics, $devices, $included, $logFh, $indexFriendlyNames, $devicesRequest;
if ($topic[1] == "bridge") if ($topic[1] == "bridge")
{ {
@ -20,6 +20,7 @@ function zigbee2mqttCallback($topic, $message)
//fwrite($logFh, var_export($topics[$topic[0]]->devices, true)); //fwrite($logFh, var_export($topics[$topic[0]]->devices, true));
mkDevicesDB($topic[0], $topics[$topic[0]]->devices); mkDevicesDB($topic[0], $topics[$topic[0]]->devices);
getDevicesValues($topic[0]); getDevicesValues($topic[0]);
$devicesRequest = false;
break; break;
case "groups": case "groups":
logger(DEBUG,_("Inserting zigbee groups in DB"), __FILE__ . ":" . __LINE__); logger(DEBUG,_("Inserting zigbee groups in DB"), __FILE__ . ":" . __LINE__);
@ -77,7 +78,7 @@ function zigbee2mqttCallback($topic, $message)
$alert = 0; $alert = 0;
while (!array_key_exists($fn, $indexFriendlyNames)) while (!array_key_exists($fn, $indexFriendlyNames))
{ {
logger(INFO, _("device does not exists in IndexFriendlyNames: ") . print_r($payloadArray,true), __FILE__ . ":" . __LINE__); logger(ERROR, $fn . _(" device does not exists in IndexFriendlyNames: ") . print_r($payloadArray,true), __FILE__ . ":" . __LINE__);
if ($flag == 0) if ($flag == 0)
{ {
logger(INFO, "Reindexing all indexes", __FILE__ . ":" . __LINE__); logger(INFO, "Reindexing all indexes", __FILE__ . ":" . __LINE__);
@ -86,26 +87,32 @@ function zigbee2mqttCallback($topic, $message)
}elseif($flag == 1) }elseif($flag == 1)
{ {
logger(INFO, "getting device list from zigbee2mqtt", __FILE__ . ":" . __LINE__); logger(INFO, "getting device list from zigbee2mqtt", __FILE__ . ":" . __LINE__);
if ($devicesRequest === false)
{
publish("zigbee2mqtt", array("bridge/devices" => ""), "get"); publish("zigbee2mqtt", array("bridge/devices" => ""), "get");
}
$flag += 1; $flag += 1;
}elseif($flag >= 2) }elseif($flag++ >= 5)
{ {
$flage = 0; $flage = 0;
if ($alert++ > 4) //if ($alert++ > 4)
{ //{
logger(ALERT, _("device does not exists in IndexFriendlyNames: ") . $fn, __FILE__ . ":" . __LINE__); logger(ERROR, _(" stopping searching for ") . $fn . " payloadArray =>" . print_r($payloadArray, true), __FILE__ . ":" . __LINE__);
break; break;
} //}
} }
} }
//logger(DEBUG, "PayloadArray = " . print_r($payloadArray,true), __FILE__ . ":" . __LINE__); //logger(DEBUG, "PayloadArray = " . print_r($payloadArray,true), __FILE__ . ":" . __LINE__);
if ($alert <= 4) if ($flag <= 4)
{ {
changeDevice($topicName, $fn, $indexFriendlyNames[$fn], $payloadArray); changeDevice($topicName, $fn, $indexFriendlyNames[$fn], $payloadArray);
}else
{
logger(ERROR, $fn . _(" not changed"), __FILE__ . ":" . __LINE__);
} }
}else }else
{ {
logger(DEBUG, _("Zigbee2mqtt doing get or set !?")); logger(DEBUG, _("Zigbee2mqtt doing get or hooks not included !?"), __FILE__ . ":" . __LINE__);
} }
}; };

View File

@ -1,5 +1,5 @@
<?php <?php
logger(DEBUG, _("Including utils.php"), __FILE__ . ":" . __LINE__); ////logger(DEBUG, _("Including utils.php"), __FILE__ . ":" . __LINE__);
function bool2string($var) function bool2string($var)
{ {
@ -64,15 +64,15 @@ function getDevice($topic, $fn)
$var = $var[$tmp]; $var = $var[$tmp];
}else }else
{ {
logger(ERROR, sprintf(_("level %s of %s do not exists in %s"), $tmp, $fn, $topic), __FILE__ . ":" . __LINE__ ); ////logger(ERROR, sprintf(_("level %s of %s do not exists in %s"), $tmp, $fn, $topic), __FILE__ . ":" . __LINE__ );
return false; return false;
} }
} }
logger(DEBUG, sprintf(_("returning a value")), __FILE__ . ":" . __LINE__ ); ////logger(DEBUG, sprintf(_("returning a value")), __FILE__ . ":" . __LINE__ );
return $var["device"]; return $var["device"];
}else }else
{ {
logger(ERROR, sprintf(_("Topic %s do not exists"), $topic), __FILE__ . ":" . __LINE__ ); ////logger(ERROR, sprintf(_("Topic %s do not exists"), $topic), __FILE__ . ":" . __LINE__ );
return false; return false;
} }
} }
@ -84,11 +84,11 @@ function getValue($ieeeAddress, $property)
if (array_key_exists($property, $indexDevices[$ieeeAddress]->properties)) if (array_key_exists($property, $indexDevices[$ieeeAddress]->properties))
{ {
$r = $indexDevices[$ieeeAddress]->properties[$property]["value"]; $r = $indexDevices[$ieeeAddress]->properties[$property]["value"];
logger(DEBUG, "device: " . $indexDevices[$ieeeAddress]->friendlyName . " value: " . $r, __FILE__ . ":" . __LINE__ ); //logger(DEBUG, "device: " . $indexDevices[$ieeeAddress]->friendlyName . " value: " . $r, __FILE__ . ":" . __LINE__ );
}else }else
{ {
$r = false; $r = false;
logger(ERROR, "device: " . $indexDevices[$ieeeAddress]->friendlyName . "property " . $property . "does not exists", __FILE__ . ":" . __LINE__ ); //logger(ERROR, "device: " . $indexDevices[$ieeeAddress]->friendlyName . "property " . $property . "does not exists", __FILE__ . ":" . __LINE__ );
} }
return $r; return $r;
} }
@ -99,7 +99,7 @@ function setValue($fn, $property, $value)
$indexDevices[$ieeeAddress]->properties[$property]["value"] = $value; $indexDevices[$ieeeAddress]->properties[$property]["value"] = $value;
} }
logger(DEBUG, _("signal handling"), __FILE__ . ":" . __LINE__, false); //logger(DEBUG, _("signal handling"), __FILE__ . ":" . __LINE__, false);
//signal handling //signal handling
function signalHandler($signal) function signalHandler($signal)
{ {

View File

@ -0,0 +1,38 @@
<?php
//logger(DEBUG, _("Including db.php"));
class db extends mysqli
{
public $mysqlServer = "127.0.0.1"; // Your production server
public $username = "moha";
public $passwd = "MysqlMoha";
public $database = "moha";
public $result;
function __construct()
{
global $testMode;
$flagError = false;
if ($testMode)
{
$this->mysqlServer = "192.168.1.253"; // Your test server
}
while ($this->connect($this->mysqlServer, $this->username, $this->passwd, $this->database) === false)
{
//logger(ERROR,_("Connection to sql server error :") . $this->connect_error, __FILE__ . ":" . __LINE__);
sleep(5);
$flagError = true;
}
if ($flagError === true)
{
//logger(ERROR, _("Connection to sql server ready"), __FILE__ . ":" . __LINE__);
}
$result = new mysqli_result($this);
}
function protect($string)
{
return $this->real_escape_string($string);
}
}
?>

5
webserver/config.php Normal file
View File

@ -0,0 +1,5 @@
<?php
$varPath = "/usr/share/moha/";
$mohaPath = "/home/daniel/moha";
$configPath = "/etc/moha/";
?>

View File

@ -2,14 +2,19 @@
/****************************************************************/ /****************************************************************/
/* */ /* */
/*need device ieeeAddress, property, startDate and finalDate */ /*need device ieeeAddress, property, startDate and endDate */
/* */ /* */
/****************************************************************/ /****************************************************************/
function displayStats($socket, $argList) require_once "config.php";
require_once "utils.php";
require_once "header.php";
function displayStats($ieeeAddress, $fn, $property, $startDate, $endDate)
{ {
global $indexFriendlyNames, $mohaDB; global $indexFriendlyNames, $mohaDB;
logger(INFO, "Function displayStats", __FILE__ . ":" . __LINE__); //logger(INFO, "Function displayStats", __FILE__ . ":" . __LINE__);
// Validation of the dates // Validation of the dates
if (validateDate($argList["startDate"]) && validateDate($argList["finalDate"])) if (validateDate($argList["startDate"]) && validateDate($argList["finalDate"]))
@ -23,10 +28,10 @@ function displayStats($socket, $argList)
}else }else
{ {
$query = "SELECT date, value FROM logs WHERE device='" . $indexFriendlyNames[$argList["fn"]]->ieeeAddress . "' AND property='" . $argList["property"] . "' AND '" . $argList["startDate"] . "'>= date AND '" . $argList["finalDate"] . "' <= date ORDER BY date"; $query = "SELECT date, value FROM logs WHERE device='" . $indexFriendlyNames[$argList["fn"]]->ieeeAddress . "' AND property='" . $argList["property"] . "' AND '" . $argList["startDate"] . "'>= date AND '" . $argList["finalDate"] . "' <= date ORDER BY date";
logger(DEBUG, _("query : ") . $query, __FILE__ . ":" . __LINE__); //logger(DEBUG, _("query : ") . $query, __FILE__ . ":" . __LINE__);
if(!($mohaDB->result = $mohaDB->query($query))) if(!($mohaDB->result = $mohaDB->query($query)))
{ {
logger(ERROR, _("mysql query error: ") . $mohaDB->error, __FILE__ . ":" . __LINE__); //logger(ERROR, _("mysql query error: ") . $mohaDB->error, __FILE__ . ":" . __LINE__);
} }
$datas = $mohaDB->result->fetch_all(MYSQLI_ASSOC); $datas = $mohaDB->result->fetch_all(MYSQLI_ASSOC);
htmlSend($socket, diagramDisplay($datas)); htmlSend($socket, diagramDisplay($datas));
@ -144,4 +149,9 @@ function diagramDisplay($datas)
//Desallouer la mémoire utiliser par l'image //Desallouer la mémoire utiliser par l'image
imagedestroy($courbe); imagedestroy($courbe);
} }
$tmp = explode("|", $_GET["device"]);
displayStats($tmp[0], $tmp[1], $tmp[2]);
?> ?>

View File

@ -1,10 +1,92 @@
<?php <?php
require_once "header.php"; require_once "header.php";
require_once "config.php"; require_once "config.php";
require_once "db_config.php"; require_once "utils.php";
require_once $mohaPath . "/constants.php";
require_once $mohaPath . "/class/db.php";
require_once $configPath . "properties2log.php";
function logger($level, $log, $pos = "")
{
global $logFh, $logLevel, $notificationLevel, $logLevels;
$logString = $logLevels[$level] . " " ;
if ($pos !== false)
{
$logString .= $pos;
}
$logString .= " - " . $log;
if ($level & $logLevel)
{
fwrite($logFh, date("c") . ' ' . $logString . EOL);
print ("MOHA-" . $logString . EOL);
}
}
function htmlGetFriendlyNames($ieeeAddress = '') : array
{
$url = "HTTP://localhost:1025/friendlyname";
$ch = curl_init($url);
if ($ieeeAddress !== '')
{
$url .= "&ieeeAddress=" . $ieeeAddress;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$fn = curl_exec($ch);
curl_close($ch);
$start = strpos($fn, "{");
$end = strpos($fn, "}");
$length = $end - $start + 1;
$fn = substr($fn, $start, $length);
return jsonDecode($fn);
}
$indexIeeeAddress = htmlGetFriendlyNames();
//print_r($indexIeeeAddress);
print (_("This is the Statistics of Moha")); print (_("This is the Statistics of Moha"));
if (empty($indexIeeeAddress))
{
$response = _("ERROR getting list of Friendly names: json error =>") . json_last_error_msg() .EOLH;
}else
{
$query = "SELECT DISTINCT device, property FROM logs";
$result = $mohaDB->query($query);
$devices = mysqli_fetch_all($result, MYSQLI_ASSOC);
$devicesList = array();
// print_r($devices);
print '<form method="GET" action="display_stats.php">';
//print '<input type="hidden" name="fn" value="">';
print '<label for="devicesSelectList">' . _("Choose a device:") . '</label>
<select name="device" id="devicesSelectList">' ;
foreach ($devices as $value)
{
if ( array_key_exists($value["device"], $indexIeeeAddress))
{
$devicesList[$value["device"]]["fn"] = $indexIeeeAddress[$value["device"]];
$devicesList[$value["device"]][] = $value["property"];
}
}
//$devicesList = array_intersect_key($indexIeeeAddress, $tmp);
//print_r($devicesList);
foreach($devicesList as $ieeeAddress => $array)
{
print '<optgroup label="' . $array["fn"] . '">';
foreach($array as $key => $property)
{
if ($key != "fn")
{
print '<option value="' . $ieeeAddress . '|' . $array["fn"] . '|' . $property . '">' . $property . '</option>' . EOL;
}
}
print '</optgroup>' . EOL;
}
print "</select>";
print '<input type="submit" value="Afficher les statistiques">';
print "</form>" . EOL;
}
require_once "footer.php"; require_once "footer.php";
?> ?>

16
webserver/utils.php Normal file
View File

@ -0,0 +1,16 @@
<?php
function jsonDecode($json)
{
$jsonArray = array();
$json = trim($json, " {[]}");
$tmp = explode(",", $json);
foreach($tmp as $value)
{
$tmp2 = explode (":" , $value);
$jsonArray[trim($tmp2[0], '"')] = trim($tmp2[1], '"');
}
return $jsonArray;
}
?>