Skip to content

Commit

Permalink
1.26.23
Browse files Browse the repository at this point in the history
- added additional device error codes
- added JSON_LOG_DIR to allow user define json output path
- updated README
  • Loading branch information
PJanisio committed Jun 19, 2024
1 parent 1df025c commit 298d770
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 25 deletions.
20 changes: 11 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# ewelinkApiPhp
# eWeLink API PHP

API connector for Sonoff/ewelink devices using simple webapi based on OAuth2 with Websockets features.
eWeLink API PHP is a connector for Sonoff / eWeLink devices. This library allows you to interact with your eWeLink-enabled devices using PHP. It supports various functionalities such as device control, retrieving device status, debugging and more.

PHP 7.4+, **no other dependiencies required**.
## Requirements

- PHP 7.4+
- cURL extension enabled

## Current features

Expand All @@ -17,7 +20,7 @@ PHP 7.4+, **no other dependiencies required**.
- debug all requests and responses to debug.log
- use Websocket connection to get and update parameters

## Public key and secret
## Configuration

Generate here: [dev.ewelink](https://dev.ewelink.cc/)

Expand Down Expand Up @@ -80,15 +83,14 @@ ewelinkApiPhp/

All classes are located in src directory.

Index.php works as a gateway to API and also as a debug for all availablemethods.
Index.php works as a gateway to API and also as a debug for all available methods.

.json files outputs will be saved in project_root (ensure writeability)
.json files outputs will be saved by default in project_root. You can define directory in Constants.php

## More inside info about current development

- main branch when commited used to be operative.
- enable DEBUG = 1; in Constants to log every get and postRequest with output and parameters to **debug.log**
- with next stable release methods and invoking functions structure can be changed (keep this in mind)
- branch **websockets** will probably be not maintened anymore
- there could be some incosistency in the code still, like f.e handling error messages or orphan methods
- index.php is a quasi-test file which helps me to check new methods and it is also a great example
- branch **websockets** will be not maintened anymore
- index.php is a quasi-test file which helps me to check all methods and it is also a great example
19 changes: 18 additions & 1 deletion src/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,10 @@ class Constants {
// Enable or disable debug logging
const DEBUG = 0; // Change to 1 to enable debug logging

// Path for JSON logs directory
const JSON_LOG_DIR = __DIR__ . '/..';

//do not change
// Error codes
const ERROR_CODES = [
400 => 'Parameter error, usually the parameter required by the interface is missing, or the type or value of the parameter is wrong.',
401 => 'Access token authentication error. Usually, the account is logged in by others, resulting in the invalidation of the current access token.',
Expand All @@ -48,6 +50,21 @@ class Constants {
412 => 'APPID calls exceed the limit, you can upgrade to the enterprise version by contacting bd@coolkit.cn.',
500 => 'Server internal error, usually the server program error.',
4002 => 'Device control failure (Check control parameter transmission or device online status).',
30003 => 'Failed to notify the device to disconnect from the temporary persistent connection, when adding a GSM device.',
30007 => 'Failed to add the GSM device, because it has been added by another user before.',
30008 => 'When you are sharing devices, the shared user does not exist.',
30009 => 'You have exceeded the limit of groups you can have for your current subscription plan.',
30010 => 'The device ID format is wrong for the device being added.',
30011 => 'The factory data cannot be found in the device being added.',
30012 => 'The "extra" field of factory data cannot be found in the device being added.',
30013 => 'The brand info of factory data cannot be found.',
30014 => 'There is an error with the chipid.',
30015 => 'There is a digest error when a device is being added.',
30016 => 'The appid could not be found when a device is being added.',
30017 => 'This appid is not allowed to add the devices of the current brand.',
30018 => 'No device can be found with current deviceid.',
30019 => 'The product model of factory data cannot be found.',
30022 => 'The device is offline and the operation fails. It will appear in batch updating the device status.'
];
}
?>
7 changes: 4 additions & 3 deletions src/Devices.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ public function __construct(HttpClient $httpClient) {
* Load devices data from a local JSON file.
*/
private function loadDevicesData() {
if (file_exists('devices.json')) {
$this->devicesData = json_decode(file_get_contents('devices.json'), true);
$devicesFile = Constants::JSON_LOG_DIR . '/devices.json';
if (file_exists($devicesFile)) {
$this->devicesData = json_decode(file_get_contents($devicesFile), true);
} else {
$this->devicesData = null;
}
Expand All @@ -60,7 +61,7 @@ public function fetchDevicesData($lang = 'en') {
'familyId' => $familyId
];
$this->devicesData = $this->httpClient->getRequest('/v2/device/thing', $params);
file_put_contents('devices.json', json_encode($this->devicesData));
file_put_contents(Constants::JSON_LOG_DIR . '/devices.json', json_encode($this->devicesData));
return $this->devicesData;
}

Expand Down
3 changes: 2 additions & 1 deletion src/Home.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function fetchFamilyData($lang = 'en') {

$this->currentFamilyId = $this->familyData['currentFamilyId'] ?? null;

file_put_contents('family.json', json_encode($this->familyData));
file_put_contents(Constants::JSON_LOG_DIR . '/family.json', json_encode($this->familyData));
return $this->familyData;
}

Expand All @@ -55,3 +55,4 @@ public function getCurrentFamilyId() {
return $this->currentFamilyId;
}
}
?>
6 changes: 4 additions & 2 deletions src/HttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,9 @@ public function createLoginUrl($state) {
* Load token data from token.json file.
*/
private function loadTokenData() {
if (file_exists('token.json')) {
$this->tokenData = json_decode(file_get_contents('token.json'), true);
$tokenFile = Constants::JSON_LOG_DIR . '/token.json';
if (file_exists($tokenFile)) {
$this->tokenData = json_decode(file_get_contents($tokenFile), true);
}
}

Expand Down Expand Up @@ -201,6 +202,7 @@ public function postRequest($endpoint, $data, $useTokenAuthorization = false) {
*
* @param string $endpoint The endpoint to make the request to.
* @param array $params The query parameters to send in the request.
* @param bool $useFullUrl Whether to use the full URL for the request.
* @return array The response data.
* @throws Exception If the request fails.
*/
Expand Down
15 changes: 9 additions & 6 deletions src/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ public function __construct(HttpClient $httpClient, $state = 'ewelinkapiphp') {
* Load token data from token.json file.
*/
private function loadTokenData() {
if (file_exists('token.json')) {
$this->tokenData = json_decode(file_get_contents('token.json'), true);
$tokenFile = Constants::JSON_LOG_DIR . '/token.json';
if (file_exists($tokenFile)) {
$this->tokenData = json_decode(file_get_contents($tokenFile), true);
}
}

Expand All @@ -54,7 +55,7 @@ public function getToken() {
];
$responseData = $this->httpClient->postRequest('/v2/user/oauth/token', $data);
$this->tokenData = $responseData;
file_put_contents('token.json', json_encode($this->tokenData));
file_put_contents(Constants::JSON_LOG_DIR . '/token.json', json_encode($this->tokenData));
return $this->tokenData;
}

Expand All @@ -79,7 +80,7 @@ public function refreshToken() {
'atExpiredTime' => $this->tokenData['atExpiredTime'],
'rtExpiredTime' => $this->tokenData['rtExpiredTime']
];
file_put_contents('token.json', json_encode($this->tokenData));
file_put_contents(Constants::JSON_LOG_DIR . '/token.json', json_encode($this->tokenData));
return $this->tokenData;
}

Expand Down Expand Up @@ -115,8 +116,9 @@ public function getTokenData() {
* Clear the content of token.json file.
*/
public function clearToken() {
if (file_exists('token.json')) {
file_put_contents('token.json', '');
$tokenFile = Constants::JSON_LOG_DIR . '/token.json';
if (file_exists($tokenFile)) {
file_put_contents($tokenFile, '');
$this->tokenData = null;
}
}
Expand All @@ -132,3 +134,4 @@ public function redirectToUrl($url, $delay = 1) {
echo '<meta http-equiv="refresh" content="' . $delay . ';url=' . htmlspecialchars($url) . '">';
}
}
?>
6 changes: 3 additions & 3 deletions src/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,12 @@ public function handleRedirect() {
}

/**
* Check if JSON files in the root directory are valid and retrieve their creation timestamps.
* Check if JSON files in the specified 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');
$files = glob(Constants::JSON_LOG_DIR . '/*.json');
$results = [];

foreach ($files as $file) {
Expand Down Expand Up @@ -185,7 +185,7 @@ public function debugLog($class, $method, $params, $headers, $output, $callerCla
var_export($output, true),
$url
);
file_put_contents('debug.log', $logEntry, FILE_APPEND);
file_put_contents(Constants::JSON_LOG_DIR . '/debug.log', $logEntry, FILE_APPEND);
}
}
?>

0 comments on commit 298d770

Please sign in to comment.