Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,14 @@ Un assistant en CLI vous posera quelques questions, (l'id du plugin, la catégor
Voila, votre plugin est basiquement prêt pour coder votre travail.



---
Démon
---
Le démon d'exemple (`resources/demond/demond.py`) fonctionne avec Jeedom 4.6 et Jeedom 5 :

* Jeedom parle au démon par un socket Unix que seul Jeedom peut ouvrir (`--socket`), sans clé API ni port réseau. Côté PHP, `template::sendToDaemon()` remplace l'ancien `socket_create(AF_INET…)` par `socket_create(AF_UNIX…)`.
* Le démon envoie ses valeurs avec `jeedom_com.add_changes()`. Avec Jeedom 5, il passe par l'API REST avec un jeton qu'il renouvelle lui-même (`--rest-credentials`). Avec Jeedom 4, il appelle `core/php/jeetemplate.php` avec la clé API du plugin.
* Dans les deux cas, le plugin reçoit les messages dans `template::handleDaemonMessages()`.
* `deamon_info()` ne déclare le démon en service que si son pid est vivant **et** s'il répond sur son socket (ligne `health` → `ok` pour `demond.py`, `GET /health` → `204` pour `jeedom.js`). Un démon figé, ou tué en laissant son socket, est ainsi relancé par Jeedom.
* Pour un démon Node.js, `resources/demond/jeedom/jeedom.js` offre les mêmes possibilités avec `Jeedom.com.config(apikey, callback, cycle, credentials)` et `Jeedom.http.config(socket)`.
120 changes: 120 additions & 0 deletions core/class/template.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,126 @@ public static function getConfigForCommunity() {
}
*/

/* * ***************************Démon******************************* */
/* À supprimer si le plugin n'a pas de démon (hasOwnDeamon à false dans info.json). */

public static function deamon_info() {
$return = array();
$return['log'] = __CLASS__;
$return['state'] = 'nok';
$pid_file = jeedom::getTmpFolder(__CLASS__) . '/deamon.pid';
if (file_exists($pid_file) && @posix_getsid(trim(file_get_contents($pid_file)))) {
// Le démon doit aussi répondre sur son socket : un processus figé ou un pid réutilisé ne suffit pas.
// Avec un démon Node.js (jeedom.js), envoyer GET /health avec com_http et attendre le code 204.
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 1, 'usec' => 0));
if (@socket_connect($socket, self::daemonSocketPath()) && socket_write($socket, "health\n") && trim((string) @socket_read($socket, 16)) == 'ok') {
$return['state'] = 'ok';
}
socket_close($socket);
}
$return['launchable'] = 'ok';
return $return;
}

public static function deamon_start() {
self::deamon_stop();
$deamon_info = self::deamon_info();
if ($deamon_info['launchable'] != 'ok') {
throw new Exception(__('Veuillez vérifier la configuration', __FILE__));
}
// Python de l'environnement du plugin, créé par l'installation des dépendances (section pip3 de packages.json).
$python = is_dir(__DIR__ . '/../../resources/python_venv') ? system::getCmdPython3(__CLASS__) : 'python3 ';
$cmd = $python . escapeshellarg(realpath(__DIR__ . '/../../resources/demond') . '/demond.py');
$cmd .= ' --loglevel ' . log::convertLogLevel(log::getLogLevel(__CLASS__));
$cmd .= ' --socket ' . escapeshellarg(self::daemonSocketPath());
$cmd .= ' --cycle ' . escapeshellarg(config::byKey('cycle', __CLASS__, 0.3));
$cmd .= ' --pid ' . escapeshellarg(jeedom::getTmpFolder(__CLASS__) . '/deamon.pid');
$cmd .= self::daemonJeedomArguments();
log::add(__CLASS__, 'info', 'Lancement du démon');
exec($cmd . ' >> ' . log::getPathToLog(__CLASS__ . '_daemon') . ' 2>&1 &');
for ($i = 0; $i < 20; $i++) {
if (self::deamon_info()['state'] == 'ok') {
message::removeAll(__CLASS__, 'unableStartDeamon');
return true;
}
sleep(1);
}
log::add(__CLASS__, 'error', __('Impossible de lancer le démon, vérifiez le log', __FILE__), 'unableStartDeamon');
return false;
}

public static function deamon_stop() {
$pid_file = jeedom::getTmpFolder(__CLASS__) . '/deamon.pid';
if (file_exists($pid_file)) {
system::kill(intval(trim(file_get_contents($pid_file))));
}
system::kill('demond.py');
if (file_exists(self::daemonSocketPath())) {
unlink(self::daemonSocketPath());
}
}

/*
* Socket Unix du démon. Seul Jeedom peut l'ouvrir : le PHP n'a pas besoin de clé API pour parler au démon.
*/
public static function daemonSocketPath() {
return jeedom::getTmpFolder(__CLASS__) . '/daemon.sock';
}

/*
* Arguments qui permettent au démon d'envoyer ses messages à Jeedom :
* - Jeedom 5 : API REST, avec un jeton propre au démon qu'il renouvelle lui-même ;
* - Jeedom 4 : core/php/jeetemplate.php, avec la clé API du plugin.
*/
private static function daemonJeedomArguments() {
$url = network::getNetworkAccess('internal', 'http:127.0.0.1:port:comp');
if (method_exists('plugin', 'daemonCredentialFile')) {
try {
$credentials = plugin::daemonCredentialFile(__CLASS__);
} catch (DomainException $e) {
// Session du démon supprimée par Jeedom (expirée ou révoquée) : on lui en ouvre une nouvelle.
$credentials = plugin::daemonCredentialFile(__CLASS__, true);
}
config::save('daemon::transport', 'rest', __CLASS__);
return ' --callback ' . escapeshellarg($url . '/api/v1/plugins/' . __CLASS__ . '/daemon/messages')
. ' --rest-credentials ' . escapeshellarg($credentials);
}
config::save('daemon::transport', 'callback', __CLASS__);
return ' --callback ' . escapeshellarg($url . '/plugins/' . __CLASS__ . '/core/php/jee' . __CLASS__ . '.php')
. ' --apikey ' . escapeshellarg(jeedom::getApiKey(__CLASS__));
}

/*
* Envoie un message au démon (reçu dans read_socket() de demond.py).
* Exemple : template::sendToDaemon(array('action' => 'test'));
*
* Avec un démon Node.js (jeedom.js, Jeedom.http.config(socket)), le PHP envoie une requête HTTP sur le socket :
* $request = new com_http('http://localhost/action');
* $request->setCURLOPT(array(CURLOPT_UNIX_SOCKET_PATH => self::daemonSocketPath()));
* $request->setHeader(array('Content-Type: application/json'));
* $request->setPost(json_encode($params));
* $request->exec();
*/
public static function sendToDaemon($params) {
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
if ($socket === false || !@socket_connect($socket, self::daemonSocketPath())) {
throw new Exception(__('Le démon ne répond pas', __FILE__));
}
$payload = json_encode($params) . "\n";
socket_write($socket, $payload, strlen($payload));
socket_close($socket);
}

/*
* Messages envoyés par le démon avec jeedom_com, regroupés par clé :
* add_changes('equipement::temperature', 21.5) donne array('equipement' => array('temperature' => 21.5)).
* Appelée par Jeedom 5 et, avec Jeedom 4, par core/php/jeetemplate.php.
*/
public static function handleDaemonMessages(array $messages) {
log::add(__CLASS__, 'debug', 'Messages du démon : ' . json_encode($messages));
}

/* * *********************Méthodes d'instance************************* */

// Fonction exécutée automatiquement avant la création de l'équipement
Expand Down
36 changes: 36 additions & 0 deletions core/php/jeetemplate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
/* This file is part of Jeedom.
*
* Jeedom is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Jeedom is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Jeedom. If not, see <http://www.gnu.org/licenses/>.
*/


/*
* Point d'entrée du démon avec Jeedom 4, appelé avec la clé API du plugin.
* Avec Jeedom 5, le démon envoie ses messages par l'API REST : ce fichier refuse alors tout.
*/
require_once __DIR__ . '/../../../../core/php/core.inc.php';

if (config::byKey('daemon::transport', 'template') == 'rest' || !jeedom::apiAccess(init('apikey'), 'template')) {
http_response_code(403);
die();
}
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
echo 'OK'; // test de connexion du démon au démarrage
die();
}
$messages = json_decode(file_get_contents('php://input'), true);
if (is_array($messages)) {
template::handleDaemonMessages($messages);
}
31 changes: 16 additions & 15 deletions resources/demond/demond.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,8 @@
def read_socket():
if not JEEDOM_SOCKET_MESSAGE.empty():
logging.debug("Message received in socket JEEDOM_SOCKET_MESSAGE")
# Message envoyé par template::sendToDaemon() : seul Jeedom peut écrire sur le socket Unix.
message = json.loads(jeedom_utils.stripped(JEEDOM_SOCKET_MESSAGE.get()))
if message['apikey'] != _apikey:
logging.error("Invalid apikey from socket: %s", message)
return
try:
print('read')
except Exception as e:
Expand Down Expand Up @@ -74,8 +72,8 @@ def shutdown():


_log_level = "error"
_socket_port = 55009
_socket_host = 'localhost'
_socket = ''
_rest_credentials = ''
_device = 'auto'
_pidfile = '/tmp/demond.pid'
_apikey = ''
Expand All @@ -89,7 +87,8 @@ def shutdown():
parser.add_argument("--apikey", help="Apikey", type=str)
parser.add_argument("--cycle", help="Cycle to send event", type=float)
parser.add_argument("--pid", help="Pid file", type=str)
parser.add_argument("--socketport", help="Port for socket server", type=int)
parser.add_argument("--socket", help="Unix socket for messages from Jeedom", type=str)
parser.add_argument("--rest-credentials", help="Daemon access file for the REST API (Jeedom 5)", type=str)
args = parser.parse_args()

if args.device:
Expand All @@ -104,32 +103,34 @@ def shutdown():
_pidfile = args.pid
if args.cycle:
_cycle = float(args.cycle)
if args.socketport:
_socket_port = args.socketport

_socket_port = int(_socket_port)
if args.socket:
_socket = args.socket
else:
# Sans socket Unix, le démon écouterait sur un port TCP sans contrôle de la clé API : on refuse.
print('Missing --socket argument: the daemon only listens on a Unix socket')
sys.exit(1)
if args.rest_credentials:
_rest_credentials = args.rest_credentials

jeedom_utils.set_log_level(_log_level)

logging.info('Start demond')
logging.info('Log level: %s', _log_level)
logging.info('Socket port: %s', _socket_port)
logging.info('Socket host: %s', _socket_host)
logging.info('Socket: %s', _socket)
logging.info('PID file: %s', _pidfile)
logging.info('Apikey: %s', _apikey)
logging.info('Device: %s', _device)

signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)

try:
jeedom_utils.write_pid(str(_pidfile))
my_jeedom_com = jeedom_com(apikey=_apikey, url=_callback, cycle=_cycle)
my_jeedom_com = jeedom_com(apikey=_apikey, url=_callback, cycle=_cycle, credentials=_rest_credentials)
if not my_jeedom_com.test():
logging.error('Network communication issues. Please fixe your Jeedom network configuration.')
shutdown()
# my_jeedom_serial = jeedom_serial(device=_device) # if you need jeedom_serial
my_jeedom_socket = jeedom_socket(port=_socket_port, address=_socket_host)
my_jeedom_socket = jeedom_socket(path=_socket)
listen()
except Exception as e:
logging.error('Fatal error: %s', e)
Expand Down
Loading
Loading