Skip to content

Commit

Permalink
Merge branch 'release/1.1.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
sabinus52 committed Jan 7, 2021
2 parents b89832c + 7d85357 commit f2e8b75
Show file tree
Hide file tree
Showing 25 changed files with 210 additions and 7 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

### v1.1.0 - 07/01/2021

- Save token in the file system


### v1.0.1 - 19/11/2020

- Library `PhpColors` frozen version in 0.*
Expand Down
Empty file modified LICENSE
100644 → 100755
Empty file.
6 changes: 4 additions & 2 deletions README.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ use Sabinus\TuyaCloudApi\Session\Session;
use Sabinus\TuyaCloudApi\Session\Platform;

$session = new Session($argv[1], $argv[2], '33', Platform::SMART_LIFE, 5.0);
// FACULTATIF : Change le dossier de stockage du jeton, par défaut dans sys_get_temp_dir()
$session->setFolderStorePool('/tmp');

// Initialize object API
$api = new TuyaCloudApi($session);
Expand All @@ -44,12 +46,12 @@ $device->activate($api);


/**
* Prise : Méthodfe 1
* Prise : Méthode 1
*/
$device = $api->getDeviceById('012345678901234598');
// Allume la prise
$rep = $api->sendEvent($device->getTurnOnEvent());
// Mets à jour l'objet pour récupér le dernier état
// Mets à jour l'objet pour récupérer le dernier état
$device->update($api);
print 'Etat : ' . $device->getState();

Expand Down
3 changes: 2 additions & 1 deletion composer.json
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"require": {
"php": "^5.2||^7",
"guzzlehttp/guzzle": "6.5.0",
"mexitek/phpcolors": "0.*"
"mexitek/phpcolors": "0.*",
"symfony/filesystem": "3.*"
},
"autoload": {
"psr-4" : {
Expand Down
Empty file modified phpunit.xml
100644 → 100755
Empty file.
Empty file modified src/Device/ClimateDevice.php
100644 → 100755
Empty file.
Empty file modified src/Device/CoverDevice.php
100644 → 100755
Empty file.
Empty file modified src/Device/Device.php
100644 → 100755
Empty file.
Empty file modified src/Device/DeviceEvent.php
100644 → 100755
Empty file.
Empty file modified src/Device/DeviceFactory.php
100644 → 100755
Empty file.
Empty file modified src/Device/DeviceInterface.php
100644 → 100755
Empty file.
Empty file modified src/Device/LightDevice.php
100644 → 100755
Empty file.
Empty file modified src/Device/SceneDevice.php
100644 → 100755
Empty file.
Empty file modified src/Device/SwitchDevice.php
100644 → 100755
Empty file.
Empty file modified src/Device/UnknownDevice.php
100644 → 100755
Empty file.
Empty file modified src/Session/Platform.php
100644 → 100755
Empty file.
38 changes: 36 additions & 2 deletions src/Session/Session.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\UriResolver;
use Sabinus\TuyaCloudApi\Tools\TokenPool;


class Session
Expand Down Expand Up @@ -65,6 +66,13 @@ class Session
*/
private $token;

/**
* Pool du jeton de connexion Tuya
*
* @var TokenPool
*/
private $tokenPool;

/**
* Valeur du timeout en secondes
*
Expand All @@ -89,6 +97,7 @@ public function __construct($username, $password, $country, $biztype = null, $ti
$this->countryCode = $country;
$this->platform = new Platform($biztype);
$this->token = new Token();
$this->tokenPool = new TokenPool();
$this->timeout = $timeout;
$this->client = $this->_createClient();
}
Expand All @@ -101,9 +110,21 @@ public function __construct($username, $password, $country, $biztype = null, $ti
*/
public function getToken()
{
if ( !$this->token->has() ) {
$this->token = $this->tokenPool->fetchTokenFromCache();

if ( is_null($this->token) ) {
// Pas de token sauvegardé sur le FS
$this->token = new Token();
$this->_createToken();
} else {
// Token sauvegardé trouvé mais vérifie que celui-ci ne soit pas vide et bien un objet Token
if ( ! $this->token instanceof Token || ! $this->token->has() ) {
$this->token = new Token();
$this->_createToken();
}
}

// Rafrachit le jeton s'il n'est plus valide
if ( !$this->token->isValid() ) {
$this->_refreshToken();
}
Expand Down Expand Up @@ -155,8 +176,9 @@ private function _createToken()
$response = json_decode((string) $response->getBody(), true);
$this->checkResponse($response, 'Failed to get a token');

// Affecte le résultat dans le token
// Affecte le résultat dans le token et le sauvegarde
$this->token->set($response);
$this->tokenPool->storeTokenInCache($this->token);

// La valeur du token retoune la region pour indiquer sur quelle plateforme, on doit se connecter
$this->platform->setRegionFromToken($this->token->get());
Expand All @@ -182,6 +204,7 @@ private function _refreshToken()

// Affecte le résultat dans le token
$this->token->set($response);
$this->tokenPool->storeTokenInCache($this->token);
}


Expand All @@ -203,4 +226,15 @@ public function checkResponse($response, $message = null)
}
}


/**
* Change le dossier de sauvegarde du token
*
* @param String $folder
*/
public function setFolderStorePool($folder)
{
$this->tokenPool->setFolder($folder);
}

}
Empty file modified src/Session/Token.php
100644 → 100755
Empty file.
Empty file modified src/Tools/Color.php
100644 → 100755
Empty file.
121 changes: 121 additions & 0 deletions src/Tools/TokenPool.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
<?php
/**
* Librairie du pooler de stockage du token Tuya via le système de fichier
*
* @author Olivier <[email protected]>
*
* @package TuyaCloudApi
*/

namespace Sabinus\TuyaCloudApi\Tools;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
use Symfony\Component\Filesystem\Exception\IOException;


class TokenPool
{

const TOKEN_FILE = 'tuya.token';


/**
* @var Filesystem
*/
private $filesystem;

/**
* Chemin contenant le fichier du token
*
* @var String
*/
private $folder;


/**
* Constructeur
*
* @param String $folder
*/
public function __construct($folder = null)
{
$this->folder = (empty($folder)) ? sys_get_temp_dir() : $folder;

$this->filesystem = new FileSystem();
}


/**
* Change l'emplacement du dossier
*
* @param String $folder
*/
public function setFolder($folder)
{
$this->folder = $folder;
}


/**
* Retourne la valeur du token sauvegardé depuis le système de fichier
*
* @return Token
*/
public function fetchTokenFromCache()
{
$file = $this->getFilePath();

try {
$token = @unserialize(@file_get_contents($file));
if ($token === false) {
return null;
}
} catch (FileNotFoundException $e) {
return null;
}

return $token;
}


/**
* Enregistre le token sur le système de fichier
*
* @param Token $token
*/
public function storeTokenInCache($token)
{
$data = serialize($token);
$file = $this->getFilePath();

if (false === @file_put_contents($file, $data)) {
throw new IOException(sprintf('Failed to write file "%s".', $file), 0, null, $file);
}
}


/**
* Efface le fichier du token
*/
public function clearFromCache()
{
try {
$this->filesystem->remove($this->getFilePath());
} catch (FileNotFoundException $e) {
return true;
}
}


/**
* Retourne le chemin complet du fichier
*
* @return String
*/
private function getFilePath()
{
return sprintf('%s/%s', $this->folder, self::TOKEN_FILE);
}

}
Empty file modified src/TuyaCloudApi.php
100644 → 100755
Empty file.
Empty file modified test/Tools/ColorTest.php
100644 → 100755
Empty file.
38 changes: 38 additions & 0 deletions test/Tools/TokenPoolTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php
/**
* Test de la class TokenPool
*
* @author Olivier <[email protected]>
*
* @package TuyaCloudApi
*/

use PHPUnit\Framework\TestCase;
use Sabinus\TuyaCloudApi\Tools\TokenPool;


class TokenPoolTest extends TestCase
{

public function testStoreToken()
{
$pool = new TokenPool();
$this->assertSame(null, $pool->fetchTokenFromCache());
$pool->storeTokenInCache([0,1,2]);
$this->assertSame([0,1,2], $pool->fetchTokenFromCache());
$pool->clearFromCache();
$this->assertSame(null, $pool->fetchTokenFromCache());
}


public function testStoreOtherFolderToken()
{
$pool = new TokenPool();
$pool->setFolder('/var/tmp');
$pool->storeTokenInCache([1,2,3]);
$this->assertSame([1,2,3], $pool->fetchTokenFromCache());
$pool->clearFromCache();
$this->assertSame(null, $pool->fetchTokenFromCache());
}

}
Empty file modified test/bootstrap.php
100644 → 100755
Empty file.
6 changes: 4 additions & 2 deletions test/exemple.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
* @param Float timeout des requêtes http en secondes
*/
$session = new Session($argv[1], $argv[2], '33', Platform::SMART_LIFE, 5.0);
// FACULTATIF : Change le dossier de stockage du jeton, par défaut dans sys_get_temp_dir()
$session->setFolderStorePool('/tmp');

// Initialize object API
$api = new TuyaCloudApi($session);
Expand All @@ -32,12 +34,12 @@


/**
* Prise : Méthodfe 1
* Prise : Méthode 1
*/
$device = $api->getDeviceById('012345678901234598');
// Allume la prise
$rep = $api->sendEvent($device->getTurnOnEvent());
// Mets à jour l'objet pour récupér le dernier état
// Mets à jour l'objet pour récupérer le dernier état
$device->update($api);
print 'Etat : ' . $device->getState();

Expand Down

0 comments on commit f2e8b75

Please sign in to comment.