1
0

debugging

This commit is contained in:
daniel Tartavel 2022-01-17 00:18:50 +01:00
parent cd20e973cd
commit 4fb5504cdc
18 changed files with 379 additions and 269 deletions

View File

@ -1,15 +1,22 @@
<?php
logger(DEBUG,"Including db.php");
class db extends mysqli
{
public $mysqlServer = "127.0.0.1";
public $mysqlServer = "192.168.1.253"; // "127.0.0.1";
public $username = "moha";
public $passwd = "MysqlMoha";
public $database = "moha";
public $result;
function __construct($mysqlServer, $username, $passwd, $database)
function __construct()
{
return $this->connect($mysqlServer, $username, $passwd, $database);
if ($this->connect($this->mysqlServer, $this->username, $this->passwd, $this->database) === false)
{
logger(ERROR,"Connection to sql server error :" . $this->connect_error);
return 2;
}
$result = new mysqli_result($this);
}
function protect($string)
@ -17,17 +24,39 @@ class db extends mysqli
return $this->real_escape_string($string);
}
function logProperty($device, $property, $value)
function logProperty($device, $propertyTree, $value, $oldValue = 0)
{
$query = "SELECT * FROM logs WHERE device='" . $device->ieeeAddress . "' AND property='" .
$query = "IF (EXISTS INSERT INTO logs(device, property, value) VALUES(" . $device->ieeeAddress . ", " . $property . ", " . $value . ") ON DUPLICATE KEY UPDATE value=" . $value
global $mohaDB, $properties2log;
$precision = 0;
echo "############## logProperty ################\nproperty => " . $propertyTree .EOL;
if (array_key_exists($propertyTree, $properties2log))
{
//echo "logging in database";
$ieeeAddress = $device->ieeeAddress;
//print_r($ieeeAddress);
$query = "INSERT INTO logs (device, property, value) VALUES('" . $this->protect($ieeeAddress) . "', '" . $this->protect($propertyTree) . "', '" . $this->protect($value) . "')";
if (is_numeric($value) and !empty($properties2log[$propertyTree]))
{
$minMax = (float)$value * (float)$properties2log[$propertyTree] / 100;
//echo "minMax = " .$minMax . EOL;
//echo "oldValue = " . $oldValue . EOL;
//echo "Value = " . $value . EOL;
if ($value >= $oldValue - $minMax and $value <= $oldValue + $minMax)
{
//echo "========>>>>>>>>>not changed" . EOL;
return 0;
}
}
if(!$this->result = $this->query($query))
{
logger(ERROR, _("mysql query errror: ") . $this->error);
}
logger(INFO, sprintf(_("New value of property: %s of device: %s stored in database"), $propertyTree, $device->friendlyName, $value));
}
}
}
$mohaDB = new db($mysqlServer, $username, $passwd, $database);
if ($mohaDB->connect_error)
{
logger(ERROR, _("Mysql connection failed: ") . $db->connect_error);
}
$mohaDB = new db();
?>

57
class/hook_class.php Normal file
View File

@ -0,0 +1,57 @@
<?php
class hook
{
public $hookName = "";
public $active = true;
public $initialized = false;
protected $devicelist;
// list of devices we are listening to
function __construct()
{
logger(DEBUG, _("Initializing hook: ") . $this->hookName);
$this->installHooks();
}
function installHooks()
{
global $indexDevices;
$result = true;
// assigne the function to the sensors devices
if ($this->active === true)
{
foreach ($this->devicelist as $ieeeAddress => $property2change)
{
logger(DEBUG, _("Device: ") . $ieeeAddress);
if ($property2change[1] === false)
{
logger(DEBUG, _("Trying to store callback"));
if (isset($indexDevices[$ieeeAddress]))
{
$property = $property2change[0];
$indexDevices[$ieeeAddress]->$property["functions"][] = array($this,"callback");
$property2change[1] = true;
logger(DEBUG, sprintf(_("Property '%s' is initialized with callback"), $property2change[0]));
}else
{
logger(WARNING, sprintf(_("Hook %s can not initialize Property '%s' of device %s"), $this->hookName, $property2change[0], $ieeeAddress));
$result = false;
}
}else
{
logger(DEBUG, _("Callback already installed"));
}
}
echo "result => "; var_dump($result);
if ($result === true)
{
$this->initialized = true;
logger(DEBUG, $this->hookName . (" initialized"));
//var_dump($this);
}
}
return $result;
}
}
?>

View File

@ -1,4 +1,6 @@
<?php
logger(DEBUG,"Including class main.php");
class Message
{
public $id;

View File

@ -25,7 +25,7 @@ $deviceTable = array(
foreach($deviceTable as $device => $name)
{
define($name, $device);
logger(INFO, _("defining constant ") . $name);
//logger(DEBUG, _("defining constant ") . $name);
}
?>

41
config/properties2log.php Normal file
View File

@ -0,0 +1,41 @@
<?php
// list of properties to log in database
// key is property name => value is % of difference with stocked value. if new value is stored if
// superior or inferior at value +/- x%
$properties2log = array(
"action" => null,
"state" =>null,
"contact" => null,
"temperature" =>2,
"state_l1" => null,
"state_l2" => null,
"humidity" => null,
"current_heating_setpoint" => null,
"position" => null,
"pressure" => 0.5,
"occupancy" => null,
"tamper" => null,
"illuminance_lux" => 8,
// "illuminance" => 8,
"requested_brightness_level" => 8,
"tempf" => 5,
"humidity" => null,
"dewptf" => 5,
"windchillf" => 5,
"winddir" => 8,
"windspeedmph" => 20,
"windgustmph" => 20,
"rainin" => null,
"dailyrainin" => null,
"weeklyrainin" => null,
"monthlyrainin" => null,
"yearlyrainin" => null,
"solarradiation" => 10,
"UV" => null,
"indoortempf" => 5,
"indoorhumidity" => null,
"baromin" => 5
);

View File

@ -1,11 +1,18 @@
<?php
logger(DEBUG,"Including db_functions.php");
// to save or not to save the DB, that is the question ...
function storeDB($db, $filepath)
{
$data = serialize($db);
$fp = fopen($filePath, "w");
fwrite($fp, $data);
fclose($fp);
file_put_contents($filepath, $data);
}
function loadDB(& $db, $filepath)
{
$data = file_get_contents($filepath);
$db = unserialize($data);
}
function mkDevicesDB($topic, $json, $group=false)
@ -23,13 +30,13 @@ function mkDevicesDB($topic, $json, $group=false)
$device = & $devices[$topic];
foreach($fnTree as $fnPart)
{
if (!isset($device[$fnPart]))
if (!array_key_exists($fnPart, $device))
{
$device[$fnPart] = array();
}
$device = & $device[$fnPart];
}
if (!isset($device["device"]))
if (!array_key_exists("device", $device))
{
$device["device"] = new device;
}
@ -71,13 +78,8 @@ function addDevice(& $device, $fn, $jsonDevice )
}
searchPropertyValue($fn, $device["device"], $jsonDevice, $listProperties);
// adding callback function for availability
//print_r($hooks);
//$device["device"]->availability["functions"][] = $hooks["availability"]->getHook();
//indexing device
$indexDevices[$device["device"]->ieeeAddress] = & $device["device"];
//print_r($device);
}
@ -119,11 +121,10 @@ function searchPropertyValue($fn, &$device, $object, $listProperties)
function changeDevice($topic, $fn, &$device, $payloadArray)
{
//$fnTree = explode("/", $fn);
//print_r($payloadArray);
if (!empty($payloadArray))
{
iterateDevice($topic, $fn, $device, $payloadArray);
iterateDevice($topic, $fn, $device, $device, $payloadArray);
}else
{
logger(ERROR, _("payloadArray is empty!"));
@ -131,43 +132,75 @@ function changeDevice($topic, $fn, &$device, $payloadArray)
}
function iterateDevice($topic, $fn, &$device, $payloadArray)
function iterateDevice($topic, $fn, $parentDevice, &$device, $payloadArray, $propertyTree="")
{
global $changed;
global $changed, $mohaDB;
$deviceType = (gettype($device) == "object"); // = true if object
//echo "devicetype = "; var_dump($deviceType); echo EOL;
//print_r($payloadArray);
//echo "device =>";print_r($device);echo EOL;
//echo "PropertyTree ==============> " . $propertyTree . EOL;
foreach($payloadArray as $key => $value)
{
$oldValue = null;
//echo "key =>"; print_r($key); echo EOL;
//echo "value =>"; print_r($value); echo EOL;
//echo "type : " . gettype($value) .EOL;
if (gettype($value) == "object")
$valueType = gettype($value);
if ( $valueType == "object")
{
$propertyTree .= $key . "/";
//echo " is Object" . EOL;
if ($deviceType === true )
{
if (!property_exists($device, $key))
{
$device->{$key} = null;
$device->{$key} = new stdClass;
}
//echo "iterating" . EOL;
iterateDevice($topic, $fn, $device, $value);
}elseif (gettype($value) == "array")
{
//echo "is array" . EOL;
iterateDevice($topic, $fn, $device, $value);
iterateDevice($topic, $fn, $parentDevice, $device->$key, $value, $propertyTree);
}else
{
//echo "is array";
if (!array_key_exists($key, $device))
{
$device[$key] = new stdClass;
}
//echo "iterating" . EOL;
iterateDevice($topic, $fn, $parentDevice, $device[$key], $value, $propertyTree);
}
}elseif ($valueType == "array")
{
$propertyTree .= $key . "/";
if ($deviceType === true )
{
$device->$key = array();
iterateDevice($topic, $fn, $parentDevice, $device->$key, $value, $propertyTree);
}else
{
$device[$key] = array();
iterateDevice($topic, $fn, $parentDevice, $device[$key], $value, $propertyTree);
}
}else
{
//echo "db_functions".EOL;
//($device);
if (empty($device->$key) or $value != null)
{
if (isset($device->$key))
if (property_exists($device, $key))
{
$oldValue = $device->$key;
if (is_array($device->$key))
{
$oldValue = $device->$key["value"];
}else
{
$device->{$key}["value"] = null;
$oldValue = $device->$key;
}
}else
{
$device->{$key} = array("value" => null);
$device->$key["functions"] = array();
}
if ($oldValue !== $value)
@ -175,8 +208,10 @@ function iterateDevice($topic, $fn, &$device, $payloadArray)
$device->$key["value"] = $value;
$changed[$fn]["key"] = $key;
$changed[$fn]["value"] = $value;
logger(INFO, sprintf(_("Device %s property %s, value changed to %s"), $device->friendlyName, $key, $value));
$mohaDB->logProperty($device, $key, $value);
logger(INFO, sprintf(_("Device %s property %s, value changed to %s"), $fn, $propertyTree . $key, $value));
//print_r($device);
//$mohaDB->logProperty($parentDevice, $propertyTree . $key, $value, $oldValue); TODO re-activate
//echo "oldvalue => " . print_r($oldValue, true) . EOL;
/*if (empty($oldValue))
{
@ -187,11 +222,9 @@ function iterateDevice($topic, $fn, &$device, $payloadArray)
}
echo " to " . $value . EOL;*/
}
//print_r($device->functions); print_r($value);
//print_r($device);
if (!empty($device->$key["functions"]))
{
echo "executing notifications functions " . EOL;
logger(DEBUG,_("executing notifications functions"));
foreach($device->$key["functions"] as $function)
{
//print_r($function);

View File

@ -1,4 +1,5 @@
<?php
logger(DEBUG,"Including events.php");
/* for all functions, datetime parameter format is 'dd/mm/yy hh:mm:ss' */

View File

@ -2,28 +2,25 @@
class availability
{
public $hookname = "availability";
public $initialized = true;
// by default all devices are listening for availability
function __construct()
{
global $devices;
$this->iterate($devices);
$this->iterate();
}
private function iterate(& $device)
private function iterate()
{
foreach ($device as $key => $value)
global $indexDevices;
foreach ($indexDevices as $value)
{
if (gettype($value) == "array")
{
$this->iterate($value);
}elseif (is_a($value, "device"))
{
$value->availability["functions"][] = array($this,"callback");
}
}
}
// callback fonction. Is called with these 3 parameters
// $device -> calling device
// $property -> parameter passed by mqtt

View File

@ -1,28 +1,19 @@
<?php
class alerte_intrusion
class alerte_intrusion extends hook
{
public $hookName = "alerte_intrusion";
public $active = true;
private $devicelist = array(ENTREE_PORTE => "contact", GARAGE_PORTE => "contact", RDC_CHAMBRE_BAIE => "contact", RDC_SALON_BAIE => "contact");
protected $devicelist = array(
ENTREE_PORTE => array("contact", false),
GARAGE_PORTE => array("contact", false),
RDC_CHAMBRE_BAIE => array("contact", false),
RDC_SALON_BAIE => array("contact", false));
public $delay = 3; // amount of time in $timeunit
public $delayManual = 10; // amount of time in $timeunit for manual mode
public $timeUnit = "minute"; // unit of time for delay, second, minute, day, week, month, year
function __construct()
{
global $indexDevices;
// assigne the function to the sensors devices
if ($this->active === true)
{
foreach ($this->devicelist as $ieeeAddress => $param)
{
$indexDevices[$ieeeAddress]->$param["functions"][] = array($this,"callback");
}
}
}
// callback fonction. Is called with these 4 parameters
public function callBack(&$device, $param, $value)
{

View File

@ -1,15 +1,14 @@
<?php
class rdc_salon_eclairage
class rdc_salon_eclairage extends hook
{
public $hookName = "rdc_salon_eclairage";
public $active = true;
// list of devices we are listening to
private $devicelist = array(
RDC_SALON_MVMT => "occupancy",
RDC_SALON_MVMT2 => "occupancy",
RDC_ENTREE_PORTE => "contact",
RDC_SALON_LUMINOSITE => "illuminance_lux"
protected $devicelist = array(
RDC_SALON_MVMT => array("occupancy", false),
RDC_SALON_MVMT2 => array("occupancy", false),
RDC_ENTREE_PORTE => array("contact", false),
RDC_SALON_LUMINOSITE => array("illuminance_lux", false)
);
public $delay = 3; // amount of time in $timeunit
@ -18,20 +17,6 @@ class rdc_salon_eclairage
public $luminance_max = 3000;
function __construct()
{
global $indexDevices;
// assigne the function to the sensors devices
if ($this->active === true)
{
foreach ($this->devicelist as $ieeeAddress => $param)
{
$indexDevices[$ieeeAddress]->$param["functions"][] = array($this,"callback");
}
}
}
// callback fonction. Is called with these 4 parameters
public function callBack(&$device, $param, $value)
{
@ -61,7 +46,7 @@ class rdc_salon_eclairage
{
global $devices, $indexDevices;
$device = & $indexDevices[RDC_SALON_ECLAIRAGE_PANNEAU];
if ($device->state_l1["value"] != $state)
if ($device->state["value"] != $state)
{
$msg = array("state" => $state);
logger(INFO, sprintf(_("publishing message: %s to %s"), json_encode($msg), $device->friendlyName));

View File

@ -1,40 +1,31 @@
<?php
class rdc_sdb_eclairage
class rdc_sdb_eclairage extends hook
{
public $hookName = "rdc_sdb_eclairage";
public $active = true;
/* already defined in hook class */
// public $active = true;
//public $initlialized = false;
public $delay = 3; // amount of time in $timeunit
public $delayManual = 10; // amount of time in $timeunit for manual mode
public $timeUnit = "minute"; // unit of time for delay, second, minute, day, week, month, year
// list of devices we are listening to
// 0x00158d0003f0f3b4 douche mvmnt
// 0x842e14fffe1c0cd1 plafond mvmnt
// 0x00124b0022ec05dc mvmnt
// 0x00158d0005c1a998 module commutateur => state_l1
private $devicelist = array(
"0x00158d0003f0f3b4" => "occupancy",
"0x842e14fffe1c0cd1" => "occupancy",
"0x00124b0022ec05dc" => "occupancy",
RDC_SDB_WC_ECLAIRAGE => "state_l1"
// devicelist[$ieeAddress][0] => property to watch
// devicelist[$ieeAddress][1] => initialized = true
protected $devicelist = array(
"0x00158d0003f0f3b4" => array("occupancy", false),
"0x842e14fffe1c0cd1" => array("occupancy", false),
"0x00124b0022ec05dc" => array("occupancy", false),
RDC_SDB_WC_ECLAIRAGE => array("state_l1", false)
);
public $delay = 3; // amount of time in $timeunit
public $delayManual = 10; // amount of time in $timeunit for manual mode
public $timeUnit = "minute"; // unit of time for delay, second, minute, day, week, month, year
function __construct()
{
global $indexDevices;
// assigne the function to the sensors devices
if ($this->active === true)
{
foreach ($this->devicelist as $ieeeAddress => $property)
{
$indexDevices[$ieeeAddress]->$property["functions"][] = array($this,"callback");
}
}
}
// callback fonction. Is called with these 4 parameters
public function callBack(&$device, $property, $value)
{
@ -73,6 +64,6 @@ class rdc_sdb_eclairage
$device->set(null);
}
}
$hooks["rdc_sdb_eclairage"] = new rdc_sdb_eclairage();
?>

View File

@ -1,30 +1,15 @@
<?php
class rdc_wc_eclairage
class rdc_wc_eclairage extends hook
{
public $hookName = "rdc_wc_eclairage";
public $active = true;
private $devicelist = array(RDC_SDB_WC_ECLAIRAGE => "state_l2");
protected $devicelist = array(RDC_SDB_WC_ECLAIRAGE => array("state_l2", false));
public $delay = 3; // amount of time in $timeunit
public $delayManual = 10; // amount of time in $timeunit for manual mode
public $timeUnit = "minute"; // unit of time for delay, second, minute, day, week, month, year
function __construct()
{
global $indexDevices;
// assigne the function to the sensors devices
if ($this->active === true)
{
foreach ($this->devicelist as $ieeeAddress => $property)
{
$indexDevices[$ieeeAddress]->$property["functions"][] = array($this,"callback");
}
}
}
// callback fonction. Is called with these 4 parameters
public function callBack(&$device, $property, $value)
{

107
moha.php
View File

@ -17,9 +17,6 @@ declare(ticks = 1);
$listProperties = array("powerSource" => "batterie");
$listPropertiesKeys = array("property");
require "class/main.php";
//global variables
$topics = array(); // list of topics
$mids = array(); // list of message IDs
@ -30,7 +27,7 @@ $hooks = array(); // array of hooks
$notificationMethods = array(); // array of notification methods objects
$events = array(); // list of event objects
$changed = array(); // list of changed devices
$dbInit = false; // flag to indicate that desvices db is initialized
$dbInit = 0; // flag to indicate that devices db is initializedl
$connected = false; // connected to MQTT server
$included = false; // flag indicate scripts are loaded
$nSubscribed = 0; // Number of topics subsribed
@ -38,9 +35,27 @@ $logFile = "/var/log/moha.log"; // Path of log file
$logFh = null; // filehandle of log file
$curlErr = 0; // Number of errors returned by curl
$configDir = "./config"; // default config dir (production value is /etc/moha/)
$properties2log = array("action", "state", "contact", "temperature", "state_l1", "state_l2", "humidity", "current_heating_setpoint", "position", "pressure", "occupancy", "tamper", "illuminance_lux","illuminance", "requested_brightness_level", );
$hooksInitialized = 0; // are all hooks initialized ? false/true
require $configDir . "/properties2log.php";
logger(DEBUG, _("lauching init function"), false);
if (!init()) exit(1);
// gettext
bindtextdomain("moha", "./locale");
textdomain("moha");
function notify($message)
{
global $notificationMethods;
$result = false;
foreach($notificationMethods as $value)
{
//$result = $result | $value->send($message);
}
return $result;
}
function logger($level, $log, $notif = true)
{
global $logFh, $logLevel, $notificationLevel;
@ -61,22 +76,6 @@ function logger($level, $log, $notif = true)
}
}
}
/*
logger(DEBUG, _("Require topics definition -> zigbee3mqtt"), false);
$topics["zigbee2mqtt"] = new topic;
require "topics_callbacks/zigbee2mqtt.php";
logger(DEBUG, _("Require topics definition -> pws2mqtt"), false);
$topics["pws2mqtt"] = new topic;
require "topics_callbacks/pws2mqtt.php";
*/
logger(DEBUG, _("gettext init"), false);
// gettext
bindtextdomain("moha", "./locale");
textdomain("moha");
logger(DEBUG, _("lauching init function"), false);
logger(DEBUG, _('assigning variable : $client'), false);
$client = new Mosquitto\Client();
@ -93,14 +92,20 @@ $logLevel = ALL;
$notificationLevel = WARNING | ERROR;
logger(DEBUG, _("requiring php modules"), false);
require "class/main.php";
require "class/db.php";
require "class/hook_class.php";
require "utils.php";
require "mqtt_functions.php";
require "events.php";
require "db.php";
require "db_functions.php";
logger(DEBUG, _("Loading stored devices datas"));
loadDB($devices, "moha.db");
// topics definition
loadHooks("./topics_callbacks", $hooksList);
listHooks("./topics_callbacks", $hooksList);
if (!empty($hooksList))
{
foreach ($hooksList as $callback)
@ -114,14 +119,17 @@ logger(DEBUG, _("requiring config files -> devices_constants.php"), false);
//include predefined file witch define constants for devices
if (is_readable($configDir . "/" . "devices_constants.php"))
{
$hooksList[] = $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 will be included :-)"), $configDir), false);
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);
logger(DEBUG, _("Program start"), false);
// Program start
$client = new Mosquitto\Client();
@ -155,11 +163,11 @@ $oneshot = false;
while (true)
{
$client->loop();
if ($dbInit == 2 and ! $included)
if (! $included)
{
logger(DEBUG, _("Making hooks list"), false);
getDevicesValues();
loadHooks("./hooks", $hooksList);
if (!empty($hooksList))
{
foreach ($hooksList as $hook)
@ -167,23 +175,38 @@ while (true)
logger(INFO, _("Including ") . $hook, false);
include $hook;
}
file_put_contents("moha.devices", print_r($devices, true));
$included = true;
}
}elseif($dbInit == 2 and $included)
}elseif($included)
{
if ($oneshot === false) // execute once initialization finished
{
logger(DEBUG, _("Oneshot part of loop"), false);
$oneshot = true;
/*foreach($topics as $name => $topic)
{
//echo $name;
$topic->mid = $client->subscribe($name . "/#", 2);
$mids[$topic->mid] = $name;
$topic->status = false;
}*/
}
checkEvents();
if($hooksInitialized == 0)
{
$i = 1;
foreach($hooks as $hookName => $hook)
{
if ($hook->initialized === false)
{
logger(WARNING, _("Hook not completely initialized :") . $hookName);
$i &= $hook->installHooks();
echo "hook->initialized";var_dump($hook->initialized);echo EOL;
// (int)$hook->initialized;
var_dump($hook);
echo "i =======> " . $i;var_dump($i); echo EOL;
}
}
$hooksInitialized = $i;
}else
{
logger(DEBUG,_("All hooks initialized"));
}
}
}
@ -193,7 +216,6 @@ function init()
{
global $logFile, $logFh, $client;
date_default_timezone_set('Europe/Paris');
if (! $logFh = fopen($logFile, "w") )
{
echo _("error opening log file");
@ -202,9 +224,8 @@ function init()
return true;
}
function loadHooks($dir, &$hookList)
function listHooks($dir, &$hookList)
{
global $included;
$files = scandir($dir);
//print_r($files);
@ -217,7 +238,7 @@ function loadHooks($dir, &$hookList)
if (is_dir($dir . "/" . $file))
{
//echo "directory : " . $dir . '/' . $file . EOL;
loadHooks($dir . '/' . $file, $hookList);
listHooks($dir . '/' . $file, $hookList);
}elseif (strpos($file, ".php", -4) !== false)
{
//echo "file : " . $dir . "/" . $file . EOL;
@ -229,13 +250,14 @@ function loadHooks($dir, &$hookList)
}
}
//print_r($hookList);
$included = true;
}
function endMoha()
{
global $topics, $nSubscribed ,$client, $logFh, $connected;
global $devices, $topics, $nSubscribed ,$client, $logFh, $connected;
$x = 0;
storeDB($devices, "moha.db");
file_put_contents("moha.devices", print_r($devices, true));
if ($connected)
{
$mid = $client->unsubscribe("#");
@ -253,6 +275,7 @@ function endMoha()
}
}
fclose($logFh);
exit(0);
}

View File

@ -1,85 +1,24 @@
<?php
logger(DEBUG,"Including mqtt_functions.php");
function messageReceived($message)
{
global $topics, $logFh, $devices, $included;
$topic = explode ("/", $message->topic);
$callback = $topics[$topic[0]]->callback;
//logger(DEBUG, "===== topic " . print_r($topic, true));
$callback($topic, $message);
/*
if ($topic[1] == "bridge")
{
switch ($topic[2])
{
case "info":
$topics[$topic[0]]->info = json_decode($message->payload);
break;
case "devices":
$topics[$topic[0]]->devices = json_decode($message->payload);
fwrite($logFh, print_r($topics[$topic[0]]->devices, true));
mkDevicesDB($topic[0], $topics[$topic[0]]->devices);
break;
case "groups":
$topics[$topic[0]]->groups = json_decode($message->payload);
mkDevicesDB($topic[0], $topics[$topic[0]]->groups, true);
break;
case "extensions":
$topics[$topic[0]]->extensions = json_decode($message->payload);
break;
case "config":
$topics[$topic[0]]->config = json_decode($message->payload);
break;
case "logging":
//TODO
break;
case "state":
$topics[$topic[0]]->state = $message->payload;
break;
default:
break;
};
}elseif (($topic[array_key_last($topic)]) != "get" and ($topic[array_key_last($topic)]) != "set" and $included)
{
$topic = explode ("/", $message->topic, 2); // get topic name
$fnTree = explode ("/" , $topic[1]); // get friendlyname
echo $topic[0] . " => " . $topic[1] . EOL;
//$devices[$topic[0]][$fnTree[0]]->json = json_decode($message->payload);
if ($fnTree[array_key_last($fnTree)] == "availability")
{
unset ($fnTree[array_key_last($fnTree)]);
$payloadArray = array("availability" => $message->payload);
//print_r($payloadArray);
}else
{
$payloadArray = json_decode($message->payload);
}
$device = & $devices[$topic[0]];
foreach($fnTree as $fn)
{
//print_r($device) ;
if (!isset($device[$fn])) //must not exists, but ...
{
logger(LOG_WARNING, $logFh, "init of " . $fn .EOL);
$device[$fn] = array();
$device[$fn]["device"] = new device;
//addDevice($device[$fn], $fn, );
}
$device = & $device[$fn];
}
changeDevice($topic[0], $topic[1], $device["device"], $payloadArray);
//fwrite($logFh, print_r($msg, true));
}*/
}
// payload is an array :
// $key is property => $value is value of the property
// $key is property and $value is value of the property
function publish($topic, $payload, $commande="set", $eventKey)
{
global $client, $mids, $logFh;
//print_r($payload);
$string = $topic . "/" . $commande;
$mid = $client->publish($string, json_encode($payload) , 2);
//$mid = $client->publish($string, json_encode($payload) , 2); //TODO activer
if (isset($mids[$mid]))
{
//echo "unsetting mids" .EOL;

View File

@ -0,0 +1,33 @@
<?php
//TODO to test and debug
$topics["linky2mqtt"] = new topic;
/*$devices["linky2mqtt"]["linky"]["device"] = new device;
$device = &$devices["linky2mqtt"]["linky"]["device"];
*/
$topics["linky2mqtt"]->callback = function($topic, $message)
{
global $topics, $logFh, $devices, $included;
$topicName = $topic[0];
$friendlyName = $topic[1]; // get friendlyName
logger(INFO, sprintf(_("Icoming notification of device %s"), $topic[0], $topic[1]));
$device = & $devices[$topic[0]];
$payloadArray = json_decode($message->payload);
//print_r($payloadArray);
//print_r($device) ;
if (!isset($device[$fn])) //must not exists, but ...
{
logger(LOG_WARNING, $logFh, "init of " . $fn .EOL);
$device[$fn] = array();
$device[$fn]["device"] = new device;
$device[$fn]["device"]->type = "mesure";
$device[$fn]["device"]->ieeeAddress = $payloadArray["ADSC"];
//addDevice($device[$fn], $fn, );
}
$device = & $device[$fn];
//print_r($device);
changeDevice($topicName, $friendlyName, $device["device"], $payloadArray);
print_r($device["device"]);
}
?>

View File

@ -1,28 +1,29 @@
<?php
$topics["pws2mqtt"] = new topic;
/*$devices["pws2mqtt"]["WH2650A"]["device"] = new device;
$device = &$devices["pws2mqtt"]["WH2650A"]["device"];*/
$topics["pws2mqtt"]->callback = function($topic, $message)
{
global $topics, $logFh, $devices, $included;
$topic = explode ("/", $message->topic, 2); // get topic name
$fnTree = explode ("/" , $topic[1]); // get friendlyname
echo $topic[0] . " => " . $topic[1] . EOL;
$fn = $topic[1]; // get friendlyname
logger(INFO, sprintf(_("Icoming notification of device %s => friendly name : %s"), $topic[0], $topic[1]));
$device = & $devices[$topic[0]];
foreach($fnTree as $fn)
{
$payloadArray = json_decode($message->payload);
//print_r($payloadArray);
//print_r($device) ;
if (!isset($device[$fn])) //must not exists, but ...
{
logger(LOG_WARNING, $logFh, "init of " . $fn .EOL);
$device[$fn] = array();
$device[$fn]["device"] = new device;
$device[$fn]["device"]->type = $payloadArray->type;
$device[$fn]["device"]->ieeeAddress = $payloadArray->ieeeAddress;
//addDevice($device[$fn], $fn, );
}
$device = & $device[$fn];
//print_r($device);
}
$payloadArray = json_decode($message->payload);
$device = & $device[$fn];
changeDevice($topic[0], $topic[1], $device["device"], $payloadArray);
print_r($device["device"]);
//print_r($device["device"]);
}
?>

View File

@ -11,11 +11,13 @@ $callback = function($topic, $message)
$topics[$topic[0]]->info = json_decode($message->payload);
break;
case "devices":
logger(DEBUG,_("Inserting zigbee devices in DB"));
$topics[$topic[0]]->devices = json_decode($message->payload);
fwrite($logFh, print_r($topics[$topic[0]]->devices, true));
mkDevicesDB($topic[0], $topics[$topic[0]]->devices);
break;
case "groups":
logger(DEBUG,_("Inserting zigbee groups in DB"));
$topics[$topic[0]]->groups = json_decode($message->payload);
mkDevicesDB($topic[0], $topics[$topic[0]]->groups, true);
break;

View File

@ -1,19 +1,19 @@
<?php
logger(DEBUG,"Including utils.php");
function now()
{
return new DateTime("now");
}
function notify($message)
function farenheit2celsius($value)
{
global $notificationMethods;
$result = false;
foreach($notificationMethods as $value)
{
$result = $result | $value->send($message);
}
return $result;
return ($value - 32 / 1.8);
}
function millibars($value)
{
return ($value * 0.029530);
}
function mktopic($device)