1
0
moha/moha.php

467 lines
13 KiB
PHP
Raw Normal View History

2021-12-30 16:18:32 +01:00
<?php
2022-12-05 12:23:43 +01:00
$title = "moha";
cli_set_process_title($title);
file_put_contents("/proc/".getmypid()."/comm",$title);
declare(ticks = 1);
2021-12-30 16:18:32 +01:00
2022-04-23 02:00:52 +02:00
$testMode = false;
2021-12-30 16:18:32 +01:00
require "constants.php";
2021-12-30 16:18:32 +01:00
2022-12-05 12:23:43 +01:00
//Test mode is executing moha from its directory
//no test mode, moha is system wide
if ($testMode)
{
$logLevel = ALL; // INFO | NOTICE | WARNING | ERROR | ALERT; //ALL;
$mqttServerIp = "192.168.1.253"; // IP address of mqttserver in test mode
$dataPath = "./";
$logFile = "./moha.log"; // Path of log file
$configDir = "./config"; // default config dir (production value is /etc/moha/)
$httpServerIp = "192.168.1.253";
}else
{
//$logLevel = DEBUG | INFO | NOTICE | WARNING | ERROR | ALERT;
$mqttServerIp = "127.0.0.1"; // IP address of mqttserver in production mode
$dataPath = "/usr/share/moha/";
$logFile = "/var/log/moha.log"; // Path of log file
$configDir = "/etc/moha"; // default config dir (production value is /etc/moha/)
$httpServerIp = "127.0.0.1";
}
require $configDir . "/config.php";
2022-12-05 12:23:43 +01:00
require $configDir . "/liste_telephones.php";
$listProperties = array("powerSource" => "batterie");
$listPropertiesKeys = array("expose");
2021-12-30 16:18:32 +01:00
//global variables
2022-02-23 10:23:16 +01:00
2021-12-30 16:18:32 +01:00
$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
2022-04-23 02:00:52 +02:00
$indexFriendlyNames = array(); // index of devices by friendly name
$indexTypes = array();
$indexProperties = array(); // index of properties
$hooksList = array(); // list of hooks to be included
2022-01-01 06:26:02 +01:00
$hooks = array(); // array of hooks
2022-12-05 12:23:43 +01:00
$scripts = array(); // array of user's script
$propertiesLoggers = array(); // array of loggers's callbacks
2022-04-23 02:00:52 +02:00
$topicsCallbacks = array(); // array of topics's callbacks
2022-01-01 06:26:02 +01:00
$notificationMethods = array(); // array of notification methods objects
$events = array(); // list of event objects
2022-01-30 00:21:50 +01:00
$monitored = array(); // list of device to watch
2022-01-01 06:26:02 +01:00
$changed = array(); // list of changed devices
2022-01-17 00:18:50 +01:00
$dbInit = 0; // flag to indicate that devices db is initializedl
2021-12-30 16:18:32 +01:00
$connected = false; // connected to MQTT server
$included = false; // flag indicate scripts are loaded
$nSubscribed = 0; // Number of topics subsribed
2022-01-01 06:26:02 +01:00
$logFh = null; // filehandle of log file
$curlErr = 0; // Number of errors returned by curl
2022-09-03 21:10:38 +02:00
//$configDir = "./config"; // default config dir (production value is /etc/moha/)
2022-01-23 09:46:06 +01:00
$hooksInitialized = 0; // are all hooks initialized ? false/true
2022-01-29 19:58:01 +01:00
$flagHooks = false;
2022-09-01 17:02:28 +02:00
$devicesRequest = false; // set to true when publishing device request to zigbee2mqtt
$presence = array(); // name and status of presence
2022-12-05 12:23:43 +01:00
$timeLoop = new datetime("now");
2022-02-07 16:58:42 +01:00
2022-12-05 12:23:43 +01:00
// initalisation
2022-01-08 23:45:38 +01:00
if (!init()) exit(1);
// (re)démarre le démon de présence
2022-09-03 21:10:38 +02:00
system("sudo /usr/bin/systemctl restart presenceD.service");
2022-09-01 17:02:28 +02:00
2022-01-17 00:18:50 +01:00
// gettext
bindtextdomain("moha", "./locale");
textdomain("moha");
2022-12-05 12:23:43 +01:00
######################################################################################################################
## Fonctions ##
######################################################################################################################
function notify($message, $device)
2022-01-17 00:18:50 +01:00
{
global $notificationMethods, $defaultUser;
2022-01-17 00:18:50 +01:00
$result = false;
$destinataire = array();
2022-09-09 16:53:49 +02:00
logger(DEBUG, _("notify function "), __FILE__ . ":" . __LINE__);
if (empty($device) or !isset($device))
{
$destinataire[] = reset($defaultUser); //default user if no device
2022-09-09 16:53:49 +02:00
logger(DEBUG, _("notify: destinataire ==>") . print_r($destinataire, true), __FILE__ . ":" . __LINE__);
}else
{
if (empty($device->users))
{
2022-09-09 16:53:49 +02:00
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);
2022-01-17 00:18:50 +01:00
foreach($notificationMethods as $value)
{
foreach($destinataire as $dest)
{
2022-09-09 16:53:49 +02:00
$result |= $value->send($message, $dest);
}
2022-01-17 00:18:50 +01:00
}
return $result;
}
function logger($level, $log, $pos = "", $device=null, $notif = true)
{
2022-01-19 00:22:34 +01:00
global $logFh, $logLevel, $notificationLevel, $logLevels;
$logString = $logLevels[$level] . " " ;
2022-09-09 16:53:49 +02:00
2022-01-28 23:05:58 +01:00
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))
{
2022-09-09 16:53:49 +02:00
echo _("logger: Notification to user") . __FILE__ . ":" . __LINE__;
if(notify("Moha\n" . $logString, $device) === false)
{
2022-09-09 16:53:49 +02:00
echo _("logger; Notification not sent") . __FILE__ . ":" . __LINE__;
return true;
}
}
return false;
}
2021-12-30 16:18:32 +01:00
2022-01-23 09:46:06 +01:00
function init()
{
2022-09-01 18:49:32 +02:00
global $logFile, $logFh, $client, $presence, $macAddresses;
2022-01-23 09:46:06 +01:00
date_default_timezone_set('Europe/Paris');
if (! $logFh = fopen($logFile, "w") )
{
2022-02-23 10:23:16 +01:00
echo _("error opening log file in ") . getcwd();
2022-01-23 09:46:06 +01:00
return false;
}
return true;
}
2022-01-02 13:07:02 +01:00
2022-01-23 09:46:06 +01:00
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;
2022-01-23 09:46:06 +01:00
$x = 0;
2022-01-28 23:05:58 +01:00
logger(WARNING, _("moha is ending"), __FILE__ . ":" . __LINE__);
if (storeDB($devices, $dataPath . "devices.db") === false)
2022-02-07 16:58:42 +01:00
{
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__);
2022-02-07 16:58:42 +01:00
}
if (storeDB($events, $dataPath . "events.db") === false)
{
logger(ERROR, _("Can not store events db" ), __FILE__ . ":" . __LINE__);
}
2022-02-02 21:18:44 +01:00
if($testMode) file_put_contents($dataPath . "moha.devices", var_export($devices, true));
2022-12-05 12:23:43 +01:00
configWatchStop();
2022-01-23 09:46:06 +01:00
if ($connected)
{
$mid = $client->unsubscribe("#");
$client->disconnect();
while ($connected)
{
2022-02-23 10:23:16 +01:00
if ( $x++ >= 60)
2022-01-23 09:46:06 +01:00
{
fclose($logFh);
exit (1);
}
$client->loop();
}
}
fclose($logFh);
exit(0);
}
function connect2mqttServer()
{
global $client;
$client->onConnect('connectResponse');
}
2022-02-07 16:58:42 +01:00
2022-12-05 12:23:43 +01:00
######################################################################################################################
## Main program ##
######################################################################################################################
2022-02-07 16:58:42 +01:00
2022-12-05 12:23:43 +01:00
logger(ALERT, _("starting moha"), __FILE__ . ":" . __LINE__);
2022-02-07 16:58:42 +01:00
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);
2022-02-07 16:58:42 +01:00
}else
{
logger(WARNING, sprintf(_("%s/devices_constants.php not found, so not included :-)"), $configDir), __FILE__ . ":" . __LINE__, false);
2022-02-07 16:58:42 +01:00
}
2022-01-28 23:05:58 +01:00
logger(DEBUG, _("requiring php modules"), __FILE__ . ":" . __LINE__);
2022-01-17 00:18:50 +01:00
require "class/main.php";
require "class/db.php";
require "class/hook_class.php";
2022-01-02 18:14:13 +01:00
require "utils.php";
2022-03-04 22:30:16 +01:00
require $configDir . "/properties2log.php";
2022-01-02 18:14:13 +01:00
require "mqtt_functions.php";
require "events.php";
require "db_functions.php";
2022-09-01 17:02:28 +02:00
require "config/liste_telephones.php";
require "presence.php";
require "apiserver/apiserver.php";
require "configWatch.php";
2022-09-01 17:02:28 +02:00
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;
}
}
2023-01-26 18:30:51 +01:00
2022-01-08 23:45:38 +01:00
// topics definition
2022-04-23 02:00:52 +02:00
listHooks("./topics_callbacks", $topicsCallbacks);
if (!empty($topicsCallbacks))
2022-01-08 23:45:38 +01:00
{
2022-04-23 02:00:52 +02:00
foreach ($topicsCallbacks as $callback)
2022-01-08 23:45:38 +01:00
{
2022-01-28 23:05:58 +01:00
logger(INFO, _("Including ") . $callback, __FILE__ . ":" . __LINE__);
2022-01-08 23:45:38 +01:00
include $callback;
}
}
2022-01-17 00:18:50 +01:00
// making the list of hooks to include
listHooks("./hooks", $hooksList);
2022-04-23 02:00:52 +02:00
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;
}
2022-12-05 12:23:43 +01:00
//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();
}
}
2022-01-17 00:18:50 +01:00
// Program start
logger(DEBUG, _("Program start"), __FILE__ . ":" . __LINE__);
$client = new Mosquitto\Client();
2022-01-23 09:46:06 +01:00
try
{
connect2mqttServer();
}catch ( Mosquitto\Exception $err)
{
logger(ALERT, sprintf(_("Error connecting to mosquitto server, retrying in 10 seconds:"), $err), __FILE__ . ":" . __LINE__);
2022-01-23 09:46:06 +01:00
sleep (10);
exit(1);
}
2021-12-30 16:18:32 +01:00
$client->onDisconnect('disconnectResponse');
$client->onSubscribe('subscribeResponse');
$client->onUnsubscribe('unsubscribeResponse');
$client->onMessage('messageReceived');
2021-12-30 16:18:32 +01:00
$client->onLog('logger');
$client->onPublish('publishResponse');
2022-01-17 21:01:11 +01:00
// connectong to mqtt server
2022-01-23 09:46:06 +01:00
$client->connect($mqttServerIp, 1883, 5);
2022-01-28 23:05:58 +01:00
logger(INFO, _("Subscribing to bridge"), __FILE__ . ":" . __LINE__, false);
foreach($topics as $name => &$topic)
2021-12-30 16:18:32 +01:00
{
$topic->mid = $client->subscribe($name . "/#", 2);
2021-12-30 16:18:32 +01:00
$mids[$topic->mid] = $name;
$topic->status = false;
}
2022-01-17 21:01:11 +01:00
// starting main loop
logger(INFO, _("Starting loop"), __FILE__ . ":" . __LINE__);
$oneshot = false;
logger(ALERT, _("Moha started"), __FILE__ . ":" . __LINE__);
2022-02-23 10:23:16 +01:00
// démarre la surveillance du dossier de configuration : /etc/moha
configWatchInit();
2021-12-30 16:18:32 +01:00
while (true)
{
2022-12-05 12:23:43 +01:00
// test if looping is more then 5 second and send and alert
2023-01-26 18:30:51 +01:00
// echo date("c") . " début";
2022-12-05 12:23:43 +01:00
$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;
2022-01-17 21:01:11 +01:00
$client->loop(); // mqtt server loop()
2023-01-26 18:30:51 +01:00
if ($oneshot === false) // execute while the first loop :WARNING all hooks may not be initialized
2022-04-23 02:00:52 +02:00
{
2023-01-26 18:30:51 +01:00
echo date("c") . " One shot";
2022-04-23 02:00:52 +02:00
logger(DEBUG, _("Oneshot part of loop"), __FILE__ . ":" . __LINE__, false);
pws2mqttGetList();
$oneshot = true;
}
2023-01-26 18:30:51 +01:00
//echo date("c") . " initialisation des hooks";
2022-04-23 02:00:52 +02:00
if($hooksInitialized == 0) // all hooks are not initialized
{
$i = 1;
foreach($hooks as $hookName => &$hook)
2022-01-17 00:18:50 +01:00
{
if ($hook->active === false)
2022-01-17 00:18:50 +01:00
{
$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);
}
2022-01-17 00:18:50 +01:00
}
}
2022-04-23 02:00:52 +02:00
$hooksInitialized = $i;
2022-12-05 12:23:43 +01:00
/*}elseif($flagHooks === false)
2022-04-23 02:00:52 +02:00
{
logger(DEBUG, _("All hooks initialized"), __FILE__ . ":" . __LINE__);
2022-12-05 12:23:43 +01:00
$flagHooks = true;*/
}else // executed when hooks initialization finished but database init may be not finished
2022-04-23 02:00:52 +02:00
{
//logger(DEBUG, _("looping"), __FILE__ . ":" . __LINE__);
}
2023-01-26 18:30:51 +01:00
// echo date("c") . " chech events";
2022-04-23 02:00:52 +02:00
checkEvents();
2023-01-26 18:30:51 +01:00
// echo date("c") . " topics availabiblity";
checkTopicsAvailability();
2023-01-26 18:30:51 +01:00
//echo date("c") . " apiserver";
2022-06-20 10:34:55 +02:00
if ($apiServerIsActive) apiServer($read);
2023-01-26 18:30:51 +01:00
//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")
{
2022-09-03 21:10:38 +02:00
logger(DEBUG, _("configWatch : inclus ") . $configDir . "/" . $event["name"], __FILE__ . ":" . __LINE__);
include $configDir . "/" . $event["name"];
}else
{
2022-12-05 12:23:43 +01:00
logger(DEBUG, _("configWatch : mauvaise extension, je n'inclus pas ") . $configDir . "/" . $event["name"], __FILE__ . ":" . __LINE__);
}
}
}
}
2023-01-26 18:30:51 +01:00
//echo date("c") . " fin";
2021-12-30 16:18:32 +01:00
}
endMoha();
?>