"batterie"); $listPropertiesKeys = array("expose"); //global variables $topics = array(); // list of topics $mids = array(); // list of message IDs $devices = array(); // array of device objetcs $indexDevices = array(); // index of devices by ieee_address $indexFriendlyNames = array(); // index of devices by friendly name $indexTypes = array(); $indexProperties = array(); // index of properties $hooksList = array(); // list of hooks to be included $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 $notificationMethods = array(); // array of notification methods objects $events = array(); // list of event objects $monitored = array(); // list of device to watch $changed = array(); // list of changed devices $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 $logFh = null; // filehandle of log file $curlErr = 0; // Number of errors returned by curl //$configDir = "./config"; // default config dir (production value is /etc/moha/) $hooksInitialized = 0; // are all hooks initialized ? false/true $flagHooks = false; $devicesRequest = false; // set to true when publishing device request to zigbee2mqtt $presence = array(); // name and status of presence $timeLoop = new datetime("now"); // initalisation if (!init()) exit(1); // (re)démarre le démon de présence system("sudo /usr/bin/systemctl restart presenceD.service"); // gettext bindtextdomain("moha", "./locale"); textdomain("moha"); ###################################################################################################################### ## Fonctions ## ###################################################################################################################### function notify($message, $device) { global $notificationMethods, $defaultUser; $result = false; $destinataire = array(); logger(DEBUG, _("notify function "), __FILE__ . ":" . __LINE__); if (empty($device) or !isset($device)) { $destinataire[] = reset($defaultUser); //default user if no device logger(DEBUG, _("notify: destinataire ==>") . print_r($destinataire, true), __FILE__ . ":" . __LINE__); }else { if (empty($device->users)) { logger(DEBUG, _("notify: pas d'utilisateur pour ce device"), true, __FILE__ . ":" . __LINE__); foreach($defaultUser as $topic => $nom) { if ( str_contains($device->friendlyName, $topic)) { $destinataire[] = $nom; } } }else { $destinataire = $device->users; } } var_dump ($destinataire); foreach($notificationMethods as $value) { foreach($destinataire as $dest) { $result |= $value->send($message, $dest); } } return $result; } function logger($level, $log, $pos = "", $device=null, $notif = true) { global $logFh, $logLevel, $notificationLevel, $logLevels; $logString = $logLevels[$level] . " " ; if ($pos !== false) { $logString .= $pos; } $logString .= " - " . $log; if ($level & $logLevel) { fwrite($logFh, date("c") . ' ' . $logString . EOL); print ("MOHA-" . $logString . EOL); } $test = $level & $notificationLevel; if (($test != 0) and ($notif === true)) { echo _("logger: Notification to user") . __FILE__ . ":" . __LINE__; if(notify("Moha\n" . $logString, $device) === false) { echo _("logger; Notification not sent") . __FILE__ . ":" . __LINE__; return true; } } return false; } function init() { global $logFile, $logFh, $client, $presence, $macAddresses; date_default_timezone_set('Europe/Paris'); if (! $logFh = fopen($logFile, "w") ) { echo _("error opening log file in ") . getcwd(); return false; } return true; } function listHooks($dir, &$hookList) { $files = scandir($dir); foreach ($files as $file) { if ($file != "." and $file != "..") { if (is_dir($dir . "/" . $file)) { listHooks($dir . '/' . $file, $hookList); }elseif (strpos($file, ".php", -4) !== false) { if (substr($file, -4) == ".php") { $hookList[] = $dir . "/" . $file; } } } } } function endMoha() { global $testMode, $devices, $topics, $events, $nSubscribed ,$client, $logFh, $connected, $dataPath, $cwfd, $watch_descriptor; $x = 0; logger(WARNING, _("moha is ending"), __FILE__ . ":" . __LINE__); if (storeDB($devices, $dataPath . "devices.db") === false) { logger(ERROR, _("Can not store devices db" ), __FILE__ . ":" . __LINE__); } if (storeDB($topics, $dataPath . "topics.db") === false) { logger(ERROR, _("Can not store topics db" ), __FILE__ . ":" . __LINE__); } if (storeDB($events, $dataPath . "events.db") === false) { logger(ERROR, _("Can not store events db" ), __FILE__ . ":" . __LINE__); } if($testMode) file_put_contents($dataPath . "moha.devices", var_export($devices, true)); configWatchStop(); if ($connected) { $mid = $client->unsubscribe("#"); $client->disconnect(); while ($connected) { if ( $x++ >= 60) { fclose($logFh); exit (1); } $client->loop(); } } fclose($logFh); exit(0); } function connect2mqttServer() { global $client; $client->onConnect('connectResponse'); } ###################################################################################################################### ## Main program ## ###################################################################################################################### logger(ALERT, _("starting moha"), __FILE__ . ":" . __LINE__); logger(DEBUG, _("requiring config files -> devices_constants.php"), __FILE__ . ":" . __LINE__); //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.php found, so it has been included :-)"), $configDir), __FILE__ . ":" . __LINE__, false); }else { logger(WARNING, sprintf(_("%s/devices_constants.php not found, so not included :-)"), $configDir), __FILE__ . ":" . __LINE__, false); } logger(DEBUG, _("requiring php modules"), __FILE__ . ":" . __LINE__); 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"; require "config/liste_telephones.php"; require "presence.php"; require "apiserver/apiserver.php"; require "configWatch.php"; logger(DEBUG, _("Loading stored events datas from ") . $dataPath . "events.db", __FILE__ . ":" . __LINE__); if (file_exists($dataPath . "events.db")) { if (($db = loadDB($dataPath . "events.db")) === false) { logger(ERROR, _("Can not load events db"), __FILE__ . ":" . __LINE__); }else { $events = $db; } } // topics definition listHooks("./topics_callbacks", $topicsCallbacks); if (!empty($topicsCallbacks)) { foreach ($topicsCallbacks as $callback) { logger(INFO, _("Including ") . $callback, __FILE__ . ":" . __LINE__); include $callback; } } // making the list of hooks to include listHooks("./hooks", $hooksList); if (!empty($hooksList)) // hooks to include if hooklist is not empty { foreach ($hooksList as $hookFile) // loop to include hooks in hookslist { logger(INFO, _("Including ") . $hookFile, __FILE__ . ":" . __LINE__, false); include_once $hookFile; } if ($logLevel & DEBUG) { file_put_contents($dataPath . "moha.devices", var_export($devices, true)); // debugging : save device list } $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__); if (file_exists($dataPath . "topics.db")) { if (($db = loadDB($dataPath . "topics.db")) === false) { logger(ERROR, _("Can not load topics db"), __FILE__ . ":" . __LINE__); }else { $topics = $db; foreach($topics as $topicName => $topic ) { $topic->notificationSent = false; logger(DEBUG, "topic: " . $topicName . " is " . bool2string($topic->notificationSent)); } } } logger(DEBUG, _("Loading stored devices datas from ") . $dataPath . "devices.db", __FILE__ . ":" . __LINE__); if (file_exists($dataPath . "devices.db")) { if (($db = loadDB($dataPath . "devices.db")) === false) { logger(ERROR, _("Can not load devices db"), __FILE__ . ":" . __LINE__); }else { $devices = $db; mkIndexes(); } } // Program start logger(DEBUG, _("Program start"), __FILE__ . ":" . __LINE__); $client = new Mosquitto\Client(); try { connect2mqttServer(); }catch ( Mosquitto\Exception $err) { logger(ALERT, sprintf(_("Error connecting to mosquitto server, retrying in 10 seconds:"), $err), __FILE__ . ":" . __LINE__); 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"), __FILE__ . ":" . __LINE__, 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"), __FILE__ . ":" . __LINE__); $oneshot = false; logger(ALERT, _("Moha started"), __FILE__ . ":" . __LINE__); // démarre la surveillance du dossier de configuration : /etc/moha configWatchInit(); while (true) { // test if looping is more then 5 second and send and alert // echo date("c") . " début"; $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() if ($oneshot === false) // execute while the first loop :WARNING all hooks may not be initialized { echo date("c") . " One shot"; logger(DEBUG, _("Oneshot part of loop"), __FILE__ . ":" . __LINE__, false); pws2mqttGetList(); $oneshot = true; } //echo date("c") . " initialisation des hooks"; if($hooksInitialized == 0) // all hooks are not initialized { $i = 1; foreach($hooks as $hookName => &$hook) { if ($hook->active === false) { $i = 1; }else { if ($hook->initialized === false); // and $hook->active === true) { logger(WARNING, _("Initializing Hook not completely initialized :") . $hookName, __FILE__ . ":" . __LINE__); $i &= $hook->installHooks($indexDevices); } } } $hooksInitialized = $i; /*}elseif($flagHooks === false) { logger(DEBUG, _("All hooks initialized"), __FILE__ . ":" . __LINE__); $flagHooks = true;*/ }else // executed when hooks initialization finished but database init may be not finished { //logger(DEBUG, _("looping"), __FILE__ . ":" . __LINE__); } // echo date("c") . " chech events"; checkEvents(); // echo date("c") . " topics availabiblity"; checkTopicsAvailability(); //echo date("c") . " apiserver"; if ($apiServerIsActive) apiServer($read); //echo date("c") . " surveillance Configuration"; // surveillance du dossier de configuration if ($cwfd !== false) { $input = inotify_read($cwfd); // Does no block, and return false if no events are pending if ($input !== false) { foreach ($input as $event) { if (pathinfo($event["name"], PATHINFO_EXTENSION) == "php") { logger(DEBUG, _("configWatch : inclus ") . $configDir . "/" . $event["name"], __FILE__ . ":" . __LINE__); include $configDir . "/" . $event["name"]; }else { logger(DEBUG, _("configWatch : mauvaise extension, je n'inclus pas ") . $configDir . "/" . $event["name"], __FILE__ . ":" . __LINE__); } } } } //echo date("c") . " fin"; } endMoha(); ?>