. */ /* * ***************************Includes********************************* */ require_once __DIR__ . '/../../../../core/php/core.inc.php'; use GuzzleHttp\Client; define('__ROOT__', dirname(dirname(dirname(__FILE__)))); require_once (__ROOT__.'/3rdparty/Netatmo-API-PHP/src/Netatmo/autoload.php'); define('__CSSICON__', str_replace($_SERVER['DOCUMENT_ROOT'], '', __ROOT__.'/core/css/icon/')); /*error_reporting(-1);*/ class netatmopro extends eqLogic { /* * *************************Attributs****************************** */ /* * Permet de définir les possibilités de personnalisation du widget (en cas d'utilisation de la fonction 'toHtml' par exemple) * Tableau multidimensionnel - exemple: array('custom' => true, 'custom::layout' => false) public static $_widgetPossibility = array(); */ public static $_typeToInfo = array( 'NAMain' => array( 'id' => '_id', 'name' => 'module_name', 'dashboard' => array( 'Temperature' => 'time_utc', 'CO2' => 'time_utc', 'Humidity' => 'time_utc', 'Noise' => 'time_utc', 'Pressure' => 'time_utc', #'AbsolutePressure' => 'time_utc', 'min_temp'=> 'date_min_temp', 'max_temp' => 'date_max_temp', 'temp_trend' => 'time_utc', 'pressure_trend' => 'time_utc' ), 'configuration' => array('station_name', 'date_setup', 'last_setup', 'last_status_store', 'firmware', 'last_upgrade', 'wifi_status', 'reachable', 'co2_calibrating') ), 'NAModule1' => array( 'id' => '_id', 'name' => 'module_name', 'dashboard' => array( 'Temperature' => 'time_utc', 'Humidity' => 'time_utc', 'min_temp' => 'date_min_temp', 'max_temp' => 'date_max_temp', 'temp_trend' => 'time_utc' ), 'configuration' => array('last_setup', 'battery_percent', 'reachable', 'firmware', 'last_message', 'last_seen', 'rf_status', 'battery_vp') ), 'NAModule2' => array( 'id' => '_id', 'name' => 'module_name', 'dashboard' => array( 'WindStrength' => 'time_utc', 'WindAngle' => 'time_utc', 'GustStrength' => 'time_utc', 'GustAngle' => 'time_utc', 'max_wind_str' => 'date_max_wind_str', 'max_wind_angle' => 'date_max_wind_str' ), 'configuration' => array('last_setup', 'battery_percent', 'reachable', 'firmware', 'last_message', 'last_seen', 'rf_status', 'battery_vp') ), 'NAModule3' => array( 'id' => '_id', 'name' => 'module_name', 'dashboard' => array( 'Rain' => 'time_utc', 'sum_rain_1' => 'time_utc', 'sum_rain_24' => 'time_utc' ), 'configuration' => array('last_setup', 'battery_percent', 'reachable', 'firmware', 'last_message', 'last_seen', 'rf_status', 'battery_vp') ), 'NAModule4' => array( 'id' => '_id', 'name' => 'module_name', 'dashboard' => array( 'Temperature' => 'time_utc', 'CO2' => 'time_utc', 'Humidity' => 'time_utc', 'min_temp' => 'date_min_temp', 'max_temp' => 'date_max_temp', 'temp_trend' => 'time_utc' ), 'configuration' => array('last_setup', 'battery_percent', 'reachable', 'firmware', 'last_message', 'last_seen', 'rf_status', 'battery_vp') ), 'NHC' => array( 'id' => '_id', 'name' => 'station_name', 'dashboard' => array( 'Temperature' => 'time_utc', 'CO2' => 'time_utc', 'Humidity' => 'time_utc', 'Noise' => 'time_utc', 'Pressure' => 'time_utc', #'AbsolutePressure' => 'time_utc', 'health_idx' => 'time_utc', 'min_temp' => 'date_min_temp', 'max_temp' => 'date_max_temp' ), 'configuration' => array('date_setup', 'last_setup', 'last_status_store', 'module_name', 'firmware', 'last_upgrade', 'wifi_status', 'reachable', 'co2_calibrating') ), 'NOC' => array( 'id' => 'id', 'name' => 'name', 'dashboard' => array('sd_status', 'alim_status', 'floodlight', 'monitoring'), 'configuration' => array('firmware_revision', 'wifi_state', 'wifi_strength', 'vpn_url', 'is_local') ), 'NACamera' => array( 'id' => 'id', 'name' => 'name', 'dashboard' => array('sd_status', 'alim_status', 'monitoring'), 'configuration' => array('firmware_revision', 'vpn_url', 'is_local') ), 'NAPerson' => array( 'id' => 'id', 'name' => 'pseudo', 'dashboard' => array('last_seen', 'out_of_sight'), 'configuration' => array() ), 'NCO' => array( 'id' => 'id', 'name' => 'name', 'dashboard' => array('last_seen'), 'configuration' => array('firmware_revision', 'wifi_strength') ), 'NSD' => array( 'id' => 'id', 'name' => 'name', 'dashboard' => array('last_seen'), 'configuration' => array('firmware_revision', 'wifi_strength') ), 'NIS' => array( 'id' => 'id', 'name' => 'name', 'dashboard' => array('last_seen', 'status', 'monitoring'), 'configuration' => array('battery_state', 'battery_level', 'firmware_revision', 'rf_state', 'rf_strength') ), 'NACamDoorTag' => array( 'id' => 'id', 'name' => 'name', 'dashboard' => array('last_seen', 'last_activity', 'status'), 'configuration' => array('battery_state', 'battery_level', 'firmware_revision', 'rf_state', 'rf_strength', 'reachable') ), 'NDB' => array( 'id' => 'id', 'name' => 'name', 'dashboard' => array('sd_status', 'alim_status'), 'configuration' => array('firmware_revision', 'wifi_state', 'wifi_strength', 'vpn_url', 'is_local') ) ); /* * ***********************Methode static*************************** */ public static function synchronize($update = true) { log::add('netatmopro', 'debug', 'synchronize:: update:' . var_export($update, true)); $dayweek = array('1' => 'Lundi', '2' => 'Mardi', '3' => 'Mercredi', '4' => 'Jeudi', '5' => 'Vendredi', '6' => 'Samedi', '7' => 'Dimanche'); $config = array("client_id" => config::byKey('client_id', 'netatmopro'), "client_secret" => config::byKey('client_secret', 'netatmopro'), "access_token" => config::byKey('access_token', 'netatmopro'), "refresh_token" => config::byKey('refresh_token', 'netatmopro'), "expires_at" => config::byKey('expires_at', 'netatmopro'), "scope" => 'read_station read_magellan write_magellan read_bubendorff write_bubendorff read_smarther write_smarther read_thermostat write_thermostat read_camera write_camera access_camera read_doorbell access_doorbell read_mx write_mx read_presence write_presence access_presence read_homecoach read_carbonmonoxidedetector read_smokedetector read_mhs1 write_mhs1'); $scope = ( $update === true ? config::byKey('scope', 'netatmopro') : [] ); $webhook = false; log::add('netatmopro', 'debug', 'synchronize:: scope:' . var_export($scope, true)); if ( $update === false || ( $update === true && preg_match("/read_station/", $scope) ) ) { log::add('netatmopro', 'debug', 'synchronize:: Weather'); $data = netatmopro::NARequest('GET', 'https://app.netatmo.net/api/getstationsdata'); log::add('netatmopro', 'debug', 'synchronize:: Weather:' . var_export($data, true)); foreach ($data['body']['devices'] as $device) { foreach ($device['modules'] as $module) { $eqLogic = eqLogic::byLogicalId($module['_id'], 'netatmopro'); if ( !is_object($eqLogic) && $update === false ) { log::add('netatmopro', 'debug', 'synchronize:: M_CREATE_IN_PROGRESS:' . var_export($module, true)); $eqLogic = new netatmopro(); $eqLogic->createEqLogicV2($module); $eqLogic->createCmd(); } if ( is_object($eqLogic) && ( $update === false || ( $update === true && array_key_exists('dashboard_data', $module) && $eqLogic->getConfiguration('time_utc') < $module['dashboard_data']['time_utc'] ) ) ) { log::add('netatmopro', 'debug', 'synchronize:: M_UPDATE_IN_PROGRESS:' . var_export($module, true)); if (array_key_exists('dashboard_data', $module)) { foreach (netatmopro::$_typeToInfo[$module['type']]['dashboard'] as $key => $value) { $eqLogic->checkAndUpdateCmd($key, $module['dashboard_data'][$key], date('Y-m-d H:i:s', $module['dashboard_data'][$value])); } $eqLogic->setConfiguration('time_utc', $module['dashboard_data']['time_utc']); } $eqLogic->checkAndUpdateCmd('battery_percent', $module['battery_percent'], date('Y-m-d H:i:s', $module['last_message'])); foreach (netatmopro::$_typeToInfo[$module['type']]['configuration'] as $key) { if ( array_key_exists($key, $module) ) { $eqLogic->setConfiguration($key, $module[$key]); } } $eqLogic->setConfiguration('station_name', $device['station_name']); $eqLogic->batteryStatus($module['battery_percent']); $eqLogic->save(); $eqLogic->refreshWidget(); } } $eqLogic = eqLogic::byLogicalId($device['_id'], 'netatmopro'); if (!is_object($eqLogic) && $update === false) { log::add('netatmopro', 'debug', 'synchronize:: D_CREATE_IN_PROGRESS:' . var_export($device, true)); $eqLogic = new netatmopro(); $eqLogic->createEqLogicV2($device); $eqLogic->createCmd(); } if ( is_object($eqLogic) && ( $update === false || ( $update === true && array_key_exists('dashboard_data', $device) && $eqLogic->getConfiguration('time_utc') < $device['dashboard_data']['time_utc'] ) ) ) { log::add('netatmopro', 'debug', 'synchronize:: D_UPDATE_IN_PROGRESS:' . var_export($device, true)); if (array_key_exists('dashboard_data', $device)) { foreach (netatmopro::$_typeToInfo[$device['type']]['dashboard'] as $key => $value) { $eqLogic->checkAndUpdateCmd($key, $device['dashboard_data'][$key], date('Y-m-d H:i:s', $device['dashboard_data'][$value])); } $eqLogic->setConfiguration('time_utc', $device['dashboard_data']['time_utc']); } foreach (netatmopro::$_typeToInfo[$device['type']]['configuration'] as $key) { if ( array_key_exists($key, $device) ) { $eqLogic->setConfiguration($key, $device[$key]); } } $eqLogic->save(); $eqLogic->refreshWidget(); } if ($update === false) { $scope[] = 'read_station'; } } } if ( $update === false || ( $update === true && preg_match("/read_homecoach/", $scope) ) ) { log::add('netatmopro', 'debug', 'synchronize:: Aircare'); $data = netatmopro::NARequest('GET', 'https://app.netatmo.net/api/gethomecoachsdata'); log::add('netatmopro', 'debug', 'synchronize:: Aircare:' . var_export($data, true)); foreach ($data['body']['devices'] as $device) { $eqLogic = eqLogic::byLogicalId($device['_id'], 'netatmopro'); if (!is_object($eqLogic) && $update === false) { log::add('netatmopro', 'debug', 'synchronize:: D_CREATE_IN_PROGRESS:' . var_export($device, true)); $eqLogic = new netatmopro(); $eqLogic->createEqLogicV2($device); $eqLogic->createCmd(); } if ( is_object($eqLogic) && ( $update === false || ( $update === true && array_key_exists('dashboard_data', $device) && $eqLogic->getConfiguration('time_utc') < $device['dashboard_data']['time_utc'] ) ) ) { log::add('netatmopro', 'debug', 'synchronize:: D_UPDATE_IN_PROGRESS:' . var_export($device, true)); if (array_key_exists('dashboard_data', $device)) { foreach (netatmopro::$_typeToInfo[$device['type']]['dashboard'] as $key => $value) { $eqLogic->checkAndUpdateCmd($key, $device['dashboard_data'][$key], date('Y-m-d H:i:s', $device['dashboard_data'][$value])); } $eqLogic->setConfiguration('time_utc', $device['dashboard_data']['time_utc']); } foreach (netatmopro::$_typeToInfo[$device['type']]['configuration'] as $key) { if ( array_key_exists($key, $device) ) { $eqLogic->setConfiguration($key, $device[$key]); } } $eqLogic->save(); $eqLogic->refreshWidget(); } if ($update === false) { $scope[] = 'read_homecoach'; } } } if ( $update === false || ( $update === true && preg_match("/read_camera write_camera access_camera read_doorbell access_doorbell read_presence write_presence access_presence read_carbonmonoxidedetector read_smokedetector/", $scope) ) ) { log::add('netatmopro', 'debug', 'synchronize:: Home + Security'); $hsdata = netatmopro::NARequest('GET', 'https://app.netatmo.net/api/homesdata'); log::add('netatmopro', 'debug', 'synchronize:: Home + Security (homesdata):' . var_export($hsdata, true)); foreach ($hsdata['body']['homes'] as $home) { if (array_key_exists('modules', $home)) { foreach ($home['modules'] as $module) { if (!in_array($module['type'], array('NOC', 'NACamera', 'NCO', 'NSD', 'NIS', 'NACamDoorTag', 'NDB'))) continue; $eqLogic = eqLogic::byLogicalId($module['id'], 'netatmopro'); if ( !is_object($eqLogic) && $update === false ) { log::add('netatmopro', 'debug', 'synchronize:: M_CREATE_IN_PROGRESS:' . var_export($module, true)); $eqLogic = new netatmopro(); $eqLogic->createEqLogicV2($module); $eqLogic->createCmd(); } if ( is_object($eqLogic) ) { $eqLogic->setConfiguration('home_id', $home['id']); $eqLogic->setConfiguration('home_name', $home['name']); $eqLogic->setConfiguration('setup_date', $module['setup_date']); $eqLogic->save(); } } } if (array_key_exists('persons', $home)) { foreach ($home['persons'] as $person) { if (!(array_key_exists('pseudo', $person))) continue; $eqLogic = eqLogic::byLogicalId($person['id'], 'netatmopro'); if ( !is_object($eqLogic) && $update === false ) { log::add('netatmopro', 'debug', 'synchronize:: P_CREATE_IN_PROGRESS:' . var_export($person, true)); $eqLogic = new netatmopro(); $eqLogic->createEqLogicV2($person, 'NAPerson'); $eqLogic->createCmd(); } if ( is_object($eqLogic) ) { $eqLogic->setConfiguration('home_id', $home['id']); $eqLogic->setConfiguration('home_name', $home['name']); $eqLogic->save(); } } } $data = netatmopro::NARequest('GET', 'https://app.netatmo.net/api/homestatus?home_id=' . $home['id']); log::add('netatmopro', 'debug', 'synchronize:: Home + Security (homestatus):' . var_export($data, true)); if (array_key_exists('body', $data)) { foreach ($data['body']['home']['modules'] as $module) { if (!in_array($module['type'], array('NOC', 'NACamera', 'NCO', 'NSD', 'NIS', 'NACamDoorTag', 'NDB'))) continue; $eqLogic = eqLogic::byLogicalId($module['id'], 'netatmopro'); if ( is_object($eqLogic) ) { log::add('netatmopro', 'debug', 'synchronize:: M_UPDATE_IN_PROGRESS:' . var_export($module, true)); foreach (netatmopro::$_typeToInfo[$module['type']]['dashboard'] as $key ) { $eqLogic->checkAndUpdateCmd($key, $module[$key]); } foreach (netatmopro::$_typeToInfo[$module['type']]['configuration'] as $key) { $eqLogic->setConfiguration($key, $module[$key]); } $eqLogic->save(); $eqLogic->refreshWidget(); } } if (array_key_exists('persons', $data['body']['home'])) { foreach ($data['body']['home']['persons'] as $person) { $eqLogic = eqLogic::byLogicalId($person['id'], 'netatmopro'); if ( is_object($eqLogic) ) { log::add('netatmopro', 'debug', 'synchronize:: P_UPDATE_IN_PROGRESS:' . var_export($person, true)); foreach (netatmopro::$_typeToInfo['NAPerson']['dashboard'] as $key ) { $eqLogic->checkAndUpdateCmd($key, $person[$key]); } $eqLogic->save(); $eqLogic->refreshWidget(); } } } } if ($update === false) { $scope[] = 'read_camera write_camera access_camera read_doorbell access_doorbell read_presence write_presence access_presence read_carbonmonoxidedetector read_smokedetector'; $webhook = true; } } } if ( $update === false || ( $update === true && preg_match("/read_thermostat write_thermostat/", $scope) ) ) { log::add('netatmopro', 'debug', 'synchronize:: NATherm2ApiClient'); #$client = new Netatmo\Clients\NATherm2ApiClient($config); #$tokens = $client->getAccessToken(); #$data = $client->getData(null, 'NAPlug'); $data = netatmopro::NARequest('GET', 'https://app.netatmo.net/api/homesdata?gateway_types=NAPlug'); log::add('netatmopro', 'debug', 'synchronize:: ENERGY:' . var_export($data, true)); netatmopro::GetGuzzleHd($guzzle, $jar); log::add('netatmopro', 'debug', 'synchronize:: guzzle:' . var_export($guzzle, true)); log::add('netatmopro', 'debug', 'synchronize:: jar:' . var_export($jar, true)); $uri = 'https://app.netatmo.net/api/homesdata'; log::add('netatmopro', 'debug', 'synchronize:: uri:' . var_export($uri, true)); $response = $guzzle->request('POST', $uri, [ 'headers' => [ 'Authorization' => 'Bearer ' . urldecode($jar->getCookieByName('netatmocomaccess_token')->getValue()) ], 'body' => '{"gateway_types":["NAPlug"],"detailed_config":true,"home_id":null,"gateway_parameters":{"NAPlug":{"sync_measures":true}}}' ]); log::add('netatmopro', 'debug', 'synchronize:: response:' . var_export($response, true)); $wdata = json_decode($response->getBody()->getContents(), true); foreach ($wdata['body']['homes'] as $whome) { $homes[$whome['id']] = $whome; } log::add('netatmopro', 'debug', 'synchronize:: homes:' . var_export($homes, true)); foreach ($data['body']['homes'] as $home) { if (!(array_key_exists('rooms', $home) && array_key_exists('modules', $home) && array_key_exists('schedules', $home))) continue; $rooms = $modules = $schedules = []; foreach ($home['rooms'] as $room) { $rooms[$room['id']] = $room; } foreach ($home['modules'] as $module) { $modules[$module['id']] = $module; } foreach ($home['schedules'] as $schedule) { $schedules[$schedule['id']] = $schedule; } #$status = $client->getStatus($home['id'], 'NAPlug'); $status = netatmopro::NARequest('GET', 'https://app.netatmo.net/api/homestatus?home_id=' . $home['id'] . '&device_types=NAPlug'); log::add('netatmopro', 'debug', 'synchronize:: ENERGY:' . var_export($status, true)); foreach ($status['body']['home']['rooms'] as $room) { $room['type'] = 'NARoom'; $rooms[$room['id']]['status'] = $room; $eqLogic = eqLogic::byLogicalId($room['id'], 'netatmopro'); if (!is_object($eqLogic) && $update === false) { log::add('netatmopro', 'debug', 'synchronize:: D_CREATE_IN_PROGRESS:' . var_export($room, true)); $eqLogic = new netatmopro(); $eqLogic->createEqLogic($room, $rooms[$room['id']]['name']); $eqLogic->createCmd(); } if ( is_object($eqLogic) ) { log::add('netatmopro', 'debug', 'synchronize:: D_UPDATE_IN_PROGRESS:' . var_export($room, true)); foreach ($eqLogic->getConfiguration('dashboard') as $key) { $eqLogic->checkAndUpdateCmd($key, $room[$key]); } $eqLogic->setConfiguration('home_id', $home['id']); $eqLogic->setConfiguration('home_name', $home['name']); $eqLogic->setConfiguration('room_type', $rooms[$room['id']]['type']); $eqLogic->save(); } } foreach ($status['body']['home']['modules'] as $module) { if ( $module['type'] == 'NOC' || $module['type'] == 'NACamera' ) continue; $eqLogic = eqLogic::byLogicalId($module['id'], 'netatmopro'); if (!is_object($eqLogic) && $update === false) { log::add('netatmopro', 'debug', 'synchronize:: D_CREATE_IN_PROGRESS:' . var_export($module, true)); $eqLogic = new netatmopro(); $eqLogic->createEqLogic($module, $modules[$module['id']]['name']); $eqLogic->createCmd(); } if ( is_object($eqLogic) ) { log::add('netatmopro', 'debug', 'synchronize:: D_UPDATE_IN_PROGRESS:' . var_export($module, true)); foreach ($eqLogic->getConfiguration('dashboard') as $key) { $eqLogic->checkAndUpdateCmd($key, $module[$key]); } $eqLogic->setConfiguration('home_id', $home['id']); $eqLogic->setConfiguration('home_name', $home['name']); $eqLogic->setConfiguration('firmware_revision', $module['firmware_revision']); if ( $module['type'] == 'NAPlug' ) { $eqLogic->setConfiguration('wifi_strength', $module['wifi_strength']); $cmd = $eqLogic->getCmd('action', 'switchhomeschedule'); if ( is_object($cmd) ) { $listValue = ''; foreach ($schedules as $kschedule => $vschedule) { $listValue .= $kschedule . '|' . $vschedule['name'] . ';'; if ( array_key_exists('selected', $vschedule) && $vschedule['selected'] == true ) { $eqLogic->checkAndUpdateCmd('homes_schedule', $vschedule['name']); $monday = date('U',strtotime('Monday this week')); $now = time(); log::add('netatmopro', 'debug', 'synchronize:: monday:' . var_export($monday, true)); foreach (array_reverse($vschedule['timetable']) as $ktimetable => $vtimetable) { if ($now-$monday >= $vtimetable['m_offset']*60) { log::add('netatmopro', 'debug', 'synchronize:: vtimetable:' . var_export($vtimetable, true)); break; } } foreach ($vschedule['zones'] as $kzones => $vzones) { if ($vtimetable['zone_id'] == $vzones['id']) { log::add('netatmopro', 'debug', 'synchronize:: vzones:' . var_export($vzones, true)); break; } } $eqLogic->checkAndUpdateCmd('therm_setpoint_zone', $vzones['name']); log::add('netatmopro', 'debug', 'synchronize:: therm_setpoint_zone:' . var_export($vzones['name'], true)); if ( count($vschedule['timetable'])-$ktimetable < count($vschedule['timetable']) ) { $nschedule = $monday + ($vschedule['timetable'][count($vschedule['timetable'])-$ktimetable]['m_offset']*60); if (date("z-Y",$now) == date("z-Y",$nschedule)) { $eqLogic->checkAndUpdateCmd('therm_setpoint_timetable', 'Jusqu\'à ' . date("H:i",$nschedule)); } else { $eqLogic->checkAndUpdateCmd('therm_setpoint_timetable', 'Jusqu\'à ' . $dayweek[date("N",$nschedule)] . ' ' . date("H:i",$nschedule)); } } else { $nschedule = date('U',strtotime('Monday next week')); $eqLogic->checkAndUpdateCmd('therm_setpoint_timetable', 'Jusqu\'à Lundi 00:00'); } } } log::add('netatmopro', 'debug', 'synchronize:: switchhomeschedule:' . var_export($listValue, true)); $cmd->setConfiguration('listValue', substr($listValue, 0, -1)); $cmd->save(); } $eqLogic->checkAndUpdateCmd('therm_mode', $home['therm_mode']); $eqLogic->checkAndUpdateCmd('therm_heating_priority', $homes[$home['id']]['therm_heating_priority']); } else { $eqLogic->setConfiguration('room_id', $rooms[$modules[$module['id']]['room_id']]['id']); $eqLogic->setConfiguration('room_name', $rooms[$modules[$module['id']]['room_id']]['name']); $eqLogic->setConfiguration('room_type', $rooms[$modules[$module['id']]['room_id']]['type']); $eqLogic->setConfiguration('bridge', $module['bridge']); $eqLogic->setConfiguration('rf_strength', $module['rf_strength']); $eqLogic->setConfiguration('battery_level', $module['battery_level']); $eqLogic->setConfiguration('battery_state', $module['battery_state']); $eqLogic->batteryStatus(($module['battery_state'] == 'full' ? 100 : (($module['battery_state'] == 'high' ? 80 : ($module['battery_state'] == 'medium' ? 50 : 20 ))))); } $eqLogic->save(); } } if ($update === false) { $scope[] = 'read_thermostat write_thermostat'; $webhook = true; } } } if ( $update === false ) { if (!empty($scope)) { log::add('netatmopro', 'debug', 'synchronize:: scope:' . var_export(implode(';', array_unique($scope)), true)); config::save('scope', implode(';', array_unique($scope)), 'netatmopro'); } if ( $webhook === true ) { log::add('netatmopro', 'debug', 'synchronize:: webhook:' . var_export(network::getNetworkAccess('external'), true)); if (filter_var(network::getNetworkAccess('external'), FILTER_VALIDATE_URL)) { #$client = new Netatmo\Clients\NAWelcomeApiClient($config); #$tokens = $client->getAccessToken(); #$client->subscribeToWebhook(network::getNetworkAccess('external') . '/plugins/netatmopro/core/php/NAWebhookClient.php?apikey=' . jeedom::getApiKey('netatmopro')); $data = netatmopro::NARequest('POST', 'https://api.netatmo.com/api/addwebhook?url=' . urlencode(network::getNetworkAccess('external') . '/plugins/netatmopro/core/php/NAWebhookClient.php?apikey=' . jeedom::getApiKey('netatmopro'))); } } } } /* * Fonction exécutée automatiquement toutes les minutes par Jeedom public static function cron() { } */ public static function cron() { $refresh = config::byKey('refresh', 'netatmopro'); log::add('netatmopro', 'debug', 'cron:: refresh:' . var_export($refresh, true)); if (!empty($refresh) && $refresh == true) { config::save('refresh', false, 'netatmopro'); netatmopro::cron5(); } } /* * Fonction exécutée automatiquement toutes les 5 minutes par Jeedom public static function cron5() { } */ public static function cron5() { #if ( time() > config::byKey('expires_at', 'netatmopro') ) { # netatmopro::cronHourly(); #} try { netatmopro::synchronize(true); } catch (Exception $ex) { log::add('netatmopro', 'alert', 'cron5:: ex:' . var_export(get_class($ex) . ' - ' . $ex->getCode() . ' - ' . $ex->getMessage(), true)); } } /* * Fonction exécutée automatiquement toutes les 10 minutes par Jeedom public static function cron10() { } */ /* * Fonction exécutée automatiquement toutes les 15 minutes par Jeedom public static function cron15() { } */ /* * Fonction exécutée automatiquement toutes les 30 minutes par Jeedom public static function cron30() { } */ /* * Fonction exécutée automatiquement toutes les heures par Jeedom */ public static function cronHourly() { #$config = array("client_id" => config::byKey('client_id', 'netatmopro'), # "client_secret" => config::byKey('client_secret', 'netatmopro'), # "access_token" => config::byKey('access_token', 'netatmopro'), # "refresh_token" => config::byKey('refresh_token', 'netatmopro'), # "expires_at" => config::byKey('expires_at', 'netatmopro'), # "scope" => 'read_station read_magellan write_magellan read_bubendorff write_bubendorff read_smarther write_smarther read_thermostat write_thermostat read_camera write_camera access_camera read_doorbell access_doorbell read_mx write_mx read_presence write_presence access_presence read_homecoach read_carbonmonoxidedetector read_smokedetector read_mhs1 write_mhs1'); #$client = new Netatmo\Clients\NAWSApiClient($config); #$tokens = $client->getAccessToken(); #log::add('netatmopro', 'debug', 'cronHourly:: jtokens:' . var_export(array("access_token" => config::byKey('access_token', 'netatmopro'), "refresh_token" => config::byKey('refresh_token', 'netatmopro'), "expires_at" => config::byKey('expires_at', 'netatmopro')), true)); #log::add('netatmopro', 'debug', 'cronHourly:: ntokens:' . var_export(array("access_token" => $client->_getAccessToken(), "refresh_token" => $client->_getRefreshToken(), "expires_at" => $client->_getExpiresAt()), true)); #config::save('access_token', $client->_getAccessToken(), 'netatmopro'); #config::save('refresh_token', $client->_getRefreshToken(), 'netatmopro'); #config::save('expires_at', $client->_getExpiresAt(), 'netatmopro'); } /* * Fonction exécutée automatiquement tous les jours par Jeedom public static function cronDaily() { } */ /* * *********************Méthodes d'instance************************* */ // Fonction exécutée automatiquement avant la création de l'équipement public function preInsert() { } // Fonction exécutée automatiquement après la création de l'équipement public function postInsert() { } // Fonction exécutée automatiquement avant la mise à jour de l'équipement public function preUpdate() { } // Fonction exécutée automatiquement après la mise à jour de l'équipement public function postUpdate() { } // Fonction exécutée automatiquement avant la sauvegarde (création ou mise à jour) de l'équipement public function preSave() { } // Fonction exécutée automatiquement après la sauvegarde (création ou mise à jour) de l'équipement public function postSave() { } // Fonction exécutée automatiquement avant la suppression de l'équipement public function preRemove() { } // Fonction exécutée automatiquement après la suppression de l'équipement public function postRemove() { } /* * Non obligatoire : permet de modifier l'affichage du widget (également utilisable par les commandes) public function toHtml($_version = 'dashboard') { } */ public function toHtml($_version = 'dashboard') { if ( $this->getConfiguration('type') == 'NAPerson' || $this->getConfiguration('type') == 'NAPlug' || $this->getConfiguration('type') == 'NATherm1' || $this->getConfiguration('type') == 'NARoom' || $this->getConfiguration('type') == 'NRV' || $this->getConfiguration('type') == 'NSD' || $this->getConfiguration('type') == 'NIS' || $this->getConfiguration('type') == 'NACamDoorTag' || $this->getConfiguration('type') == 'NDB' ) { return parent::toHtml(); } $replace = $this->preToHtml($_version); if (!is_array($replace)) { return $replace; } $version = jeedom::versionAlias($_version); $array = array( 'down' => '', 'up' => '', 'stable' => '', ); foreach ($this->getCmd() as $cmd) { if ($cmd->getType() == 'info') { $replace['#' . $cmd->getLogicalId() . '#'] = $cmd->execCmd(); } } if ( $this->getConfiguration('type') == 'NAMain' ) { $replace['#last_status_store#'] = date('H:i:s', $this->getConfiguration('last_status_store')); $replace['#TemperatureCSS#'] = $this->temperatureToCSS($replace['#Temperature#']); $replace['#temp_symbol#'] = (array_key_exists($replace['#temp_trend#'], $array) ? $array[$replace['#temp_trend#']] : ''); $replace['#pressure_symbol#'] = (array_key_exists($replace['#pressure_trend#'], $array) ? $array[$replace['#pressure_trend#']] : ''); } elseif ( $this->getConfiguration('type') == 'NAModule1' ) { $replace['#last_message#'] = date('H:i:s', $this->getConfiguration('last_message')); $replace['#TemperatureCSS#'] = $this->temperatureToCSS($replace['#Temperature#']); $replace['#temp_symbol#'] = (array_key_exists($replace['#temp_trend#'], $array) ? $array[$replace['#temp_trend#']] : ''); } elseif ( $this->getConfiguration('type') == 'NAModule2' ) { $replace['#last_message#'] = date('H:i:s', $this->getConfiguration('last_message')); $replace['#WindStrengthText#'] = $this->WindStrengthToLib($replace['#WindStrength#']); $replace['#WindAngleText#'] = $this->WindAngleToLib($replace['#WindAngle#']); $replace['#WingAngleCSS#'] = ".thearrow2,.thearrow2:after{left:50%;top:0;transition-duration:3s}.thearrow2:after,.thearrow2:before{content:'';position:absolute;box-sizing: border-box;}.thearrow2{transform:rotate(" . $replace['#WindAngle#'] . "deg);position:absolute;z-index:200;margin-left:-5px;width:10px;height:50%;transform-origin:50% 100%}.thearrow2:after{background-color:NONE;width:0;height:0;border-style:solid;border-width:14px 9px 0;border-color:RGBA(255,121,58,1) transparent transparent;transform:translate(-50%,-50%)}.thearrow2:before{width:6px;height:6px;z-index:9;left:2px;top:-5px;border:2px solid;border-radius:100%}"; } elseif ( $this->getConfiguration('type') == 'NAModule3' ) { $replace['#last_message#'] = date('H:i:s', $this->getConfiguration('last_message')); $SumRain24CSS1 = '
'; $SumRain24CSS2 = '
h-24
'; $replace['#NA3SvgUrl1#'] = __CSSICON__ . 'marker.svg'; $replace['#NA3SvgUrl2#'] = __CSSICON__ . 'water.svg'; $replace['#NA3SvgUrl3#'] = __CSSICON__ . 'rainrulerw34.svg'; $replace['#Rain#'] = (is_numeric($replace['#Rain#']) ? number_format($replace['#Rain#'], 1) : 0); $replace['#sum_rain_24#'] = (is_numeric($replace['#sum_rain_24#']) ? number_format($replace['#sum_rain_24#'], 1) : 0); $replace['#sum_rain_1#'] = (is_numeric($replace['#sum_rain_1#']) ? number_format($replace['#sum_rain_1#'], 1) : 0); $replace['#SumRain24CSS#'] = ($replace['#sum_rain_24#'] == 0 ? $SumRain24CSS1 : $SumRain24CSS2); $replace['#SumRain24#'] = ($replace['#sum_rain_24#'] == 0 ? 0 : number_format(($replace['#sum_rain_24#'] * 2) + 7, 0)); $replace['#SumRain1#'] = ($replace['#sum_rain_1#'] == 0 ? 0 : number_format(($replace['#sum_rain_1#'] * 6) + 3, 0)); } elseif ( $this->getConfiguration('type') == 'NAModule4' ) { $replace['#last_message#'] = date('H:i:s', $this->getConfiguration('last_message')); $replace['#TemperatureCSS#'] = $this->temperatureToCSS($replace['#Temperature#']); $replace['#temp_symbol#'] = (array_key_exists($replace['#temp_trend#'], $array) ? $array[$replace['#temp_trend#']] : ''); } elseif ( $this->getConfiguration('type') == 'NHC' ) { $replace['#last_status_store#'] = date('H:i:s', $this->getConfiguration('last_status_store')); $replace['#TemperatureCSS#'] = $this->temperatureToCSS($replace['#Temperature#']); $replace['#temp_symbol#'] = (array_key_exists($replace['#temp_trend#'], $array) ? $array[$replace['#temp_trend#']] : ''); $replace['#pressure_symbol#'] = (array_key_exists($replace['#pressure_trend#'], $array) ? $array[$replace['#pressure_trend#']] : ''); $replace['#HealthIndexCSS#'] = $this->HealthIndexToCSS($replace['#health_idx#']); } elseif ( $this->getConfiguration('type') == 'NACamera' ) { $replace['#vpn_url#'] = $this->getConfiguration('vpn_url'); } elseif ( $this->getConfiguration('type') == 'NOC' ) { $replace['#vpn_url#'] = $this->getConfiguration('vpn_url'); } return $this->postToHtml($_version, template_replace($replace, getTemplate('core', $version, $this->getConfiguration('type'), 'netatmopro'))); } /* * Non obligatoire : permet de déclencher une action après modification de variable de configuration public static function postConfig_() { } */ /* * Non obligatoire : permet de déclencher une action avant modification de variable de configuration public static function preConfig_() { } */ public function getIconFile() { log::add('netatmopro', 'debug', 'getIconFile::'); $type = $this->getConfiguration('type'); $filename = __ROOT__.'/core/config/devices/'.$type.'/'.$type.'.png'; return (file_exists($filename) === true ? ('plugins/netatmopro/core/config/devices/'.$type.'/'.$type.'.png') : ('plugins/netatmopro/core/config/devices/default.png')); } private function loadConfigFile() { log::add('netatmopro', 'debug', 'loadConfigFile::'); $type = $this->getConfiguration('type'); $filename = __ROOT__.'/core/config/devices/'.$type.'/'.$type.'.json'; if ( file_exists($filename) === false ) { throw new Exception('Impossible de trouver le fichier de configuration pour l\'équipement de type ' . $this->getConfiguration('type')); } $content = file_get_contents($filename); if (!is_json($content)) { throw new Exception('Le fichier de configuration \'' . $filename . '\' est corrompu'); } $data = json_decode($content, true); if (!is_array($data) || !isset($data['configuration']) || !isset($data['commands'])) { throw new Exception('Le fichier de configuration \'' . $filename . '\' est invalide'); } return $data; } private function createEqLogicV2($data, $type = NULL) { log::add('netatmopro', 'debug', 'createEqLogic:: data:' . var_export($data, true) . ', type:' . var_export($type, true)); $type = (isset($data['type']) ? $data['type'] : $type); $eqLogicalId = $data[netatmopro::$_typeToInfo[$type]['id']]; $eqName = (isset($data[netatmopro::$_typeToInfo[$type]['name']]) ? $data[netatmopro::$_typeToInfo[$type]['name']] : $eqLogicalId); $this->setName($eqName); $this->setLogicalId($eqLogicalId); $this->setEqType_name('netatmopro'); $this->setIsEnable(1); $this->setConfiguration('type', $type); $config = $this->loadConfigFile(); foreach ($config['configuration'] as $key => $value) { $this->setConfiguration($key, $value); } $this->save(); } private function createEqLogic($data = null, $name = null) { log::add('netatmopro', 'debug', 'createEqLogic:: data:' . var_export($data, true)); log::add('netatmopro', 'debug', 'createEqLogic:: name:' . var_export($name, true)); $eqLogicalId = ($data['type'] == 'NOC' || $data['type'] == 'NACamera' || $data['type'] == 'NAPlug' || $data['type'] == 'NATherm1' || $data['type'] == 'NRV' || $data['type'] == 'NARoom' || $data['type'] == 'NAPerson' || $data['type'] == 'NSD' || $data['type'] == 'NIS' || $data['type'] == 'NACamDoorTag' || $data['type'] == 'NDB' ) ? $data['id'] : $data['_id']; $eqName = $data['type'] == 'NHC' ? $data['station_name'] : ( ($data['type'] == 'NOC' || $data['type'] == 'NACamera' || $data['type'] == 'NAPlug' || $data['type'] == 'NATherm1' || $data['type'] == 'NRV' || $data['type'] == 'NARoom' || $data['type'] == 'NAPerson' || $data['type'] == 'NSD' || $data['type'] == 'NIS' || $data['type'] == 'NACamDoorTag' || $data['type'] == 'NDB' ) ? ( ($data['type'] == 'NAPlug' || $data['type'] == 'NATherm1' || $data['type'] == 'NRV' || $data['type'] == 'NARoom' || $data['type'] == 'NAPerson' ) ? $name : $data['name'] ) : $data['module_name'] ); if (!isset($eqName)) { $eqName = $eqLogicalId; } $this->setName($eqName); $this->setLogicalId($eqLogicalId); $this->setEqType_name('netatmopro'); $this->setIsEnable(1); $this->setConfiguration('type', $data['type']); $config = $this->loadConfigFile(); foreach ($config['configuration'] as $key => $value) { $this->setConfiguration($key, $value); } $this->save(); } private function createCmd() { log::add('netatmopro', 'debug', 'createCmd::'); $config = $this->loadConfigFile(); $dashboard = array(); $i = 0; foreach ($config['commands'] as $command) { $cmd = new netatmoproCmd(); $cmd->setOrder($i++); $cmd->setEqLogic_id($this->getId()); utils::a2o($cmd, $command); $cmd->save(); if ( $command['isDashboard'] == true ) { $dashboard[] = $command['logicalId']; } } $this->setConfiguration('dashboard', $dashboard); $this->save(); } private function temperatureToCSS($temperature) { log::add('netatmopro', 'debug', 'temperatureToCSS:: temperature:' . var_export($temperature, true)); $array = array( 'freezing' => '270deg, #00a4b4, #32004b', 'cold' => '270deg, #00a4b4, #087883', 'gettingcolder' => '90deg, #01a4b4, #03bf87', 'colder' => '90deg, #00a4b4, #88b04b', 'cooler' => '270deg, #9aba2f, #1b9aa7', 'mild' => '90deg, #9aba2f, #ffae00', 'milder' => '90deg, #88b04b, #e5c21f', 'gettingcooler' => '90deg, #88b04b, #ff8841', 'warm' => '90deg, #efa80f, #ff8841', 'warmer' => '90deg, #ff8841, #ec6615', 'hot' => '90deg, #ff8841, #ec6615', 'hotter' => '90deg, #ff8841, #e60e4b', 'veryhot' => '90deg, #fd7641, #637ff6', 'extremehot' => '90deg, #de2c52, #637ff6', ); $key = ( $temperature < 0 ? 'freezing' : ( $temperature < 5 ? 'cold' : ( $temperature < 7 ? 'gettingcolder' : ( $temperature < 10 ? 'colder' : ( $temperature < 12 ? 'cooler' : ( $temperature < 15 ? 'mild' : ( $temperature < 18 ? 'milder' : ( $temperature < 20 ? 'gettingcooler' : ( $temperature < 23 ? 'warm' : ( $temperature < 25 ? 'warmer' : ( $temperature < 27 ? 'hot' : ( $temperature < 30 ? 'hotter' : ( $temperature < 35 ? 'hotter' : ( $temperature < 40 ? 'veryhot' : 'extremehot' ) ) ) ) ) ) ) ) ) ) ) ) ) ); return $array[$key]; } private function WindStrengthToLib($wstrength) { log::add('netatmopro', 'debug', 'WindStrengthToLib:: wstrength:' . var_export($wstrength, true)); return ( $wstrength < 1 ? 'Calme' : ( $wstrength < 6 ? 'Très légère brise' : ( $wstrength < 12 ? 'Légère brise' : ( $wstrength < 20 ? 'Petite brise' : ( $wstrength < 29 ? 'Jolie brise' : ( $wstrength < 39 ? 'Bonne brise' : ( $wstrength < 50 ? 'Vent frais' : ( $wstrength < 62 ? 'Grand frais' : ( $wstrength < 75 ? 'Coup de vent' : ( $wstrength < 89 ? 'Fort coup de vent' : ( $wstrength < 103 ? 'Tempête' : ( $wstrength < 118 ? 'Violente tempête' : 'Ouragan' ) ) ) ) ) ) ) ) ) ) ) ); } private function WindAngleToLib($wangle) { log::add('netatmopro', 'debug', 'WindAngleToLib:: wangle:' . var_export($wangle, true)); return ( $wangle < 16.88 ? 'Nord' : ( $wangle < 39.38 ? 'Nord
Nord-Est' : ( $wangle < 61.88 ? 'Nord-Est' : ( $wangle < 84.38 ? 'Est
Nord-Est' : ( $wangle < 106.88 ? 'Est' : ( $wangle < 129.38 ? 'Est
Sud-Est' : ( $wangle < 151.88 ? 'Sud Est' : ( $wangle < 174.38 ? 'Sud
Sud-Est' : ( $wangle < 196.88 ? 'Sud' : ( $wangle < 219.38 ? 'Sud
Sud-Ouest' : ( $wangle < 241.88 ? 'Sud-Ouest' : ( $wangle < 264.38 ? 'Ouest
Sud-Ouest' : ( $wangle < 268.88 ? 'Ouest
' : ( $wangle < 309.38 ? 'Ouest
Nord-Ouest' : ( $wangle < 331.88 ? 'Nord-Ouest' : ( $wangle < 354.38 ? 'Nord
Nord-Ouest' : 'Nord' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ); } private function HealthIndexToCSS($index) { log::add('netatmopro', 'debug', 'HealthIndexToCSS:: index:' . var_export($index, true)); $array = array( 0 => '#2ecc71', 1 => '#ffc300', 2 => '#ef5733', 3 => '#c70039', 4 => '#900c3f', ); return $array[$index]; } public static function NARequest($method, $path, $body = '') { log::add('netatmopro', 'debug', 'NARequest:: ' . var_export($method, true) . ' ' . var_export($path, true) . ' ' . var_export($body, true)); $client = new Client(); if ( time() > config::byKey('expires_at', 'netatmopro') ) { $response = $client->request('POST', 'https://app.netatmo.net/oauth2/token', [ 'form_params' => [ 'grant_type' => 'refresh_token', 'client_id' => config::byKey('client_id', 'netatmopro'), 'client_secret' => config::byKey('client_secret', 'netatmopro'), 'refresh_token' => config::byKey('refresh_token', 'netatmopro'), 'scope' => 'read_station read_magellan write_magellan read_bubendorff write_bubendorff read_smarther write_smarther read_thermostat write_thermostat read_camera write_camera access_camera read_doorbell access_doorbell read_mx write_mx read_presence write_presence access_presence read_homecoach read_carbonmonoxidedetector read_smokedetector read_mhs1 write_mhs1' ] ]); $data = json_decode($response->getBody()->getContents(), true); log::add('netatmopro', 'debug', 'NARequest:: data:' . var_export($data, true)); config::save('access_token', $data['access_token'], 'netatmopro'); config::save('refresh_token', $data['refresh_token'], 'netatmopro'); config::save('expires_at', time() + $data['expires_in'] - 30, 'netatmopro'); } $response = $client->request($method, $path, [ 'headers' => [ 'Authorization' => 'Bearer ' . config::byKey('access_token', 'netatmopro'), 'Content-Type' => 'application/json; charset=utf-8', 'Host' => 'app.netatmo.net', 'Connection' => 'Keep-Alive' ], 'body' => $body ]); $json = $response->getBody()->getContents(); log::add('netatmopro', 'debug', 'NARequest:: json:' . var_export($json, true)); return json_decode($json, true); } public static function GetGuzzleHd(&$client, &$jar) { $jar = new \GuzzleHttp\Cookie\FileCookieJar(jeedom::getTmpFolder('netatmopro') . '/b27536f76a9d4d240a34dbd84bc85085', true); $client = new Client([ 'cookies' => $jar ]); log::add('netatmopro', 'debug', 'GetGuzzleHd:: FileCookieJar:' . var_export($jar, true)); log::add('netatmopro', 'debug', 'GetGuzzleHd:: netatmocomaccess_token:' . var_export($jar->getCookieByName('netatmocomaccess_token'), true)); if ( $jar->getCookieByName('netatmocomaccess_token') ) { log::add('netatmopro', 'debug', 'GetGuzzleHd:: netatmocomaccess_token:' . var_export(date('l jS \of F Y h:i:s A',$jar->getCookieByName('netatmocomaccess_token')->getExpires()), true)); } if ( $jar->getCookieByName('netatmocomaccess_token') == null || ($jar->getCookieByName('netatmocomaccess_token')->getExpires() - 600) < time() ) { $jar->clear(); $response = $client->request('GET', 'https://auth.netatmo.com/fr-fr/access/login'); $body = $response->getBody()->getContents(); $response = $client->request('GET', 'https://auth.netatmo.com/access/csrf'); $payload = $response->getBody()->getContents(); log::add('netatmopro', 'debug', 'GetGuzzleHd:: csrf:' . var_export($payload, true)); $wdata = json_decode($payload, true); $response = $client->request('POST', 'https://auth.netatmo.com/access/postlogin', [ 'form_params' => [ 'email' => config::byKey('username', 'netatmopro'), 'password' => config::byKey('password', 'netatmopro'), 'stay_logged' => 'on', '_token' => $wdata['token'] ] ]); $jar->save(jeedom::getTmpFolder('netatmopro') . '/b27536f76a9d4d240a34dbd84bc85085'); } } /* * **********************Getteur Setteur*************************** */ } class netatmoproCmd extends cmd { /* * *************************Attributs****************************** */ /* public static $_widgetPossibility = array(); */ /* * ***********************Methode static*************************** */ /* * *********************Methode d'instance************************* */ /* * Non obligatoire permet de demander de ne pas supprimer les commandes même si elles ne sont pas dans la nouvelle configuration de l'équipement envoyé en JS public function dontRemoveCmd() { return true; } */ // Exécution d'une commande public function execute($_options = array()) { log::add('netatmopro', 'debug', 'execute:: options:' . var_export($_options, true)); log::add('netatmopro', 'debug', 'execute:: this:' . var_export($this, true)); log::add('netatmopro', 'debug', 'execute:: this:' . var_export($this->getConfiguration(), true)); log::add('netatmopro', 'alert', 'Starting task (' . $this->getEqLogic()->getName() . '/' . $this->getName() . ' #' . $this->getId() . ')'); if ( $this->getLogicalId() == 'floodlight' || $this->getLogicalId() == 'monitoring' ) { try { $data = netatmopro::NARequest('POST', 'https://app.netatmo.net/api/setstate', '{"home":{"id":"' . $this->getEqLogic()->getConfiguration('home_id') . '","modules":[{"id":"' . $this->getEqLogic()->getLogicalId() . '","' . $this->getLogicalId() . '":"'. $_options['select'] . '"}]}}'); } catch (Exception $ex) { log::add('netatmopro', 'error', 'execute:: ex:' . var_export(get_class($ex) . ' - ' . $ex->getCode() . ' - ' . $ex->getMessage(), true)); throw $ex; } log::add('netatmopro', 'alert', 'Task finished (' . $this->getEqLogic()->getName() . '/' . $this->getName() . ' #' . $this->getId() . ')'); return; } $options = array( 'changestatus' => [ 'method' => 'GET', 'select' => [ 0 => 'status=off', 1 => 'status=on' ] ], 'floodlight_set_config' => [ 'method' => 'GET', 'select' => [ 0 => 'config=%7B%22mode%22:%22off%22%7D', 1 => 'config=%7B%22mode%22:%22on%22%7D', 2 => 'config=%7B%22mode%22:%22auto%22%7D' ] ], 'presence_record_humans' => [ 'method' => 'POST', 'select' => [ 0 => 'presence_settings%5Bpresence_record_humans%5D=ignore', 1 => 'presence_settings%5Bpresence_record_humans%5D=record', 2 => 'presence_settings%5Bpresence_record_humans%5D=record_and_notify' ] ], 'presence_record_vehicles' => [ 'method' => 'POST', 'select' => [ 0 => 'presence_settings%5Bpresence_record_vehicles%5D=ignore', 1 => 'presence_settings%5Bpresence_record_vehicles%5D=record', 2 => 'presence_settings%5Bpresence_record_vehicles%5D=record_and_notify' ] ], 'presence_record_animals' => [ 'method' => 'POST', 'select' => [ 0 => 'presence_settings%5Bpresence_record_animals%5D=ignore', 1 => 'presence_settings%5Bpresence_record_animals%5D=record', 2 => 'presence_settings%5Bpresence_record_animals%5D=record_and_notify' ] ], 'presence_record_movements' => [ 'method' => 'POST', 'select' => [ 0 => 'presence_settings%5Bpresence_record_movements%5D=ignore', 1 => 'presence_settings%5Bpresence_record_movements%5D=record', 2 => 'presence_settings%5Bpresence_record_movements%5D=record_and_notify' ] ], 'notify_unknowns' => [ 'method' => 'POST', 'select' => [ 0 => 'notify_unknowns=empty', 1 => 'notify_unknowns=always' ] ], 'record_movements' => [ 'method' => 'POST', 'select' => [ 0 => 'record_movements=never', 1 => 'record_movements=empty', 2 => 'record_movements=always', ] ], 'notify_movements' => [ 'method' => 'POST', 'select' => [ 0 => 'notify_movements=never', 1 => 'notify_movements=empty', 2 => 'notify_movements=always', ] ], 'record_alarms' => [ 'method' => 'POST', 'select' => [ 0 => 'record_alarms=never', 1 => 'record_alarms=empty', 2 => 'record_alarms=always', ] ], 'smart_notifs' => [ 'method' => 'POST', 'select' => [ 0 => 'smart_notifs=false', 1 => 'smart_notifs=true', ] ], 'startcalibration' => [ 'method' => 'POST', ], 'setthermmode' => [ 'class' => 'Netatmo\Clients\NATherm2ApiClient', 'select' => [ 0 => 'hg', 1 => 'away', 2 => 'schedule', ], ], 'switchhomeschedule' => [ 'class' => 'Netatmo\Clients\NATherm2ApiClient', ], 'setroomthermpoint' => [ 'class' => 'Netatmo\Clients\NATherm2ApiClient', ], 'cancelroomthermpoint' => [ 'class' => 'Netatmo\Clients\NATherm2ApiClient', ], 'setpersonshome' => [ 'class' => 'Netatmo\Clients\NAWelcomeApiClient', ], 'setpersonsaway' => [ 'class' => 'Netatmo\Clients\NAWelcomeApiClient', ], 'truetemperature' => [ 'method' => 'POST', ], 'setheatingpriority' => [ 'method' => 'POST', 'select' => [ 0 => 'priority=eco', 1 => 'priority=comfort', ], ], ); if ( array_key_exists('method', $options[$this->getLogicalId()]) ) { try { netatmopro::GetGuzzleHd($guzzle, $jar); log::add('netatmopro', 'debug', 'execute:: guzzle:' . var_export($guzzle, true)); log::add('netatmopro', 'debug', 'execute:: jar:' . var_export($jar, true)); if ( $options[$this->getLogicalId()]['method'] === 'GET' ) { $uri = $this->getEqLogic()->getConfiguration('vpn_url') . '/command/' . $this->getLogicalId() . '?' . $options[$this->getLogicalId()]['select'][$_options['select']]; #$uri = str_replace('/restricted', '', $uri); log::add('netatmopro', 'debug', 'execute:: uri:' . var_export($uri, true)); $response = $guzzle->request($options[$this->getLogicalId()]['method'], $uri); } elseif ( $options[$this->getLogicalId()]['method'] === 'POST') { if ( $this->getEqLogic()->getConfiguration('type') == 'NOC' || $this->getEqLogic()->getConfiguration('type') == 'NACamera' ) { $uri = 'https://app.netatmo.net/api/updatehome?home_id=' . $this->getEqLogic()->getConfiguration('home_id') . '&' . $options[$this->getLogicalId()]['select'][$_options['select']]; } elseif ( $this->getEqLogic()->getConfiguration('type') == 'NARoom' ) { $uri = 'https://app.netatmo.net/api/truetemperature?home_id=' . $this->getEqLogic()->getConfiguration('home_id') . '&room_id=' . $this->getEqLogic()->getLogicalId() . '&corrected_temperature=' . $_options['title'] . '¤t_temperature=' . $this->getEqLogic()->getCmd('info', 'therm_measured_temperature')->execCmd(); } elseif ( $this->getEqLogic()->getConfiguration('type') == 'NAPlug' ) { $uri = 'https://app.netatmo.net/api/setheatingpriority?home_id=' . $this->getEqLogic()->getConfiguration('home_id') . '&' . $options[$this->getLogicalId()]['select'][$_options['select']]; } else { $uri = 'https://app.netatmo.net/syncapi/v1/' . $this->getLogicalId() . '?home_id=' . $this->getEqLogic()->getConfiguration('home_id') . '&device_id=' . $this->getEqLogic()->getConfiguration('bridge') . '&module_id=' . $this->getEqLogic()->getLogicalId(); } log::add('netatmopro', 'debug', 'execute:: uri:' . var_export($uri, true)); $response = $guzzle->request($options[$this->getLogicalId()]['method'], $uri, [ 'headers' => [ 'Authorization' => 'Bearer ' . urldecode($jar->getCookieByName('netatmocomaccess_token')->getValue()) ] ]); } } catch (GuzzleHttp\Exception\ClientException $ex) { log::add('netatmopro', 'debug', 'execute:: ex:' . var_export('GuzzleHttp\Exception\ClientException' . ' - ' . get_class($ex) . ' - ' . $ex->getCode() . ' - ' . $ex->getMessage(), true)); if ($ex->getCode() === 409 && (preg_match('/Clienterror:`GEThttps:\/\/.+\/command\/changestatus\?status=off`resultedina`409Conflict`response:{"error":{"code":35,"message":"Alreadyoff"}}/', preg_replace('/\s+/', '', $ex->getMessage())) || preg_match('/Clienterror:`GEThttps:\/\/.+\/command\/changestatus\?status=on`resultedina`409Conflict`response:{"error":{"code":7,"message":"Alreadyon"}}/', preg_replace('/\s+/', '', $ex->getMessage())))) { } else { log::add('netatmopro', 'error', 'execute:: ex:' . var_export('GuzzleHttp\Exception\ClientException' . ' - ' . get_class($ex) . ' - ' . $ex->getCode() . ' - ' . $ex->getMessage(), true)); throw $ex; } } catch (Exception $ex) { log::add('netatmopro', 'error', 'execute:: ex:' . var_export(get_class($ex) . ' - ' . $ex->getCode() . ' - ' . $ex->getMessage(), true)); throw $ex; } } else { $config = array("client_id" => config::byKey('client_id', 'netatmopro'), "client_secret" => config::byKey('client_secret', 'netatmopro'), "access_token" => config::byKey('access_token', 'netatmopro'), "refresh_token" => config::byKey('refresh_token', 'netatmopro'), "expires_at" => config::byKey('expires_at', 'netatmopro'), "scope" => 'read_station read_thermostat write_thermostat read_camera write_camera access_camera read_doorbell access_doorbell read_presence write_presence access_presence read_carbonmonoxidedetector read_smokedetector read_homecoach'); $client = new $options[$this->getLogicalId()]['class']($config); $tokens = $client->getAccessToken(); try { if ( $this->getLogicalId() == 'setthermmode' ) { $client->setThermMode($this->getEqLogic()->getConfiguration('home_id'), $options[$this->getLogicalId()]['select'][$_options['select']]); } elseif ($this->getLogicalId() == 'switchhomeschedule' ) { $client->switchHomeSchedule($_options['select'], $this->getEqLogic()->getConfiguration('home_id')); } elseif ($this->getLogicalId() == 'setroomthermpoint' ) { $client->setRoomThermpoint($this->getEqLogic()->getConfiguration('home_id'), $this->getEqLogic()->getLogicalId(), $_options['title'] ? 'manual' : 'home', $_options['title'] ? $_options['title'] : NULL, ($_options['title'] && $_options['message']) ? (time() + ($_options['message']*60)) : NULL); } elseif ($this->getLogicalId() == 'cancelroomthermpoint' ) { $client->setRoomThermpoint($this->getEqLogic()->getConfiguration('home_id'), $this->getEqLogic()->getLogicalId(), 'home'); } elseif ($this->getLogicalId() == 'setpersonshome' ) { $client->setPersonsHome($this->getEqLogic()->getConfiguration('home_id'), [$this->getEqLogic()->getLogicalId()]); } elseif ($this->getLogicalId() == 'setpersonsaway' ) { $client->setPersonsAway($this->getEqLogic()->getConfiguration('home_id'), $this->getEqLogic()->getConfiguration('type') == 'NACamera' ? NULL : $this->getEqLogic()->getLogicalId()); } } catch (Exception $ex) { log::add('netatmopro', 'error', 'execute:: ex:' . var_export(get_class($ex) . ' - ' . $ex->getCode() . ' - ' . $ex->getMessage(), true)); throw $ex; } } log::add('netatmopro', 'alert', 'Task finished (' . $this->getEqLogic()->getName() . '/' . $this->getName() . ' #' . $this->getId() . ')'); } /* * **********************Getteur Setteur*************************** */ }