sureflap.php

Created Diff never expires
<?php
<?php


/*
/*
indice 1.1 du 19 decembre 2019 par Merguez07
indice 1.1 du 19 decembre 2019 par Merguez07
1.0 : Creation du plugin
1.0 : Creation du plugin
1.1 : integration des chatieres de type door connect
1.1 : integration des chatieres de type door connect
modification de la gestion du cache
modification de la gestion du cache
1.2 : Correction d'un bug dans les led hub et changement d'icone
1.2 : Correction d'un bug dans les led hub et changement d'icone
remerciements :
remerciements :
Bart de Eedomus pour le code de la gestion du cache
Bart de Eedomus pour le code de la gestion du cache
RAR69 pour les icones
RAR69 pour les icones
eedomus.yves.delort pour les beta-tests
eedomus.yves.delort pour les beta-tests
Kebiel pour l'integration du door connect(indice 1.1)
Kebiel pour l'integration du door connect(indice 1.1)
2.0 : Mise à jour vers la nouvelle API :
- nouveau endpoint + header par défaut + suppression de sdk_logout
- réorganisation du xml de sortie pour coller à l'API et limiter les appels :
suppresion de sdk_getpetlocation car déplacement dans l'API du petLocation, car /pet/".$pet_id."/position n'existe plus
suppresion de sdk_getCurfewStatus car déplacement dans l'API ['control']['led_mode'], ['control']['locking'], ['control']['curfew']
*/
*/



$mode = getArg('mode',false); // mode=list pour la configuration du plugin
$mode = getArg('mode',false); // mode=list pour la configuration du plugin


$device_id = (string) rand(1000000000,9999999999);
$device_id = (string) sdk_genuuid();
$endpoint = "https://app.api.surehub.io";
$endpoint = "https://app-api.production.surehub.io";
$logout = "/api/auth/logout";
$url_logout = "/api/auth/logout";
$login = "/api/auth/login";
$url_login = "/api/auth/login";
$household = "/api/household";
$url_household = "/api/household";
$url_device = "/api/device";
$url_pet = "/api/pet";
$header_default = array(
"Host: app.api.surehub.io",
"Connection: keep-alive",
"Accept: application/json, text/plain, */*",
"Accept-Encoding: gzip, deflate",
"Accept-Language: en-US,en-GB;q=0.9",
"Content-Type: application/json",
"Origin: https://surepetcare.io",
"Referer: https://surepetcare.io",
"X-Requested-With: com.sureflap.surepetcare",
"X-Device-Id: ".$device_id
);


//---------------------------config du plugin------------------------------------
//---------------------------config du plugin------------------------------------
if ($mode == 'list') {
if ($mode == 'list') {
if (isset($_POST['email'])&& isset($_POST['motdepasse'])){
if (isset($_POST['email'])&& isset($_POST['motdepasse'])){
$email_address = $_POST['email'];
$email_address = $_POST['email'];
$password = $_POST['motdepasse'];
$password = $_POST['motdepasse'];
saveVariable("email",$email_address);
saveVariable("email",$email_address);
saveVariable("password",$password );
saveVariable("password",$password );
sdk_login();sdk_gethousehold(); sdk_getdevices();sdk_getpet();
sdk_login();sdk_gethousehold(); sdk_getdevices();sdk_getpet();
sdk_inithtml();
sdk_inithtml();
echo utf8_encode($head.$html_hub.$html_flap.$html_pet.$html_script.$end);
echo utf8_encode($head.$html_hub.$html_flap.$html_pet.$html_script.$end);
die();
die();
} else {
} else {
sdk_inithtml();
sdk_inithtml();
echo utf8_encode($head.$html_login.$end);
echo utf8_encode($head.$html_login.$end);
}
}
die;
die;
}
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------


$email_address = loadVariable("email");
$email_address = loadVariable("email");
$password = loadVariable("password");
$password = loadVariable("password");
$set = getArg('set',false); // ledbright/leddim/ledoff
$set = getArg('set',false); // ledbright/leddim/ledoff
// lockin/lockout/lockboth/locknone
// lockin/lockout/lockboth/locknone
// pos1/pos2
// pos1/pos2
// curfew
// curfew


//---------------------------lumiere du Hub-------------------------------------
//---------------------------lumiere du Hub-------------------------------------
$test=sdk_Targ($set,'led');
$test=sdk_Targ($set,'led');
if ($test[0]) {
if ($test[0]) {
$hub_id= getArg('hubid',true);
$hub_id= getArg('hubid',true);
sdk_login();
sdk_login();
sdk_gethousehold();
sdk_gethousehold();
sdk_getdevices();
sdk_getdevices();
sdk_sethubledbrightness($test[1],$hub_id) ;
sdk_sethubledbrightness($test[1],$hub_id) ;
echo $xml;
echo $xml;
die;
die;
}
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------


//--------------------verrouillage de la chatiere--------------------------------
//--------------------verrouillage de la chatiere--------------------------------
$test=sdk_Targ($set,'lock');
$test=sdk_Targ($set,'lock');
if ($test[0]) {
if ($test[0]) {
$flap_id= getArg('flapid',true);
$flap_id= getArg('flapid',true);
sdk_login();
sdk_login();
sdk_gethousehold();
sdk_gethousehold();
sdk_getdevices();
sdk_getdevices();
sdk_setlockmode ($test[1],$flap_id) ;
sdk_setlockmode ($test[1],$flap_id) ;
echo $xml;
echo $xml;
die;
die;
}
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------


//---------------------------position de l'animal--------------------------------
//---------------------------position de l'animal--------------------------------
$test=sdk_Targ($set,'pos');
$test=sdk_Targ($set,'pos');
if ($test[0]) {
if ($test[0]) {
$pet_id= getArg('petid',true);
$pet_id= getArg('petid',true);
sdk_login();
sdk_login();
sdk_setpetlocation($test[1],$pet_id) ;
sdk_setpetlocation($test[1],$pet_id) ;
echo $xml;
echo $xml;
die;
die;
}
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------


//---------------------------reglage du couvre-feu-------------------------------
//---------------------------reglage du couvre-feu-------------------------------
if ($set=="curfew") {
if ($set=="curfew") {
$locktime = getArg('locktime',false);
$locktime = getArg('locktime',false);
$unlocktime = getArg('unlocktime',false);
$unlocktime = getArg('unlocktime',false);
$id = getArg('id',true);
$id = getArg('id',true);
sdk_login();
sdk_login();
sdk_setEnableCurfew($locktime,$unlocktime,$id) ;
sdk_setEnableCurfew($locktime,$unlocktime,$id) ;
echo $xml;
echo $xml;
die;
die;
}
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
$cache_duration = 1; // minutes
$cache_duration = 0.1; // minutes
$time_last_xml = loadVariable('time_last_xml');
$time_last_xml = loadVariable('time_last_xml');
if ((time() - $time_last_xml) / 60 < $cache_duration)
if ((time() - $time_last_xml) / 60 < $cache_duration)
{
{
sdk_header('text/xml');
sdk_header('text/xml');
$cached_xml = loadVariable('cached_xml');
$cached_xml = loadVariable('cached_xml');
echo $cached_xml;
echo $cached_xml;
die();
die();
}
}


//$xml = '<root>' ."\n";
//$xml = '<root>' ."\n";


sdk_login();
sdk_login();
sdk_gethousehold();
sdk_gethousehold();
sdk_getCurfewStatus();
sdk_getdevices();
sdk_getdevices();
sdk_getpet();
sdk_getpet();
sdk_getpetlocation();


//$xml .= '</root>' ."\n";
//$xml .= '</root>' ."\n";


$cached_xml = '<root>';
$cached_xml = '<root>';
$cached_xml .= '<cached>0</cached>';
$cached_xml .= '<cached>0</cached>';
$cached_xml .= $xml;
$cached_xml .= $xml;
$cached_xml .= '</root>';
$cached_xml .= '</root>';


echo $cached_xml;
echo $cached_xml;


if ($xml != '') // non vide
if ($xml != '') // non vide
{
{
$cached_xml = str_replace('<cached>0</cached>', '<cached>1</cached>', $cached_xml);
$cached_xml = str_replace('<cached>0</cached>', '<cached>1</cached>', $cached_xml);
saveVariable('cached_xml', $cached_xml);
saveVariable('cached_xml', $cached_xml);
saveVariable('time_last_xml', time());
saveVariable('time_last_xml', time());
}
}
die;
die;


function sdk_genuuid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}

function sdk_headerTokened(){
global $token,$header_default;
return array_merge($header_default, array("Authorization: Bearer $token"));
}

#---------------------------------------logout---------------------------------------------
#---------------------------------------logout---------------------------------------------
function sdk_logout(){
function sdk_logout(){
global $oldtoken,$endpoint,$logout;
global $oldtoken,$endpoint,$url_logout;
$url = $endpoint.$logout;
$url = $endpoint.$url_logout;
$action = 'GET';
$action = 'GET';
$header = array("Content-Type: application/json",
$header = array("Content-Type: application/json",
"Authorization: Bearer $oldtoken");
"Authorization: Bearer $oldtoken");
$result = sdk_curl($url,$action,null,$header);
$result = sdk_curl($url,$action,null,$header);
}
}
#------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------


#---------------------------------------login----------------------------------------------
#---------------------------------------login----------------------------------------------
function sdk_login(){
function sdk_login(){
global $oldtoken,$email_address,$password,$device_id,
global $oldtoken,$email_address,$password,$device_id,
$endpoint,$login,$token,$xml;
$endpoint,$url_login,$token,$xml,$header_default;
if ($oldtoken = loadVariable("token")) {
if ($oldtoken = loadVariable("token")) {
sdk_logout();
//sdk_logout();
}
}
$url = $endpoint.$login;
$url = $endpoint.$url_login;
$action = 'POST';
$action = 'POST';
$post = '{"email_address":"'.$email_address.'",
$post = '{"email_address":"'.$email_address.'",
"password":"' .$password. '",
"password":"' .$password. '",
"device_id":"' .$device_id. '"}';
"device_id":"' .$device_id. '"}';
$header =array("Content-Type: application/json",
$result =sdk_curl($url,$action,$post,$header_default);
"Content-Length: ".strlen($post)) ;
$result =sdk_curl($url,$action,$post,$header);

if (array_key_exists(token,$result['data'])) {
if (array_key_exists(token,$result['data'])) {
$token = $result['data']['token'];
$token = $result['data']['token'];
saveVariable("token",$token);
saveVariable("token",$token);
$xml .= '<status>' ."success!" .'</status>'."\n";
$xml .= '<status>' ."success!" .'</status>'."\n";
} else {
} else {
$xml .= '<status>' ."Token Invalid/Expired!" .'</status>'."\n";
$xml .= '<status>' ."Token Invalid/Expired!" .'</status>'."\n";
//$xml .= '</root>' ."\n";
//$xml .= '</root>' ."\n";
die("Login Failed!\n");
die("Login Failed!\n");
}
}
}
}
#------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------


#-------------------------------------gethouseold------------------------------------------
#-------------------------------------gethouseold------------------------------------------
function sdk_gethousehold() {
function sdk_gethousehold() {
global $endpoint,$household,$token,$xml,$Thouses;
global $endpoint,$url_household,$xml,$Thouses;
$xml .= '<Houses>'."\n";
$xml .= '<Houses>'."\n";
$Thouses = array();
$Thouses = array();
$url = $endpoint.$household;
$url = $endpoint.$url_household;
$action = 'GET';
$action = 'GET';
$header = array("Authorization: Bearer $token");
$result = sdk_curl($url,$action,null,sdk_headerTokened());
$result = sdk_curl($url,$action,null,$header);
$houses = $result['data'];
$houses = $result['data'];
if($houses) {
if($houses) {
foreach($houses as $house){
foreach($houses as $house){
$Thouses += array($house['id']=>$house['name']);
$Thouses += array($house['id']=>$house['name']);
$xml .= ' <ID'.$house['id'].'>' .$house['name'] .'</ID'.$house['id'].'>'."\n";
$xml .= ' <ID'.$house['id'].'>' .$house['name'] .'</ID'.$house['id'].'>'."\n";
}
}
$xml .= '</Houses>'."\n";
$xml .= '</Houses>'."\n";
} else {
} else {
$xml .= ' <House>' ."No House!" .'</House>'."\n";
$xml .= ' <House>' ."No House!" .'</House>'."\n";
$xml .= '</Houses>'."\n";
$xml .= '</Houses>'."\n";
die("No House!");
die("No House!");
}
}
}
}
#------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------


#---------------------------------------getpet---------------------------------------------
#---------------------------------------getpet---------------------------------------------
function sdk_getpet() {
function sdk_getpet() {
global $endpoint,$household,$token,$xml,$Thouses,$Tpets;
global $endpoint,$url_pet,$xml,$Thouses,$Tpets;
$xml .= '<Pets>'."\n";
$xml .= '<Pets>'."\n";
$Tpets=array();
$Tpets=array();
foreach($Thouses as $house_id=>$house_name) {

$xml .= ' <Pethouse>' .$house_name .'</Pethouse>'."\n";
$url = $endpoint.$url_pet;
$url = $endpoint.$household ."/".$house_id."/pet";
$action = 'GET';
$action = 'GET';
$result = sdk_curl($url,$action,null,sdk_headerTokened());
$header = array("Authorization: Bearer $token");
$pets = $result['data'];
$result = sdk_curl($url,$action,null,$header);
if($pets) {
$pets = $result['data'];
foreach ($pets as $pet) {
if($pets) {
$chien = ($pet['gender'] === 0 )? "Chienne":"Chien";
$compteur=1;
$chat = ($pet['gender'] === 0 )? "Chatte":"Chat";
foreach ($pets as $pet) {
$species= ($pet['species_id'] === 2 )? $chien:$chat;
$chien = ($pet['gender'] === 0 )? "Chienne":"Chien";
$Tpets += array($pet['id']=>$pet['name']);
$chat = ($pet['gender'] === 0 )? "Chatte":"Chat";
$xml .= ' <ID'.$pet['id'].'>' ."\n";
$species= ($pet['species_id'] === 2 )? $chien:$chat;
$xml .= ' <House>' .$Thouses[$pet['household_id']] .'</House>'."\n";
$Tpets += array($pet['id']=>$pet['name']);
$xml .= ' <Species>' .$species .'</Species>'."\n";
$xml .= ' <ID'.$pet['id'].'>' ."\n";
$xml .= ' <Name>' .$pet['name'] .'</Name>'."\n";
$xml .= ' <species>' .$species .'</species>'."\n";
if($pet['position']['where'] == "1") {
$xml .= ' <name>' .$pet['name'] .'</name>'."\n";
$xml .= ' <Location>' ."Inside" .'</Location>'."\n";
$xml .= ' </ID'.$pet['id'].'>' . "\n";
} else {
++$compteur;
$xml .= ' <Location>' ."Outside".'</Location>'."\n";
//Pet Description : $pet['comments']
}
//Pet DOB : substr($pet['date_of_birth'],0,10)
$xml .= ' <LocationSince>'.$pet['position']['since'].'</LocationSince>'."\n";
//Pet Weight : $pet['weight']
$xml .= ' </ID'.$pet['id'].'>' . "\n";
}
}
} else {
} else {
$xml .= ' <Pet>' ."No Pet!" .'</Pet>'."\n";
$xml .= ' <Pet>' ."No Pet!" .'</Pet>'."\n";
}
}
}
$xml .= '</Pets>'."\n";
$xml .= '</Pets>'."\n";
}
}
#------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------


#-------------------------------------getdevices-------------------------------------------
#-------------------------------------getdevices-------------------------------------------
function sdk_getdevices() {
function sdk_getdevices() {
global $endpoint,$household,$token,$xml,$Tflaps,$Thubs, $Thouses, $Trepeaters,
global $endpoint,$url_device,$xml,$Tflaps,$Thubs, $Thouses, $Trepeaters,$Tfeeder_connects,$Tprogrammers ;
$Tdoor_connects,$Tfeeder_connects,$Tprogrammers,$Thub_leds,$Tcurfews,$Tflap_lock ;
$xml .= '<Devices>'."\n";
$xml .= '<Devices>'."\n";
$Tflaps = array();$Thubs = array();$Trepeaters= array() ;$Tdoor_connects= array();
$Tflaps = array();$Thubs = array();$Trepeaters= array() ;
$Tfeeder_connects= array();$Tprogrammers= array();
$Tfeeder_connects= array();$Tprogrammers= array();
foreach($Thouses as $house_id=>$house_name) {
$xml .= ' <Devicehouse>' .$house_name .'</Devicehouse>'."\n";
$url = $endpoint.$household."/".$house_id."/device";
$action = 'GET';
$header = array("Authorization: Bearer $token");
$result = sdk_curl($url,$action,null,$header);
$devices= $result['data'];
if ($devices) {
foreach ($devices as $device) {
switch($device['product_id']) {
case 1:
$Thubs += array($device['id']=>$device['name']);
$DeviceType = "Hub";
break;
case 2:
$Trepeaters += array($device['id']=>$device['name']);
$DeviceType = "Repeater";
break;
case 3:
//$Tdoor_connects += array($device['id']=>$device['name']);
$Tflaps += array($device['id']=>$device['name']);
$DeviceType = "Pet Door Connect";
break;
case 4:
$Tfeeder_connects += array($device['id']=>$device['name']);
$DeviceType = "Pet Feeder Connect";
break;
case 5:
$Tprogrammers += array($device['id']=>$device['name']);
$DeviceType = "Programmer";
break;
case 6:
$Tflaps += array($device['id']=>$device['name']);
$DeviceType = "DualScan Cat Flap Connect";
break;
}
if (array_key_exists(serial_number,$device)) $DeviceSN = $device['serial_number']; else $DeviceSN = "";
$xml .= ' <ID'.$device['id'].">\n";
$xml .= ' <type>' .$DeviceType .'</type>'."\n";
$xml .= ' <Name>' .$device['name'] .'</Name>'."\n";
$xml .= ' <Mac>' .$device['mac_address'] .'</Mac>' ."\n";
$xml .= ' <Battery>' .$device['battery'] .'</Battery>' ."\n";
$xml .= ' <SN>' .$DeviceSN .'</SN>' ."\n";
if ($DeviceType == "Hub") {
$Tled=array(1=>"Bright", 4=>"Dim", 0=>"Off");
$xml .= ' <Led>'.$Tled[$Thub_leds[$device['id']]].'</Led>' ."\n";
}
if (array_key_exists($device['id'],$Tcurfews)){
if (array_key_exists(0,$Tcurfews[$device['id']])) {
for ($i = 0; $i < count($Tcurfews[$device['id']]); $i++) {
$etat= ($Tcurfews[$device['id']][$i]['enabled'])? "Enabled":"Disabled";
$xml .= ' <curfew'.($i+1).'>' .$etat .'</curfew'.($i+1).'>' ."\n";
if ($etat=="enabled") {
$Curfew_LockTime = $Tcurfews[$device['id']][$i]['lock_time'];
$Curfew_UnlockTime = $Tcurfews[$device['id']][$i]['unlock_time'];
$xml .= ' <LockTime>' .$Curfew_LockTime .'</LockTime>' ."\n";
$xml .= ' <UnLockTime>' .$Curfew_UnlockTime .'</UnLockTime>' ."\n";
}
}
} else {
// $xml .= ' <curfew1>Disabled</curfew1>' ."\n";
$etat= ($Tcurfews[$device['id']]['enabled'])? "Enabled":"Disabled";
$xml .= ' <curfew'.($i+1).'>' .$etat .'</curfew'.($i+1).'>' ."\n";
if ($etat=="enabled") {
$Curfew_LockTime = $Tcurfews[$device['id']]['lock_time'];
$Curfew_UnlockTime = $Tcurfews[$device['id']]['unlock_time'];
$xml .= ' <LockTime>' .$Curfew_LockTime .'</LockTime>' ."\n";
$xml .= ' <UnLockTime>' .$Curfew_UnlockTime .'</UnLockTime>' ."\n";
}
}
}
if (array_key_exists($device['id'],$Tflap_lock)){
$Tlock=array(2=>"In", 1=>"Out", 3=>"Both",0=>"None");
$xml .= ' <Lock>' .$Tlock[$Tflap_lock[$device['id']]] .'</Lock>' ."\n";
}
$xml .= ' </ID'.$device['id'].'>' ."\n";
}
} else {
$xml .= ' <Device>' ."No Device!" .'</Device>'."\n";
}
}
$xml .= '</Devices>'."\n";
}


#--------------------------------------getCurfewStatus----------------------------------------
$url = $endpoint.$url_device;
function sdk_getCurfewStatus(){
$action = 'GET';
global $endpoint,$household,$token,$xml,$Thouses,$Thub_leds,$Tcurfews,$Tflap_lock ;
$result = sdk_curl($url,$action,null,sdk_headerTokened());
$Thub_leds = array();
$devices= $result['data'];
$Tcurfews = array();
if ($devices) {
$Tflap_lock = array();
foreach ($devices as $device) {
foreach($Thouses as $house_id=>$house_name) {
switch($device['product_id']) {
$url = $endpoint.$household."/".$house_id."/device?with[]=control";
case 1:
$action = 'GET';
$Thubs += array($device['id']=>$device['name']);
$header = array("Authorization: Bearer $token");
$DeviceType = "Hub";
$result = sdk_curl($url,$action,null,$header);
break;
$CurfewStatus = $result['data'];
case 2:
if($CurfewStatus) {
$Trepeaters += array($device['id']=>$device['name']);
foreach($CurfewStatus as $Tdevice ) {
$DeviceType = "Repeater";
if (array_key_exists(led_mode,$Tdevice['control'])){
break;
$Thub_leds += array($Tdevice['id']=>$Tdevice['control']['led_mode']);
case 3:
}
$Tflaps += array($device['id']=>$device['name']);
if (array_key_exists(locking,$Tdevice['control'])){
$DeviceType = "Pet Door Connect";
$Tflap_lock += array($Tdevice['id']=>$Tdevice['control']['locking']);
break;
}
case 4:
if (array_key_exists(curfew,$Tdevice['control'])){
$Tfeeder_connects += array($device['id']=>$device['name']);
$Tcurfews += array($Tdevice['id']=>$Tdevice['control']['curfew']);
$DeviceType = "Pet Feeder Connect";
}
break;
}
case 5:
}
$Tprogrammers += array($device['id']=>$device['name']);
}
$DeviceType = "Programmer";
break;
case 6:
$Tflaps += array($device['id']=>$device['name']);
$DeviceType = "DualScan Cat Flap Connect";
break;
}
if (array_key_exists(serial_number,$device)) $DeviceSN = $device['serial_number']; else $DeviceSN = "";
$xml .= ' <ID'.$device['id'].">\n";
$xml .= ' <House>' .$Thouses[$device['household_id']] .'</House>'."\n";
$xml .= ' <Type>' .$DeviceType .'</Type>'."\n";
$xml .= ' <Name>' .$device['name'] .'</Name>'."\n";
$xml .= ' <Mac>' .$device['mac_address'] .'</Mac>' ."\n";
$xml .= ' <SN>' .$DeviceSN .'</SN>' ."\n";
if (array_key_exists(status,$device)) {
if (array_key_exists(battery,$device['status'])) {
$xml .= ' <Battery>' .$device['status']['battery'] .'</Battery>' ."\n";
}
if (array_key_exists(locking,$device['status'])) {
if (array_key_exists(mode,$device['status'])) {
$Tlock=array(2=>"In", 1=>"Out", 3=>"Both",0=>"None");
$xml .= ' <Lock>' .$Tlock[$device['status']['locking']['mode']] .'</Lock>' ."\n";
}
}
if (array_key_exists(led_mode,$device['status'])) {
$Tled=array(1=>"Bright", 4=>"Dim", 0=>"Off");
$xml .= ' <Led>' .$Tled[$device['status']['led_mode']] .'</Led>' ."\n";
}
}
if (array_key_exists(control,$device)) {
if (array_key_exists(curfew,$device['control'])) {
if (array_key_exists(0,$device['control']['curfew'])) {
for ($i = 0; $i < count($device['control']['curfew']); $i++) {
$etat= ($device['control']['curfew'][$i]['enabled'])? "Enabled":"Disabled";
$xml .= ' <curfew'.($i+1).'>' .$etat .'</curfew'.($i+1).'>' ."\n";
if ($etat=="Enabled") {
$Curfew_LockTime = $device['control']['curfew'][$i]['lock_time'];
$Curfew_UnlockTime = $device['control']['curfew'][$i]['unlock_time'];
$xml .= ' <LockTime>' .$Curfew_LockTime .'</LockTime>' ."\n";
$xml .= ' <UnLockTime>' .$Curfew_UnlockTime .'</UnLockTime>' ."\n";
}
}
} else {
$etat= ($device['control']['curfew']['enabled'])? "Enabled":"Disabled";
$xml .= ' <curfew'.($i+1).'>' .$etat .'</curfew'.($i+1).'>' ."\n";
if ($etat=="Enabled") {
$Curfew_LockTime = $device['control']['curfew']['lock_time'];
$Curfew_UnlockTime = $device['control']['curfew']['unlock_time'];
$xml .= ' <LockTime>' .$Curfew_LockTime .'</LockTime>' ."\n";
$xml .= ' <UnLockTime>' .$Curfew_UnlockTime .'</UnLockTime>' ."\n";
}
}
}
}
$xml .= ' </ID'.$device['id'].'>' ."\n";
}
} else {
$xml .= ' <Device>' ."No Device!" .'</Device>'."\n";
}
$xml .= '</Devices>'."\n";
}
}
#---------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------

#--------------------------------------getpetlocation-----------------------------------------
function sdk_getpetlocation(){
global $endpoint,$Tpets,$token,$xml ;
$xml .= '<PetLocations>'."\n";
foreach($Tpets as $pet_id=>$pet_name) {
$url = $endpoint."/api/pet/".$pet_id."/position";
$action = 'GET';
$header = array("Authorization: Bearer $token");
$result = sdk_curl($url,$action,null,$header);
$PetLocation = $result['data'];
if($PetLocation) {
if($PetLocation['where'] == "1") {
$xml .= ' <ID'.$pet_id.'>' ."Inside" .'</ID'.$pet_id.'>'."\n";
} else {
$xml .= ' <ID'.$pet_id.'>' ."Outside".'</ID'.$pet_id.'>'."\n";
}
} else {
$xml .= ' <ID'.$pet_id.'>' ."No location!" .'</ID'.$pet_id.'>'."\n";
}
}
$xml .= '</PetLocations>'."\n";
}
#---------------------------------------------------------------------------------------------


#-----------------------------sethubledbrightness bright|dim|off-----------------------------
#-----------------------------sethubledbrightness bright|dim|off-----------------------------
function sdk_sethubledbrightness($led,$hub_id) {
function sdk_sethubledbrightness($led,$hub_id) {
global $endpoint,$Thubs,$token,$xml ;
global $endpoint,$Thubs,$xml ;
$xml = '<root>' ."\n";
$xml = '<root>' ."\n";
switch($led) {
switch($led) {
case "bright":
case "bright":
$ledN = 1;
$ledN = 1;
break;
break;
case "dim":
case "dim":
$ledN = 4;
$ledN = 4;
break;
break;
case "off":
case "off":
$ledN = 0;
$ledN = 0;
break;
break;
default:
default:
$ledN = null;
$ledN = null;
}
}
if (isset($ledN)) {
if (isset($ledN)) {
$post = "{\"led_mode\":$ledN}";
$post = "{\"led_mode\":$ledN}";
$url = $endpoint."/api/device/$hub_id/control";
$url = $endpoint."/api/device/$hub_id/control";
$action ='PUT';
$action ='PUT';
$header = array("Content-Type: application/json",
$result = sdk_curl($url,$action,$post,sdk_headerTokened());
"Content-Length: ".strlen($post),
"Authorization: Bearer $token");
$result = sdk_curl($url,$action,$post,$header);
if($result['data']['led_mode']==$ledN) {
if($result['data']['led_mode']==$ledN) {
$hubname=$Thubs[$hub_id];
$hubname=$Thubs[$hub_id];
$xml .= sdk_framed('<action>' ."Successfully Set \"$hubname\" LED Brightness! \"$led\"" .'</action>');
$xml .= sdk_framed('<action>' ."Successfully Set \"$hubname\" LED Brightness! \"$led\"" .'</action>');
} else {
} else {
$xml .= sdk_framed('<action>' ."LED Brightness Change Failed!" .'</action>');
$xml .= sdk_framed('<action>' ."LED Brightness Change Failed!" .'</action>');
}
}
} else {
} else {
$xml .= sdk_framed('<action>' ."wrong parameter \"$led\"==> reminder: &ledbright ou &leddim ou &ledoff" .'</action>');
$xml .= sdk_framed('<action>' ."wrong parameter \"$led\"==> reminder: &ledbright ou &leddim ou &ledoff" .'</action>');
}
}
$xml .= '</root>' ."\n";
$xml .= '</root>' ."\n";
}
}
#---------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------


#------------------------------setlockmode(in|out|both|none,$flap_id)-------------------------
#------------------------------setlockmode(in|out|both|none,$flap_id)-------------------------
function sdk_setlockmode ($lock,$flap_id) {
function sdk_setlockmode ($lock,$flap_id) {
global $endpoint,$Tflaps,$token,$xml ;
global $endpoint,$Tflaps,$xml ;
$xml = '<root>' ."\n";
$xml = '<root>' ."\n";
switch($lock) {
switch($lock) {
case "in":
case "in":
$lockN = 2;
$lockN = 2;
break;
break;
case "out":
case "out":
$lockN = 1;
$lockN = 1;
break;
break;
case "both":
case "both":
$lockN = 3;
$lockN = 3;
break;
break;
case "none":
case "none":
$lockN = 0;
$lockN = 0;
break;
break;
default:
default:
$lockN = -1;
$lockN = -1;
}
}
if (!($lockN==-1)) {
if (!($lockN==-1)) {
$post = "{\"locking\":\"$lockN\"}";
$post = "{\"locking\":\"$lockN\"}";
$url = $endpoint."/api/device/$flap_id/control";
$url = $endpoint."/api/device/$flap_id/control";
$action = 'PUT';
$action = 'PUT';
$header = array("Content-Type: application/json",
$result =sdk_curl($url,$action,$post,sdk_headerTokened());
"Content-Length: ".strlen($post),
"Authorization: Bearer $token");
$result =sdk_curl($url,$action,$post,$header);
if($result['data']['locking']==$lockN) {
if($result['data']['locking']==$lockN) {
$flap_name = $Tflaps[$flap_id];
$flap_name = $Tflaps[$flap_id];
$xml .= sdk_framed('<action>' ."Successfully Set \"$flap_name\" Lock Mode! \"$lock\"" .'</action>');
$xml .= sdk_framed('<action>' ."Successfully Set \"$flap_name\" Lock Mode! \"$lock\"" .'</action>');
} else {
} else {
$xml .= sdk_framed('<action>' ."Lock Mode Change Failed!" .'</action>');
$xml .= sdk_framed('<action>' ."Lock Mode Change Failed!" .'</action>');
}
}
} else {
} else {
$xml .= sdk_framed('<action>' ."wrong parameter \"$lock\"==> reminder: &set=lockin|&set=lockout|&set=lockboth|&set=locknone" .'</action>');
$xml .= sdk_framed('<action>' ."wrong parameter \"$lock\"==> reminder: &set=lockin|&set=lockout|&set=lockboth|&set=locknone" .'</action>');
}
}
$xml .= '</root>' ."\n";
$xml .= '</root>' ."\n";
}
}
#---------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------


#-------------------------setpetlocation(1(inside)|2(outside),$pet_id)------------------------
#-------------------------setpetlocation(1(inside)|2(outside),$pet_id)------------------------
function sdk_setpetlocation($position,$pet_id){
function sdk_setpetlocation($position,$pet_id){
global $endpoint,$token,$xml ;
global $endpoint,$xml ;
$xml = '<root>' ."\n";
$xml = '<root>' ."\n";
$date= date("Y-m-d H:i");
$date= date("Y-m-d H:i");
$post = "{\"where\":\"$position\",\"since\":\"$date\"}";
$post = "{\"where\":\"$position\",\"since\":\"$date\"}";
$url = $endpoint."/api/pet/$pet_id/position";
$url = $endpoint."/api/pet/$pet_id/position";
$action = 'POST';
$action = 'POST';
$header = array("Content-Type: application/json",
$result =sdk_curl($url,$action,$post,sdk_headerTokened());
"Content-Length: ".strlen($post),
"Authorization: Bearer $token");
$result =sdk_curl($url,$action,$post,$header);
if(!$result['error']){
if(!$result['error']){
if($result['data']['where']==$position) {
if($result['data']['where']==$position) {
$Tposition=($position==1)? "inside":"outside";
$Tposition=($position==1)? "inside":"outside";
$xml .= sdk_framed('<action>' ."Successfully Set \"$pet_id\" location \"$Tposition\"!" .'</action>');
$xml .= sdk_framed('<action>' ."Successfully Set \"$pet_id\" location \"$Tposition\"!" .'</action>');
} else {
} else {
$xml .= sdk_framed('<action>' ."Set Location Failed" .'</action>');
$xml .= sdk_framed('<action>' ."Set Location Failed" .'</action>');
}
}
} else {
} else {
$xml .= sdk_framed('<action>' ."pet not found" .'</action>');
$xml .= sdk_framed('<action>' ."pet not found" .'</action>');
}
}
$xml .= '</root>' ."\n";
$xml .= '</root>' ."\n";
}
}
#---------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------


#-----------------------setEnableCurfew("18:00", "06:00",$device_id)--------------------------------------------
#-----------------------setEnableCurfew("18:00", "06:00",$device_id)--------------------------------------------

function sdk_setEnableCurfew($locktime, $unlocktime,$device_id) {
function sdk_setEnableCurfew($locktime, $unlocktime,$device_id) {
global $endpoint,$token,$xml ;
global $endpoint,$xml ;
$xml = '<root>' ."\n";
$xml = '<root>' ."\n";
$set = (($locktime)&&($unlocktime));
$set = (($locktime)&&($unlocktime));
$set1= ($set)?"true":"false";
$set1= ($set)?"true":"false";
$post = "{\"curfew\":[{\"enabled\":$set1,\"lock_time\":\"$locktime\",\"unlock_time\":\"$unlocktime\"},[],[]]}" ;
$post = "{\"curfew\":[{\"enabled\":$set1,\"lock_time\":\"$locktime\",\"unlock_time\":\"$unlocktime\"},[],[]]}" ;
$url = $endpoint."/api/device/$device_id/control";
$url = $endpoint."/api/device/$device_id/control";
$action = 'PUT';
$action = 'PUT';
$header = array("Content-Type: application/json",
$result =sdk_curl($url,$action,$post,sdk_headerTokened(),$set);
"Content-Length: ".strlen($post),
"Authorization: Bearer $token");
$result =sdk_curl($url,$action,$post,$header,$set);
if($result['data']['curfew'][0]['enabled']==true) {
if($result['data']['curfew'][0]['enabled']==true) {
$xml .= sdk_framed('<action>' ."Successfully Enabled Curfew For \"$DeviceName\" Between $locktime & $unlocktime" .'</action>');
$xml .= sdk_framed('<action>' ."Successfully Enabled Curfew For \"$DeviceName\" Between $locktime & $unlocktime" .'</action>');
} else {
} else {
$xml .= sdk_framed('<action>' ."Successfully disabled Curfew!" .'</action>');
$xml .= sdk_framed('<action>' ."Successfully disabled Curfew!" .'</action>');
}
}
$xml .= '</root>' ."\n";
$xml .= '</root>' ."\n";
}
}
#---------------------------------------------------------------------------------------------


function sdk_Targ($arg,$text){
function sdk_Targ($arg,$text){
#$arg='pos1' et $text='pos' --> array(true,1)
#$arg='pos1' et $text='pos' --> array(true,1)
$Targ[0] = (substr($arg,0,strlen($text))==$text);
$Targ[0] = (substr($arg,0,strlen($text))==$text);
$Targ[1] = substr($arg,-(strlen($arg)-strlen($text)));
$Targ[1] = substr($arg,-(strlen($arg)-strlen($text)));
return $Targ;
return $Targ;
}
}


function sdk_Utf8_ansi($text) {
function sdk_Utf8_ansi($text) {
#remet en forme $text pour voir les accents
#remet en forme $text pour voir les accents
$text = str_replace('\u','u',$text);
$text = str_replace('\u','u',$text);
$text = preg_replace('/u([\da-fA-F]{4})/', '&#x\1;', $text);
$text = preg_replace('/u([\da-fA-F]{4})/', '&#x\1;', $text);
$text = sdk_json_decode($text);
$text = sdk_json_decode($text);
return $text;
return $text;
}
}


function sdk_since($time){
function sdk_since($time){
#donne le temps ecoule depuis $time
#donne le temps ecoule depuis $time
$duration = strtotime(date("Y-m-d H:i:s", time()))-strtotime($time);
$duration = strtotime(date("Y-m-d H:i:s", time()))-strtotime($time);
switch (true) {
switch (true) {
case $duration < 60:
case $duration < 60:
return $duration." s";
return $duration." s";
case $duration < 3600:
case $duration < 3600:
return floor($duration/60)." min";
return floor($duration/60)." min";
case $duration < 86400:
case $duration < 86400:
return floor($duration/3600)." h";
return floor($duration/3600)." h";
case $duration < 172800:
case $duration < 172800:
return "1 jour";
return "1 jour";
case $duration < 2592000:
case $duration < 2592000:
return floor($duration/86400)." jours";
return floor($duration/86400)." jours";
case $duration < 5184000:
case $duration < 5184000:
return "1 mois";
return "1 mois";
case $duration < 31536000:
case $duration < 31536000:
return floor($duration/2592000)." mois";
return floor($duration/2592000)." mois";
case $duration < 63072000:
case $duration < 63072000:
return "1 an";
return "1 an";
case $duration > 63071999:
case $duration > 63071999:
return floor($duration/31536000)." annees";
return floor($duration/31536000)." annees";
default:
default:
}
}
}
}


function sdk_only_letters($text){
function sdk_only_letters($text){
#ne garde que les lettres du debut de $text
#ne garde que les lettres du debut de $text
$text = substr($text,0,sdk_getPosInteger($text));
$text = substr($text,0,sdk_getPosInteger($text));
$text = preg_replace('`[0-9. ]`sm', '', $text);
$text = preg_replace('`[0-9. ]`sm', '', $text);
return $text;
return $text;
}
}


function sdk_getPosInteger($text) {
function sdk_getPosInteger($text) {
#donne la position du premier chiffre dans $text
#donne la position du premier chiffre dans $text
$i = 0;
$i = 0;
$nLen = strlen($text);
$nLen = strlen($text);
while ($i<$nLen) {
while ($i<$nLen) {
if ( is_numeric( $text[$i] ) ) break;
if ( is_numeric( $text[$i] ) ) break;
$i++;
$i++;
}
}
return $i;
return $i;
}
}


function sdk_curl($url,$action,$post,$header){
function sdk_curl($url,$action,$post,$header){
$response = httpQuery( $url = $url,
$response = httpQuery( $url = $url,
$action = $action,
$action = $action,
$post = $post,
$post = $post,
$oauth_token = null,
$oauth_token = null,
$header = $header,
$header = $header,
$use_cookies = false,
$use_cookies = false,
$ignore_errors = false,
$ignore_errors = false,
$info = null);
$info = null);
$result = sdk_Utf8_ansi($response);
$result = sdk_Utf8_ansi($response);
return $result;
return $result;
}
}


function sdk_framed($text){
function sdk_framed($text){
$text="#".$text."#";
$text="#".$text."#";
$nLen = strlen($text);
$nLen = strlen($text);
$text="\n".str_repeat("#", $nLen)."\n".$text."\n".str_repeat("#", $nLen)."\n"."\n";
$text="\n".str_repeat("#", $nLen)."\n".$text."\n".str_repeat("#", $nLen)."\n"."\n";
return $text;
return $text;
}
}


function sdk_inithtml() {
function sdk_inithtml() {
global $head,$html_login,$html_hub,$html_flap,$html_pet,$html_script,$end,$Thubs,$Tflaps,$Tpets,$Tdoor_connects;
global $head,$html_login,$html_hub,$html_flap,$html_pet,$html_script,$end,$Thubs,$Tflaps,$Tpets;


$head = "<html>".
$head = "<html>".
"<head>".
"<head>".
"<meta charset='UTF-8'>".
"<meta charset='UTF-8'>".
"<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'>".
"<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'>".
"<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>".
"<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>".
"<style>".
"<style>".
"body {font-size: 14px;font-family: 'Roboto', sans-serif;width:50%;}".
"body {font-size: 14px;font-family: 'Roboto', sans-serif;width:50%;}".
"body {font-size: 14px;font-family: 'Roboto', sans-serif;width:50%;}".
"body {font-size: 14px;font-family: 'Roboto', sans-serif;width:50%;}".
"input[type='text'] {font-family: 'Roboto', sans-serif;}".
"input[type='text'] {font-family: 'Roboto', sans-serif;}".
"ul {list-style: symbols;}".
"ul {list-style: symbols;}".
"</style>".
"</style>".
"</head>".
"</head>".
"<body>".
"<body>".
"<img src='https://www.surepetcare.io/assets/images/onboarding/Sure_Petcare_Logo.png' alt='sure petcare' style='width:50%;' /><br />";
"<img src='https://www.surepetcare.io/assets/images/onboarding/Sure_Petcare_Logo.png' alt='sure petcare' style='width:50%;' /><br />";
$html_login = "<p> Veuillez taper vos identifiants Sure Petcare</p>".
$html_login = "<p> Veuillez taper vos identifiants Sure Petcare</p>".
"<form action='/script/?exec=sureflap.php&mode
"<form action='/script/?exec=sureflap.php&mode=list' method='post'>".
"<p>";
$email =(loadVariable('email'))?loadVariable('email'):"";
$password=(loadVariable('password'))?loadVariable('password'):"";
$html_login .= "<input type='text' size='60' placeholder='votre email' name='email' value='$email' /><br /><br />".
"<input type='password' size='20' placeholder='votre mot de passe' name='motdepasse' value='$password' /><br /><br />".
"<input type='submit' value='Valider' />".
"</p>".
"</form>";

$html_hub = "<div class='wrapper'>".
"<p>identifiant de votre Hub : ".
"<input id='hub_id' type='text' size='20' name='device_list' class='inputChoice' value='' onclick='this.select();' >".
"<ul class='elements'>";
foreach ($Thubs as $hubid=>$hubname){
$html_hub.= "<li><input type='radio' name='hub_list' class='inputRadio' value='$hubid' id=''>".$hubid."-".$hubname."<br /></li>";
}
$html_hub.= "</ul>".
"</p>".
"</div>";
$html_flap= "<div class='wrapper'>".
"<p>identifiant de votre chatiere : ".
"<input id='flap_id' type='text' size='20' name='device_list' class='inputChoice' value='' onclick='this.select();' >".
"<ul class='elements'>";
foreach ($Tflaps as $flapid=>$flapname){
$html_flap .="<li><input type='radio' name='flap_list' class='inputRadio' value='$flapid' id=''>".$flapid."-".$flapname."<br /></li>";
}
$html_flap.= "</ul>".
"</p>".
"</div>";
$html_pet = "<div class='wrapper'>".
"<p>identifiant de votre animal : ".
"<input id='pet_id' type='text' size='20' name='device_list' class='inputChoice' value='' onclick='this.select();' >".
"<ul class='elements'>";
foreach ($Tpets as $petid=>$petname){
$html_pet .="<li><input type='radio' name='pet_list' class='inputRadio' value='$petid' id=''>".$petid."-".$petname."<br /></li>";
}
$html_pet.= "</ul>".
"</p>".
"</div>";
$html_script= "<script type='text/javascript'>".
"$('html').on('click','.inputRadio', function(e) {".
"$(this).closest('.wrapper').find('.inputChoice').val($(this).val());".
"});".
"</script>";
$end = "</body>".
"</html>";
return;
}