Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?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/>.
- */
- /* * ***************************Includes********************************* */
- require_once dirname(__FILE__) . '/../../../../core/php/core.inc.php';
- class openWrt extends eqLogic
- {
- /* * ************************* Attributs ****************************** */
- public static $_connection = false;
- /* * *********************** Methodes statiques *************************** */
- /*
- * Fonction exécutée automatiquement toutes les minutes par Jeedom */
- public static function cron()
- {
- if (self::getCron() == 'cron1') {
- self::refreshDevices();
- self::refreshRouters();
- }
- }
- public static function cron5()
- {
- if (self::getCron() == 'cron5') {
- self::refreshDevices();
- self::refreshRouters();
- }
- }
- public static function cron10()
- {
- if (self::getCron() == 'cron10') {
- self::refreshDevices();
- self::refreshRouters();
- }
- }
- public static function cron15()
- {
- if (self::getCron() == 'cron15') {
- self::refreshDevices();
- self::refreshRouters();
- }
- }
- public static function cron30()
- {
- if (self::getCron() == 'cron30') {
- self::refreshDevices();
- self::refreshRouters();
- }
- }
- public static function cronHourly()
- {
- if (self::getCron() == 'cron60') {
- self::refreshDevices();
- self::refreshRouters();
- }
- }
- private static function getCron()
- {
- $cron = config::byKey('cron', 'openWrt');
- return array_search('1', $cron);
- }
- public static function refreshDevices()
- {
- $equipments = openWrt::getDevices();
- foreach (eqLogic::byType("openWrt", true) as $equipment) {
- $equipment->refreshEq($equipments);
- }
- }
- public static function refreshRouters()
- {
- $result = openWrt::getRouter();
- $eqlogic = openWrt::byLogicalId('router', 'openWrt');
- if (!is_object($eqlogic)) {
- $eqlogic = new openWrt();
- $eqlogic->setEqType_name('openWrt');
- $eqlogic->setLogicalId('router');
- $eqlogic->setIsEnable(1);
- $eqlogic->setIsVisible(1);
- $eqlogic->setName('Routeur');
- $eqlogic->save();
- }
- $eqlogic->loadCmdFromConf('router');
- //Récupération des interfaces wifi
- foreach ($result['wifiIface'] as $logicalid => $wiface) {
- $command = null;
- if (sizeof($wiface->interfaces) > 0) {
- $command["logicalId"] = $logicalid;
- $command["name"] = $wiface->interfaces[0]->ifname . " Statut (" . $wiface->interfaces[0]->config->ssid . ")";
- $command["type"] = "info";
- $command["subtype"] = "binary";
- $command["isVisible"] = 0;
- $cmdInfo = $eqlogic->createCmd($command);
- $eqlogic->checkAndUpdateCmd($logicalid, sizeof($wiface->interfaces) > 0);
- $command["logicalId"] = $logicalid . "on";
- $command["name"] = $wiface->interfaces[0]->ifname . " On";
- $command["type"] = "action";
- $command["subtype"] = "other";
- $command["value"] = $cmdInfo->getId();
- $command["configuration"] = ['type' => 'ifaceon'];
- $eqlogic->createCmd($command);
- $command["logicalId"] = $logicalid . "off";
- $command["name"] = $wiface->interfaces[0]->ifname . " Off";
- $command["configuration"] = ['type' => 'ifaceoff'];
- $eqlogic->createCmd($command);
- } else {
- $eqlogic->checkAndUpdateCmd($logicalid, sizeof($wiface->interfaces) > 0);
- }
- }
- //Calculs de la vitesse des échanges en fonction du dernier cron
- $MBpsConvert = substr(self::getCron(), 4) * 60 * 1048576;
- $cmd = cmd::byEqLogicIdAndLogicalId($eqlogic->getId(), 'txtotal');
- $past = $cmd->execCmd();
- $speed = round(($result['txtotal'] - $past) / $MBpsConvert, 2);
- $eqlogic->checkAndUpdateCmd('txspeed', $speed);
- $cmd = cmd::byEqLogicIdAndLogicalId($eqlogic->getId(), 'rxtotal');
- $past = $cmd->execCmd();
- $speed = round(($result['rxtotal'] - $past) / $MBpsConvert, 2);
- $eqlogic->checkAndUpdateCmd('rxspeed', $speed);
- // Met à jour les commandes info
- foreach ($result as $logicalid => $value) {
- if ($logicalid != 'wifiIface')
- $eqlogic->checkAndUpdateCmd($logicalid, $value);
- }
- }
- public static function getDevices($enforceDisconnect = false)
- {
- $result = array();
- // Récupère l'équipement Routeur
- foreach (eqLogic::byType('openWrt') as $openWrt) {
- if ($openWrt->getLogicalId('id') == 'router') {
- continue;
- }
- $result[$openWrt->getConfiguration('mac')]['status'] = 0;
- $result[$openWrt->getConfiguration('mac')]['mac'] = $openWrt->getConfiguration('mac');
- }
- // Connexion SSH
- if (!$connection = openWrt::sshConnect()) return 'error connecting';
- // Récupération des bauds actifs
- $stream = ssh2_exec($connection, "cat /tmp/dhcp.leases | awk '{print $2\" \"$3\" \"$4}'");
- stream_set_blocking($stream, true);
- while ($line = stream_get_line($stream, 65535, "\n")) {
- $array = explode(" ", $line);
- $mac = trim(strtolower($array[0]));
- if ($mac == '') {
- continue;
- }
- $result[$mac]['mac'] = $mac;
- $result[$mac]['ip'] = $array[1];
- $result[$mac]['hostname'] = $array[2];
- $result[$mac]['rssi'] = 0;
- $result[$mac]['status'] = 0;
- $result[$mac]['connexion'] = 'Ethernet';
- }
- fclose($stream);
- //Table ARP
- $stream = ssh2_exec($connection, 'ip neigh');
- stream_set_blocking($stream, true);
- while ($line = stream_get_line($stream, 65535, "\n")) {
- if (preg_match('/^(\d+\.\d+\.\d+\.\d+).*(.{2}:.{2}:.{2}:.{2}:.{2}:.{2}).* (.*)/i', $line, $array)) {
- $mac = trim(strtolower($array[2]));
- if (!array_key_exists($mac, $result)) {
- $result[$mac]['mac'] = $mac;
- $result[$mac]['hostname'] = "*";
- $result[$mac]['rssi'] = 0;
- $result[$mac]['connexion'] = 'Ethernet';
- $result[$mac]['ip'] = $array[1];
- }
- $result[$mac]['status'] = ($array[3] == "FAILED" || $array[3] == "DELAY" || $array[3] == "INCOMPLETE" ? 0 : 1);
- }
- }
- fclose($stream);
- //Récupération des interfaces Wifi
- $stream = ssh2_exec($connection, 'iwinfo | grep ESSID | cut -f 1 -s -d" "');
- stream_set_blocking($stream, true);
- while ($iface = stream_get_line($stream, 65535, "\n")) {
- log::add('openWrt', 'debug', 'Wifi: interface ' . $iface);
- //Récupération des équipements connectés au wifi
- $stream2 = ssh2_exec($connection, 'iwinfo ' . $iface . ' assoclist | grep dBm');
- stream_set_blocking($stream2, true);
- while ($line = fgets($stream2)) {
- if (preg_match('/^(.{2}:.{2}:.{2}:.{2}:.{2}:.{2}).* (.*) dBm/i', $line, $array)) {
- $mac = trim(strtolower($array[1]));
- if (!array_key_exists($mac, $result)) {
- $result[$mac]['mac'] = $mac;
- $result[$mac]['hostname'] = "*";
- $result[$mac]['ip'] = '?';
- }
- $result[$mac]['connexion'] = 'Wifi ' . $iface;
- $result[$mac]['rssi'] = $array[2];
- $result[$mac]['status'] = 1;
- }
- }
- fclose($stream2);
- }
- fclose($stream);
- //conserve la connexion pour le scan du routeur
- if ($enforceDisconnect)
- openWrt::sshDisconnect();
- log::add('openWrt', 'debug', 'Scan openWrt, result ' . json_encode($result));
- return $result;
- }
- public static function getRouter()
- {
- $result = array();
- if (!$connection = openWrt::sshConnect()) return 'error connecting';
- $cpu = explode(' ', openWrt::getSshContents($connection, "top -bn1 | head -3 | awk '/CPU/ {print $2,$4,$6,$8,$10,$12,$14}' | sed 's/%//g'"));
- $result['cpu_user'] = $cpu[0];
- $result['cpu_sys'] = $cpu[1];
- $result['cpu_nic'] = $cpu[2];
- $result['cpu_idle'] = $cpu[3];
- $result['cpu_io'] = $cpu[4];
- $result['cpu_irq'] = $cpu[5];
- $result['cpu_sirq'] = $cpu[6];
- $result['cpu_load'] = 100 - $cpu[3];
- $result['txtotal'] = openWrt::getSshContents($connection, 'cat /sys/class/net/eth0/statistics/tx_bytes');
- $result['rxtotal'] = openWrt::getSshContents($connection, 'cat /sys/class/net/eth0/statistics/rx_bytes');
- $result['wifiIface'] = json_decode(openWrt::getSshContents($connection, 'ubus call network.wireless status'));
- $ping0 = openWrt::getSshContents($connection, "ping -c1 -W1 www.google.com | tail -1");
- log::add('openWrt', 'debug', 'Ping Google ' . $ping0);
- $ping = explode(' = ', $ping0);
- $ping2 = explode('/', $ping[1]);
- $result['ping_google'] = floatval($ping2[0]);
- log::add('openWrt', 'debug', 'Ping Google ' . $result['ping_google']);
- $ping = explode(' = ', openWrt::getSshContents($connection, "ping -c1 -W1 8.8.8.8 | tail -1"));
- $ping2 = explode('/', $ping[1]);
- $result['ping_dns'] = floatval($ping2[0]);
- $memory = explode(' ', openWrt::getSshContents($connection, "top -bn1 | head -3 | awk '/Mem/ {print $2,$4}' | sed 's/K//g'"));
- $result['mem_used'] = round($memory[0] / 1024, 2);
- $result['mem_free'] = round($memory[1] / 1024, 2);
- if (preg_match('/up (.*),.*load/i', openWrt::getSshContents($connection, 'uptime'), $array)) {
- $result['uptime'] = $array[1];
- }
- //Récupération de la température
- $element = openWrt::getSshContents($connection, "cat /sys/kernel/debug/ieee80211/phy1/*/temperature | sed -n -e 's/^.*: //p'");
- if (self::is_really_numeric($element)) {
- $result['temperature'] = $element;
- } else {
- $element = openWrt::getSshContents($connection, "echo $((`cat /sys/class/thermal/thermal_zone0/temp`/1000))");
- $result['temperature'] = self::is_really_numeric($element) ? $element : 0;
- }
- openWrt::sshDisconnect();
- log::add('openWrt', 'debug', 'Speed openWrt, result ' . json_encode($result));
- return $result;
- }
- private static function is_really_numeric($string) {
- return preg_match('#^(?!0[1-9])\d*\.?(?!\.)\d+$#', $string);
- }
- public static function getSshContents($connection = false, $cmd = '')
- {
- if (!$connection = openWrt::sshConnect()) return 'error connecting';
- log::add('openWrt', 'debug', 'GetContent commande : ' . $cmd);
- $stream = ssh2_exec($connection, $cmd);
- stream_set_blocking($stream, true);
- $result = stream_get_contents($stream);
- fclose($stream);
- log::add('openWrt', 'debug', 'GetContent résultat : ' . $result);
- return $result;
- }
- public static function sshConnect()
- {
- if (!self::$_connection) {
- log::add('openWrt', 'debug', 'Tentative de connexion SSH...');
- $sshport = config::byKey('sshport', 'openWrt') == '' ? '22' : config::byKey('sshport', 'openWrt');
- if (!self::$_connection = ssh2_connect(config::byKey('addr', 'openWrt'), $sshport)) {
- log::add('openWrt', 'error', 'Connexion SSH KO');
- return false;
- }
- if (self::$_connection && !ssh2_auth_password(self::$_connection, config::byKey('user', 'openWrt'), config::byKey('password', 'openWrt'))) {
- log::add('openWrt', 'error', 'Authentification SSH KO');
- return false;
- } else {
- log::add('openWrt', 'debug', 'SSH Connecté !');
- }
- }
- return self::$_connection;
- }
- public static function sshDisconnect()
- {
- if (self::$_connection) {
- $closesession = ssh2_exec(self::$_connection, 'exit');
- stream_set_blocking($closesession, true);
- stream_get_contents($closesession);
- self::$_connection = false;
- log::add('openWrt', 'debug', 'Session SSH terminée.');
- }
- }
- /* * ********************* Méthodes d'instance ************************* */
- public function loadCmdFromConf($type)
- {
- if (!is_file(dirname(__FILE__) . '/../config/devices/' . $type . '.json')) {
- return;
- }
- $content = file_get_contents(dirname(__FILE__) . '/../config/devices/' . $type . '.json');
- if (!is_json($content)) {
- return;
- }
- $device = json_decode($content, true);
- if (!is_array($device) || !isset($device['commands'])) {
- return true;
- }
- foreach ($device['commands'] as $command) {
- $this->createCmd($command);
- }
- }
- private function createCmd($command)
- {
- $cmd = null;
- foreach ($this->getCmd() as $liste_cmd) {
- if ((isset($command['logicalId']) && $liste_cmd->getLogicalId() == $command['logicalId'])
- || (isset($command['name']) && $liste_cmd->getName() == $command['name'])
- ) {
- $cmd = $liste_cmd;
- break;
- }
- }
- if ($cmd == null || !is_object($cmd)) {
- $cmd = new openWrtCmd();
- $cmd->setEqLogic_id($this->getId());
- utils::a2o($cmd, $command);
- $cmd->save();
- }
- return $cmd;
- }
- public function preInsert()
- {
- //Récupère la liste des équipements
- $equipments = openWrt::getDevices();
- //Récupère l'équipement qui vient d'être créé via son adresse mac
- $equipment = $equipments[$this->name];
- //défini le nom et l'adresse mac
- if ($equipment['hostname'] != '') {
- $this->setName($equipment['hostname']);
- $this->setConfiguration('mac', $equipment['mac']);
- $this->setConfiguration('hostname', $equipment['hostname']);
- $this->setIsEnable(1);
- $this->setIsVisible(1);
- }
- }
- public function postUpdate()
- {
- if ($this->getLogicalId('id') != 'router') {
- $this->loadCmdFromConf('client');
- }
- }
- public function refreshEq($equipments)
- {
- try {
- //passer la valeur en variable depuis le cron (plus performant que de tout lister ici ou faire les deux traitement pour pouvoir utiliser la fonction standard de refresh automatique)
- $macAddress = $this->getConfiguration('mac');
- if ($macAddress == '') {
- return;
- }
- log::add('openWrt', 'debug', 'Refresh equipment ' . $macAddress);
- if ($equipments == null) {
- $equipments = openWrt::getDevices();
- }
- $equipment = $equipments[$macAddress];
- if ($equipment != null) {
- $this->checkAndUpdateCmd('status', $equipment['status']);
- $this->checkAndUpdateCmd('ip', $equipment['ip']);
- $this->checkAndUpdateCmd('mac', $equipment['mac']);
- $this->checkAndUpdateCmd('hostname', $equipment['hostname']);
- $this->checkAndUpdateCmd('connexion', $equipment['connexion']);
- $this->checkAndUpdateCmd('rssi', $equipment['rssi']);
- } else {
- $this->checkAndUpdateCmd('status', 0);
- $this->checkAndUpdateCmd('rssi', 0);
- }
- } catch (Exception $e) {
- log::add('openWrt', 'error', $e->getCode());
- }
- }
- public function restartRouter()
- {
- $this->sendCmdRouter('reboot');
- }
- public function ifaceOn($iface)
- {
- $this->sendCmdRouter("uci -q set wireless.default_" . $iface . ".disabled=0 && wifi reload " . $iface);
- }
- public function ifaceOff($iface)
- {
- $this->sendCmdRouter("uci -q set wireless.default_" . $iface . ".disabled=1 && wifi reload " . $iface);
- }
- public function sendCmdRouter($_cmd = '')
- {
- $connection = openWrt::sshConnect();
- if (!$connection) return 'error connecting';
- $response = '';
- if (is_array($_cmd)) {
- foreach ($_cmd as $command) {
- $response .= $this->sendCmdToRouter($connection, $command);
- }
- } else {
- $response .= $this->sendCmdToRouter($connection, $_cmd);
- }
- openWrt::sshDisconnect();
- return $response;
- }
- private function sendCmdToRouter($connection, $_cmd = '')
- {
- log::add('openWrt', 'debug', 'Send : ' . $_cmd);
- $stream = @ssh2_exec($connection, $_cmd);
- $errorStream = @ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
- /* Enable Blocking */
- @stream_set_blocking($errorStream, true);
- @stream_set_blocking($stream, true);
- /* Grab Response */
- $response = stream_get_contents($stream);
- $error = stream_get_contents($errorStream);
- if (strlen($error) > 0) {
- log::add('openWrt', 'error', 'Error when sending command ' . $_cmd . ' : ' . $error);
- }
- if (is_null($response)) {
- return false;
- }
- return $response;
- }
- }
- class openWrtCmd extends cmd
- {
- public function execute($_options = null)
- {
- if ($this->getType() != "info") {
- if ($this->getLogicalId() == 'refresh') {
- $this->getEqLogic()->refreshEq();
- return;
- }
- switch ($this->getConfiguration('type')) {
- case 'restart':
- $this->getEqLogic()->restartRouter();
- break;
- case 'ifaceon':
- $this->getEqLogic()->ifaceOn(substr($this->getLogicalId(), 0, -2));
- $cmd = cmd::byId($this->getValue())->event(1);
- break;
- case 'ifaceoff':
- $this->getEqLogic()->ifaceOff(substr($this->getLogicalId(), 0, -3));
- $cmd = cmd::byId($this->getValue())->event(0);
- break;
- default:
- break;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement