Skip to content
This repository has been archived by the owner on Oct 12, 2023. It is now read-only.

Commit

Permalink
Add tests and add more functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
inverse committed Jul 29, 2018
1 parent 0eb417c commit 3cfc9e9
Show file tree
Hide file tree
Showing 20 changed files with 591 additions and 21 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/vendor/
/composer.lock
/.idea/
/phpunit.xml
/phpunit.xml
.php_cs.cache
13 changes: 13 additions & 0 deletions .php_cs.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php
$finder = PhpCsFixer\Finder::create()
->in(['src', 'tests'])
;

return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
])
->setUsingCache(true)
->setRiskyAllowed(true)
->setFinder($finder)
;
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Malachi Soord

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
43 changes: 42 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,47 @@
# API Client for Tuya

An API Client build for [Tuya][1] heavily inspired by [tuyapy][0].
An WIP API Client build for [Tuya][1] heavily inspired by [tuyapy][0].

## Currently Supporting

- Switch devices

## Example

```php
require __DIR__ . '../vendor/autoload.php';

use Inverse\TuyaClient\Session;
use Inverse\TuyaClient\ApiClient;
use Inverse\TuyaClient\Device\SwitchDevice;

// Setup credentials
$username = getenv('TUYA_USERNAME');
$password = getenv('TUYA_PASSWORD');
$countryCode = getenv('TUYA_COUNTRYCODE');

// Make client
$session = new Session($username, $password, $countryCode);
$apiClient = new ApiClient($session);

// Get all devices
$devices = $apiClient->discoverDevices();

// Switch on all switches
foreach ($devices as $device) {
if ($device instanceOf SwitchDevice) {
$apiClient->sendEvent($device->getOnEvent());
}
}
```

## Testing

Copy `phpunit.xml.dist` to `phpunit.xml` and replace the server variables with your credentials.

## Licence

MIT

[0]: https://pypi.org/project/tuyapy
[1]: https://www.tuya.com/
11 changes: 9 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
"require": {
"php": "^7.1",
"guzzlehttp/guzzle": "^6.3",
"webmozart/assert": "^1.3",
"webmozart/assert": "^1.3"
},
"require-dev": {
"phpunit/phpunit": "^7.2"
},
"autoload": {
Expand All @@ -22,7 +24,12 @@
},
"autoload-dev": {
"psr-4": {
"Tests\\Inverse\\TuyaClient\\": "tests/"
"Tests\\Functional\\Inverse\\TuyaClient\\": "tests/Functional",
"Tests\\Unit\\Inverse\\TuyaClient\\": "tests/unit"
}
},
"scripts": {
"test": "phpunit --testsuite unit",
"cs": "php-cs-fixer fix"
}
}
12 changes: 9 additions & 3 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,18 @@
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
syntaxCheck="true"
bootstrap="./tests/bootstrap.php"
>
bootstrap="./tests/bootstrap.php">
<php>
<env name="TUYA_USERNAME" value=""/>
<env name="TUYA_PASSWORD" value="" />
<env name="TUYA_COUNTRYCODE" value="" />
</php>
<testsuites>
<testsuite name="unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="functional">
<directory>tests/Functional</directory>
</testsuite>
</testsuites>
</phpunit>
116 changes: 110 additions & 6 deletions src/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\UriResolver;
use Inverse\TuyaClient\Device\DeviceEvent;
use Inverse\TuyaClient\Device\DeviceFactory;
use Inverse\TuyaClient\Exception\TuyaClientException;
use Psr\Http\Message\UriInterface;

class ApiClient
Expand All @@ -21,17 +24,79 @@ class ApiClient
*/
private $session;

/**
* @var DeviceFactory
*/
private $deviceFactory;


public function __construct(Session $session, Client $client = null)
{
$this->session = $session;
$this->client = $client ?? new Client();
$this->deviceFactory = new DeviceFactory();
}

public function discoverDevices(): array
{
$response = $this->request('Discovery', 'discovery');

$devices = [];
foreach ($response['payload']['devices'] as $device) {
$devices[] = $this->deviceFactory->fromArray($device);
}

return $devices;
}

public function sendEvent(DeviceEvent $event, $namespace = 'control')
{
$this->request($event->getAction(), $namespace, $event->getDeviceId(), $event->getPayload());
}

public function getAccessToken()
private function request(string $name, string $namespace, string $deviceId = null, array $payload = []): array
{
$baseUrl = $this->getBaseUrl($this->session);
if (!$this->session->hasAccessToken()) {
$this->session->setToken($this->getAccessToken());
}

if (!$this->isAccessTokenValid()) {
$this->session->setToken($this->refreshAccessToken());
}

$uri = UriResolver::resolve($this->getBaseUrl($this->session), new Uri('homeassistant/skill'));

$header = [
'name' => $name,
'namespace' => $namespace,
'payloadVersion' => 1,
];

$payload['accessToken'] = $this->session->getToken()->getAccessToken();

if ($deviceId) {
$payload['devId'] = $deviceId;
}

$data = [
'header' => $header,
'payload' => $payload,
];

$response = $this->client->post($uri, [
'json' => $data,
]);

$response = json_decode((string)$response->getBody(), true);

$this->validate($response, sprintf('Failed to get response from %s', $name));

return $response;
}

$uri = UriResolver::resolve($baseUrl, new Uri('homeassistant/auth.do'));
private function getAccessToken(): Token
{
$uri = UriResolver::resolve($this->getBaseUrl($this->session), new Uri('homeassistant/auth.do'));

$response = $this->client->request('POST', $uri, [
'form_params' => [
Expand All @@ -44,11 +109,50 @@ public function getAccessToken()

$response = json_decode((string)$response->getBody(), true);

return $response;
$this->validate($response, 'An error occurred while fetching access token');

$token = Token::fromArray($response);

return $token;
}

private function refreshAccessToken(): Token
{
$uri = UriResolver::resolve($this->getBaseUrl($this->session), new Uri('homeassistant/access.do'));

$response = $this->client->request('GET', $uri, [
'query' => [
'grant_type' => 'refresh_token',
'refresh_token' => $this->session->getToken()->getRefreshToken(),
]
]);

$response = json_decode((string)$response->getBody(), true);

$this->validate($response, 'Failed to refresh access token');

$token = Token::fromArray($response);

return $token;
}

private function isAccessTokenValid(): bool
{
$token = $this->session->getToken();

return time() + $token->getExpireTime() > time();
}

private function getBaseUrl(Session $session): UriInterface
{
return new Uri(sprintf(self::BASE_URL_FORMAT, $session->getRegion()->getValue()));
return new Uri(sprintf(self::BASE_URL_FORMAT, $session->getRegion()));
}

private function validate(array $response, string $message = null)
{
if (isset($response['responseStatus']) && $response['responseStatus'] === 'error') {
$message = $message ?? $response['responseMsg'];
throw new TuyaClientException($message);
}
}
}
}
80 changes: 80 additions & 0 deletions src/Device/AbstractDevice.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

namespace Inverse\TuyaClient\Device;

class AbstractDevice
{
/**
* @var string
*/
protected $name;

/**
* @var string
*/
protected $icon;

/**
* @var string
*/
protected $id;

/**
* @var string
*/
protected $devType;

/**
* @var string
*/
protected $haType;

/**
* @var bool
*/
protected $isOnline;

public function __construct(string $name, string $icon, string $id, string $devType, string $haType)
{
$this->name = $name;
$this->icon = $icon;
$this->id = $id;
$this->devType = $devType;
$this->haType = $haType;
}

public function getName(): string
{
return $this->name;
}

public function getIcon(): string
{
return $this->icon;
}

public function getId(): string
{
return $this->id;
}

public function getDevType(): string
{
return $this->devType;
}

public function getHaType(): string
{
return $this->haType;
}

public function isOnline(): bool
{
return $this->isOnline;
}

public function setIsOnline(bool $isOnline): void
{
$this->isOnline = $isOnline;
}
}
Loading

0 comments on commit 3cfc9e9

Please sign in to comment.