Skip to content

Commit

Permalink
1.19.20
Browse files Browse the repository at this point in the history
- fixed bug with old deviceStatus fetched from json after changing parameters, now it will be validated with live response from API
- added function checkJsonFiles for validity and creation time
- added function to validate user config made in Constants in constructor of HttpClient Class
- renamed method refreshDeviceParam to getAllDeviceParamLive
- added comments
- updated index.php and README
  • Loading branch information
PJanisio committed Jun 16, 2024
1 parent 6d7a991 commit 857dee7
Show file tree
Hide file tree
Showing 9 changed files with 153 additions and 16 deletions.
11 changes: 3 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ API connector for Sonoff/ewelink devices using simple webapi based on OAuth2.

PHP 7.4+, no other dependiencies required.

Current version from branch **main** should be operative, but not yet tested in 100% and in active development, so please keep this in mind.
For pre released versions look at recent released [Tagged versions](https://github.com/PJanisio/ewelinkApiPhp/tags)

## Current features

- login and authorization to ewelink (with refresh token)
Expand Down Expand Up @@ -50,15 +47,14 @@ try {
$deviceId = '100xxxxxx'; // Replace with your actual device ID

// Turn on the device
$setStatusResult = $devices->setDeviceStatus($deviceId, ['switch' => 'on']);
echo '<h1>Turn Device On Result</h1>';
echo '<pre>' . print_r($setStatusResult, true) . '</pre>';
$param = ['switch' => 'on'];
$setStatusResult = $devices->setDeviceStatus($deviceId, $param);

} else {

//if we have no token, or we are not authorized paste link to authorization
$loginUrl = $httpClient->getLoginUrl();
echo '<a href="' . htmlspecialchars($loginUrl) . '">Login with OAuth</a>';
echo '<a href="' . htmlspecialchars($loginUrl) . '">Authorize ewelinkApiPhp</a>';
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
Expand Down Expand Up @@ -92,7 +88,6 @@ Index.php works as a gateway to API and also as a debug for all availablemethods

## More inside info about current development

- released version is expected to be ready on **01.07.2024** latest
- main branch when commited used to be operative.
- with next stable release methods and invoking functions structure can be changed (keep this in mind)
- branch **websockets** will probably be not maintened anymore
Expand Down
8 changes: 8 additions & 0 deletions autoloader.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
<?php

/**
* Class: ewelinkApiPhp
* Author: Paweł 'Pavlus' Janisio
* Website: https://github.com/AceExpert/ewelink-api-python
* Dependencies: PHP 7.4+
* Description: API connector for Sonoff / ewelink devices
*/

// Autoloader function to load classes automatically
spl_autoload_register(function ($class) {
$base_dir = __DIR__ . '/src/';
Expand Down
18 changes: 13 additions & 5 deletions index.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
<?php

/**
* Class: ewelinkApiPhp
* Author: Paweł 'Pavlus' Janisio
* Website: https://github.com/AceExpert/ewelink-api-python
* Dependencies: PHP 7.4+
* Description: API connector for Sonoff / ewelink devices
*/

require_once __DIR__ . '/autoloader.php';

$httpClient = new HttpClient();
Expand Down Expand Up @@ -44,9 +52,9 @@
echo '<h1>Live Device Parameter</h1>';
echo '<pre>' . print_r($liveResult, true) . '</pre>';

// Example usage of refreshDeviceStatusLive
$refreshResult = $devices->refreshDeviceStatusLive($deviceId);
echo '<h1>Refresh Device Status Live</h1>';
// Example usage of getAllDeviceParamLive
$refreshResult = $devices->getAllDeviceParamLive($deviceId);
echo '<h1>Get All Device Parameters Live</h1>';
echo '<pre>' . print_r($refreshResult, true) . '</pre>';

// Example usage of setDeviceStatus for multi-channel device
Expand All @@ -63,7 +71,7 @@

// Example usage of setDeviceStatus for single-channel device
$singleChannelDeviceId = '10011015b6';
$singleChannelParams = ['bright' => 80];
$singleChannelParams = ['switch' => 'off'];
$setStatusResultSingle = $devices->setDeviceStatus($singleChannelDeviceId, $singleChannelParams);
echo '<h1>Set Single-Channel Device Status Result</h1>';
echo '<pre>' . print_r($setStatusResultSingle, true) . '</pre>';
Expand Down Expand Up @@ -104,6 +112,6 @@
}
} else {
$loginUrl = $httpClient->getLoginUrl();
echo '<a href="' . htmlspecialchars($loginUrl) . '">Login with OAuth</a>';
echo '<a href="' . htmlspecialchars($loginUrl) . '">Authorize ewelinkApiPhp</a>';
}
}
8 changes: 8 additions & 0 deletions src/Constants.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
<?php

/**
* Class: ewelinkApiPhp
* Author: Paweł 'Pavlus' Janisio
* Website: https://github.com/AceExpert/ewelink-api-python
* Dependencies: PHP 7.4+
* Description: API connector for Sonoff / ewelink devices
*/

class Constants {
// Your eWeLink application ID, obtained from the eWeLink developer platform
const APPID = 'your_app_id';
Expand Down
14 changes: 11 additions & 3 deletions src/Devices.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
<?php

/**
* Class: ewelinkApiPhp
* Author: Paweł 'Pavlus' Janisio
* Website: https://github.com/AceExpert/ewelink-api-python
* Dependencies: PHP 7.4+
* Description: API connector for Sonoff / ewelink devices
*/

class Devices {
private $devicesData;
private $httpClient;
Expand Down Expand Up @@ -182,14 +190,14 @@ public function getDeviceParamLive($deviceId, $param, $type = 1) {
}

/**
* Refresh device status live using the API.
* Get all device parameters live using the API.
*
* @param string $deviceId The ID of the device.
* @param int $type The type (default is 1).
* @return mixed The updated device status from the API response or null if not found.
* @throws Exception If there is an error in the request.
*/
public function refreshDeviceStatusLive($deviceId, $type = 1) {
public function getAllDeviceParamLive($deviceId, $type = 1) {
$endpoint = '/v2/device/thing/status';
$queryParams = [
'id' => $deviceId,
Expand Down Expand Up @@ -219,7 +227,7 @@ public function refreshDeviceStatusLive($deviceId, $type = 1) {
*/
public function setDeviceStatus($deviceId, $params) {
$device = $this->getDeviceById($deviceId);
$currentParams = $device['params'] ?? null;
$currentParams = $this->getAllDeviceParamLive($deviceId) ?? null; // Use getAllDeviceParamLive to get current state

if ($currentParams === null) {
return "Device $deviceId does not have any parameters to update.";
Expand Down
8 changes: 8 additions & 0 deletions src/Home.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
<?php

/**
* Class: ewelinkApiPhp
* Author: Paweł 'Pavlus' Janisio
* Website: https://github.com/AceExpert/ewelink-api-python
* Dependencies: PHP 7.4+
* Description: API connector for Sonoff / ewelink devices
*/

class Home {
private $httpClient;
private $familyData;
Expand Down
24 changes: 24 additions & 0 deletions src/HttpClient.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
<?php

/**
* Class: ewelinkApiPhp
* Author: Paweł 'Pavlus' Janisio
* Website: https://github.com/AceExpert/ewelink-api-python
* Dependencies: PHP 7.4+
* Description: API connector for Sonoff / ewelink devices
*/

require_once __DIR__ . '/Utils.php';
require_once __DIR__ . '/Constants.php';
require_once __DIR__ . '/Home.php';
Expand All @@ -16,6 +24,22 @@ class HttpClient {

public function __construct() {
$utils = new Utils();

// Validate constants
$validationResults = $utils->validateConstants();
$errors = [];
foreach ($validationResults as $key => $result) {
if (!$result['is_valid']) {
$errors[] = "Invalid {$key}: " . $result['value'];
}
}
if (!empty($errors)) {
foreach ($errors as $error) {
echo "<p>$error</p>";
}
exit;
}

$this->region = Constants::REGION; // Assign region from Constants
$this->loginUrl = $this->createLoginUrl('ewelinkapiphp'); // Default state

Expand Down
8 changes: 8 additions & 0 deletions src/Token.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
<?php

/**
* Class: ewelinkApiPhp
* Author: Paweł 'Pavlus' Janisio
* Website: https://github.com/AceExpert/ewelink-api-python
* Dependencies: PHP 7.4+
* Description: API connector for Sonoff / ewelink devices
*/

require_once __DIR__ . '/Utils.php';
require_once __DIR__ . '/Constants.php';

Expand Down
70 changes: 70 additions & 0 deletions src/Utils.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
<?php

/**
* Class: ewelinkApiPhp
* Author: Paweł 'Pavlus' Janisio
* Website: https://github.com/AceExpert/ewelink-api-python
* Dependencies: PHP 7.4+
* Description: API connector for Sonoff / ewelink devices
*/

class Utils {
/**
* Generate a nonce (an 8-digit alphanumeric random string).
Expand Down Expand Up @@ -54,4 +62,66 @@ public function handleRedirect() {
return [$code, $region];
}

/**
* Check if JSON files in the root directory are valid and retrieve their creation timestamps.
*
* @return array The validation results and creation timestamps of the JSON files.
*/
public function checkJsonFiles() {
$files = glob('*.json');
$results = [];

foreach ($files as $file) {
$content = file_get_contents($file);
$isValidJson = json_decode($content) !== null;
$creationTime = filectime($file);
$results[] = [
'file' => $file,
'validation' => $isValidJson,
'creation_time' => $creationTime
];
}

return $results;
}

/**
* Validate the constants in the Constants class.
*
* @return array The validation results for REDIRECT_URL, EMAIL, and REGION.
*/
public function validateConstants() {
$results = [];

// Validate REDIRECT_URL
$url = Constants::REDIRECT_URL;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // Set timeout to 5 seconds
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$results['REDIRECT_URL'] = [
'value' => $url,
'is_valid' => $httpCode >= 200 && $httpCode < 400 // Consider 2xx and 3xx responses as valid
];

// Validate EMAIL
$email = Constants::EMAIL;
$results['EMAIL'] = [
'value' => $email,
'is_valid' => filter_var($email, FILTER_VALIDATE_EMAIL) !== false
];

// Validate REGION
$region = Constants::REGION;
$validRegions = ['cn', 'us', 'eu', 'as'];
$results['REGION'] = [
'value' => $region,
'is_valid' => in_array($region, $validRegions)
];

return $results;
}
}

0 comments on commit 857dee7

Please sign in to comment.