1
0
moha/moha.php

300 lines
8.2 KiB
PHP

<?php
$title = "moha";
cli_set_process_title($title);
file_put_contents("/proc/".getmypid()."/comm",$title);
declare(ticks = 1);
$testMode = true;
$webServerIsActive = true;
require "constants.php";
$listProperties = array("powerSource" => "batterie");
$listPropertiesKeys = array("property");
//global variables
$logLevel = ALL; // INFO | NOTICE | WARNING | ERROR | ALERT; //ALL;
$notificationLevel = ALERT | ERROR;
$topics = array(); // list of topics
$mids = array(); // list of message IDs
$devices = array(); // array of device objetcs
$indexDevices = array(); // index devices by ieee_address
$hooksList = array(); // list of hooks to be included
$hooks = array(); // array of hooks
$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;
if ($testMode)
{
$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/)
}else
{
$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/config"; // default config dir (production value is /etc/moha/)
}
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, $pos = false, $notif = true)
{
global $logFh, $logLevel, $notificationLevel, $logLevels;
$logString = date("c") . ' ' . $logLevels[$level] . " " ;
if ($pos !== false)
{
$logString .= $pos;
}
$logString .= " - " . $log;
if ($level & $logLevel)
{
fwrite($logFh, $logString . EOL);
print ($logString . EOL);
}
$test = $level & $notificationLevel;
if (($test != 0) and ($notif === true))
{
if(notify("Moha\n" . $logString) === false)
{
logger(INFO, _("Notification not sent"), __FILE__ . ":" . __LINE__, false);
}
}else
{
logger(INFO, _("Notification not sent because of testMode"), __FILE__ . ":" . __LINE__, false);
}
}
function init()
{
global $logFile, $logFh, $client;
date_default_timezone_set('Europe/Paris');
if (! $logFh = fopen($logFile, "w") )
{
echo _("error opening log file");
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, $nSubscribed ,$client, $logFh, $connected, $dataPath;
$x = 0;
logger(WARNING, _("moha is ending"), __FILE__ . ":" . __LINE__);
storeDB($devices, $dataPath . "moha.db");
if($testMode) file_put_contents($dataPath . "moha.devices", var_export($devices, true));
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');
}
logger(WARNING, _("starting moha"), __FILE__ . ":" . __LINE__);
logger(DEBUG, _("requiring php modules"), __FILE__ . ":" . __LINE__);
require "class/main.php";
require "class/db.php";
require "class/hook_class.php";
require "utils.php";
require "config/properties2log.php";
require "mqtt_functions.php";
require "events.php";
require "db_functions.php";
require "webserver.php";
//logger(DEBUG, _('assigning variable $client to mosquitto class "client"'), false);
//$client = new Mosquitto\Client();
logger(DEBUG, _("Loading stored devices datas"), __FILE__ . ":" . __LINE__);
loadDB($devices, "moha.db");
// topics definition
listHooks("./topics_callbacks", $hooksList);
if (!empty($hooksList))
{
foreach ($hooksList as $callback)
{
logger(INFO, _("Including ") . $callback, __FILE__ . ":" . __LINE__);
include $callback;
}
}
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.define found, so it has been included :-)"), $configDir), __FILE__ . ":" . __LINE__, false);
}elseif(is_readable("config/devices_constants.php"))
{
include "config/devices_constants.php";
//echo "hooklist"; print_r($hooksList); echo EOL;
logger(INFO, sprintf(_("%s/devices_constants.define found, so it has been included :-)"), $configDir), __FILE__ . ":" . __LINE__, false);
}else
{
logger(WARNING, sprintf(_("%s/devices_constants.define not found, so not included :-)"), $configDir), __FILE__ . ":" . __LINE__, false);
}
// making the list of hooks to include
listHooks("./hooks", $hooksList);
// Program start
logger(DEBUG, _("Program start"), __FILE__ . ":" . __LINE__, 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), __FILE__ . ":" . __LINE__, 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"), __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__, false);
$oneshot = false;
while (true)
{
$client->loop(); // mqtt server loop()
if (! $included) // hooks not already included
{
logger(DEBUG, _("Making hooks list"), __FILE__ . ":" . __LINE__, 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, __FILE__ . ":" . __LINE__, false);
include $hook;
}
file_put_contents($dataPath . "moha.devices", var_export($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"), __FILE__ . ":" . __LINE__, 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, __FILE__ . ":" . __LINE__);
$i &= $hook->installHooks();
}
}
$hooksInitialized = $i;
}elseif($flagHooks === false)
{
logger(DEBUG, _("All hooks initialized"), __FILE__ . ":" . __LINE__);
$flagHooks = true;
}
checkEvents();
askWebServer($read);
}
}
endMoha();
?>