1
0

modified device database and the code for managing it

This commit is contained in:
daniel Tartavel 2022-02-12 15:23:58 +01:00
parent 314305bcb1
commit 7d1dd25f2a
13 changed files with 156 additions and 113 deletions

View File

@ -75,7 +75,7 @@ class db extends mysqli
logger(ERROR, _("mysql query errror: ") . $this->error, __FILE__ . ":" . __LINE__);
}
}
logger(INFO, sprintf(_("New value (%s) of property: '%s' of device: %s stored in database"), $value, $propertyTree, $device->friendlyName), __FILE__ . ":" . __LINE__);
logger(INFO, sprintf(_("New value (%s) of property: '%s' of device: %s stored in database"), bool2string($value), $propertyTree, $device->friendlyName), __FILE__ . ":" . __LINE__);
}
}
}

View File

@ -53,7 +53,12 @@ class hook
logger(DEBUG, $this->hookName . _(" initialized"), __FILE__ . ":" . __LINE__);
//var_dump($this);
}
}else
{
$this->initialized = true;
logger(DEBUG, $this->hookName . _("hook is disabled"), __FILE__ . ":" . __LINE__);
}
return $result;
}
}

View File

@ -34,6 +34,7 @@ class device
public $availability;
public $toConfirm;
public $triggerDevice;
public $properties = array();
public function __construct()
{
@ -89,17 +90,17 @@ class watch
public function __construct($topic, $fn, $property, $condition, $value)
{
global $conditions, $acceptedValues, $indexDevices;
global $conditions, $indexDevices;
logger(DEBUG, _("New Notification"), __FILE__ . ":" . __LINE__);
if (($device = getDevice($topic, $fn)) !== false)
{
$this->topic = $topic;
if (property_exists($device, $property))
if (array_key_exists($property, $device->properties))
{
$this->property = $property;
if (!is_numeric($value) and array_search($value, $this->acceptedValues) === false)
if (!is_numeric($value) or array_search($value, $this->acceptedValues) === false)
{
logger(ERROR, _("Value is not numeric"), __FILE__ . ":" . __LINE__ );
logger(ERROR, _("Value is not numeric or not accepted"), __FILE__ . ":" . __LINE__ );
return false;
}
if (array_search($condition, $this->conditions))
@ -112,7 +113,7 @@ class watch
logger(ERROR, sprintf(_("Condition %s is not one of the permitted : "), $condition) . print_r($conditions, true), __FILE__ . ":" . __LINE__ );
return false;
}
$indexDevices[$device->ieeeAddress]->$property["functions"][] = array($this,"notifyCallback");
$indexDevices[$device->ieeeAddress]->properties[$property]["functions"][] = array($this,"notifyCallback");
}else
{
logger(ERROR, _("Property do not exists"), __FILE__ . ":" . __LINE__ );
@ -132,11 +133,9 @@ class watch
if (eval($this->function))
{
logger(DEBUG, _("notifyCallback"));
$msg = sprintf(_("Device '%s' have property '%s' value %s %s %s"), $device->friendlyName, $property, $value, $this->condition, $this->PropertyValue );
$msg = sprintf(_("Device '%s' have property '%s' value %s %s %s"), $device->friendlyName, $property, bool2string($value), $this->condition, bool2string($this->PropertyValue) );
notify($msg);
}
}
}

View File

@ -46,12 +46,13 @@ function mkDevicesDB($topic, $json, $group=false)
}
$device["device"]->topic = $topic;
//$device["device"]->device = $jsonDevice;
$device["device"]->friendlyName = $jsonDevice->friendly_name;
$device["device"]->friendlyName = $fn;
if ($group)
{
//print_r($device);
$device["device"]->groupID = $jsonDevice->id;
$indexDevices[$device["device"]->groupID] = $jsonDevice->friendly_name;
$indexDevices[$device["device"]->groupID] = & $device["device"];
$indexFriendlyNames[$fn] = & $device["device"];
}else
{
addDevice($device, $fn, $jsonDevice);
@ -68,7 +69,7 @@ function mkDevicesDB($topic, $json, $group=false)
function addDevice(& $device, $fn, $jsonDevice )
{
global $listProperties, $listPropertiesKeys, $hooks, $indexDevices;
global $listProperties, $listPropertiesKeys, $hooks, $indexDevices, $indexFriendlyNames;
$device["device"]->type = $jsonDevice->type;
$device["device"]->ieeeAddress = $jsonDevice->ieee_address;
if ( !empty($jsonDevice->power_source ) )
@ -84,6 +85,7 @@ function addDevice(& $device, $fn, $jsonDevice )
//indexing device
$indexDevices[$device["device"]->ieeeAddress] = & $device["device"];
$indexFriendlyNames[$fn] = & $device["device"];
}
function searchPropertyKey($fn, &$device, $object, $listPropertiesKeys)
@ -99,8 +101,8 @@ function searchPropertyKey($fn, &$device, $object, $listPropertiesKeys)
if ( isset($value->property))
{
$string = $value->property;
$device->{$string}["value"] = null;
$device->$string["functions"] = array();
$device->properties[$string]["value"] = null;
$device->properties[$string]["functions"] = array();
}
}
//print_r($device);
@ -139,7 +141,7 @@ function changeDevice($topic, $fn, &$device, $payloadArray)
function iterateDevice($topic, $fn, $parentDevice, &$device, $payloadArray, $propertyTree="")
{
global $changed, $mohaDB, $testMode;
$deviceType = (gettype($device) == "object"); // = true if object
$deviceType = (is_a($device, "device")); // = true if object
//echo "==================== New iterate =====================" .EOL;
//echo "devicetype = "; var_dump($deviceType); echo EOL;
//echo "device =>";print_r($device);echo EOL;
@ -159,24 +161,24 @@ function iterateDevice($topic, $fn, $parentDevice, &$device, $payloadArray, $pro
if ($deviceType === true )
{
//echo "deviceType = true" . EOL;
if (!property_exists($device, $key))
if (!array_key_exists($key, $device->properties))
{
//echo "Property do not exists" . EOL;
$device->{$key} = new stdClass;
$device->properties[$key] = new stdClass;
}
//echo "iterating" . EOL;
//echo "===============>";
iterateDevice($topic, $fn, $parentDevice, $device->$key, $value, $propertyTree);
iterateDevice($topic, $fn, $parentDevice, $device->properties[$key], $value, $propertyTree);
}else
{
//echo "is array";
if (!array_key_exists($key, $device))
if (!array_key_exists($key, $device->properties))
{
$device[$key] = new stdClass;
$device->properties[$key] = new stdClass;
}
//echo "iterating" . EOL;
iterateDevice($topic, $fn, $parentDevice, $device[$key], $value, $propertyTree);
iterateDevice($topic, $fn, $parentDevice, $device->properties[$key], $value, $propertyTree);
}
}elseif ($valueType == "array")
@ -184,12 +186,12 @@ function iterateDevice($topic, $fn, $parentDevice, &$device, $payloadArray, $pro
$propertyTree .= $key . "/";
if ($deviceType === true )
{
$device->$key = array();
iterateDevice($topic, $fn, $parentDevice, $device->$key, $value, $propertyTree);
$device->properties[$key] = array();
iterateDevice($topic, $fn, $parentDevice, $device->properties[$key], $value, $propertyTree);
}else
{
$device[$key] = array();
iterateDevice($topic, $fn, $parentDevice, $device[$key], $value, $propertyTree);
$device->properties[$key] = array();
iterateDevice($topic, $fn, $parentDevice, $device->properties[$key], $value, $propertyTree);
}
}else
@ -208,7 +210,7 @@ function iterateDevice($topic, $fn, $parentDevice, &$device, $payloadArray, $pro
}
}else
{
$device->{$key} = array("value" => null);
$device->$key = array("value" => null);
$device->$key["functions"] = array();
}
//echo $key . ' ===> oldvalue = ' . $oldValue . " value = " . $value . EOL;
@ -222,13 +224,12 @@ function iterateDevice($topic, $fn, $parentDevice, &$device, $payloadArray, $pro
if (!empty($device->$key["functions"]))
{
logger(DEBUG,_("executing notifications functions"), __FILE__ . ":" . __LINE__);
foreach($device->$key["functions"] as $function)
foreach($device->properties[$key]["functions"] as $function)
{
$function($device, $key, $value);
}
}
}
//}
}
}
@ -245,25 +246,24 @@ function getDevicesValues($topic)
logger(DEBUG, "device: " . $device->friendlyName);
$payload = "{";
$flag = false;
$properties = array_slice($device, 12);
logger(DEBUG, print_r($properties, true));
foreach($properties as $property)
//$properties = array_slice($device, 12);
//logger(DEBUG, print_r($properties, true));
foreach($device->properties as $property => $value)
{
if (flag)
if ($flag)
{
$payload = ",";
$payload .= ",";
}else {
$flag = true;
}
$payload .= $property . ':""';
$payload .= '"' . $property . '":""';
}
$device->payload = $payload . "}";
logger(DEBUG, $device->payload);
$device->get();
}
}
exit(0);
}
?>

View File

@ -1,12 +1,12 @@
<?php
logger(DEBUG, _("Including events.php"));
logger(DEBUG, _("Including events.php"), __FILE__ . ":" . __LINE__);
/* for all functions, datetime parameter format is 'dd/mm/yy hh:mm:ss' */
function checkEvents()
{
global $logLevel, $events, $indexDevices, $devices;
global $logLevel, $events;
$oldLevel = $logLevel;
$loglevel = DEBUG;
$exception = false;

View File

@ -41,7 +41,7 @@ class availability
// $log = INFO;
//}
//$device->availability = $value;
logger($log, sprintf(_("Device: %s/%s is %s"), $device->topic, $device->friendlyName, $value), __FILE__ . ":" . __LINE__);
logger($log, sprintf(_("Device: %s/%s is %s"), $device->topic, $device->friendlyName, bool2string($value)), __FILE__ . ":" . __LINE__);
}
break;
}

View File

@ -3,10 +3,10 @@
class etage_plan_travail_eclairage extends hook
{
public $hookName = "etage_plan_travail_eclairage";
public $active = true; //enable/disable hook (true => enabled)
public $active = false; //enable/disable hook (true => enabled)
public $delay = 3; // amount of time in $timeunit
public $timeUnit = "hour"; // unit of time for delay, second, minute, hour, day, week, month, year
protected $devicelist = array("ETAGE_CUISINE_PLAN_TRAVAIL_ECLAIRAGE" => array("state", false));
protected $devicelist = array(ETAGE_CUISINE_PLAN_TRAVAIL_ECLAIRAGE => array("state", false));
// callback fonction. Is called with these 3 parameters
// $device -> calling device

View File

@ -30,7 +30,7 @@ class rdc_chambre_eclairage extends hook
{
$this->send(RDC_CHAMBRE_ECLAIRAGE, "ON", "OFF", AUTO);
}
logger (INFO, sprintf(_("%s: notification received from MQTT from %s => parameter: %s value: %s"), $this->hookName, $device->friendlyName, $property, $value), __FILE__ . ":" . __LINE__);
logger (INFO, sprintf(_("%s: notification received from MQTT from %s => parameter: %s value: %s"), $this->hookName, $device->friendlyName, $property, bool2string($value)), __FILE__ . ":" . __LINE__);
}
private function send($device, $state, $delayState = false, $method = MANUAL)

View File

@ -1,4 +1,5 @@
<?php
class rdc_salon_eclairage extends hook
{
public $hookName = "rdc_salon_eclairage";
@ -14,14 +15,14 @@ class rdc_salon_eclairage extends hook
public $delay = 3; // amount of time in $timeunit
public $timeUnit = "minute"; // unit of time for delay, second, minute, hour, day, week, month, year
public $luminance_min = 60;
public $luminance_max = 3000;
public $luminance_max = 100;
// callback fonction. Is called with these 4 parameters
public function callBack(&$device, $param, $value)
{
global $devices, $indexDevices;
global $indexDevices;
logger(INFO, _("hook : rdc_salon_eclairage"), __FILE__ . ":" . __LINE__);
$device = &$indexDevices[RDC_SALON_ECLAIRAGE_PANNEAU];
switch($param)
{
case "occupancy":
@ -31,14 +32,14 @@ class rdc_salon_eclairage extends hook
{
logger(DEBUG, _("setting to ON"), __FILE__ . ":" . __LINE__);
$this->send("ON", null, AUTO);
removeEvent($indexDevices[RDC_SALON_ECLAIRAGE_PANNEAU], "state", "OFF");
removeEvent($device, "state", "OFF");
}elseif ($value == OFF)
{
logger(DEBUG, _("Value is OFF"), __FILE__ . ":" . __LINE__);
if (getValue(RDC_SALON_MVMT, "occupancy") == OFF and (getValue(RDC_SALON_MVMT2, "occupancy") == OFF))
{
logger(DEBUG, _("Setting to OFF"), __FILE__ . ":" . __LINE__);
setDelay($indexDevices[RDC_SALON_ECLAIRAGE_PANNEAU], $this->delay, $this->timeUnit, "state", "OFF", true);
setDelay($device, $this->delay, $this->timeUnit, "state", "OFF", true);
//$this->send("ON", "OFF", AUTO);
}
}
@ -64,7 +65,10 @@ class rdc_salon_eclairage extends hook
logger(DEBUG, _("illuminace is > to max"), __FILE__ . ":" . __LINE__);
//$this->send("OFF", null, AUTO);
//removeEvent($indexDevices[RDC_SALON_ECLAIRAGE_PANNEAU], "state", "OFF");
setDelay($indexDevices[RDC_SALON_ECLAIRAGE_PANNEAU], $this->delay, $this->timeUnit, "state", "OFF", true);
if (searchEvent($device, "state", "OFF") === false)
{
setDelay($device, $this->delay, $this->timeUnit, "state", "OFF", true);
}
}elseif ($value <= $this->luminance_min and (getValue(RDC_SALON_MVMT, "occupancy") == ON OR getValue(RDC_SALON_MVMT2,"occupancy") == ON))
{
logger(DEBUG, _("illuminance < min and movement detected"), __FILE__ . ":" . __LINE__);
@ -77,7 +81,7 @@ class rdc_salon_eclairage extends hook
private function send($state, $delayState = false, $method = MANUAL)
{
global $devices, $indexDevices;
global $indexDevices;
$device = & $indexDevices[RDC_SALON_ECLAIRAGE_PANNEAU];
$msg = array("state" => $state);
if ($device->state["value"] != $state)
@ -89,7 +93,6 @@ class rdc_salon_eclairage extends hook
}else
{
logger(INFO, sprintf(_("not publishing message: %s to %s, already set"), json_encode($msg), $device->friendlyName), __FILE__ . ":" . __LINE__);
}
//echo 'delaystate = ' . var_dump($delayState);
if ($delayState !== false) setDelay($device, $this->delay, $this->timeUnit, "state", $delayState, true);

View File

@ -28,7 +28,7 @@ class rdc_wc_eclairage extends hook
}
break;
}
logger (INFO, sprintf(_("%s: notification received from MQTT from %s => parameter: %s value: %s"), $this->hookName, $device->friendlyName, $property, $value), __FILE__ . ":" . __LINE__);
logger (INFO, sprintf(_("%s: notification received from MQTT from %s => parameter: %s value: %s"), $this->hookName, $device->friendlyName, $property, bool2string($value)), __FILE__ . ":" . __LINE__);
}
}

View File

@ -10,7 +10,7 @@ $webServerIsActive = true;
require "constants.php";
$listProperties = array("powerSource" => "batterie");
$listPropertiesKeys = array("property");
$listPropertiesKeys = array("expose");
//global variables
$logLevel = ALL; // INFO | NOTICE | WARNING | ERROR | ALERT; //ALL;
@ -18,7 +18,8 @@ $notificationLevel = ALERT | ERROR;
$topics = array(); // list of topics
$mids = array(); // list of message IDs
$devices = array(); // array of device objetcs
$indexDevices = array(); // index devices by ieee_address
$indexDevices = array(); // index of devices by ieee_address
$indexFriendlyNames = array(); // index of devices by freindly name
$hooksList = array(); // list of hooks to be included
$hooks = array(); // array of hooks
$notificationMethods = array(); // array of notification methods objects
@ -271,7 +272,7 @@ while (true)
}else
{
if ($oneshot === false) // execute once initialization finished :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);
@ -284,7 +285,7 @@ while (true)
{
if ($hook->initialized === false)
{
logger(WARNING, _("Hook not completely initialized :") . $hookName, __FILE__ . ":" . __LINE__);
logger(WARNING, _("Initializing Hook not completely initialized :") . $hookName, __FILE__ . ":" . __LINE__);
$i &= $hook->installHooks();
}
}
@ -293,7 +294,11 @@ while (true)
{
logger(DEBUG, _("All hooks initialized"), __FILE__ . ":" . __LINE__);
$flagHooks = true;
getDevicesValues();exit (0);
}else // executed when initialization finished
{
logger(DEBUG, _("looping"), __FILE__ . ":" . __LINE__);
}
checkEvents();
askWebServer($read);

View File

@ -12,6 +12,7 @@ $listenPort = 1025;
$Dashboards = array();
require_once $configDir . "/dashboard_conf.php";
require_once "class/main.php";
// opening listening server
$socket = stream_socket_server("tcp://" . $listenHost . ":" . $listenPort, $error_code, $error_message) or logger(ERROR, _("Could not create socket") . EOL);
@ -37,7 +38,7 @@ function webListTopics()
$response = "";
foreach ($topics as $name => $topic)
{
$response .= '<a href="/topic=' . $name . '">' . $name ."</a><br>";
$response .= '<a href="/browse&topic=' . $name . '">' . $name ."</a><br>";
}
return $response;
}
@ -45,7 +46,6 @@ function webListTopics()
function webBrowse($socket, $argList)
{
global $topics, $devices;
$response = "";
logger(DEBUG, _("Generic response to choose device and property"), __FILE__ . ":" . __LINE__);
//$response = "<html><header></header><body>" . _("unknown command") . "</body></html>";
$response = "";
@ -55,13 +55,14 @@ function webBrowse($socket, $argList)
if (array_key_exists($argList["topic"], $topics))
{
logger(DEBUG, _("Topic exists") , __FILE__ . ":" . __LINE__);
$topicRef = '<a href="topic=' . $argList["topic"];
$topicRef = '<a href="browse&amp;topic=' . $argList["topic"];
if (array_key_exists("fn", $argList))
{
logger(DEBUG, _("FriendlyName exists: ") . $argList["fn"] , __FILE__ . ":" . __LINE__);
$fn = "";
$fnArray = explode("/", $argList["fn"]);
$device = $devices[$argList["topic"]];
var_dump($fnArray);
foreach($fnArray as $value)
{
if ($flag) $fn .= "/";
@ -74,21 +75,25 @@ function webBrowse($socket, $argList)
$device = $device[$value];
$flag = true;
}
if (array_key_exists("device", $device))
var_dump($device);
if (array_key_exists("device", $device)) // TODO
{
$device = $device["device"];
$fn .= "device/" . $fn;
}
if (is_object($device))
if (is_a($device, "device"))
{
foreach($device as $key => $value)
{
if ($key != "device" and is_array($value))
if ($key != "devicarray_key_existse" and is_array($value))
{
print_r($value);
//print_r($value);
if (array_key_exists("value", $value))
{
$response .= $key . ' = ' . bool2string($value["value"]) . "<br>";
}else
{
$response .= $key . ' = ' . bool2string($value) . "<br>";
}
}
}
@ -96,7 +101,7 @@ function webBrowse($socket, $argList)
{
foreach($device as $key => $value)
{
$response .= $topicRef . "&fn=" . $fn . "/" . $key . '">' . $key . "</a><br>";
$response .= $topicRef . "&amp;fn=" . $fn . "/" . $key . '">' . $key . "</a><br>";
}
}
logger(DEBUG, _("response: ") . EOL . $response , __FILE__ . ":" . __LINE__);
@ -106,8 +111,9 @@ function webBrowse($socket, $argList)
{
foreach($devices[$argList["topic"]] as $key => $value)
{
print "key = " . print_r($key, true) . " value = " . print_r($value, true) . EOLR;
logger(DEBUG, _("devices de topic: ") . $key , __FILE__ . ":" . __LINE__);
$response .= $topicRef . "&fn=" . $key . '">' . $key . "</a><br>";
$response .= $topicRef . "&amp;fn=" . $key . '">' . $key . "</a><br>";
logger(DEBUG, _("response: ") . $response , __FILE__ . ":" . __LINE__);
}
}
@ -157,27 +163,26 @@ function askWebServer($read)
logger(DEBUG, _("socket accepted"), __FILE__ . ":" . __LINE__);
$input = fgets($spawn, 4096);
logger(DEBUG, $input, __FILE__ . ":" . __LINE__);
if (!empty($input))
{
$input = substr($input,5);
$input = explode(" ", $input); // suppress text
if (!empty($input[0]))
{
$argTmp = explode("&", urldecode($input[0]));
foreach($argTmp as $tmp)
{
logger(DEBUG, $tmp, __FILE__ . ":" . __LINE__);
if(strpos($tmp, "=") === false)
{
logger(DEBUG, _("no ="));
$argList[trim($tmp)] = "";
logger(DEBUG, _("no ="), __FILE__ . ":" . __LINE__);
$argList["cmd"] = trim($tmp);
}else
{
$argList[trim(strchr($tmp, "=", true))] = trim(substr(strchr($tmp, "="), 1));
}
}
logger(DEBUG, print_r($argList, true));
logger(DEBUG, print_r($argList, true), __FILE__ . ":" . __LINE__);
if (array_key_exists("browse", $argList))
/*if (array_key_exists("browse", $argList))
{
logger(DEBUG, _("Browsing"));
webBrowse($spawn, $argList);
@ -186,13 +191,21 @@ function askWebServer($read)
{
webDashboard($spawn, $argList["dashboard"]);
return true;
}
}*/
if(array_key_exists("cmd", $argList))
{
$command = strtolower($argList["cmd"]);
logger(DEBUG, _("command is ") . $command);
logger(DEBUG, _("command is ") . $command, __FILE__ . ":" . __LINE__);
switch($command)
{
case "dashboard":
webDashboard($spawn, $argList["dashboard"]);
break;
case "browse":
logger(DEBUG, _("Browsing"), __FILE__ . ":" . __LINE__);
webBrowse($spawn, $argList);
//return true;
break;
case "get":
logger(DEBUG, _("GET reached"), __FILE__ . ":" . __LINE__);
if(!array_key_exists("topic", $argList) or !array_key_exists("fn", $argList) or !array_key_exists("property", $argList))
@ -228,7 +241,10 @@ function askWebServer($read)
case "dump":
case "print":
logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__);
if (array_key_exists($argList["object"], $GLOBALS))
{
$var = $GLOBALS[$argList["object"]];
if (isset($argList["topic"]))
{
$topic = $argList["topic"];
@ -258,12 +274,17 @@ function askWebServer($read)
}
if ($command === "print")
{
$response = print_r($var, true);
$response = "<pre>" . nl2br(print_r($var, true)) . "<pre>";
}elseif($command === "dump")
{
$response = "Dump" . EOL;
$response .= var_export($var, true);
$response .= "<pre>" . nl2br(var_export($var, true)) . "<pre>";
}
}else
{
$response = _("Object do not exists");
}
htmlSend($spawn, $response);
break;
case "notify":
@ -278,14 +299,14 @@ function askWebServer($read)
$monitored[] = new watch($argList["topic"], $argList["fn"], $argList["property"], $argList["condition"], $argList["value"]);
htmlSend($spawn, $response);
}
logger(DEBUG, print_r($monitored, true));
logger(DEBUG, print_r($monitored, true), __FILE__ . ":" . __LINE__);
break;
default:
webBrowse($spawn, $argList);
}
}else
{
webBrowse($spawn,$argList);
webDashboard($spawn);
}
}else
{

10
www/index.php Normal file
View File

@ -0,0 +1,10 @@
<?php
require "class/db.php";
require "header.php";
require "menu.php";
?>