1
0

récupération après crash

This commit is contained in:
Daniel Tartavel 2022-12-05 12:23:43 +01:00
parent 559039b5e3
commit a27db71327
22 changed files with 300 additions and 147 deletions

View File

@ -90,13 +90,16 @@ function apiServer($read)
logger(DEBUG, _("command is ") . $command, __FILE__ . ":" . __LINE__); logger(DEBUG, _("command is ") . $command, __FILE__ . ":" . __LINE__);
switch($command) switch($command)
{ {
case "?":
case "help":
htmlSend($spawn, help($argList));
break;
case "dashboard": case "dashboard":
apiDashboard($spawn, $argList["dashboard"]); apiDashboard($spawn, $argList["dashboard"]);
break; break;
case "browse": case "browse":
logger(DEBUG, _("Browsing"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("Browsing"), __FILE__ . ":" . __LINE__);
apiBrowse($spawn, $argList); apiBrowse($spawn, $argList);
//return true;
break; break;
case "get": case "get":
logger(DEBUG, _("GET reached"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("GET reached"), __FILE__ . ":" . __LINE__);
@ -116,8 +119,8 @@ function apiServer($read)
htmlSend($spawn, apiNotify($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, apiDisplayByType($argList)); //htmlSend($spawn, apiDisplayByType($argList));
case "enable": case "enable":
logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__); logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__);
@ -155,6 +158,10 @@ function apiServer($read)
logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__); logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__);
htmlSend($spawn, test($argList)); htmlSend($spawn, test($argList));
break; break;
case "unavailable":
logger(DEBUG, $command . _(" reached"), __FILE__ . ":" . __LINE__);
htmlSend($spawn, unavailable($argList));
break;
default: default:
if (is_numeric(array_key_first($argList))) if (is_numeric(array_key_first($argList)))
{ {

View File

@ -606,22 +606,86 @@ function whoIsPresent($argList)
function test() function test()
{ {
global $hooks; global $scripts;
$portes = array(); $portes = array();
$msg = ""; $msg = _("<b>Opened doors:</b>") . EOLH;
logger(DEBUG, _("Testing doors") , __FILE__ . ":" . __LINE__); logger(DEBUG, _("Testing doors") , __FILE__ . ":" . __LINE__);
echo "testing doors"; echo "testing doors";
$portes = $hooks["test_portes"]->testPortes(); $portes = $scripts["test_portes"]->testPortes();
if (!empty($portes)) if (!empty($portes))
{ {
$msg = _("Opened doors:") . EOLH;
foreach($portes as $value) foreach($portes as $value)
{ {
$msg .= $value . EOL; $msg .= $value . EOL;
} }
}else
{
$msg .= _("No doors opened");
}
return $msg;
}
function unavailable()
{
global $indexDevices;
$msg = _("<b>List of unavailable devices:</b>") . EOLH;
foreach($indexDevices as $ieeeAddress => $device)
{
if (key_exists("availability", $device->properties))
{
if ($device->properties["availability"]["value"] == "offline")
{
$msg .= $device->friendlyName . EOLH;
}
}
} }
return $msg; return $msg;
} }
function help()
{
$msg = "<table>";
$msg .= "<tr><td><b>Commands</b></td><td><b>Description and Parameters</b></td>";
$msg .= "<tr><td>browse</td><td>Browse device List<br>fn=friendlyname topic=topicname</td></tr>";
$msg .= "<tr><td>dashboard</td><td>Display dashboards<br>Name of the dashboard</td></tr>";
// $msg .= "<tr><td>deletedevice</td><td></td></tr>";
$msg .= "<tr><td>disable</td><td>Disable a hook<br>name of the hook</td></tr>";
$msg .= "<tr><td>dump</td><td>Display the content of a variable<br>variable name</td></tr>";
$msg .= "<tr><td>enable</td><td>Enable a hook<br>name of the hook</td></tr>";
$msg .= "<tr><td>friendlyname</td><td>Return friendlyname from ieeeadress<br>ieeeadress of device</td></tr>";
$msg .= "<tr><td>get</td><td>Get value of the property of a device<br>fn=friendlyname, topic=topic name, property=property name</td></tr>";
$msg .= "<tr><td>ispresent</td><td>Return the presence of a person<br>Name of the person</td></tr>";
$msg .= "<tr><td>notify</td><td>Notify when property condition and value<br>topic, fn, property, condition, value</td></tr>";
// $msg .= "<tr><td>type</td><td></td></tr>";
$msg .= "<tr><td>present</td><td>List persons present</td></tr>";
$msg .= "<tr><td>print</td><td>Dump the content of a variable<br>variable name</td></tr>";
$msg .= "<tr><td>property</td><td>Display all devices with given property<br>Property to display</td></tr>";
$msg .= "<tr><td>set</td><td>Set value of the property of a device<br>fn=friendlyname, topic=topic name, property=property name</td></tr>";
$msg .= "<tr><td>test</td><td>Return all opened doors</td></tr>";
$msg .= "<tr><td>unavailable</td><td>Displey all unavalaible devices</td></tr>";
$msg .= "<tr><td>verbose</td><td>Enable or disable log levels<br>" . htmlDisplayLoglevels() . "</td></tr>";
$msg .= "</table>";
return $msg;
}
function htmlDisplayLoglevels()
{
global $logLevels;
$text = "";
$flag = false;
foreach($logLevels as $level)
{
if ($flag === true)
{
$text .= " ,";
}else
{
$flag = true;
}
$text .= $level;
}
return $text;
}
?> ?>

View File

@ -18,10 +18,6 @@ class hook
{ {
$this->init(); $this->init();
} }
if (method_exists($this, "iterate"))
{
$this->iterate();
}
foreach ($this->devicelist as $ieeeAddress => $property) foreach ($this->devicelist as $ieeeAddress => $property)
{ {
$this->propertyInitialized[$ieeeAddress][$property] = false; $this->propertyInitialized[$ieeeAddress][$property] = false;

View File

@ -41,14 +41,17 @@ class device
public function __construct() public function __construct()
{ {
$this->availability = array("value" => null, "functions" => array()); $this->properties["availability"] = array("value" => null, "functions" => array());
} }
public function set($property, $method = IDLE) //, $event = null) public function set($property, $method = null) //, $event = null)
{
if ($method !== null)
{ {
publish($this->topic . "/" . $this->friendlyName, $this->payload, "set");//, $event);
$this->properties[$property]["method"] = $method; $this->properties[$property]["method"] = $method;
} }
publish($this->topic . "/" . $this->friendlyName, $this->payload, "set");//, $event);
}
public function get() public function get()
{ {

View File

@ -1,8 +1,9 @@
<?php <?php
$notificationLevel = ALERT; $notificationLevel = ALERT;
$logLevel = DEBUG | INFO | NOTICE | WARNING | ERROR | ALERT; $logLevel = NOTICE | WARNING | ERROR | ALERT;
//set the apiServer activ or not
$apiServerIsActive = true;
// le premier utilisateur est l'utilisateur par défaut // le premier utilisateur est l'utilisateur par défaut
$defaultUser = array( $defaultUser = array(
"rdc" => "Daniel", "rdc" => "Daniel",

View File

@ -35,7 +35,7 @@ $properties2log = array(
"UV" => null, "UV" => null,
"indoortempc" => 0.5, "indoortempc" => 0.5,
"indoorhumidity" => 0.5, "indoorhumidity" => 0.5,
"baromin" => 10, "barominmb" => 10,
"presence" => null, "presence" => null,
"vibration" => null "vibration" => null
); );

View File

@ -1,22 +1,22 @@
<?php <?php
$directionVent = array( $directionVent = array(
array("N", "Nord", "0"), 1 => array("N", "Nord", "0"),
array("NNE", "NordNordEst", "22,5"), 2 => array("NNE", "NordNordEst", "22,5"),
array("NE", "NordEst", "45"), 3 => array("NE", "NordEst", "45"),
array("ENE", "EstNordEst", "67,5"), 4 => array("ENE", "EstNordEst", "67,5"),
array("E", "Est", "90"), 5 => array("E", "Est", "90"),
array("ESE", "EstSudEst", "112,5"), 6 => array("ESE", "EstSudEst", "112,5"),
array("SE", "SudEst", "135"), 7 => array("SE", "SudEst", "135"),
array("SSE", "SudSudEst", "157,5"), 8 => array("SSE", "SudSudEst", "157,5"),
array("S", "Sud", "180"), 9 => array("S", "Sud", "180"),
array("SSO", "SudSudOuest", "202,5"), 10 => array("SSO", "SudSudOuest", "202,5"),
array("SO", "SudOuest", "225"), 11 => array("SO", "SudOuest", "225"),
array("OSO", "OuestSudOuest", "247,5"), 12 => array("OSO", "OuestSudOuest", "247,5"),
array("O", "Ouest", "270"), 13 => array("O", "Ouest", "270"),
array("ONO", "OuestNordOuest", "292,5"), 14 => array("ONO", "OuestNordOuest", "292,5"),
array("NO", "NordOuest", "315"), 15 => array("NO", "NordOuest", "315"),
array("NNO", "NordNordOuest", "337,5") 16 => array("NNO", "NordNordOuest", "337,5")
) )
?> ?>

View File

@ -23,5 +23,12 @@ function configWatchInit()
} }
} }
function configWatchStop()
{
// stop la surveillance
inotify_rm_watch($cwfd, $watch_descriptor);
// Destruction de l'instance inotify
fclose($cwfd);
}
?> ?>

View File

@ -51,7 +51,7 @@ while (1)
} }
} }
$result = array(); $result = array();
//ésleep(1); //sleep(1);
} }
function search($string) function search($string)
@ -63,15 +63,15 @@ function search($string)
//echo "searching in " . $string . EOL; //echo "searching in " . $string . EOL;
foreach ($macAddresses as $needle => $nom) foreach ($macAddresses as $needle => $nom)
{ {
echo $string . " ==> presenceD:" . $nom ." => " . $needle . EOL; //echo $string . " ==> presenceD:" . $nom ." => " . $needle . EOL;
if (str_contains($string, $needle)) if (str_contains($string, $needle))
{ {
echo "presenceD: found " . $needle . EOL; //echo "presenceD: found " . $needle . EOL;
$presenceTemp[$nom] = true; $presenceTemp[$nom] = true;
$flag = true; $flag = true;
} }
} }
var_dump($presenceTemp); //var_dump($presenceTemp);
return $presenceTemp; return $presenceTemp;
} }
@ -87,7 +87,7 @@ function send($msg)
// return the transfer as a string // return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $result contains the output string // $result contains the output string
echo _("presenceDaemon: Curl sending message -") . $msg . __FILE__ . ":" . __LINE__ . EOL; //echo _("presenceDaemon: Curl sending message -") . $msg . __FILE__ . ":" . __LINE__ . EOL;
if ($curlErr <= 5) if ($curlErr <= 5)
{ {

View File

@ -88,6 +88,7 @@ function addDevice($topic, $fn, $jsonDevice, $group=false )
{ {
$device["device"]->type = $jsonDevice["type"]; $device["device"]->type = $jsonDevice["type"];
$device["device"]->ieeeAddress = $jsonDevice["ieee_address"]; $device["device"]->ieeeAddress = $jsonDevice["ieee_address"];
$hooks["availability"]->installHook($device);
if ( !empty($jsonDevice["power_source"] )) if ( !empty($jsonDevice["power_source"] ))
{ {
$device["device"]->powerSource = $jsonDevice["power_source"]; $device["device"]->powerSource = $jsonDevice["power_source"];
@ -126,7 +127,7 @@ function searchPropertyKey($fn, &$device, $inputObject, $listPropertiesKeys)
$device->properties[$string]["functions"] = array(); $device->properties[$string]["functions"] = array();
if(array_key_exists("access", $inputObject)) if(array_key_exists("access", $inputObject))
{ {
if ($inputObject["access"] && 2) if ($inputObject["access"] & 2)
{ {
$device->properties[$string]["method"] = IDLE; $device->properties[$string]["method"] = IDLE;
} }
@ -231,7 +232,7 @@ function iterateDevice($topic, $fn, &$parentDevice, &$properties, $payloadArray,
$properties[$key]["functions"] = array(); $properties[$key]["functions"] = array();
if (array_key_exists("access", $properties[$key])) if (array_key_exists("access", $properties[$key]))
{ {
if ($properties[$key]["access]"] && 2) if ($properties[$key]["access]"] & 2)
{ {
$properties[$key]["method"] = IDLE; $properties[$key]["method"] = IDLE;
} }
@ -265,17 +266,13 @@ function getDevicesValues($topic)
{ {
if ($value["access"] & 4) if ($value["access"] & 4)
{ {
logger(DEBUG, _("Getting values of property: " . $property), __FILE__ . ":" . __LINE__ );
$device->payload[$property] = ""; $device->payload[$property] = "";
$flag = true; $device->get();
break; break;
} }
} }
} }
//logger(DEBUG, print_r($device->payload, true), __FILE__ . ":" . __LINE__ );
if ($flag === true)
{
$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__ );
@ -295,6 +292,15 @@ function changeValue(&$property, $value, &$parentDevice, $propertyTree, $key)
{ {
logger(INFO, sprintf(_("Logging Device property %s, %s"), $propertyTree . $key, bool2string($value)), __FILE__ . ":" . __LINE__); logger(INFO, sprintf(_("Logging Device property %s, %s"), $propertyTree . $key, bool2string($value)), __FILE__ . ":" . __LINE__);
$mohaDB->logProperty($parentDevice, $key, $value); $mohaDB->logProperty($parentDevice, $key, $value);
/*
if (!empty($propertiesLoggers))
{
foreach($propertiesLoggers as $logger)
{
$logger->callBack($parentDevice, $key, $value);
}
}
*/
logger(DEBUG, sprintf(_("old value was %s, new is %s" ), bool2string($property["value"]), bool2string($value)), __FILE__ . ":" . __LINE__); logger(DEBUG, sprintf(_("old value was %s, new is %s" ), bool2string($property["value"]), bool2string($value)), __FILE__ . ":" . __LINE__);
} }
$property["value"] = $value; $property["value"] = $value;

View File

@ -7,34 +7,31 @@ class availability extends hook
// by default all devices are listening for availability // by default all devices are listening for availability
protected $devicelist = array(); protected $devicelist = array();
function init()
{
global $indexDevices;
$this->iterate();
}
protected function iterate() protected function iterate()
{ {
global $indexDevices; global $indexDevices;
foreach ($indexDevices as $ieeeAddress => $value) foreach ($indexDevices as $ieeeAddress => $value)
{ {
$deviceList[] = array( $ieeeAddress => "availability"); if (!key_exists("availability", $value->properties))
{
$value->properties["availability"] = "";
}
} }
$this->installHooksFunction($indexDevices); $this->installHooksFunction($indexDevices);
} }
function installHooks(&$indexDevices) function installHooks(&$indexDevices)
{ {
static $indexDevicesSize; $this->installHooksFunction($indexDevices);
$tmp = count($indexDevices);
if ($tmp != $indexDevicesSize)
{
$this->iterate();
$indexDevicesSize = $tmp;
}
return false; return false;
} }
function installHook(&$device)
{
global $indexDevices;
$this->devicelist = array($device["device"]->ieeeAddress => "availability");
$this->installHooksFunction($indexDevices);
}
// callback fonction. Is called with these 3 parameters // callback fonction. Is called with these 3 parameters
// $device -> calling device // $device -> calling device
// $property -> parameter passed by mqtt // $property -> parameter passed by mqtt
@ -48,7 +45,7 @@ class availability extends hook
{ {
//echo "==========>>>>>> Availability $value" . EOL; //echo "==========>>>>>> Availability $value" . EOL;
//if (!empty($device->availability)) //if (!empty($device->availability))
//{[ Torrent911.com] //{
$log = ALERT; $log = ALERT;
//}else //}else
//{ //{

View File

@ -9,7 +9,7 @@ class etage_temperature_int_ext extends hook
protected $devicelist = array( protected $devicelist = array(
METEO=> "tempc", METEO => "tempc",
); );
protected $portesList = array( protected $portesList = array(

View File

@ -49,11 +49,6 @@ class radiateurs extends hook
// ETAGE_CHAMBRE_RADIATEUR => 0 // ETAGE_CHAMBRE_RADIATEUR => 0
); );
function installHooks(&$indexDevices)
{
return $this->installHooksFunction($indexDevices);
}
// callback fonction. Is called with these 3 parameters // callback fonction. Is called with these 3 parameters
public function callBack(&$device, $property, $value) public function callBack(&$device, $property, $value)
{ {
@ -61,6 +56,7 @@ class radiateurs extends hook
logger(DEBUG, "Callback : " . $this->hookName, __FILE__ . ":" . __LINE__); logger(DEBUG, "Callback : " . $this->hookName, __FILE__ . ":" . __LINE__);
if ($this->active === true) if ($this->active === true)
{ {
// test mois entre mai et octobre
$now = date("MM"); $now = date("MM");
if ($now <= 5 or $now >= 11) if ($now <= 5 or $now >= 11)
{ {
@ -98,17 +94,22 @@ class radiateurs extends hook
} }
} }
// state = true when a door or window is open
function send($device, $state) function send($device, $state)
{ {
global $indexDevices; global $indexDevices;
$flag = false; $flag = false;
if ($state === false) $setTo = 0;
if ($state === true)
{ {
$t = getValue($device->ieeeAddress, "current_heating_setpoint"); $t = getValue($device->ieeeAddress, "current_heating_setpoint");
if ($t != $this->minTemp) if ($t != $this->minTemp)
{ {
$this->prevTemp[$device->ieeeAddress] = getValue($device->ieeeAddress, "current_heating_setpoint"); $this->prevTemp[$device->ieeeAddress] = getValue($device->ieeeAddress, "current_heating_setpoint");
} }
$setTo = $minTemp;
}else }else
{ {
$r = array_keys($this->hvac, $device->ieeeAddress); $r = array_keys($this->hvac, $device->ieeeAddress);
@ -123,12 +124,17 @@ class radiateurs extends hook
} }
if ($flag === false) if ($flag === false)
{ {
$msg = array("current_heating_setpoint" => (!empty($this->prevTemp[$device->ieeeAddress])?$this->prevTemp[$device->ieeeAddress]:19)); $setTo = (!empty($this->prevTemp[$device->ieeeAddress])?$this->prevTemp[$device->ieeeAddress]:19);
}
}
if ($setTo <> 0)
{
$msg = array("current_heating_setpoint" => $setTo );
logger(INFO, sprintf(_("publishing message: %s to %s"), json_encode($msg), $device->friendlyName), __FILE__ . ":" . __LINE__); logger(INFO, sprintf(_("publishing message: %s to %s"), json_encode($msg), $device->friendlyName), __FILE__ . ":" . __LINE__);
$device->payload = $msg; $device->payload = $msg;
$device->set("current_heating_setpoint", AUTO); $device->set("current_heating_setpoint", AUTO);
$device->properties["current_heating_setpoint"]["method"] = AUTO; //$device->properties["current_heating_setpoint"]["method"] = AUTO;
}
} }
} }
} }

View File

@ -48,7 +48,9 @@ class rdc_salon_eclairage extends hook
$method = $deviceTarget->properties["state"]["method"]; $method = $deviceTarget->properties["state"]["method"];
logger(INFO, sprintf (_("CASE: %s => "), $param) . bool2string($value), __FILE__ . ":" . __LINE__); logger(INFO, sprintf (_("CASE: %s => "), $param) . bool2string($value), __FILE__ . ":" . __LINE__);
//print_r(getValue(RDC_SALON_LUMINOSITE, "illuminance_lux")); //print_r(getValue(RDC_SALON_LUMINOSITE, "illuminance_lux"));
if ($value == ON and $method == IDLE) if ($value == ON)
{
if ($method == IDLE)
{ {
logger(INFO, _("illuminance value : ") . $illuminance, __FILE__ . ":" . __LINE__); logger(INFO, _("illuminance value : ") . $illuminance, __FILE__ . ":" . __LINE__);
if ($illuminance <= $this->luminance_min) if ($illuminance <= $this->luminance_min)
@ -57,11 +59,11 @@ class rdc_salon_eclairage extends hook
$this->send($deviceTarget, "ON", false, AUTO); $this->send($deviceTarget, "ON", false, AUTO);
removeEvent($deviceTarget, "state", "OFF"); removeEvent($deviceTarget, "state", "OFF");
} }
}else }
}elseif ($method == AUTO)
{ {
logger(INFO, _("Value is OFF and method is ") . $method, __FILE__ . ":" . __LINE__); logger(INFO, _("Value is OFF and method is ") . $method, __FILE__ . ":" . __LINE__);
if ((testActionneurs($this->actionneurs) == false) and ($method == AUTO)) if (testActionneurs($this->actionneurs) == 0)
//if ((getValue(RDC_SALON_MVMT, "occupancy") == OFF) and (getValue(RDC_SALON_MVMT2, "occupancy") == OFF) and $method == AUTO)
{ {
logger(INFO, _("Setting to OFF"), __FILE__ . ":" . __LINE__); logger(INFO, _("Setting to OFF"), __FILE__ . ":" . __LINE__);
$this->send($deviceTarget, "OFF", false, IDLE); $this->send($deviceTarget, "OFF", false, IDLE);
@ -97,10 +99,13 @@ class rdc_salon_eclairage extends hook
case "state": case "state":
logger(INFO, _("CASE : State"), __FILE__ . ":" . __LINE__); logger(INFO, _("CASE : State"), __FILE__ . ":" . __LINE__);
$method = $deviceTarget->properties["state"]["method"]; $method = $deviceTarget->properties["state"]["method"];
if($value == "ON" and $method == IDLE) if($value == "ON")
{
if ($method == IDLE)
{ {
$deviceTarget->properties["state"]["method"] = MANUAL; $deviceTarget->properties["state"]["method"] = MANUAL;
removeEvent($deviceTarget, "state", "OFF"); removeEvent($deviceTarget, "state", "OFF");
}
}else }else
{ {
$deviceTarget->properties["state"]["method"] = IDLE; $deviceTarget->properties["state"]["method"] = IDLE;

View File

@ -9,9 +9,9 @@ class rdc_sdb_eclairage extends hook
// public $active = true; // public $active = true;
//public $initlialized = false; //public $initlialized = false;
public $delay = 3; // amount of time in $timeunit //public $delay = 3; // amount of time in $timeunit
public $delayManual = 20; // amount of time in $timeunit for manual mode public $delayManual = 2; // amount of time in $timeunit for manual mode
public $timeUnit = "minute"; // unit of time for delay, second, minute, day, week, month, year public $timeUnit = "hour"; // unit of time for delay, second, minute, day, week, month, year
// list of devices we are listening to // list of devices we are listening to
// devicelist[$ieeAddress][0] => property to watch // devicelist[$ieeAddress][0] => property to watch
@ -45,42 +45,42 @@ class rdc_sdb_eclairage extends hook
$deviceTarget = &$indexDevices[RDC_SDB_WC_ECLAIRAGE]; $deviceTarget = &$indexDevices[RDC_SDB_WC_ECLAIRAGE];
logger(DEBUG, "Callback : " . $this->hookName, __FILE__ . ":" . __LINE__); logger(DEBUG, "Callback : " . $this->hookName, __FILE__ . ":" . __LINE__);
$method = $deviceTarget->properties["state_l1"]["method"]; $method = $deviceTarget->properties["state_l1"]["method"];
logger(DEBUG, "Method is " . $method, __FILE__ . ":" . __LINE__);
switch($property) switch($property)
{ {
case "occupancy": case "occupancy":
logger(DEBUG, _("CASE: occupancy"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("CASE: occupancy"), __FILE__ . ":" . __LINE__);
if ($value == ON) if ($value === ON)
{ {
if($method == IDLE) if($method === IDLE)
{ {
logger(DEBUG, _("lighting with method auto"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("lighting with method auto"), __FILE__ . ":" . __LINE__);
//$deviceTarget->properties["state_l1"]["method"] = AUTO;
$this->send("ON", AUTO); $this->send("ON", AUTO);
removeEvent($deviceTarget, "state", "OFF"); //removeEvent($deviceTarget, "state", "OFF");
} }
}elseif (!testActionneurs($this->actionneurs)) }elseif ((testActionneurs($this->actionneurs) == 0) and ($method == AUTO))
{ {
logger(DEBUG, _("Actionneurs are all false"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("Actionneurs are all false"), __FILE__ . ":" . __LINE__);
$this->send("OFF", IDLE); $this->send("OFF", IDLE);
removeEvent($deviceTarget, "state", "OFF"); //removeEvent($deviceTarget, "state", "OFF");
} }
break; break;
case "state_l1": case "state_l1":
logger(DEBUG, _("CASE: state_l1"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("CASE: state_l1"), __FILE__ . ":" . __LINE__);
if ($value == "ON") if ($value == "ON")
{ {
if ($method == IDLE) if ($method === IDLE)
{ {
logger(DEBUG, _("State_l1 is IDLE"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("State_l1 is IDLE"), __FILE__ . ":" . __LINE__);
removeEvent($deviceTarget, "state_l1", "OFF"); //removeEvent($deviceTarget, "state_l1", "OFF");
$deviceTarget->properties["state_l1"]["method"] = MANUAL; $deviceTarget->properties["state_l1"]["method"] = MANUAL;
//setDelay($deviceTarget, $this->delayManual, $this->timeUnit, "state_l1", "OFF", true, IDLE); setDelay($deviceTarget, $this->delayManual, $this->timeUnit, "state_l1", "OFF", true, IDLE);
} }
}elseif ($value == "OFF" and $method == MANUAL) }elseif ($value == "OFF")
{ {
$deviceTarget->properties["state_l1"]["method"] = IDLE; $deviceTarget->properties["state_l1"]["method"] = IDLE;
removeEvent($deviceTarget, "state_l1", "OFF"); removeEvent($deviceTarget, "state_l1", "OFF");
//$deviceTarget->properties["state_l1"]["method"] = IDLE;
logger(DEBUG, _("State_l1 is false light is off and method is ") . $method, __FILE__ . ":" . __LINE__); logger(DEBUG, _("State_l1 is false light is off and method is ") . $method, __FILE__ . ":" . __LINE__);
} }
break; break;
@ -93,17 +93,17 @@ class rdc_sdb_eclairage extends hook
} }
} }
private function send($state, $method) public function send($state, $method)
{ {
global $indexDevices; global $indexDevices;
$device = &$indexDevices[RDC_SDB_WC_ECLAIRAGE]; $device = &$indexDevices[RDC_SDB_WC_ECLAIRAGE];
$device->properties["state_l1"]["method"] = $method; //$device->properties["state_l1"]["method"] = $method;
logger(DEBUG, "method = " . $device->properties["state_l1"]["method"], __FILE__ . ":" . __LINE__);
$msg = array("state_l1" => $state); $msg = array("state_l1" => $state);
$device->payload = $msg; $device->payload = $msg;
$device->set("state_l1"); $device->set("state_l1", $method);
logger(INFO, sprintf(_("publishing message: %s to %s"), $state, $device->friendlyName), __FILE__ . ":" . __LINE__); logger(INFO, sprintf(_("publishing message: %s to %s"), $state, $device->friendlyName), __FILE__ . ":" . __LINE__);
} }
} }
$hooks["rdc_sdb_eclairage"] = new rdc_sdb_eclairage(); $hooks["rdc_sdb_eclairage"] = new rdc_sdb_eclairage();

View File

@ -251,7 +251,7 @@ class rdc_store extends hook
{ {
global $indexDevices; global $indexDevices;
$deviceObject = $indexDevices[RDC_STORE]; $deviceObject = $indexDevices[RDC_STORE];
$msg = array("position" => $level); $msg = array("position" => 100 - $level);
logger(INFO, sprintf(_("publishing message: %s to %s"), json_encode($msg), $deviceObject->friendlyName), __FILE__ . ":" . __LINE__); logger(INFO, sprintf(_("publishing message: %s to %s"), json_encode($msg), $deviceObject->friendlyName), __FILE__ . ":" . __LINE__);
$deviceObject->payload = $msg; $deviceObject->payload = $msg;
$deviceObject->set("position", $method); $deviceObject->set("position", $method);

View File

@ -29,7 +29,7 @@ class rdc_temperature_int_ext extends hook
// callback fonction. Is called with these 4 parameters // callback fonction. Is called with these 4 parameters
public function callBack(&$device, $property, $value) public function callBack(&$device, $property, $value)
{ {
global $indexDevices, $hooks; global $indexDevices, $scripts;
static $time; static $time;
$portes = array(); $portes = array();
$status = -1; $status = -1;
@ -76,7 +76,7 @@ class rdc_temperature_int_ext extends hook
//print_r($portes); //print_r($portes);
if ($status == 1) if ($status == 1)
{ {
$portes = $hooks["test_portes"]->testPortes($this->portesList, false, false); $portes = $scripts["test_portes"]->testPortes($this->portesList, false, false);
if (empty($portes)) if (empty($portes))
{ {
$time = now(); $time = now();
@ -88,7 +88,7 @@ class rdc_temperature_int_ext extends hook
} }
}else }else
{ {
$portes = $hooks["test_portes"]->testPortes($this->portesList, false, true); $portes = $scripts["test_portes"]->testPortes($this->portesList, false, true);
if (!empty($portes)) if (!empty($portes))
{ {
$time = now(); $time = now();

View File

@ -1,14 +1,17 @@
<?php <?php
$title = "moha"; $title = "moha";
cli_set_process_title($title); 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 = false; $testMode = false;
$apiServerIsActive = true;
require "constants.php"; require "constants.php";
//Test mode is executing moha from its directory
//no test mode, moha is system wide
if ($testMode) if ($testMode)
{ {
$logLevel = ALL; // INFO | NOTICE | WARNING | ERROR | ALERT; //ALL; $logLevel = ALL; // INFO | NOTICE | WARNING | ERROR | ALERT; //ALL;
@ -28,6 +31,8 @@ if ($testMode)
} }
require $configDir . "/config.php"; require $configDir . "/config.php";
require $configDir . "/liste_telephones.php";
$listProperties = array("powerSource" => "batterie"); $listProperties = array("powerSource" => "batterie");
$listPropertiesKeys = array("expose"); $listPropertiesKeys = array("expose");
@ -42,6 +47,8 @@ $indexTypes = array();
$indexProperties = array(); // index of properties $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
$scripts = array(); // array of user's script
$propertiesLoggers = array(); // array of loggers's callbacks
$topicsCallbacks = array(); // array of topics's callbacks $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
@ -58,10 +65,9 @@ $hooksInitialized = 0; // are all hooks initialized ? false/true
$flagHooks = false; $flagHooks = false;
$devicesRequest = false; // set to true when publishing device request to zigbee2mqtt $devicesRequest = false; // set to true when publishing device request to zigbee2mqtt
$presence = array(); // name and status of presence $presence = array(); // name and status of presence
$timeLoop = new datetime("now");
// initalisation
if (!init()) exit(1); if (!init()) exit(1);
// (re)démarre le démon de présence // (re)démarre le démon de présence
@ -71,6 +77,10 @@ system("sudo /usr/bin/systemctl restart presenceD.service");
bindtextdomain("moha", "./locale"); bindtextdomain("moha", "./locale");
textdomain("moha"); textdomain("moha");
######################################################################################################################
## Fonctions ##
######################################################################################################################
function notify($message, $device) function notify($message, $device)
{ {
global $notificationMethods, $defaultUser; global $notificationMethods, $defaultUser;
@ -192,10 +202,9 @@ function endMoha()
logger(ERROR, _("Can not store events db" ), __FILE__ . ":" . __LINE__); logger(ERROR, _("Can not store events db" ), __FILE__ . ":" . __LINE__);
} }
if($testMode) file_put_contents($dataPath . "moha.devices", var_export($devices, true)); if($testMode) file_put_contents($dataPath . "moha.devices", var_export($devices, true));
// stop la surveillance
inotify_rm_watch($cwfd, $watch_descriptor); configWatchStop();
// Destruction de l'instance inotify
fclose($cwfd);
if ($connected) if ($connected)
{ {
$mid = $client->unsubscribe("#"); $mid = $client->unsubscribe("#");
@ -219,9 +228,12 @@ function connect2mqttServer()
global $client; global $client;
$client->onConnect('connectResponse'); $client->onConnect('connectResponse');
} }
######################################################################################################################
## Main program ##
######################################################################################################################
logger(ALERT, _("starting moha"), __FILE__ . ":" . __LINE__); logger(ALERT, _("starting moha"), __FILE__ . ":" . __LINE__);
logger(DEBUG, _("requiring config files -> devices_constants.php"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("requiring config files -> devices_constants.php"), __FILE__ . ":" . __LINE__);
//include predefined file witch define constants for devices //include predefined file witch define constants for devices
if (is_readable($configDir . "/devices_constants.php")) if (is_readable($configDir . "/devices_constants.php"))
@ -247,9 +259,6 @@ require "config/liste_telephones.php";
require "presence.php"; require "presence.php";
require "apiserver/apiserver.php"; require "apiserver/apiserver.php";
require "configWatch.php"; require "configWatch.php";
require $configDir . "/liste_telephones.php";
logger(DEBUG, _("Loading stored events datas from ") . $dataPath . "events.db", __FILE__ . ":" . __LINE__); logger(DEBUG, _("Loading stored events datas from ") . $dataPath . "events.db", __FILE__ . ":" . __LINE__);
if (file_exists($dataPath . "events.db")) if (file_exists($dataPath . "events.db"))
@ -290,6 +299,17 @@ if (!empty($hooksList)) // hooks to include if hooklist is not empty
$included = true; $included = true;
} }
//making list of scripts to include
listHooks("./scripts", $scriptsList);
if (!empty($scriptsList))
{
foreach ($scriptsList as $script)
{
logger(INFO, _("Including ") . $script, __FILE__ . ":" . __LINE__);
include $script;
}
}
logger(DEBUG, _("Loading stored topics datas from ") . $dataPath . "topics.db", __FILE__ . ":" . __LINE__); logger(DEBUG, _("Loading stored topics datas from ") . $dataPath . "topics.db", __FILE__ . ":" . __LINE__);
if (file_exists($dataPath . "topics.db")) if (file_exists($dataPath . "topics.db"))
{ {
@ -366,16 +386,25 @@ configWatchInit();
while (true) while (true)
{ {
// test if looping is more then 5 second and send and alert
$now = new datetime("now");
$testTime = clone $now;
$testTime->modify("-5 second");
if ($timeLoop < $testTime)
{
logger(ALERT, _("MOHA Looping is > to 5 seconds"), __FILE__ . ":" . __LINE__);
}
$timeLoop = $now;
$client->loop(); // mqtt server loop() $client->loop(); // mqtt server loop()
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 may not be initialized
{ {
logger(DEBUG, _("Oneshot part of loop"), __FILE__ . ":" . __LINE__, false); logger(DEBUG, _("Oneshot part of loop"), __FILE__ . ":" . __LINE__, false);
pws2mqttGetList(); pws2mqttGetList();
$oneshot = true; $oneshot = true;
} }
$nn = 0;
if($hooksInitialized == 0) // all hooks are not initialized if($hooksInitialized == 0) // all hooks are not initialized
{ {
$i = 1; $i = 1;
@ -394,16 +423,17 @@ while (true)
} }
} }
$hooksInitialized = $i; $hooksInitialized = $i;
}elseif($flagHooks === false) /*}elseif($flagHooks === false)
{ {
logger(DEBUG, _("All hooks initialized"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("All hooks initialized"), __FILE__ . ":" . __LINE__);
$flagHooks = true; $flagHooks = true;*/
}else // executed when hooks initialization finished but database init not finished }else // executed when hooks initialization finished but database init may be not finished
{ {
//logger(DEBUG, _("looping"), __FILE__ . ":" . __LINE__); //logger(DEBUG, _("looping"), __FILE__ . ":" . __LINE__);
} }
checkEvents(); checkEvents();
checkTopicsAvailability(); checkTopicsAvailability();
if ($apiServerIsActive) apiServer($read); if ($apiServerIsActive) apiServer($read);
// surveillance du dossier de configuration // surveillance du dossier de configuration
@ -420,13 +450,11 @@ while (true)
include $configDir . "/" . $event["name"]; include $configDir . "/" . $event["name"];
}else }else
{ {
logger(DEBUG, _("configWatch : mauvaise extension, n'inclus pas ") . $configDir . "/" . $event["name"], __FILE__ . ":" . __LINE__); logger(DEBUG, _("configWatch : mauvaise extension, je n'inclus pas ") . $configDir . "/" . $event["name"], __FILE__ . ":" . __LINE__);
} }
} }
} }
} }
//presence();
} }
endMoha(); endMoha();

View File

@ -1,4 +1,6 @@
<?php <?php
// mosquitto-php related functions
logger(DEBUG,"Including mqtt_functions.php"); logger(DEBUG,"Including mqtt_functions.php");
function messageReceived($message) function messageReceived($message)
@ -98,7 +100,7 @@ function disconnectResponse($r)
{ {
$str = _('Cleanly '); $str = _('Cleanly ');
} }
logger(ERROR, $str . _("disconnected from server")); logger(ALERT, $str . _("disconnected from server"));
$connected = false; $connected = false;
} }

View File

@ -2,27 +2,51 @@
require_once "events.php"; require_once "events.php";
class test_portes extends hook class test_portes
{ {
public $hookName = "test_portes"; public $hookName = "test_portes";
public $active = true; public $active = true;
protected $devicelist = array( public $deviceList = array(
RDC_ENTREE_PORTE => "contact",
GARAGE_PORTAIL => "contact",
GARAGE_PORTE => "contact",
ETAGE_PORTE_FENETRE => "contact",
ETAGE_CUISINE_FENETRE => "contact",
ETAGE_SALON_FENETRE => "contact",
RDC_CHAMBRE_BAIE => "contact",
RDC_SALON_BAIE => "contact",
); );
function installHooks(&$indexDevices) /*function installHooks(&$indexDevices)
{ {
return $this->installHooksFunction($indexDevices); return 1;
} }*/
public function testPortes($deviceList=false, $send=true, $opened=true) :array public function testPortes($deviceList=false, $send=true, $opened=true) :array
{ {
global $indexDevices; global $indexDevices, $hooks;
$portes = array(); $portes = array();
logger(DEBUG, _("Function testPorte"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("Function testPorte"), __FILE__ . ":" . __LINE__);
if ($deviceList === false) $deviceList = $hooks["rdc_portes_ouvertes"]->devicelist; if ($deviceList === false)
{
if (key_exists("rdc_portes_ouvertes", $hooks))
{
if (property_exists($hooks["rdc_portes_ouvertes"], devicelist))
{
$deviceList = $hooks["rdc_portes_ouvertes"]->devicelist;
}else
{
$deviceList = $this->deviceList;
}
}else
{
$deviceList = $this->deviceList;
}
}
$msg = ""; $msg = "";
foreach ($deviceList as $device => $property) foreach ($deviceList as $device => $property)
{ {
@ -55,8 +79,8 @@ class test_portes extends hook
return $portes; return $portes;
} }
} }
$hooks["test_portes"] = new test_portes(); $scripts["test_portes"] = new test_portes();
logger(DEBUG, _("Initializing event"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("Initializing test_portes"), __FILE__ . ":" . __LINE__);
$function = array($hooks["test_portes"], "testPortes"); $function = array($scripts["test_portes"], "testPortes");
//setRecurrentEvent("test_portes", $function, "", "", 0, -1, "", "", false, 21); //setRecurrentEvent("test_portes", $function, "", "", 0, -1, "", "", false, 21);
?> ?>

View File

@ -17,7 +17,14 @@ chown domotique:domotique -R /var/log/moha.log
# GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost'; # GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
systemctl daemon-reload systemctl daemon-reload
systemctl enable presenceD.service R=`systemctl is-enabled presenceD.service`
systemctl enable moha.service if [ $R != "enabled" ];then
echo "enabling presenceD.service"
systemctl enable presenceD.service
fi
R=`systemctl is-enabled moha.service`
if [ $R != "enabled" ];then
echo "enabling moha.service"
systemctl enable moha.service
fi
#must enable service #must enable service

View File

@ -24,7 +24,7 @@ function checkTopicsAvailability()
{ {
if ($topic->status == 1) if ($topic->status == 1)
{ {
logger(DEBUG, "Topic is :" . $topicName . " and time is " . time() . " lastSeen is " . $topic->lastSeen, __FILE__ . ":" . __LINE__ ); //logger(DEBUG, "Topic is :" . $topicName . " and time is " . time() . " lastSeen is " . $topic->lastSeen, __FILE__ . ":" . __LINE__ );
if ((time() - $topic->lastSeen > $topic->timeOut*60) and ($topic->notificationSent == false)) if ((time() - $topic->lastSeen > $topic->timeOut*60) and ($topic->notificationSent == false))
{ {
if (logger(ALERT, $topicName . _(" is not available"), __FILE__ . ":" . __LINE__) == false); if (logger(ALERT, $topicName . _(" is not available"), __FILE__ . ":" . __LINE__) == false);