public static function returnState($_options)
 {
     $cmd = cmd::byId($_options['cmd_id']);
     if (is_object($cmd)) {
         $cmd->returnState();
     }
 }
Example #2
0
 public function execute($_options = array())
 {
     switch ($this->getConfiguration('mode')) {
         case 'fixe':
             return $this->getConfiguration('coordinate');
             break;
         case 'dynamic':
             break;
         case 'distance':
             $from = cmd::byId($this->getConfiguration('from'));
             $to = cmd::byId($this->getConfiguration('to'));
             if (!is_object($from)) {
                 throw new Exception('Commande point de départ introuvable : ' . $this->getConfiguration('from'));
             }
             if (!is_object($to)) {
                 throw new Exception('Commande point d\'arrivé introuvable : ' . $this->getConfiguration('to'));
             }
             $to = explode(',', $to->execCmd());
             $from = explode(',', $from->execCmd());
             if (count($to) == 2 && count($from) == 2) {
                 return self::distance($from[0], $from[1], $to[0], $to[1]);
             }
             return -1;
             break;
         default:
             break;
     }
 }
Example #3
0
 public function execute($_options = array())
 {
     switch ($this->getConfiguration('mode')) {
         case 'fixe':
             $result = $this->getConfiguration('coordinate');
             return $result;
         case 'distance':
             $from = cmd::byId($this->getConfiguration('from'));
             $to = cmd::byId($this->getConfiguration('to'));
             if (!is_object($from)) {
                 throw new Exception(__('Commande point de départ introuvable : ', __FILE__) . $this->getConfiguration('from'));
             }
             if (!is_object($to)) {
                 throw new Exception(__('Commande point d\'arrivé introuvable : ', __FILE__) . $this->getConfiguration('to'));
             }
             $to = explode(',', $to->execCmd(null, 0));
             $from = explode(',', $from->execCmd(null, 0));
             if (count($to) > 2) {
                 $to[2] = implode(',', array_slice($to, 1));
             }
             if (count($from) > 2) {
                 $from[2] = implode(',', array_slice($from, 1));
             }
             if (count($to) == 2 && count($from) == 2) {
                 return self::distance($from[0], $from[1], $to[0], $to[1]);
             }
             return 0;
         case 'travelTime':
             $from = cmd::byId($this->getConfiguration('from'));
             $to = cmd::byId($this->getConfiguration('to'));
             try {
                 $highways = true;
                 if ($this->getConfiguration('noHighways', 0) == 1) {
                     $highways = false;
                 }
                 $result = self::get_driving_information($from->execCmd(null, 0), $to->execCmd(null, 0), $highways);
                 return $result['time'];
             } catch (Exception $e) {
                 return 0;
             }
         case 'travelDistance':
             $from = cmd::byId($this->getConfiguration('from'));
             $to = cmd::byId($this->getConfiguration('to'));
             try {
                 $highways = true;
                 if ($this->getConfiguration('noHighways', 0) == 1) {
                     $highways = false;
                 }
                 $result = self::get_driving_information($from->execCmd(null, 0), $to->execCmd(null, 0), $highways);
                 return $result['distance'];
             } catch (Exception $e) {
                 return 0;
             }
     }
 }
Example #4
0
 if (init('action') == 'forgotPassword') {
     log::add('user', 'info', __('Demande de récupération de mot de passe pour : ', __FILE__) . init('login'));
     $user = user::byLogin(init('login'));
     if (!is_object($user)) {
         connection::failed();
         throw new Exception('Utilisateur introuvable');
     }
     $newPassword = config::genKey();
     $oldPassword = $user->getPassword();
     $user->setPassword(sha1($newPassword));
     $cmds = explode('&&', config::byKey('emailAdmin'));
     $found = false;
     try {
         if (count($cmds) > 0) {
             foreach ($cmds as $id) {
                 $cmd = cmd::byId(str_replace('#', '', $id));
                 if (is_object($cmd)) {
                     $found = true;
                     $cmd->execCmd(array('title' => __('[JEEDOM] Récuperation de mot de passe', __FILE__), 'message' => 'Voici votre nouveau mot de passe pour votre installation jeedom : ' . $newPassword));
                 }
             }
         }
     } catch (Exception $e) {
         throw new Exception(__('Aucune commande trouvé pour envoyé le nouveau mot de passe, la demande de récupération a echouée', __FILE__));
     }
     if (!$found) {
         throw new Exception(__('Aucune commande trouvé pour envoyé le nouveau mot de passe, la demande de récupération a echouée, vous pouvez trouver une procedure <a href="https://www.jeedom.fr/doc/documentation/howto/fr_FR/doc-howto-reset.password.html" target="_blank">ici</a>', __FILE__));
     }
     $user->save();
     ajax::success();
 }
Example #5
0
 public function execute($_trigger = '', $_message = '')
 {
     if ($this->getIsActive() != 1) {
         $this->setLog(__('Impossible d\'exécuter le scénario : ', __FILE__) . $this->getHumanName() . __(' sur : ', __FILE__) . $_message . __(' car il est désactivé', __FILE__));
         $this->persistLog();
         return;
     }
     if ($this->getConfiguration('timeDependency', 0) == 1 && !jeedom::isDateOk()) {
         $this->setLog(__('Lancement du scénario : ', __FILE__) . $this->getHumanName() . __(' annulé car il utilise une condition de type temporelle et que la date système n\'est pas OK', __FILE__));
         $this->persistLog();
         return;
     }
     $cmd = cmd::byId(str_replace('#', '', $_trigger));
     if (is_object($cmd)) {
         log::add('event', 'event', __('Exécution du scénario ', __FILE__) . $this->getHumanName() . __(' déclenché par : ', __FILE__) . $cmd->getHumanName());
     } else {
         log::add('event', 'event', __('Exécution du scénario ', __FILE__) . $this->getHumanName() . __(' déclenché par : ', __FILE__) . $_trigger);
     }
     $this->setLog(__('Début d\'exécution du scénario : ', __FILE__) . $this->getHumanName() . '. ' . $_message);
     $this->setLastLaunch(date('Y-m-d H:i:s'));
     if ($this->getConfiguration('speedPriority', 0) == 0) {
         $this->setDisplay('icon', '');
         $this->setState('in progress');
         $this->setPID(getmypid());
         $this->save();
     }
     $this->setRealTrigger($_trigger);
     foreach ($this->getElement() as $element) {
         $element->execute($this);
     }
     if ($this->getConfiguration('speedPriority', 0) == 0) {
         $this->setState('stop');
         $this->setPID('');
     }
     $this->setLog(__('Fin correcte du scénario', __FILE__));
     $this->persistLog();
     $this->save();
     if ($this->getReturn() != '') {
         return $this->getReturn();
     }
     return true;
 }
Example #6
0
 public function execute(&$scenario = null)
 {
     if ($this->getOptions('enable', 1) == 0) {
         return;
     }
     $message = '';
     try {
         if ($this->getType() == 'element') {
             $element = scenarioElement::byId($this->getExpression());
             if (is_object($element)) {
                 $this->setLog($scenario, __('Exécution d\'un bloc élément : ', __FILE__) . $this->getExpression());
                 return $element->execute($scenario);
             }
             return;
         }
         $options = $this->getOptions();
         if (isset($options['enable'])) {
             unset($options['enable']);
         }
         if (is_array($options) && $this->getExpression() != 'wait') {
             foreach ($options as $key => $value) {
                 $options[$key] = str_replace('"', '', self::setTags($value, $scenario));
             }
         }
         if ($this->getType() == 'action') {
             if ($this->getExpression() == 'icon') {
                 if ($scenario != null) {
                     $options = $this->getOptions();
                     $this->setLog($scenario, __('Changement de l\'icone du scénario : ', __FILE__) . $options['icon']);
                     $scenario->setDisplay('icon', $options['icon']);
                     $scenario->save();
                 }
                 return;
             } else {
                 if ($this->getExpression() == 'wait') {
                     if (!isset($options['condition'])) {
                         return;
                     }
                     $result = false;
                     $occurence = 0;
                     $limit = isset($options['timeout']) && is_numeric($options['timeout']) ? $options['timeout'] : 7200;
                     while ($result !== true) {
                         $expression = self::setTags($options['condition'], $scenario);
                         $result = evaluate($expression);
                         if ($occurence > $limit) {
                             $this->setLog($scenario, __('[Wait] Condition valide par dépassement de temps', __FILE__));
                             return;
                         }
                         $occurence++;
                         sleep(1);
                     }
                     $this->setLog($scenario, __('[Wait] Condition valide : ', __FILE__) . $expression);
                     return;
                 } else {
                     if ($this->getExpression() == 'sleep') {
                         if (isset($options['duration'])) {
                             try {
                                 $options['duration'] = evaluate($options['duration']);
                             } catch (Exception $e) {
                             }
                             if (is_numeric($options['duration']) && $options['duration'] > 0) {
                                 $this->setLog($scenario, __('Pause de ', __FILE__) . $options['duration'] . __(' seconde(s)', __FILE__));
                                 if ($options['duration'] < 1) {
                                     return usleep($options['duration'] * 1000);
                                 } else {
                                     return sleep($options['duration']);
                                 }
                             }
                         }
                         $this->setLog($scenario, __('Aucune durée trouvée pour l\'action sleep ou la durée n\'est pas valide : ', __FILE__) . $options['duration']);
                         return;
                     } else {
                         if ($this->getExpression() == 'stop') {
                             if ($scenario != null) {
                                 $this->setLog($scenario, __('Arret du scénario', __FILE__));
                                 $scenario->setState('stop');
                                 $scenario->setPID('');
                                 $scenario->persistLog();
                                 $scenario->save();
                             }
                             die;
                         } else {
                             if ($this->getExpression() == 'log') {
                                 if ($scenario != null) {
                                     $scenario->setLog('Log : ' . $options['message']);
                                     if ($scenario->getConfiguration('speedPriority', 0) == 1) {
                                         $scenario->persistLog();
                                     }
                                 }
                                 return;
                             } else {
                                 if ($this->getExpression() == 'message') {
                                     message::add('scenario', $options['message']);
                                     return;
                                 } else {
                                     if ($this->getExpression() == 'equipement') {
                                         $eqLogic = eqLogic::byId(str_replace(array('#eqLogic', '#'), '', $this->getOptions('eqLogic')));
                                         if (!is_object($eqLogic)) {
                                             throw new Exception(__('Action sur l\'équipement impossible. Equipement introuvable - Vérifiez l\'id : ', __FILE__) . $this->getOptions('eqLogic'));
                                         }
                                         switch ($this->getOptions('action')) {
                                             case 'show':
                                                 $this->setLog($scenario, __('Equipement visible : ', __FILE__) . $eqLogic->getHumanName());
                                                 $eqLogic->setIsVisible(1);
                                                 $eqLogic->save();
                                                 break;
                                             case 'hide':
                                                 $this->setLog($scenario, __('Equipement masqué : ', __FILE__) . $eqLogic->getHumanName());
                                                 $eqLogic->setIsVisible(0);
                                                 $eqLogic->save();
                                                 break;
                                             case 'deactivate':
                                                 $this->setLog($scenario, __('Equipement désactivé : ', __FILE__) . $eqLogic->getHumanName());
                                                 $eqLogic->setIsEnable(0);
                                                 $eqLogic->save();
                                                 break;
                                             case 'activate':
                                                 $this->setLog($scenario, __('Equipement activé : ', __FILE__) . $eqLogic->getHumanName());
                                                 $eqLogic->setIsEnable(1);
                                                 $eqLogic->save();
                                                 break;
                                         }
                                         return;
                                     } else {
                                         if ($this->getExpression() == 'say') {
                                             $this->setLog($scenario, __('Je dis : ', __FILE__) . $options['message']);
                                             nodejs::pushUpdate('jeedom::say', $options['message']);
                                             return;
                                         } else {
                                             if ($this->getExpression() == 'gotodesign') {
                                                 $this->setLog($scenario, __('Changement design : ', __FILE__) . $options['plan_id']);
                                                 nodejs::pushUpdate('jeedom::gotoplan', $options['plan_id']);
                                                 return;
                                             } else {
                                                 if ($this->getExpression() == 'return') {
                                                     $this->setLog($scenario, __('Je vais retourner : ', __FILE__) . $options['message']);
                                                     $scenario->setReturn($scenario->getReturn() . $options['message']);
                                                     return;
                                                 } else {
                                                     if ($this->getExpression() == 'scenario') {
                                                         if ($scenario != null && $this->getOptions('scenario_id') == $scenario->getId()) {
                                                             $actionScenario =& $scenario;
                                                         } else {
                                                             $actionScenario = scenario::byId($this->getOptions('scenario_id'));
                                                         }
                                                         if (!is_object($actionScenario)) {
                                                             throw new Exception($scenario, __('Action sur scénario impossible. Scénario introuvable - Vérifiez l\'id : ', __FILE__) . $this->getOptions('scenario_id'));
                                                         }
                                                         switch ($this->getOptions('action')) {
                                                             case 'start':
                                                                 $this->setLog($scenario, __('Lancement du scénario : ', __FILE__) . $actionScenario->getName());
                                                                 if ($scenario != null) {
                                                                     $actionScenario->launch(false, __('Lancement provoqué par le scénario  : ', __FILE__) . $scenario->getHumanName());
                                                                 } else {
                                                                     $actionScenario->launch(false, __('Lancement provoqué', __FILE__));
                                                                 }
                                                                 break;
                                                             case 'stop':
                                                                 $this->setLog($scenario, __('Arrêt forcé du scénario : ', __FILE__) . $actionScenario->getName());
                                                                 $actionScenario->stop();
                                                                 break;
                                                             case 'deactivate':
                                                                 $this->setLog($scenario, __('Désactivation du scénario : ', __FILE__) . $actionScenario->getName());
                                                                 $actionScenario->setIsActive(0);
                                                                 $actionScenario->save();
                                                                 break;
                                                             case 'activate':
                                                                 $this->setLog($scenario, __('Activation du scénario : ', __FILE__) . $actionScenario->getName());
                                                                 $actionScenario->setIsActive(1);
                                                                 $actionScenario->save();
                                                                 break;
                                                         }
                                                         return;
                                                     } else {
                                                         if ($this->getExpression() == 'variable') {
                                                             $options['value'] = self::setTags($options['value']);
                                                             try {
                                                                 $result = evaluate($options['value']);
                                                                 if (!is_numeric($result)) {
                                                                     $result = $options['value'];
                                                                 }
                                                             } catch (Exception $ex) {
                                                                 $result = $options['value'];
                                                             }
                                                             $message = __('Affectation de la variable ', __FILE__) . $this->getOptions('name') . __(' => ', __FILE__) . $options['value'] . ' = ' . $result;
                                                             $this->setLog($scenario, $message);
                                                             $dataStore = new dataStore();
                                                             $dataStore->setType('scenario');
                                                             $dataStore->setKey($this->getOptions('name'));
                                                             $dataStore->setValue($result);
                                                             $dataStore->setLink_id(-1);
                                                             $dataStore->save();
                                                             return;
                                                         } else {
                                                             $cmd = cmd::byId(str_replace('#', '', $this->getExpression()));
                                                             if (is_object($cmd)) {
                                                                 if ($cmd->getSubtype() == 'slider' && isset($options['slider'])) {
                                                                     $options['slider'] = evaluate($options['slider']);
                                                                 }
                                                                 if (is_array($options) && count($options) != 0) {
                                                                     $this->setLog($scenario, __('Exécution de la commande ', __FILE__) . $cmd->getHumanName() . __(" avec comme option(s) : \n", __FILE__) . print_r($options, true));
                                                                 } else {
                                                                     $this->setLog($scenario, __('Exécution de la commande ', __FILE__) . $cmd->getHumanName());
                                                                 }
                                                                 if (is_object($scenario) && $scenario->getConfiguration('cmdNoWait', 0) == 1) {
                                                                     $options['speedAndNoErrorReport'] = true;
                                                                 }
                                                                 return $cmd->execCmd($options);
                                                             }
                                                             $this->setLog($scenario, __('[Erreur] Aucune commande trouvée pour ', __FILE__) . $this->getExpression());
                                                             return;
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         } else {
             if ($this->getType() == 'condition') {
                 $expression = self::setTags($this->getExpression(), $scenario, true);
                 $message = __('Evaluation de la condition : [', __FILE__) . $expression . '] = ';
                 $result = evaluate($expression);
                 if (is_bool($result)) {
                     if ($result) {
                         $message .= __('Vrai', __FILE__);
                     } else {
                         $message .= __('Faux', __FILE__);
                     }
                 } else {
                     $message .= $result;
                 }
                 $this->setLog($scenario, $message);
                 return $result;
             } else {
                 if ($this->getType() == 'code') {
                     $this->setLog($scenario, __('Exécution d\'un bloc code', __FILE__));
                     return eval($this->getExpression());
                 }
             }
         }
     } catch (Exception $e) {
         $this->setLog($scenario, $message . $e->getMessage());
     }
 }
Example #7
0
 public function executeAndReply($_parameters)
 {
     $interactDef = interactDef::byId($this->getInteractDef_id());
     if (!is_object($interactDef)) {
         return __('Inconsistance de la base de données', __FILE__);
     }
     if (isset($_parameters['profile']) && trim($interactDef->getPerson()) != '') {
         $person = strtolower($interactDef->getPerson());
         $person = explode('|', $person);
         if (!in_array($_parameters['profile'], $person)) {
             return __('Vous n\'êtes pas autorisé à exécuter cette action', __FILE__);
         }
     }
     $reply = $interactDef->selectReply();
     $replace = array();
     $tags = interactDef::getTagFromQuery($this->getQuery(), $_parameters['dictation']);
     $tags_replace = array();
     foreach ($tags as $key => $value) {
         $tags_replace['#' . $key . '#'] = $value;
         $replace['#' . $key . '#'] = $value;
     }
     $executeDate = null;
     $dateConvert = array('heure' => 'hour', 'mois' => 'month', 'semaine' => 'week', 'année' => 'year');
     if (isset($tags_replace['#duration#'])) {
         $tags_replace['#duration#'] = str_replace(array_keys($dateConvert), $dateConvert, $tags_replace['#duration#']);
         $executeDate = strtotime('+' . $tags_replace['#duration#']);
     }
     if (isset($tags_replace['#time#'])) {
         $time = str_replace(array('h'), array(':'), $tags_replace['#time#']);
         if (strlen($time) == 2) {
             $time .= ':00';
         } else {
             if (strlen($time) == 3) {
                 $time .= '00';
             }
         }
         $executeDate = strtotime($time);
         if ($executeDate < strtotime('now')) {
             $executeDate += 3600;
         }
     }
     if ($executeDate !== null && !isset($_parameters['execNow'])) {
         if (date('Y', $executeDate) < 2000) {
             return __('Erreur impossible de calculer la date de programmation', __FILE__);
         }
         if ($executeDate < strtotime('now') + 60) {
             $executeDate = strtotime('now') + 60;
         }
         $crons = cron::searchClassAndFunction('interactQuery', 'doIn', '"interactQuery_id":' . $this->getId());
         if (is_array($crons)) {
             foreach ($crons as $cron) {
                 if ($cron->getState() != 'run') {
                     $cron->remove();
                 }
             }
         }
         $cron = new cron();
         $cron->setClass('interactQuery');
         $cron->setFunction('doIn');
         $cron->setOption(array_merge(array('interactQuery_id' => intval($this->getId())), $_parameters));
         $cron->setLastRun(date('Y-m-d H:i:s'));
         $cron->setOnce(1);
         $cron->setSchedule(date('i', $executeDate) . ' ' . date('H', $executeDate) . ' ' . date('d', $executeDate) . ' ' . date('m', $executeDate) . ' * ' . date('Y', $executeDate));
         $cron->save();
         $replace['#value#'] = date('Y-m-d H:i:s', $executeDate);
         $result = scenarioExpression::setTags(str_replace(array_keys($replace), $replace, $reply));
         return $result;
     }
     $colors = config::byKey('convertColor');
     foreach ($this->getActions('cmd') as $action) {
         try {
             $options = array();
             if (isset($action['options'])) {
                 $options = $action['options'];
             }
             if ($tags != null) {
                 foreach ($options as &$option) {
                     $option = str_replace(array_keys($tags_replace), $tags_replace, $option);
                 }
                 if (isset($options['color']) && isset($colors[strtolower($options['color'])])) {
                     $options['color'] = $colors[strtolower($options['color'])];
                 }
             }
             $cmd = cmd::byId(str_replace('#', '', $action['cmd']));
             if (is_object($cmd) && $cmd->getType() == 'info') {
                 $replace['#unite#'] = $cmd->getUnite();
                 $replace['#commande#'] = $cmd->getName();
                 $replace['#objet#'] = '';
                 $replace['#equipement#'] = '';
                 $eqLogic = $cmd->getEqLogic();
                 if (is_object($eqLogic)) {
                     $replace['#equipement#'] = $eqLogic->getName();
                     $object = $eqLogic->getObject();
                     if (is_object($object)) {
                         $replace['#objet#'] = $object->getName();
                     }
                 }
             }
             $options['tags'] = $tags_replace;
             $return = scenarioExpression::createAndExec('action', $action['cmd'], $options);
             if (trim($return) != '') {
                 $replace['#valeur#'] = $return;
             }
         } catch (Exception $e) {
             log::add('interact', 'error', __('Erreur lors de l\'éxecution de ', __FILE__) . $action['cmd'] . __('. Détails : ', __FILE__) . $e->getMessage());
         }
     }
     $replace['#profile#'] = isset($_parameters['profile']) ? $_parameters['profile'] : '';
     if ($interactDef->getOptions('convertBinary') != '') {
         $convertBinary = $interactDef->getOptions('convertBinary');
         $convertBinary = explode('|', $convertBinary);
         $replace['1'] = $convertBinary[1];
         $replace['0'] = $convertBinary[0];
     }
     $result = scenarioExpression::setTags(str_replace(array_keys($replace), $replace, $reply));
     return $result;
 }
Example #8
0
 public function execute($_options = array())
 {
     $eqLogic = $this->getEqLogic();
     if ($this->getConfiguration('armed') == '1') {
         if ($eqLogic->getConfiguration('cmd_armed_id') != '') {
             $cmd_armed = cmd::byId($eqLogic->getConfiguration('cmd_armed_id'));
             $cmd_state = cmd::byId($eqLogic->getConfiguration('cmd_state_id'));
             $cmd_immediateState = cmd::byId($eqLogic->getConfiguration('cmd_immediatState_id'));
             if ($this->getConfiguration('state') == 0) {
                 $cmd_armed->event($this->getConfiguration('state'));
                 /* RaZ */
                 if ($cmd_state->execCmd() == 1) {
                     log::add('alarm', 'debug', 'Remise à zero de l\'alarme');
                     foreach ($eqLogic->getConfiguration('raz') as $raz) {
                         $cmd = cmd::byId(str_replace('#', '', $raz['cmd']));
                         $option = array();
                         if (isset($raz['options'])) {
                             $option = $raz['options'];
                         }
                         log::add('alarm', 'debug', 'Exécution de ' . $cmd->getHumanName() . ' avec les options : ' . print_r($option, true));
                         if (is_object($cmd)) {
                             try {
                                 $cmd->execCmd($option);
                             } catch (Exception $e) {
                                 log::add('alarm', 'error', 'Erreur lors de l\'éxecution de ' . $cmd->getHumanName() . '. Détails : ' . $e->getMessage());
                             }
                         }
                     }
                 }
                 /* RaZ immediate */
                 if ($cmd_immediateState->execCmd() == 1) {
                     log::add('alarm', 'debug', 'Remise à zero immédiate de l\'alarme');
                     foreach ($eqLogic->getConfiguration('razImmediate') as $razImmediate) {
                         $cmd = cmd::byId(str_replace('#', '', $razImmediate['cmd']));
                         $option = array();
                         if (isset($razImmediate['options'])) {
                             $option = $razImmediate['options'];
                         }
                         log::add('alarm', 'debug', 'Exécution de ' . $cmd->getHumanName() . ' avec les options : ' . print_r($option, true));
                         if (is_object($cmd)) {
                             try {
                                 $cmd->execCmd($option);
                             } catch (Exception $e) {
                                 log::add('alarm', 'error', 'Erreur lors de l\'éxecution de ' . $cmd->getHumanName() . '. Détails : ' . $e->getMessage());
                             }
                         }
                     }
                 }
                 $cmd_state->event(0);
                 $cmd_immediateState->event(0);
                 $eqLogic->setConfiguration('pingState', 1);
                 $eqLogic->save();
             } else {
                 $cmd_armed->event($this->getConfiguration('state'));
                 $cmd_mode = cmd::byId($eqLogic->getConfiguration('cmd_mode_id'));
                 $select_mode = $cmd_mode->execCmd();
                 $modes = $eqLogic->getConfiguration('modes');
                 $zones = $eqLogic->getConfiguration('zones');
                 foreach ($modes as $mode) {
                     if ($mode['name'] == $select_mode) {
                         foreach ($zones as $zone) {
                             if (!is_array($mode['zone']) && $zone['name'] == $mode['zone'] || is_array($mode['zone']) && in_array($zone['name'], $mode['zone'])) {
                                 log::add('alarm', 'debug', 'Vérification de la zone : ' . $zone['name']);
                                 foreach ($zone['triggers'] as $trigger) {
                                     $cmd = cmd::byId(str_replace('#', '', $trigger['cmd']));
                                     if (is_object($cmd)) {
                                         log::add('alarm', 'debug', 'Vérification de la commande : ' . $cmd->getHumanName());
                                         $result = $cmd->execCmd();
                                         if ($result == 1) {
                                             $eqLogic->launch($cmd->getId(), $result);
                                             return;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
                 /*                     * *****************Activation reussi***************** */
                 log::add('alarm', 'debug', 'Activation de l\'alarme réussie');
                 foreach ($eqLogic->getConfiguration('activationOk') as $activationOk) {
                     $cmd = cmd::byId(str_replace('#', '', $activationOk['cmd']));
                     $option = array();
                     if (isset($activationOk['options'])) {
                         $option = $activationOk['options'];
                     }
                     log::add('alarm', 'debug', 'Exécution de ' . $cmd->getHumanName() . ' avec les options : ' . print_r($option, true));
                     if (is_object($cmd)) {
                         try {
                             $cmd->execCmd($option);
                         } catch (Exception $e) {
                             log::add('alarm', 'error', 'Erreur lors de l\'éxecution de ' . $cmd->getHumanName() . '. Détails : ' . $e->getMessage());
                         }
                     }
                 }
             }
         }
     }
     if ($this->getConfiguration('mode') == '1') {
         if ($eqLogic->getConfiguration('cmd_mode_id') != '') {
             $cmd_zone = cmd::byId($eqLogic->getConfiguration('cmd_mode_id'));
             $cmd_zone->event($this->getConfiguration('state'));
         }
     }
 }
Example #9
0
 public function save()
 {
     if ($this->getMessage() == '') {
         return;
     }
     if ($this->getLogicalId() == '') {
         $this->setLogicalId($this->getPlugin() . '::' . config::genKey());
     }
     $values = array('message' => $this->getMessage(), 'logicalId' => $this->getLogicalId(), 'plugin' => $this->getPlugin());
     $sql = 'SELECT count(*)
             FROM message
             WHERE plugin=:plugin
                   AND ( logicalId=:logicalId
                     OR message=:message ) ';
     $result = DB::Prepare($sql, $values, DB::FETCH_TYPE_ROW);
     if ($result['count(*)'] == 0) {
         DB::save($this);
         @nodejs::pushNotification(__('Message de ', __FILE__) . $this->getPlugin(), $this->getMessage(), 'message');
         $cmds = explode('&&', config::byKey('emailAdmin'));
         if (count($cmds) > 0) {
             foreach ($cmds as $id) {
                 $cmd = cmd::byId(str_replace('#', '', $id));
                 if (is_object($cmd)) {
                     $cmd->execCmd(array('title' => __('[JEEDOM] Message de ', __FILE__) . $this->getPlugin(), 'message' => $this->getMessage()));
                 } else {
                     log::add('message', 'info', __('Impossible de trouver la commande correspondant à :', __FILE__) . $id);
                 }
             }
         }
     }
     @nodejs::pushUpdate('message::refreshMessageNumber');
 }
Example #10
0
 if ($jsonrpc->getMethod() == 'cmd::getStatistique') {
     $cmd = cmd::byId($params['id']);
     if (!is_object($cmd)) {
         throw new Exception('Cmd introuvable : ' . $params['id'], -32702);
     }
     $jsonrpc->makeSuccess($cmd->getStatistique($params['startTime'], $params['endTime']));
 }
 if ($jsonrpc->getMethod() == 'cmd::getTendance') {
     $cmd = cmd::byId($params['id']);
     if (!is_object($cmd)) {
         throw new Exception('Cmd introuvable : ' . $params['id'], -32702);
     }
     $jsonrpc->makeSuccess($cmd->getTendance($params['startTime'], $params['endTime']));
 }
 if ($jsonrpc->getMethod() == 'cmd::getHistory') {
     $cmd = cmd::byId($params['id']);
     if (!is_object($cmd)) {
         throw new Exception('Cmd introuvable : ' . $params['id'], -32702);
     }
     $jsonrpc->makeSuccess(utils::o2a($cmd->getHistory($params['startTime'], $params['endTime'])));
 }
 /*             * ************************Scénario*************************** */
 if ($jsonrpc->getMethod() == 'scenario::all') {
     $jsonrpc->makeSuccess(utils::o2a(scenario::all()));
 }
 if ($jsonrpc->getMethod() == 'scenario::byId') {
     $scenario = scenario::byId($params['id']);
     if (!is_object($scenario)) {
         throw new Exception('Scenario introuvable : ' . $params['id'], -32703);
     }
     $jsonrpc->makeSuccess(utils::o2a($scenario));
Example #11
0
 public static function clean()
 {
     $sql = "DELETE FROM `cache`  WHERE (UNIX_TIMESTAMP(`datetime`) + lifetime) < UNIX_TIMESTAMP(NOW()) AND lifetime > 0";
     DB::Prepare($sql, array(), DB::FETCH_TYPE_ROW);
     $sql = "SELECT * FROM `cache`  WHERE `key` LIKE 'cmd%' AND lifetime = 0";
     $results = DB::Prepare($sql, array(), DB::FETCH_TYPE_ALL);
     foreach ($results as $result) {
         $id = str_replace('cmd', '', $result['key']);
         if (is_numeric($id)) {
             $cmd = cmd::byId($id);
             if (!is_object($cmd)) {
                 $sql = "DELETE FROM `cache`  WHERE `key`=:key";
                 $value = array('key' => $result['key']);
                 DB::Prepare($sql, $value, DB::FETCH_TYPE_ROW);
             }
         }
     }
     $sql = "SELECT * FROM `cache`  WHERE `key` LIKE 'core::eqLogic%::lastCommunication'";
     $results = DB::Prepare($sql, array(), DB::FETCH_TYPE_ALL);
     foreach ($results as $result) {
         $id = str_replace(array('core::eqLogic', '::lastCommunication'), '', $result['key']);
         if (is_numeric($id)) {
             $eqLogic = eqLogic::byId($id);
             if (!is_object($eqLogic)) {
                 $sql = "DELETE FROM `cache`  WHERE `key`=:key";
                 $value = array('key' => $result['key']);
                 DB::Prepare($sql, $value, DB::FETCH_TYPE_ROW);
             }
         }
     }
     $sql = "SELECT * FROM `cache`  WHERE `key` LIKE 'core::eqLogic%::numberTryWithoutSuccess'";
     $results = DB::Prepare($sql, array(), DB::FETCH_TYPE_ALL);
     foreach ($results as $result) {
         $id = str_replace(array('core::eqLogic', '::numberTryWithoutSuccess'), '', $result['key']);
         if (is_numeric($id)) {
             $eqLogic = eqLogic::byId($id);
             if (!is_object($eqLogic)) {
                 $sql = "DELETE FROM `cache`  WHERE `key`=:key";
                 $value = array('key' => $result['key']);
                 DB::Prepare($sql, $value, DB::FETCH_TYPE_ROW);
             }
         }
     }
     $sql = "SELECT * FROM `cache`  WHERE `key` LIKE 'core::eqLogic%::numberTryWithoutSuccess'";
     $results = DB::Prepare($sql, array(), DB::FETCH_TYPE_ALL);
     foreach ($results as $result) {
         $id = str_replace(array('core::eqLogic', '::numberTryWithoutSuccess'), '', $result['key']);
         if (is_numeric($id)) {
             $eqLogic = eqLogic::byId($id);
             if (!is_object($eqLogic)) {
                 $sql = "DELETE FROM `cache`  WHERE `key`=:key";
                 $value = array('key' => $result['key']);
                 DB::Prepare($sql, $value, DB::FETCH_TYPE_ROW);
             }
         }
     }
     $sql = "SELECT * FROM `cache`  WHERE `key` LIKE 'widgetHtmldashboard%'";
     $results = DB::Prepare($sql, array(), DB::FETCH_TYPE_ALL);
     foreach ($results as $result) {
         $id = str_replace(array('widgetHtmldashboard'), '', $result['key']);
         if (is_numeric($id)) {
             $eqLogic = eqLogic::byId($id);
             if (!is_object($eqLogic)) {
                 $sql = "DELETE FROM `cache`  WHERE `key`=:key";
                 $value = array('key' => $result['key']);
                 DB::Prepare($sql, $value, DB::FETCH_TYPE_ROW);
             }
         }
     }
 }
Example #12
0
 public function getCmd()
 {
     return cmd::byId($this->cmd_id);
 }
Example #13
0
 public function applyModuleConfiguration($_light = false)
 {
     $this->setConfiguration('applyDevice', $this->getConfiguration('device'));
     if ($this->getConfiguration('device') == '') {
         $this->save();
         return true;
     }
     $device = self::devicesParameters($this->getConfiguration('device'));
     if (!is_array($device) || !isset($device['commands'])) {
         return true;
     }
     if (isset($device['configuration'])) {
         foreach ($device['configuration'] as $key => $value) {
             try {
                 $this->setConfiguration($key, $value);
             } catch (Exception $e) {
             }
         }
     }
     $cmd_order = 0;
     $link_cmds = array();
     $razberry_id = zwave::getZwaveInfo('controller::data::nodeId::value', $this->getConfiguration('serverID', 1));
     nodejs::pushUpdate('jeedom::alert', array('level' => 'warning', 'message' => __('Mise en place des groupes par défaut', __FILE__)));
     if (isset($device['groups']) && isset($device['groups']['associate'])) {
         foreach ($this->getAssociation() as $group_id => $associate) {
             foreach ($associate['nodes']['value'] as $node) {
                 if ($node['id'] == $razberry_id && !isset($device['groups']['associate'][$group_id])) {
                     $this->changeAssociation('remove', $group_id, $razberry_id);
                 }
             }
         }
         foreach ($device['groups']['associate'] as $group) {
             try {
                 $this->changeAssociation('add', $group, $razberry_id);
             } catch (Exception $e) {
             }
         }
     }
     nodejs::pushUpdate('jeedom::alert', array('level' => 'warning', 'message' => __('Création des commandes', __FILE__)));
     if (self::$_listZwaveServer == null) {
         self::listServerZway();
     }
     if (isset($device['commands_openzwave']) && self::$_listZwaveServer[$this->getConfiguration('serverID', 1)]['isOpenZwave'] == 1) {
         $commands = $device['commands_openzwave'];
     } else {
         $commands = $device['commands'];
     }
     foreach ($commands as &$command) {
         if (!isset($command['configuration']['instanceId'])) {
             $command['configuration']['instanceId'] = 0;
         }
         if (!isset($command['configuration']['class'])) {
             $command['configuration']['class'] = '';
         }
         $cmd = null;
         foreach ($this->getCmd() as $liste_cmd) {
             if ($liste_cmd->getConfiguration('instanceId', 0) == $command['configuration']['instanceId'] && $liste_cmd->getConfiguration('class') == $command['configuration']['class'] && $liste_cmd->getConfiguration('value') == $command['configuration']['value']) {
                 $cmd = $liste_cmd;
                 break;
             }
         }
         try {
             if ($cmd == null || !is_object($cmd)) {
                 $cmd = new zwaveCmd();
                 $cmd->setOrder($cmd_order);
                 $cmd->setEqLogic_id($this->getId());
             } else {
                 $command['name'] = $cmd->getName();
                 if (isset($command['display'])) {
                     unset($command['display']);
                 }
             }
             utils::a2o($cmd, $command);
             if (isset($command['value'])) {
                 $cmd->setValue(null);
             }
             $cmd->save();
             if (isset($command['value'])) {
                 $link_cmds[$cmd->getId()] = $command['value'];
             }
             $cmd_order++;
         } catch (Exception $exc) {
         }
     }
     if (count($link_cmds) > 0) {
         foreach ($this->getCmd() as $eqLogic_cmd) {
             foreach ($link_cmds as $cmd_id => $link_cmd) {
                 if ($link_cmd == $eqLogic_cmd->getName()) {
                     $cmd = cmd::byId($cmd_id);
                     if (is_object($cmd)) {
                         $cmd->setValue($eqLogic_cmd->getId());
                         $cmd->save();
                     }
                 }
             }
         }
     }
     if (isset($device['wakeup']) && is_numeric($device['wakeup']) && $device['wakeup'] > 1) {
         try {
             $this->setWakeUp($device['wakeup']);
         } catch (Exception $ex) {
         }
     }
     if (!$_light) {
         try {
             nodejs::pushUpdate('jeedom::alert', array('level' => 'warning', 'message' => __('Récupération de la configuration d\'origine du module', __FILE__)));
             $configuration = $this->getDeviceConfiguration(true);
             $optimiseConfigFound = false;
             foreach ($configuration as $id => &$parameter) {
                 if (isset($device['parameters'][$id]['set'])) {
                     $optimiseConfigFound = true;
                     $configuration[$id]['value'] = $device['parameters'][$id]['set'];
                 }
             }
             if ($optimiseConfigFound) {
                 nodejs::pushUpdate('jeedom::alert', array('level' => 'warning', 'message' => __('Envoi de la configuration optimisée Jeedom', __FILE__)));
                 $this->setDeviceConfiguration($configuration);
             }
         } catch (Exception $ex) {
         }
         if (isset($device['configure']) && is_array($device['configure'])) {
             try {
                 nodejs::pushUpdate('jeedom::alert', array('level' => 'warning', 'message' => __('Execution des commandes post-configuration', __FILE__)));
                 $this->applyDeviceConfigurationCommand();
             } catch (Exception $ex) {
             }
         }
     }
     $this->save();
     nodejs::pushUpdate('jeedom::alert', array('level' => 'warning', 'message' => ''));
 }
Example #14
0
        $return['data'] = $data;
        ajax::success($return);
    }
    if (init('action') == 'emptyHistory') {
        if (!isConnect('admin')) {
            throw new Exception(__('401 - Accès non autorisé', __FILE__), -1234);
        }
        $cmd = cmd::byId(init('id'));
        if (!is_object($cmd)) {
            throw new Exception(__('Cmd ID inconnu : ', __FILE__) . init('id'));
        }
        $cmd->emptyHistory(init('date'));
        ajax::success();
    }
    if (init('action') == 'setOrder') {
        $cmds = json_decode(init('cmds'), true);
        foreach ($cmds as $cmd_json) {
            $cmd = cmd::byId($cmd_json['id']);
            if (!is_object($cmd)) {
                throw new Exception(__('Commande inconnu verifié l\'id :', __FILE__) . ' ' . $cmd_json['id']);
            }
            $cmd->setOrder($cmd_json['order']);
            $cmd->save();
        }
        ajax::success();
    }
    throw new Exception(__('Aucune méthode correspondante à : ', __FILE__) . init('action'));
    /*     * *********Catch exeption*************** */
} catch (Exception $e) {
    ajax::error(displayExeption($e), $e->getCode());
}
Example #15
0
 public function applyModuleConfiguration()
 {
     if ($this->getConfiguration('device') == '') {
         return true;
     }
     $device = self::devicesParameters($this->getConfiguration('device'));
     if (!is_array($device) || !isset($device['commands'])) {
         return true;
     }
     if (isset($device['configuration'])) {
         foreach ($device['configuration'] as $key => $value) {
             $this->setConfiguration($key, $value);
         }
     }
     $this->setConfiguration('applyDevice', $this->getConfiguration('device'));
     $cmd_order = 0;
     $link_cmds = array();
     foreach ($device['commands'] as $command) {
         if (!isset($command['configuration']['instanceId'])) {
             $command['configuration']['instanceId'] = 0;
         }
         $cmd = null;
         foreach ($this->getCmd() as $liste_cmd) {
             if ($liste_cmd->getConfiguration('instanceId', 0) == $command['configuration']['instanceId'] && $liste_cmd->getConfiguration('class') == $command['configuration']['class'] && $liste_cmd->getConfiguration('value') == $command['configuration']['value']) {
                 $cmd = $liste_cmd;
                 break;
             }
         }
         try {
             if ($cmd == null || !is_object($cmd)) {
                 $cmd = new zwaveCmd();
                 $cmd->setOrder($cmd_order);
                 $cmd->setEqLogic_id($this->getId());
             } else {
                 $command['name'] = $cmd->getName();
             }
             utils::a2o($cmd, $command);
             if (isset($command['value'])) {
                 $cmd->setValue(null);
             }
             $cmd->save();
             if (isset($command['value'])) {
                 $link_cmds[$cmd->getId()] = $command['value'];
             }
             $cmd_order++;
         } catch (Exception $exc) {
             error_log($exc->getMessage());
         }
     }
     if (count($link_cmds) > 0) {
         foreach ($this->getCmd() as $eqLogic_cmd) {
             foreach ($link_cmds as $cmd_id => $link_cmd) {
                 if ($link_cmd == $eqLogic_cmd->getName()) {
                     $cmd = cmd::byId($cmd_id);
                     if (is_object($cmd)) {
                         $cmd->setValue($eqLogic_cmd->getId());
                         $cmd->save();
                     }
                 }
             }
         }
     }
     $this->save();
 }
Example #16
0
        if (!is_object($widget)) {
            throw new Exception('Widget non trouvé : ' . init('path'));
        }
        $widget->remove();
        ajax::success();
    }
    if (init('action') == 'applyWidget') {
        if (init('path') != 'default') {
            $widget = widget::byPath(init('path'));
            if (!is_object($widget)) {
                throw new Exception('Widget non trouvé : ' . init('path'));
            }
        }
        $cmds = json_decode(init('cmds'), true);
        foreach ($cmds as $cmd_id) {
            $cmd = cmd::byId($cmd_id);
            if (!is_object($cmd)) {
                throw new Exception('Commande introuvable : ' . $cmd_id);
            }
            if (init('path') != 'default') {
                $cmd->setTemplate($widget->getVersion(), $widget->getName());
            } else {
                $cmd->setTemplate(init('version'), 'default');
            }
            $cmd->save();
        }
        ajax::success();
    }
    throw new Exception('Aucune methode correspondante à : ' . init('action'));
} catch (Exception $e) {
    ajax::error(displayExeption($e), $e->getCode());
Example #17
0
    <?php 
if (!isConnect('admin')) {
    throw new Exception('{{401 - Accès non autorisé}}');
}
$cmd = cmd::byId(init('cmd_id'));
if (!is_object($cmd)) {
    throw new Exception('Commande non trouvé : ' . init('cmd_id'));
}
sendVarToJS('cmdInfo', jeedom::toHumanReadable(utils::o2a($cmd)));
$cmd_widgetDashboard = cmd::availableWidget('dashboard');
$cmd_widgetMobile = cmd::availableWidget('mobile');
?>
<div style="display: none;" id="md_displayCmdConfigure"></div>


<a class="btn btn-success btn-sm pull-right" id="bt_cmdConfigureSave"><i class="fa fa-check-circle"></i> {{Enregistrer}}</a>
<a class="btn btn-default pull-right btn-sm" id="bt_cmdConfigureSaveOn"><i class="fa fa-plus-circle"></i> {{Appliquer à}}</a>

<div role="tabpanel">

  <!-- Nav tabs -->
  <ul class="nav nav-tabs" role="tablist">
    <li role="presentation" class="active"><a href="#information" aria-controls="home" role="tab" data-toggle="tab"><i class="fa fa-info-circle"></i> {{Informations}}</a></li>
    <li role="presentation"><a href="#configuration" aria-controls="profile" role="tab" data-toggle="tab"><i class="fa fa-wrench"></i> {{Configuration avancée}}</a></li>
    <li role="presentation"><a href="#display" aria-controls="messages" role="tab" data-toggle="tab"><i class="fa fa-desktop"></i> {{Affichage avancé}}</a></li>
  </ul>


  <div class="tab-content" id="div_displayCmdConfigure">
    <div role="tabpanel" class="tab-pane active" id="information">
      <br/>
Example #18
0
 public function executeAlertCmdAction()
 {
     if ($this->getConfiguration('jeedomCheckCmdActionType') == 'cmd') {
         $cmd = cmd::byId(str_replace('#', '', $this->getConfiguration('jeedomCheckCmdCmdActionId')));
         if (!is_object($cmd)) {
             return;
         }
         $cmd->execCmd($this->getConfiguration('jeedomCheckCmdCmdActionOption'));
         return;
     }
     if ($this->getConfiguration('jeedomCheckCmdActionType') == 'scenario') {
         $scenario = scenario::byId($this->getConfiguration('jeedomCheckCmdScenarioActionId'));
         if (!is_object($scenario)) {
             return;
         }
         switch ($this->getConfiguration('jeedomCheckCmdScenarioActionMode')) {
             case 'start':
                 $scenario->launch(false, __('Lancement direct provoqué par le scénario  : ', __FILE__) . $this->getHumanName());
                 break;
             case 'stop':
                 $scenario->stop();
                 break;
             case 'deactivate':
                 $scenario->setIsActive(0);
                 $scenario->save();
                 break;
             case 'activate':
                 $scenario->setIsActive(1);
                 $scenario->save();
                 break;
         }
     }
 }
Example #19
0
 public function executeAndReply($_parameters)
 {
     $interactDef = interactDef::byId($this->getInteractDef_id());
     if (!is_object($interactDef)) {
         return __('Inconsistance de la base de données', __FILE__);
     }
     if (isset($_parameters['profile']) && trim($interactDef->getPerson()) != '') {
         $person = strtolower($interactDef->getPerson());
         $person = explode('|', $person);
         if (!in_array($_parameters['profile'], $person)) {
             return __('Vous n\'êtes pas autorisé à exécuter cette action', __FILE__);
         }
     }
     if ($this->getLink_type() == 'whatDoYouKnow') {
         $object = object::byId($this->getLink_id());
         if (is_object($object)) {
             $reply = self::whatDoYouKnow($object);
             if (trim($reply) == '') {
                 return __('Je ne sais rien sur ', __FILE__) . $object->getName();
             }
             return $reply;
         }
         return self::whatDoYouKnow();
     }
     if ($this->getLink_type() == 'scenario') {
         $scenario = scenario::byId($this->getLink_id());
         if (!is_object($scenario)) {
             return __('Impossible de trouver le scénario correspondant', __FILE__);
         }
         log::add('interact', 'debug', 'Execution du scénario : ' . $scenario->getHumanName() . ' => ' . $interactDef->getOptions('scenario_action'));
         $interactDef = $this->getInteractDef();
         if (!is_object($interactDef)) {
             return __('Impossible de trouver la définition de l\'interaction', __FILE__);
         }
         $reply = $interactDef->selectReply();
         if (trim($reply) == '') {
             $reply = self::replyOk();
         }
         $replace = array();
         $replace['#profile#'] = isset($_parameters['profile']) ? $_parameters['profile'] : '';
         $reply = scenarioExpression::setTags(str_replace(array_keys($replace), $replace, $reply));
         switch ($interactDef->getOptions('scenario_action')) {
             case 'start':
                 $scenario->setTags(array('#query#' => $this->getQuery(), '#profile#' => $replace['#profile#']));
                 $return = $scenario->launch(false, 'interact', __('Scénario exécuté sur interaction (S.A.R.A.H, SMS...)', __FILE__), 1);
                 if (is_string($return) && $return != '') {
                     $return = str_replace(array_keys($replace), $replace, $return);
                     return $return;
                 }
                 return $reply;
             case 'stop':
                 $scenario->stop();
                 return $reply;
             case 'activate':
                 $scenario->setIsActive(1);
                 $scenario->save();
                 return $reply;
             case 'deactivate':
                 $scenario->setIsActive(0);
                 $scenario->save();
                 return $reply;
             default:
                 return __('Aucune action n\'est définie dans l\'interaction sur le scénario : ', __FILE__) . $scenario->getHumanName();
         }
     }
     $reply = $interactDef->selectReply();
     $synonymes = array();
     if ($interactDef->getOptions('synonymes') != '') {
         foreach (explode('|', $interactDef->getOptions('synonymes')) as $value) {
             $values = explode('=', $value);
             $synonymes[strtolower($values[0])] = explode(',', $values[1]);
         }
     }
     $replace = array();
     $replace['#profile#'] = isset($_parameters['profile']) ? $_parameters['profile'] : '';
     if ($this->getLink_type() == 'cmd') {
         foreach (explode('&&', $this->getLink_id()) as $cmd_id) {
             $cmd = cmd::byId($cmd_id);
             if (!is_object($cmd)) {
                 continue;
             }
             $replace['#commande#'] = $cmd->getName();
             if (isset($synonymes[strtolower($cmd->getName())])) {
                 $replace['#commande#'] = $synonymes[strtolower($cmd->getName())][rand(0, count($synonymes[strtolower($cmd->getName())]) - 1)];
             }
             $replace['#objet#'] = '';
             $replace['#equipement#'] = '';
             $eqLogic = $cmd->getEqLogic();
             if (is_object($eqLogic)) {
                 $replace['#equipement#'] = $eqLogic->getName();
                 $object = $eqLogic->getObject();
                 if (is_object($object)) {
                     $replace['#objet#'] = $object->getName();
                 }
             }
             $replace['#unite#'] = $cmd->getUnite();
             if ($cmd->getType() == 'action') {
                 $options = null;
                 if ($cmd->getSubType() == 'slider') {
                     preg_match_all("/([0-9]*)/", $_parameters['dictation'], $matches);
                     foreach ($matches[1] as $number) {
                         if (is_numeric($number)) {
                             $options['slider'] = $number;
                         }
                     }
                 }
                 if ($cmd->getSubType() == 'color') {
                     $colors = config::byKey('convertColor');
                     foreach (explode(' ', $_parameters['dictation']) as $word) {
                         if (isset($colors[strtolower($word)])) {
                             $options['color'] = $colors[strtolower($word)];
                         }
                     }
                 }
                 try {
                     log::add('interact', 'debug', 'Execution de la commande : ' . $cmd->getHumanName() . ' => ' . print_r($options, true));
                     if ($cmd->execCmd($options) === false) {
                         return __('Impossible d\'exécuter la commande', __FILE__);
                     }
                 } catch (Exception $exc) {
                     return $exc->getMessage();
                 }
                 if ($options != null) {
                     foreach ($options as $key => $value) {
                         $replace['#' . $key . '#'] = $value;
                     }
                 }
             }
             if ($cmd->getType() == 'info') {
                 $value = $cmd->execCmd();
                 if ($value === null) {
                     return __('Impossible de récupérer la valeur de la commande', __FILE__);
                 } else {
                     $replace['#valeur#'] = $value;
                     if ($cmd->getSubType() == 'binary' && $interactDef->getOptions('convertBinary') != '') {
                         $convertBinary = $interactDef->getOptions('convertBinary');
                         $convertBinary = explode('|', $convertBinary);
                         $replace['#valeur#'] = $convertBinary[$replace['#valeur#']];
                     }
                 }
             }
         }
     }
     return scenarioExpression::setTags(str_replace(array_keys($replace), $replace, $reply));
 }
 public function loadCmdFromConf($_update = false)
 {
     if (!is_file(dirname(__FILE__) . '/../config/devices/' . $this->getConfFilePath())) {
         return;
     }
     $content = file_get_contents(dirname(__FILE__) . '/../config/devices/' . $this->getConfFilePath());
     if (!is_json($content)) {
         return;
     }
     $device = json_decode($content, true);
     if (!is_array($device) || !isset($device['commands'])) {
         return true;
     }
     $cmd_order = 0;
     $link_cmds = array();
     if (isset($device['name']) && !$_update) {
         $this->setName('[' . $this->getLogicalId() . ']' . $device['name']);
     }
     if (isset($device['configuration'])) {
         foreach ($device['configuration'] as $key => $value) {
             try {
                 $this->setConfiguration($key, $value);
             } catch (Exception $e) {
             }
         }
     }
     nodejs::pushUpdate('jeedom::alert', array('level' => 'warning', 'message' => __('Création des commandes à partir d\'une configuration', __FILE__)));
     $commands = $device['commands'];
     foreach ($commands as &$command) {
         if (!isset($command['configuration']['instanceId'])) {
             $command['configuration']['instanceId'] = 0;
         }
         if (!isset($command['configuration']['class'])) {
             $command['configuration']['class'] = '';
         }
         try {
             $cmd = new openzwaveCmd();
             $cmd->setOrder($cmd_order);
             $cmd->setEqLogic_id($this->getId());
             utils::a2o($cmd, $command);
             if (isset($command['value'])) {
                 $cmd->setValue(null);
             }
             $cmd->save();
             if (isset($command['value'])) {
                 $link_cmds[$cmd->getId()] = $command['value'];
             }
             $cmd_order++;
         } catch (Exception $exc) {
         }
     }
     if (count($link_cmds) > 0) {
         foreach ($this->getCmd() as $eqLogic_cmd) {
             foreach ($link_cmds as $cmd_id => $link_cmd) {
                 if ($link_cmd == $eqLogic_cmd->getName()) {
                     $cmd = cmd::byId($cmd_id);
                     if (is_object($cmd)) {
                         $cmd->setValue($eqLogic_cmd->getId());
                         $cmd->save();
                     }
                 }
             }
         }
     }
     $this->save();
     nodejs::pushUpdate('jeedom::alert', array('level' => 'warning', 'message' => ''));
 }
Example #21
0
 public function getData($_startDate = null, $_endDate = null)
 {
     $nowtime = floatval(strtotime(date('Y-m-d H:i:s') . " UTC"));
     $now = strtotime(date('Y-m-d H:i:s'));
     $archiveTime = (config::byKey('historyArchiveTime') + 1) * 3600;
     $packetTime = config::byKey('historyArchivePackage') * 3600;
     $return = array('history' => array('power' => array(), 'consumption' => null), 'stats' => array('minPower' => null, 'maxPower' => null), 'real' => array('power' => 0, 'consumption' => 0));
     $cmd_histories = array();
     preg_match_all("/#([0-9]*)#/", $this->getPower(), $matches);
     foreach ($matches[1] as $cmd_id) {
         if (is_numeric($cmd_id)) {
             $cmd = cmd::byId($cmd_id);
             if (is_object($cmd) && $cmd->getIsHistorized() == 1) {
                 $prevDatetime = null;
                 $prevValue = 0;
                 foreach ($cmd->getHistory($_startDate, $_endDate) as $history) {
                     if (!isset($cmd_histories[$history->getDatetime()])) {
                         $cmd_histories[$history->getDatetime()] = array();
                     }
                     if (!isset($cmd_histories[$history->getDatetime()]['#' . $cmd_id . '#'])) {
                         if ($prevDatetime != null) {
                             $datetime = strtotime($history->getDatetime());
                             while ($now - strtotime($prevDatetime) > $archiveTime && strtotime($prevDatetime) < $datetime) {
                                 $prevDatetime = date('Y-m-d H:00:00', strtotime($prevDatetime) + $packetTime);
                                 $cmd_histories[$prevDatetime]['#' . $cmd_id . '#'] = 0;
                             }
                             while ($now - strtotime($prevDatetime) > 300 && strtotime($prevDatetime) < $datetime) {
                                 $prevDatetime = date('Y-m-d H:i:00', strtotime($prevDatetime) + 300);
                                 $cmd_histories[$prevDatetime]['#' . $cmd_id . '#'] = $prevValue;
                             }
                         }
                         if (strtotime($history->getDatetime()) <= $now) {
                             $cmd_histories[$history->getDatetime()]['#' . $cmd_id . '#'] = $history->getValue();
                         }
                     }
                     $prevDatetime = $history->getDatetime();
                     $prevValue = $history->getValue();
                 }
             }
         }
     }
     foreach ($cmd_histories as $datetime => $cmd_history) {
         $datetime = floatval(strtotime($datetime . " UTC"));
         $calcul = template_replace($cmd_history, $this->getPower());
         try {
             if ($datetime <= $nowtime) {
                 $test = new evaluate();
                 $result = floatval($test->Evaluer($calcul));
                 if ($this->getConsumption() == '' && count($return['history']['power']) > 0) {
                     $last_datetime = end(array_keys($return['history']['power']));
                     if ($datetime - $last_datetime > 0) {
                         $last_value = end($return['history']['power']);
                         $return['history']['consumption'][$datetime] = array($datetime, $last_value[1] * (($datetime - $last_datetime) / 1000) / 3600);
                         $return['real']['consumption'] += $return['history']['consumption'][$datetime][1];
                     }
                 }
                 $return['history']['power'][$datetime] = array($datetime * 1000, $result);
                 if ($return['stats']['minPower'] === null || $return['stats']['minPower'] > $result) {
                     $return['stats']['minPower'] = $result;
                 }
                 if ($return['stats']['maxPower'] === null || $return['stats']['maxPower'] < $result) {
                     $return['stats']['maxPower'] = $result;
                 }
             }
         } catch (Exception $e) {
         }
     }
     if ($this->getConsumption() == '' && count($return['history']['power']) > 0) {
         $last_datetime = end(array_keys($return['history']['power']));
         $last_value = end($return['history']['power']);
         if ($datetime - $last_datetime > 0) {
             $return['history']['consumption'][$datetime] = array($datetime * 1000, $last_value[1] * (($nowtime - $last_datetime) / 1000) / 3600);
             $return['real']['consumption'] += $return['history']['consumption'][$datetime][1];
         }
     }
     $calcul = cmd::cmdToValue($this->getPower());
     try {
         $test = new evaluate();
         $result = floatval($test->Evaluer($calcul));
         $return['real']['power'] = $result;
         $return['history']['power'][$nowtime] = array($nowtime * 1000, $result);
     } catch (Exception $e) {
     }
     if ($this->getConsumption() != '') {
         $cmd_histories = array();
         preg_match_all("/#([0-9]*)#/", $this->getConsumption(), $matches);
         foreach ($matches[1] as $cmd_id) {
             if (is_numeric($cmd_id)) {
                 $cmd = cmd::byId($cmd_id);
                 if (is_object($cmd) && $cmd->getIsHistorized() == 1) {
                     $prevDatetime = null;
                     foreach ($cmd->getHistory($_startDate, $_endDate) as $history) {
                         if (!isset($cmd_histories[$history->getDatetime()])) {
                             $cmd_histories[$history->getDatetime()] = array();
                         }
                         if (!isset($cmd_histories[$history->getDatetime()]['#' . $cmd_id . '#'])) {
                             if ($prevDatetime != null) {
                                 $datetime = strtotime($history->getDatetime());
                                 while ($now - strtotime($prevDatetime) > $archiveTime && strtotime($prevDatetime) < $datetime) {
                                     $prevDatetime = date('Y-m-d H:00:00', strtotime($prevDatetime) + $packetTime);
                                     $cmd_histories[$prevDatetime]['#' . $cmd_id . '#'] = 0;
                                 }
                                 while ($now - strtotime($prevDatetime) < 300 && strtotime($prevDatetime) < $datetime) {
                                     $prevDatetime = date('Y-m-d H:00:00', strtotime($prevDatetime) + 300);
                                     $cmd_histories[$prevDatetime]['#' . $cmd_id . '#'] = $prevValue;
                                 }
                             }
                             if (strtotime($history->getDatetime()) <= $now) {
                                 $cmd_histories[$history->getDatetime()]['#' . $cmd_id . '#'] = $history->getValue();
                             }
                         }
                         $prevDatetime = $history->getDatetime();
                         $prevValue = $history->getValue();
                     }
                 }
             }
         }
         foreach ($cmd_histories as $datetime => $cmd_history) {
             $datetime = floatval(strtotime($datetime . " UTC"));
             $calcul = template_replace($cmd_history, $this->getConsumption());
             try {
                 if ($datetime <= $nowtime) {
                     $test = new evaluate();
                     $result = floatval($test->Evaluer($calcul));
                     $return['history']['consumption'][$datetime] = array($datetime * 1000, $result);
                 }
             } catch (Exception $e) {
             }
         }
         $calcul = cmd::cmdToValue($this->getConsumption());
         try {
             $test = new evaluate();
             $result = floatval($test->Evaluer($calcul));
             $return['real']['consumption'] = $result;
             $return['history']['consumption'][$nowtime] = array($nowtime * 1000, $result);
         } catch (Exception $e) {
         }
     }
     if (is_array($return['history']['consumption'])) {
         ksort($return['history']['consumption']);
     }
     if (is_array($return['history']['power'])) {
         ksort($return['history']['power']);
     }
     return $return;
 }
Example #22
0
 * 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/>.
 */
require_once dirname(__FILE__) . '/../../core/php/core.inc.php';
include_file('core', 'authentification', 'php');
if (!isConnect()) {
    throw new Exception(__('401 - Accès non autorisé', __FILE__));
}
$type = init('type');
switch ($type) {
    case 'cmdHistory':
        $cmd = cmd::byId(init('id'));
        if (!is_object($cmd)) {
            throw new Exception(__('Commande introuvable : ', __FILE__) . init('id'));
        }
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=' . str_replace(' ', '_', $cmd->getHumanName()) . '.csv');
        $histories = $cmd->getHistory();
        foreach ($histories as $history) {
            echo $history->getDatetime();
            echo ';';
            echo str_replace('.', ',', $history->getValue());
            echo "\n";
        }
        break;
    case 'eqLogic':
        $eqLogic = eqLogic::byId(init('id'));
 public function execute($_options = null)
 {
     switch ($this->getType()) {
         case 'info':
             if ($this->getConfiguration('virtualAction', 0) == '0') {
                 try {
                     $result = jeedom::evaluateExpression($this->getConfiguration('calcul'));
                     if ($this->getSubType() == 'numeric') {
                         if (is_numeric($result)) {
                             $result = number_format($result, 2);
                         } else {
                             $result = str_replace('"', '', $result);
                         }
                         if (strpos($result, '.') !== false) {
                             $result = str_replace(',', '', $result);
                         } else {
                             $result = str_replace(',', '.', $result);
                         }
                     }
                     return $result;
                 } catch (Exception $e) {
                     log::add('virtual', 'info', $e->getMessage());
                     return jeedom::evaluateExpression(str_replace('"', '', cmd::cmdToValue($this->getConfiguration('calcul'))));
                 }
             }
             break;
         case 'action':
             $virtualCmd = virtualCmd::byId($this->getConfiguration('infoId'));
             if (!is_object($virtualCmd)) {
                 $cmds = explode('&&', $this->getConfiguration('infoName'));
                 if (is_array($cmds)) {
                     foreach ($cmds as $cmd_id) {
                         $cmd = cmd::byId(str_replace('#', '', $cmd_id));
                         $cmd->execCmd($_options);
                     }
                     return;
                 } else {
                     $cmd = cmd::byId(str_replace('#', '', $this->getConfiguration('infoName')));
                     return $cmd->execCmd($_options);
                 }
             } else {
                 if ($virtualCmd->getEqType() != 'virtual') {
                     throw new Exception(__('La cible de la commande virtuel n\'est pas un équipement de type virtuel', __FILE__));
                 }
                 if ($this->getSubType() == 'slider') {
                     $value = $_options['slider'];
                 } else {
                     if ($this->getSubType() == 'color') {
                         $value = $_options['color'];
                     } else {
                         $value = $this->getConfiguration('value');
                     }
                 }
                 $result = jeedom::evaluateExpression($value);
                 if ($this->getSubtype() == 'message') {
                     $result = $_options['title'] . ' ' . $_options['message'];
                 }
                 $virtualCmd->event($result);
             }
             break;
     }
 }