1
0

- added values in celsius degree and in km/h in pws2mqtt

- debug of hooks
-added webserver.php
This commit is contained in:
daniel Tartavel 2022-01-27 18:41:16 +01:00
parent fc4eaf2238
commit 1361cb9395
13 changed files with 214 additions and 57 deletions

View File

@ -50,18 +50,12 @@ class db extends mysqli
{ {
// calculate a min/max value for storing data // calculate a min/max value for storing data
$var = $properties2log[$propertyTree]; $minMax = $properties2log[$propertyTree];
if (is_callable($var)) if (is_callable($minMax))
{ {
$var = $var($value); $minMax = $minMax($value);
} }
//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

@ -33,8 +33,9 @@ class device
public $payload; public $payload;
public $availability; public $availability;
public $toConfirm; public $toConfirm;
public $triggerDevice;
private function __construct() public function __construct()
{ {
$this->availability = array("value" => null, "functions" => array()); $this->availability = array("value" => null, "functions" => array());
} }

View File

@ -22,7 +22,12 @@ $deviceTable = array(
"0x00124b002226e384" => "RDC_SALON_BAIE", "0x00124b002226e384" => "RDC_SALON_BAIE",
"0x842e14fffe8c53a5" => "ETAGE_CUISINE_PLAN_TRAVAIL_INTER", "0x842e14fffe8c53a5" => "ETAGE_CUISINE_PLAN_TRAVAIL_INTER",
"0x680ae2fffe403f22" => "ETAGE_CUISINE_PLAN_TRAVAIL_ECLAIRAGE", "0x680ae2fffe403f22" => "ETAGE_CUISINE_PLAN_TRAVAIL_ECLAIRAGE",
"0xbc33acfffe65621b" => "ETAGE_CUISINE_PLAN_TRAVAIL_SPOT" "0xbc33acfffe65621b" => "ETAGE_CUISINE_PLAN_TRAVAIL_SPOT",
"0x086bd7fffe5aeab6" => "RDC_CHAMBRE_AMBIANCE",
"0xbc33acfffe6561e4" => "RDC_CHAMBRE_ECLAIRAGE",
"0x00124b00234484ad" => "RDC_CHAMBRE_MVMT",
"0x04cf8cdf3c7b6056" => "RDC_CHAMBRE_LUMINOSITE",
"0x00158d0006c0447c" => "RDC_CHAMBRE_ARMOIRE_GAUCHE"
); );
foreach($deviceTable as $device => $name) foreach($deviceTable as $device => $name)

View File

@ -27,8 +27,8 @@ $properties2log = array(
"dewptf" => 0.5, "dewptf" => 0.5,
"windchillf" => 0.5, "windchillf" => 0.5,
"winddir" => 40, "winddir" => 40,
"windspeedmph" => 20, "windspeedmph" => 5,
"windgustmph" => 20, "windgustmph" => 5,
"rainin" => null, "rainin" => null,
//"dailyrainin" => null, //"dailyrainin" => null,
//"weeklyrainin" => null, //"weeklyrainin" => null,

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,8 +207,6 @@ 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);
}
if (!empty($device->$key["functions"])) if (!empty($device->$key["functions"]))
{ {
logger(DEBUG,_("executing notifications functions")); logger(DEBUG,_("executing notifications functions"));
@ -217,6 +215,8 @@ function iterateDevice($topic, $fn, $parentDevice, &$device, $payloadArray, $pro
$function($device, $key, $value); $function($device, $key, $value);
} }
} }
}
//} //}
} }
} }

View File

@ -159,6 +159,14 @@ function setDelay(&$device, $delay, $unit="second", $property, $value, $replace=
$loglevel = $oldLevel; $loglevel = $oldLevel;
} }
function removeEvent($device, $property , $value)
{
if (($eventKey = searchEvent($device, $property , $value)) === true)
{
deleteEvent($eventKey);
}
}
function searchEvent($device, $property , $value) function searchEvent($device, $property , $value)
{ {
global $events; global $events;
@ -188,7 +196,6 @@ function deleteEvent($eventKey)
//try to delete an flase event //try to delete an flase event
logger(WARNING, _("Try to delete event with key = ") . var_dump($eventKey)); logger(WARNING, _("Try to delete event with key = ") . var_dump($eventKey));
} }
} }

View File

@ -6,15 +6,7 @@ class etage_plan_travail_eclairage extends hook
public $active = true; //enable/disable hook (true => enabled) public $active = true; //enable/disable hook (true => enabled)
public $delay = 3; // amount of time in $timeunit public $delay = 3; // amount of time in $timeunit
public $timeUnit = "hour"; // unit of time for delay, second, minute, hour, day, week, month, year 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)); protected $devicelist = array("ETAGE_CUISINE_PLAN_TRAVAIL_ECLAIRAGE" => array("state", 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 // callback fonction. Is called with these 3 parameters
// $device -> calling device // $device -> calling device
@ -47,7 +39,6 @@ class etage_plan_travail_eclairage extends hook
}else }else
{ {
logger(INFO, sprintf(_("not publishing message: %s to %s, already set"), json_encode($msg), $device->friendlyName)); logger(INFO, sprintf(_("not publishing message: %s to %s, already set"), json_encode($msg), $device->friendlyName));
} }
//echo 'delaystate = ' . var_dump($delayState); //echo 'delaystate = ' . var_dump($delayState);
if ($delayState !== false) setDelay($device, $this->delay, $this->timeUnit, "state", $delayState, true); if ($delayState !== false) setDelay($device, $this->delay, $this->timeUnit, "state", $delayState, true);

View File

@ -4,16 +4,16 @@ class rdc_chambre_eclairage extends hook
{ {
public $hookName = "rdc_chambre_eclairage"; public $hookName = "rdc_chambre_eclairage";
public $active = false; //enable/disable hook (true => enabled) public $active = false; //enable/disable hook (true => enabled)
public $delay = 5; // amount of time in $timeunit
protected $devicelist = array(); public $timeUnit = "minute"; // unit of time for delay, second, minute, hour, day, week, month, year
public $luminance_min = 60;
// if you need some initialisation when creating the object, uncomment andput your code here. public $luminance_max = 3000;
// If existing, This function is called by __construct protected $devicelist = array(
/*protected function init() "RDC_CHAMBRE_AMBIANCE" => array("state", false),
{ "RDC_CHAMBRE_ECLAIRAGE" => array("state_l1", false),
// Your code here "RDC_CHAMBRE_MVMT" => array("occupancy", false),
} "RDC_CHAMBRE_ARMOIRE_GAUCHE" => array("contact", false)
*/ );
// callback fonction. Is called with these 3 parameters // callback fonction. Is called with these 3 parameters
// $device -> calling device // $device -> calling device
@ -21,9 +21,33 @@ class rdc_chambre_eclairage extends hook
// $value -> value of the property // $value -> value of the property
public function callBack(&$device, $property, $value) public function callBack(&$device, $property, $value)
{ {
// here your code global $devices, $indexDevices;
$lux = $indexDevices[RDC_CHAMBRE_LUMINOSITE]->illuminance_lux;
if ($property == "occupancy" and $value == "ON")
{
$this->send(RDC_CHAMBRE_LUMINOSITE, "ON", "OFF", AUTO);
}
logger (INFO, sprintf(_("%s: notification received from MQTT from %s => parameter: %s value: %s"), $this->hookName, $device->friendlyName, $property, $value));
}
logger (INFO,sprintf(_("%s: notification received from MQTT from %s => parameter: %s value: %s"), $this->hookName, $device->friendlyName, $property, $value)); private function send($device, $state, $delayState = false, $method = MANUAL)
{
global $devices, $indexDevices;
$device = &$indexDevices[$device];
$msg = array("state" => $state);
if ($device->state["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);
} }
} }

View File

@ -11,7 +11,7 @@ class rdc_salon_eclairage extends hook
RDC_SALON_LUMINOSITE => array("illuminance_lux", false) RDC_SALON_LUMINOSITE => array("illuminance_lux", false)
); );
public $delay = 5; // amount of time in $timeunit public $delay = 3; // amount of time in $timeunit
public $timeUnit = "minute"; // unit of time for delay, second, minute, hour, 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;
@ -28,19 +28,29 @@ class rdc_salon_eclairage extends hook
//print_r($indexDevices[RDC_SALON_LUMINOSITE]); //print_r($indexDevices[RDC_SALON_LUMINOSITE]);
if ($value == ON and $indexDevices[RDC_SALON_LUMINOSITE]->illuminance_lux["value"] <= $this->luminance_min) if ($value == ON and $indexDevices[RDC_SALON_LUMINOSITE]->illuminance_lux["value"] <= $this->luminance_min)
{ {
$this->send("ON", "OFF", AUTO); $this->send("ON", null, AUTO);
removeEvent($indexDevices[RDC_SALON_ECLAIRAGE_PANNEAU], "state", "OFF");
}
if ($value == OFF)
{
if ($indexDevices(RDC_SALON_MVMT)->occupancy == OFF and $indexDevices(RDC_SALON_MVMT2)->occupancy == OFF)
{
setDelay($indexDevices[RDC_SALON_ECLAIRAGE_PANNEAU], $this->delay, $this->timeUnit, "state", "OFF", true);
//$this->send("ON", "OFF", AUTO);
}
} }
break; break;
case "contact": case "contact":
if ($value == false and $indexDevices[RDC_SALON_LUMINOSITE]->illuminance_lux["value"] <= $this->luminance_min) if ($value == false and $indexDevices[RDC_SALON_LUMINOSITE]->illuminance_lux["value"] <= $this->luminance_min)
{ {
$this->send("ON", "OFF", AUTO); //$this->send("ON", "OFF", AUTO);
} }
break; break;
case "illuminance_lux": case "illuminance_lux":
if ($value >= $this->luminance_max) if ($value >= $this->luminance_max)
{ {
$this->send("OFF"); //$this->send("OFF", null, AUTO);
removeEvent($indexDevices[RDC_SALON_ECLAIRAGE_PANNEAU], "state", "OFF");
} }
break; break;
} }

View File

@ -1,21 +1,19 @@
<?php <?php
$title = "moha"; $title = "moha";
$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);
declare(ticks = 1);
$testMode = true;
$webServerIsActive = true;
require "constants.php"; require "constants.php";
declare(ticks = 1);
$listProperties = array("powerSource" => "batterie"); $listProperties = array("powerSource" => "batterie");
$listPropertiesKeys = array("property"); $listPropertiesKeys = array("property");
//global variables //global variables
$logLevel = INFO | NOTICE | WARNING | ERROR | ALERT; //ALL; $logLevel = ALL; // INFO | NOTICE | WARNING | ERROR | ALERT; //ALL;
$notificationLevel = ALERT | 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
@ -61,7 +59,7 @@ 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;
$logString = date("c") . ' ' . $logLevels[$level] . " : $log"; $logString = date("c") . ' ' . $logLevels[$level] . " " . __FILE__ . ":" . __LINE__ . " : " . $log;
if ($level & $logLevel) if ($level & $logLevel)
{ {
fwrite($logFh, $logString . EOL); fwrite($logFh, $logString . EOL);
@ -112,7 +110,7 @@ function listHooks($dir, &$hookList)
function endMoha() function endMoha()
{ {
global $devices, $topics, $nSubscribed ,$client, $logFh, $connected; global $testMode, $devices, $topics, $nSubscribed ,$client, $logFh, $connected;
$x = 0; $x = 0;
storeDB($devices, "/usr/share/moha/moha.db"); storeDB($devices, "/usr/share/moha/moha.db");
if($testMode) file_put_contents("moha.devices", print_r($devices, true)); if($testMode) file_put_contents("moha.devices", print_r($devices, true));
@ -149,6 +147,7 @@ require $configDir . "/properties2log.php";
require "mqtt_functions.php"; require "mqtt_functions.php";
require "events.php"; require "events.php";
require "db_functions.php"; require "db_functions.php";
require "webserver.php";
//logger(DEBUG, _('assigning variable $client to mosquitto class "client"'), false); //logger(DEBUG, _('assigning variable $client to mosquitto class "client"'), false);
//$client = new Mosquitto\Client(); //$client = new Mosquitto\Client();
@ -263,6 +262,7 @@ while (true)
logger(DEBUG,_("All hooks initialized")); logger(DEBUG,_("All hooks initialized"));
} }
checkEvents(); checkEvents();
askWebServer($read);
} }
} }

View File

@ -8,9 +8,10 @@ $topics["pws2mqtt"]->callback = function($topic, $message)
logger(INFO, sprintf(_("Incoming notification of device %s => friendly name : %s"), $topic[0], $topic[1])); logger(INFO, sprintf(_("Incoming notification of device %s => friendly name : %s"), $topic[0], $topic[1]));
$device = & $devices[$topic[0]]; $device = & $devices[$topic[0]];
$payloadArray = json_decode($message->payload); $payloadArray = json_decode($message->payload);
if (!isset($device[$fn])) if (!isset($device[$fn]))
{ {
logger(LOG_WARNING, $logFh, "init of " . $fn .EOL); logger(WARNING, $logFh, "init of " . $fn .EOL);
$device[$fn] = array(); $device[$fn] = array();
$device[$fn]["device"] = new device; $device[$fn]["device"] = new device;
$device[$fn]["device"]->type = $payloadArray->type; $device[$fn]["device"]->type = $payloadArray->type;
@ -19,6 +20,24 @@ $topics["pws2mqtt"]->callback = function($topic, $message)
$indexDevices[$device[$fn]["device"]->ieeeAddress] = & $device[$fn]["device"]; $indexDevices[$device[$fn]["device"]->ieeeAddress] = & $device[$fn]["device"];
} }
$device = & $device[$fn]; $device = & $device[$fn];
foreach ($payloadArray as $property => $value)
{
$str = substr($property, -1);
if ($str == "f")
{
$newProperty = rtrim($property, "f") . "c";
$payloadArray->{$newProperty} = farenheit2celsius($value);
}elseif ($str == "h")
{
$newProperty = substr($property, 0, -3) . "kmh";
$payloadArray->{$newProperty} = mph2kmh($value);
}
if ($property == "baromin")
{
$newProperty = "barominmb";
$payloadArray->{"barominmb"} = millibars($value);
}
}
changeDevice($topic[0], $fn, $device["device"], $payloadArray); changeDevice($topic[0], $fn, $device["device"], $payloadArray);
} }
?> ?>

View File

@ -23,12 +23,17 @@ function now()
function farenheit2celsius($value) function farenheit2celsius($value)
{ {
return ($value - 32 / 1.8); return round((((float)$value - 32) / 1.8),2);
}
function mph2kmh($value)
{
return round(((float)$value * 1.60934),2);
} }
function millibars($value) function millibars($value)
{ {
return ($value * 0.029530); return round(((float)$value * 33.86),2);
} }
function mktopic($device) function mktopic($device)

101
webserver.php Normal file
View File

@ -0,0 +1,101 @@
<?php
// server init: No Timeout
set_time_limit(0);
ob_implicit_flush();
$error_message = null;
$error_code = null;
$listenHost = "0.0.0.0";
$listenPort = 1025;
$socket = stream_socket_server("tcp://" . $listenHost . ":" . $listenPort, $error_code, $error_message) or logger(ERROR, _("Could not create socket") . EOL);
stream_set_blocking($socket, false);
$read = array( $socket );
function askWebServer($read)
{
$array = array();
$argList =array();
if ( stream_select( $read, $array, $array, 0 ))
{
logger(DEBUG,_("socket ready to read"));
$spawn = stream_socket_accept($read[0]);
if ($spawn !== false)
{
logger(DEBUG,_("socket accepted"));
$input = fgets($spawn, 4096);
logger(DEBUG, $input);
if (!empty($input))
{
$input = substr($input,5);
$input = explode(" ", $input); // suppress text
$argTmp = explode("&", $input[0]);
foreach($argTmp as $tmp)
{
logger(DEBUG, $tmp);
$array = explode("=", $tmp);
print_r($array);
if (isset($array[1])) $argList[$array[0]] = $array[1];
}
if(array_key_exists("cmd", $argList))
{
switch(strtolower($argList["cmd"]))
{
case "get":
logger(DEBUG, "get reached");
if(empty($argList["device"]))
{
$response = "<html><header><body>get passed</body></header><html>";
}
fwrite($spawn, $response);
break;
case "set":
logger(DEBUG, "set reached");
$response = "<html><header><body>set passed</body></header><html>";
fwrite($spawn, $response);
break;
case "print":
logger(DEBUG, "print reached");
$var = $GLOBALS[$argList["object"]];
if (isset($argList["topic"]))
{
$topic = $argList["topic"];
}
if (isset($argList["address"]))
{
$var = $var[$argList["address"]];
}elseif (isset($argList["fn"]))
{
if(!empty($topic))
{
$var = $var[$topic];
$path = explode("/", $argList["fn"]);
foreach($path as $tmp)
{
$var = $var[$tmp];
}
}else
{
logger(ERROR, _("topic is not defining: add &topic=zigbee2mqtt to the resquest"));
}
}
$error = error_get_last();
if($error !== null)
{
$response = "<html><header><body>" . $error["message"] . " file: " . $error["file"] . " line: " . $error["line"] . "</body></header><html>";
}
$response = "<html><header><body>" . print_r($var, true) . "</body></header><html>";
fwrite($spawn, $response);
break;
default:
logger(DEBUG, "not understanding command");
fwrite($spawn, "not understanding command");
}
}
}
}
}
}
?>