1
0

debuggage

This commit is contained in:
daniel Tartavel 2022-01-23 09:46:06 +01:00
parent 10f2a1087a
commit fc4eaf2238
14 changed files with 294 additions and 157 deletions

View File

@ -3,7 +3,7 @@ logger(DEBUG,"Including db.php");
class db extends mysqli class db extends mysqli
{ {
public $mysqlServer = "localhost"; // "127.0.0.1"; public $mysqlServer = "127.0.0.1"; // Your production server
public $username = "moha"; public $username = "moha";
public $passwd = "MysqlMoha"; public $passwd = "MysqlMoha";
public $database = "moha"; public $database = "moha";
@ -11,10 +11,21 @@ class db extends mysqli
function __construct() function __construct()
{ {
if ($this->connect($this->mysqlServer, $this->username, $this->passwd, $this->database) === false) global $testMode;
$flagError = false;
if ($testMode)
{ {
logger(ERROR,"Connection to sql server error :" . $this->connect_error); $this->mysqlServer = "192.168.1.253"; // Your test server
return 2; }
while ($this->connect($this->mysqlServer, $this->username, $this->passwd, $this->database) === false)
{
logger(ERROR,_("Connection to sql server error :") . $this->connect_error);
sleep(5);
$flagError = true;
}
if ($flagError === true)
{
logger(ERROR, _("Connection to sql server ready"));
} }
$result = new mysqli_result($this); $result = new mysqli_result($this);
} }
@ -38,14 +49,19 @@ class db extends mysqli
if (is_numeric($value) and !empty($properties2log[$propertyTree])) if (is_numeric($value) and !empty($properties2log[$propertyTree]))
{ {
// calculate a min/max value for storing data // calculate a min/max value for storing data
$var = $properties2log[$propertyTree]; $var = $properties2log[$propertyTree];
if (!is_numeric($var)) if (is_callable($var))
{ {
$minMax = (float)$value * (float)$var / 100; $var = $var($value);
}else
{
$minMax = $var;
} }
//if (!is_numeric($var))
//{
$minMax = (float)$value + $var;
//}else
//{
// $minMax = $var;
//}
echo "minMax = " .$minMax . EOL; echo "minMax = " .$minMax . EOL;
//echo "oldValue = " . $oldValue . EOL; //echo "oldValue = " . $oldValue . EOL;
//echo "Value = " . $value . EOL; //echo "Value = " . $value . EOL;

View File

@ -11,6 +11,10 @@ class hook
{ {
logger(DEBUG, _("Initializing hook: ") . $this->hookName); logger(DEBUG, _("Initializing hook: ") . $this->hookName);
$this->installHooks(); $this->installHooks();
if (method_exists($this, "init"))
{
$this->init();
}
} }
function installHooks() function installHooks()

View File

@ -32,11 +32,11 @@ class device
public $functions; public $functions;
public $payload; public $payload;
public $availability; public $availability;
public $toConfirm;
private function __construct() private function __construct()
{ {
$this->availability = array("value" => null, "functions" => array()); $this->availability = array("value" => null, "functions" => array());
var_dump($this->availability);
} }
public function set($method=0) //, $event = null) public function set($method=0) //, $event = null)

View File

@ -19,7 +19,10 @@ $deviceTable = array(
"0x00124b001f90ee7e" => "ENTREE_PORTE", "0x00124b001f90ee7e" => "ENTREE_PORTE",
"0x00124b002226d9a2" => "GARAGE_PORTE", "0x00124b002226d9a2" => "GARAGE_PORTE",
"0x00124b001f90e725" => "RDC_CHAMBRE_BAIE", "0x00124b001f90e725" => "RDC_CHAMBRE_BAIE",
"0x00124b002226e384" => "RDC_SALON_BAIE" "0x00124b002226e384" => "RDC_SALON_BAIE",
"0x842e14fffe8c53a5" => "ETAGE_CUISINE_PLAN_TRAVAIL_INTER",
"0x680ae2fffe403f22" => "ETAGE_CUISINE_PLAN_TRAVAIL_ECLAIRAGE",
"0xbc33acfffe65621b" => "ETAGE_CUISINE_PLAN_TRAVAIL_SPOT"
); );
foreach($deviceTable as $device => $name) foreach($deviceTable as $device => $name)

View File

@ -19,9 +19,9 @@ $properties2log = array(
"pressure" => 10, "pressure" => 10,
"occupancy" => null, "occupancy" => null,
"tamper" => null, "tamper" => null,
"illuminance_lux" => '10%', "illuminance_lux" => function($value) {($value < 500?50:$value*10/100); return $value;},
// "illuminance" => 8, // "illuminance" => 8,
"requested_brightness_level" => '10%', "requested_brightness_level" => function($value) {($value < 500?50:$value*10/100);return $value;},
"tempf" => 0.5, "tempf" => 0.5,
"humidity" => null, "humidity" => null,
"dewptf" => 0.5, "dewptf" => 0.5,

View File

@ -199,7 +199,7 @@ function iterateDevice($topic, $fn, $parentDevice, &$device, $payloadArray, $pro
$device->{$key} = array("value" => null); $device->{$key} = array("value" => null);
$device->$key["functions"] = array(); $device->$key["functions"] = array();
} }
echo $key . 'oldvalue = ' . $oldValue . " value = " . $value . EOL; echo $key . ' ===> oldvalue = ' . $oldValue . " value = " . $value . EOL;
if ($oldValue !== $value) if ($oldValue !== $value)
{ {
$device->$key["value"] = $value; $device->$key["value"] = $value;
@ -207,14 +207,14 @@ function iterateDevice($topic, $fn, $parentDevice, &$device, $payloadArray, $pro
//$changed[$fn]["value"] = $value; //$changed[$fn]["value"] = $value;
logger(INFO, sprintf(_("Device %s property %s, %s"), $fn, $propertyTree . $key, bool2string($value))); logger(INFO, sprintf(_("Device %s property %s, %s"), $fn, $propertyTree . $key, bool2string($value)));
$mohaDB->logProperty($parentDevice, $propertyTree . $key, $value, $oldValue); $mohaDB->logProperty($parentDevice, $propertyTree . $key, $value, $oldValue);
print_r($device->$key);
if (!empty($device->$key["functions"])) }
if (!empty($device->$key["functions"]))
{
logger(DEBUG,_("executing notifications functions"));
foreach($device->$key["functions"] as $function)
{ {
logger(DEBUG,_("executing notifications functions")); $function($device, $key, $value);
foreach($device->$key["functions"] as $function)
{
$function($device, $key, $value);
}
} }
} }
//} //}

View File

@ -6,7 +6,9 @@ logger(DEBUG,"Including events.php");
function checkEvents() function checkEvents()
{ {
global $events, $indexDevices, $devices; global $logLevel, $events, $indexDevices, $devices;
$oldLevel = $logLevel;
$loglevel = DEBUG;
$exception = false; $exception = false;
foreach ($events as $key => $event) foreach ($events as $key => $event)
{ {
@ -51,6 +53,7 @@ function checkEvents()
} }
} }
//print_r($events); //print_r($events);
$logLevel = $oldLevel;
} }
function setOneshotEvent(&$device, $datetime, $property, $value, $replace=false) function setOneshotEvent(&$device, $datetime, $property, $value, $replace=false)
@ -99,9 +102,11 @@ function setRecurrentEvent(&$device, $property, $value, $startDatetime, $stopDat
function setDelay(&$device, $delay, $unit="second", $property, $value, $replace=false) function setDelay(&$device, $delay, $unit="second", $property, $value, $replace=false)
{ {
global $events; global $events, $logLevel;
$oldLevel = $logLevel;
$loglevel = DEBUG;
$datetime = new dateTime(); $datetime = new dateTime();
//print_r($datetime); strtolower($unit);
switch($unit) switch($unit)
{ {
case "second": case "second":
@ -150,6 +155,8 @@ function setDelay(&$device, $delay, $unit="second", $property, $value, $replace=
$events[$key]->value = $value; $events[$key]->value = $value;
$events[$key]->device = & $device; $events[$key]->device = & $device;
logger (DEBUG, _('Setting new delay in $events[]')); logger (DEBUG, _('Setting new delay in $events[]'));
print_r($events[$key]);
$loglevel = $oldLevel;
} }
function searchEvent($device, $property , $value) function searchEvent($device, $property , $value)

View File

@ -8,7 +8,7 @@ class notificationFreemobile
function __construct() function __construct()
{ {
$this->level = WARNING | ERROR; $this->level = ALERT | ERROR;
} }
function send($message) function send($message)

View File

@ -0,0 +1,58 @@
<?php
class etage_plan_travail_eclairage extends hook
{
public $hookName = "etage_plan_travail_eclairage";
public $active = true; //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("action", false));
// if you need some initialisation when creating the object, uncomment andput your code here.
// If existing, This function is called by __construct
/*protected function init()
{
// Your code here
}
*/
// callback fonction. Is called with these 3 parameters
// $device -> calling device
// $property -> property of the device (given by mqtt)
// $value -> value of the property
public function callBack(&$device, $property, $value)
{
// here your code
if($value == "ON") // ON
{
$this->send("ON", "OFF");
}elseif($value == "OFF")
{
$this->send("OFF", null, AUTO);
}
logger (INFO,sprintf(_("%s: notification received from MQTT from %s => parameter: %s value: %s"), $this->hookName, $device->friendlyName, $property, $value));
}
private function send($state, $delayState = false, $method = MANUAL)
{
global $devices, $indexDevices;
$device = & $indexDevices[ETAGE_CUISINE_PLAN_TRAVAIL_SPOT];
$msg = array("state_l1" => $state);
if ($device->state_l1["value"] != $state)
{
logger(INFO, sprintf(_("publishing message: %s to %s"), json_encode($msg), $device->friendlyName));
$device->payload = $msg;
$device->set();
$device->method = $method;
}else
{
logger(INFO, sprintf(_("not publishing message: %s to %s, already set"), json_encode($msg), $device->friendlyName));
}
//echo 'delaystate = ' . var_dump($delayState);
if ($delayState !== false) setDelay($device, $this->delay, $this->timeUnit, "state", $delayState, true);
}
}
$hooks["etage_plan_travail_eclairage"] = new etage_plan_travail_eclairage();
?>

View File

@ -0,0 +1,31 @@
<?php
class rdc_chambre_eclairage extends hook
{
public $hookName = "rdc_chambre_eclairage";
public $active = false; //enable/disable hook (true => enabled)
protected $devicelist = array();
// if you need some initialisation when creating the object, uncomment andput your code here.
// If existing, This function is called by __construct
/*protected function init()
{
// Your code here
}
*/
// callback fonction. Is called with these 3 parameters
// $device -> calling device
// $property -> property of the device (given by mqtt)
// $value -> value of the property
public function callBack(&$device, $property, $value)
{
// here your code
logger (INFO,sprintf(_("%s: notification received from MQTT from %s => parameter: %s value: %s"), $this->hookName, $device->friendlyName, $property, $value));
}
}
$hooks["rdc_chambre_eclairage"] = new rdc_chambre_eclairage();
?>

View File

@ -12,7 +12,7 @@ class rdc_salon_eclairage extends hook
); );
public $delay = 5; // amount of time in $timeunit public $delay = 5; // amount of time in $timeunit
public $timeUnit = "minute"; // unit of time for delay, second, minute, day, week, month, year public $timeUnit = "minute"; // unit of time for delay, second, minute, hour, day, week, month, year
public $luminance_min = 60; public $luminance_min = 60;
public $luminance_max = 3000; public $luminance_max = 3000;

View File

@ -3,6 +3,7 @@
class rdc_sdb_eclairage extends hook class rdc_sdb_eclairage extends hook
{ {
public $hookName = "rdc_sdb_eclairage"; public $hookName = "rdc_sdb_eclairage";
public $active = true;
/* already defined in hook class */ /* already defined in hook class */
// public $active = true; // public $active = true;
@ -26,7 +27,7 @@ class rdc_sdb_eclairage extends hook
public function callBack(&$device, $property, $value) public function callBack(&$device, $property, $value)
{ {
global $devices, $indexDevices; global $devices, $indexDevices;
var_dump($value); //var_dump($value);
switch($property) switch($property)
{ {
case "occupancy": case "occupancy":
@ -56,9 +57,10 @@ class rdc_sdb_eclairage extends hook
global $devices, $indexDevices; global $devices, $indexDevices;
$msg = array("state_l1" => $state); $msg = array("state_l1" => $state);
$device = & $indexDevices[RDC_SDB_WC_ECLAIRAGE]; $device = & $indexDevices[RDC_SDB_WC_ECLAIRAGE];
logger(INFO, sprintf(_("publishing message: %s to %s"), $msg, $device->friendlyName)); logger(INFO, sprintf(_("publishing message: %s to %s"), $state, $device->friendlyName));
$device->payload = $msg; $device->payload = $msg;
$device->set(null); $device->set(null);
} }
} }
$hooks["rdc_sdb_eclairage"] = new rdc_sdb_eclairage(); $hooks["rdc_sdb_eclairage"] = new rdc_sdb_eclairage();

View File

@ -14,7 +14,7 @@ class rdc_wc_eclairage extends hook
public function callBack(&$device, $property, $value) public function callBack(&$device, $property, $value)
{ {
global $devices, $indexDevices; global $devices, $indexDevices;
var_dump($value); //var_dump($value);
switch($property) switch($property)
{ {
case "state_l2": case "state_l2":

272
moha.php
View File

@ -2,6 +2,8 @@
$title = "moha"; $title = "moha";
$testMode = true; $testMode = true;
$webServerIsActive = true;
cli_set_process_title($title); cli_set_process_title($title);
file_put_contents("/proc/".getmypid()."/comm",$title); file_put_contents("/proc/".getmypid()."/comm",$title);
@ -14,7 +16,7 @@ $listPropertiesKeys = array("property");
//global variables //global variables
$logLevel = INFO | NOTICE | WARNING | ERROR | ALERT; //ALL; $logLevel = INFO | NOTICE | WARNING | ERROR | ALERT; //ALL;
$notificationLevel = WARNING | ERROR; $notificationLevel = ALERT | ERROR;
$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
@ -32,8 +34,12 @@ $logFile = "/var/log/moha.log"; // Path of log file
$logFh = null; // filehandle of log file $logFh = null; // filehandle of log file
$curlErr = 0; // Number of errors returned by curl $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
$mqttServerIp = "127.0.0.1"; // IP address of mqttserver in production mode
if ($testMode)
{
$mqttServerIp = "192.168.1.253"; // IP address of mqttserver in test mode
}
if (!init()) exit(1); if (!init()) exit(1);
@ -47,7 +53,7 @@ function notify($message)
$result = false; $result = false;
foreach($notificationMethods as $value) foreach($notificationMethods as $value)
{ {
//$result = $result | $value->send($message); $result = $result | $value->send($message);
} }
return $result; return $result;
} }
@ -55,8 +61,6 @@ function notify($message)
function logger($level, $log, $notif = true) function logger($level, $log, $notif = true)
{ {
global $logFh, $logLevel, $notificationLevel, $logLevels; global $logFh, $logLevel, $notificationLevel, $logLevels;
//echo "=====>>>> $level => $logLevel => $notificationLevel" . EOL ;
//echo $log .EOL;
$logString = date("c") . ' ' . $logLevels[$level] . " : $log"; $logString = date("c") . ' ' . $logLevels[$level] . " : $log";
if ($level & $logLevel) if ($level & $logLevel)
{ {
@ -64,7 +68,6 @@ function logger($level, $log, $notif = true)
print ($logString . EOL); print ($logString . EOL);
} }
$test = $level & $notificationLevel; $test = $level & $notificationLevel;
//echo "notif =>" .$notif . EOL;
if (($test != 0) and ($notif === true)) if (($test != 0) and ($notif === true))
{ {
if(notify("Moha\n" . $logString) === false) if(notify("Moha\n" . $logString) === false)
@ -74,125 +77,6 @@ function logger($level, $log, $notif = true)
} }
} }
logger(DEBUG, _("requiring php modules"), false);
require "class/main.php";
require "class/db.php";
require "class/hook_class.php";
require "utils.php";
require $configDir . "/properties2log.php";
require "mqtt_functions.php";
require "events.php";
require "db_functions.php";
logger(DEBUG, _('assigning variable $client to mosquitto class "client"'), false);
$client = new Mosquitto\Client();
logger(DEBUG, _("Loading stored devices datas"));
loadDB($devices, "moha.db");
// topics definition
listHooks("./topics_callbacks", $hooksList);
if (!empty($hooksList))
{
foreach ($hooksList as $callback)
{
logger(INFO, _("Including ") . $callback, false);
include $callback;
}
}
logger(DEBUG, _("requiring config files -> devices_constants.php"), false);
//include predefined file witch define constants for devices
if (is_readable($configDir . "/" . "devices_constants.php"))
{
include $configDir . "/" . "devices_constants.php";
//echo "hooklist"; print_r($hooksList); echo EOL;
logger(INFO, sprintf(_("%s/devices_constants.define found, so it has been included :-)"), $configDir), false);
}else
{
logger(WARNING, sprintf(_("%s/devices_constants.define not found, so not included :-)"), $configDir), false);
}
// making the list of hooks to include
listHooks("./hooks", $hooksList);
// Program start
logger(DEBUG, _("Program start"), false);
$client = new Mosquitto\Client();
// defining callback functions
$client->onConnect('connectResponse');
$client->onDisconnect('disconnectResponse');
$client->onSubscribe('subscribeResponse');
$client->onUnsubscribe('unsubscribeResponse');
$client->onMessage('messageReceived');
$client->onLog('logger');
$client->onPublish('publishResponse');
// connectong to mqtt server
$client->connect("192.168.1.253", 1883, 5);
logger(INFO, _("Subscribing to bridge"), false);
foreach($topics as $name => $topic)
{
$topic->mid = $client->subscribe($name . "/#", 2);
$mids[$topic->mid] = $name;
$topic->status = false;
}
// starting main loop
logger(INFO, _("Starting loop"), false);
$oneshot = false;
while (true)
{
$client->loop(); // mqtt server loop()
if (! $included) // hooks not already included
{
logger(DEBUG, _("Making hooks list"), false);
getDevicesValues(); // TODO get the values of devices
if (!empty($hooksList)) // some hooks to include if hooklist is not empty
{
foreach ($hooksList as $hook) // loop to include hooks in hookslist
{
logger(INFO, _("Including ") . $hook, false);
include $hook;
}
file_put_contents("moha.devices", print_r($devices, true)); // debugging : save device list
$included = true;
}
}else
{
if ($oneshot === false) // execute once initialization finished :WARNING hooks can to be not initialized
{
logger(DEBUG, _("Oneshot part of loop"), false);
$oneshot = true;
}
checkEvents();
if($hooksInitialized == 0) // all hooks are not initialized
{
$i = 1;
foreach($hooks as $hookName => $hook)
{
if ($hook->initialized === false)
{
logger(WARNING, _("Hook not completely initialized :") . $hookName);
$i &= $hook->installHooks();
}
}
$hooksInitialized = $i;
}else
{
logger(DEBUG,_("All hooks initialized"));
}
}
}
endMoha();
function init() function init()
{ {
global $logFile, $logFh, $client; global $logFile, $logFh, $client;
@ -230,8 +114,8 @@ function endMoha()
{ {
global $devices, $topics, $nSubscribed ,$client, $logFh, $connected; global $devices, $topics, $nSubscribed ,$client, $logFh, $connected;
$x = 0; $x = 0;
storeDB($devices, "moha.db"); storeDB($devices, "/usr/share/moha/moha.db");
file_put_contents("moha.devices", print_r($devices, true)); if($testMode) file_put_contents("moha.devices", print_r($devices, true));
if ($connected) if ($connected)
{ {
$mid = $client->unsubscribe("#"); $mid = $client->unsubscribe("#");
@ -250,6 +134,138 @@ function endMoha()
exit(0); exit(0);
} }
function connect2mqttServer()
{
global $client;
$client->onConnect('connectResponse');
}
logger(DEBUG, _("requiring php modules"), false);
require "class/main.php";
require "class/db.php";
require "class/hook_class.php";
require "utils.php";
require $configDir . "/properties2log.php";
require "mqtt_functions.php";
require "events.php";
require "db_functions.php";
//logger(DEBUG, _('assigning variable $client to mosquitto class "client"'), false);
//$client = new Mosquitto\Client();
logger(DEBUG, _("Loading stored devices datas"));
loadDB($devices, "moha.db");
// topics definition
listHooks("./topics_callbacks", $hooksList);
if (!empty($hooksList))
{
foreach ($hooksList as $callback)
{
logger(INFO, _("Including ") . $callback, false);
include $callback;
}
}
logger(DEBUG, _("requiring config files -> devices_constants.php"), false);
//include predefined file witch define constants for devices
if (is_readable($configDir . "/" . "devices_constants.php"))
{
include $configDir . "/" . "devices_constants.php";
//echo "hooklist"; print_r($hooksList); echo EOL;
logger(INFO, sprintf(_("%s/devices_constants.define found, so it has been included :-)"), $configDir), false);
}else
{
logger(WARNING, sprintf(_("%s/devices_constants.define not found, so not included :-)"), $configDir), false);
}
// making the list of hooks to include
listHooks("./hooks", $hooksList);
// Program start
logger(DEBUG, _("Program start"), false);
$client = new Mosquitto\Client();
// defining callback functions
try
{
connect2mqttServer();
}catch ( Mosquitto\Exception $err)
{
logger(ALERT, sprintf(_("Error connecting to mosquitto server, retrying in 10 seconds:"), $err), false);
sleep (10);
exit(1);
}
$client->onDisconnect('disconnectResponse');
$client->onSubscribe('subscribeResponse');
$client->onUnsubscribe('unsubscribeResponse');
$client->onMessage('messageReceived');
$client->onLog('logger');
$client->onPublish('publishResponse');
// connectong to mqtt server
$client->connect($mqttServerIp, 1883, 5);
logger(INFO, _("Subscribing to bridge"), false);
foreach($topics as $name => $topic)
{
$topic->mid = $client->subscribe($name . "/#", 2);
$mids[$topic->mid] = $name;
$topic->status = false;
}
// starting main loop
logger(INFO, _("Starting loop"), false);
$oneshot = false;
while (true)
{
$client->loop(); // mqtt server loop()
if (! $included) // hooks not already included
{
logger(DEBUG, _("Making hooks list"), false);
getDevicesValues(); // TODO get the values of devices
if (!empty($hooksList)) // some hooks to include if hooklist is not empty
{
foreach ($hooksList as $hook) // loop to include hooks in hookslist
{
logger(INFO, _("Including ") . $hook, false);
include $hook;
}
file_put_contents("/usr/share/moha/moha.devices", print_r($devices, true)); // debugging : save device list
$included = true;
}
}else
{
if ($oneshot === false) // execute once initialization finished :WARNING hooks can to be not initialized
{
logger(DEBUG, _("Oneshot part of loop"), false);
$oneshot = true;
}
if($hooksInitialized == 0) // all hooks are not initialized
{
$i = 1;
foreach($hooks as $hookName => $hook)
{
if ($hook->initialized === false)
{
logger(WARNING, _("Hook not completely initialized :") . $hookName);
$i &= $hook->installHooks();
}
}
$hooksInitialized = $i;
}else
{
logger(DEBUG,_("All hooks initialized"));
}
checkEvents();
}
}
endMoha();
?> ?>