Skip to content

Commit

Permalink
0.10.7 (pre-release)
Browse files Browse the repository at this point in the history
- second pre-release version
- removed method getDevicesData from HttpClient as we use the same method in Devices class
- updated index.php
- updated README
  • Loading branch information
PJanisio authored Jun 13, 2024
1 parent f7f46c8 commit a3ddcd0
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 78 deletions.
17 changes: 7 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ API connector for Sonoff/ewelink devices using simple webapi based on OAuth2.

PHP 7.4+, no other dependiencies required.

Version **0.9.5** is currently operative and ***pre released***, but not yet tested in 100%, so feedback is appreciated **create issues / PR** if needed.
Version **0.10.7** is currently operative and ***pre released***, but not yet tested in 100%, so feedback is appreciated **create issues / PR** if needed.

## Current features

- login and authorization to ewelink (with refresh token)
- get devices list with all parameters
- saving devices to .json
- search value of parameter for each device (f.e switch status, productName etc.)
- saving devices and other outputs from API to .json
- search value of parameter for each device (f.e switch status, productName, MAC etc.)
- update parameter of device
- check if device has MultiChannel support

## Public key and secret

Expand All @@ -24,8 +25,6 @@ And put your keys and redirect Url in **Constants.php**

```
project_root/
├── src/
Expand All @@ -36,22 +35,20 @@ project_root/
└── index.php
```

All classes are located in src directory.

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

.json files outputs will be saved in project_root
.json files outputs will be saved in project_root (ensure writeability)

## Example

Examples will follow with stable release, for now - see **index.php**

## More inside info
## More inside info about current development

- with next stable release methods and invoking functions structure can be changed (keep this in mind)
- branch **websockets** will probably be not maintened
- branch **websockets** will probably be not maintened anymore
- there could be some incosistency in the code still, like f.e handling error messages
7 changes: 2 additions & 5 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,11 @@ function getQueryParam($name) {
echo '<pre>' . print_r($familyData, true) . '</pre>';
echo '<p>Current Family ID: ' . htmlspecialchars($httpClient->getCurrentFamilyId()) . '</p>';

$devicesData = $httpClient->getDevicesData();
$devices = new Devices();
$devicesData = $devices->getDevicesData();
echo '<h1>Devices Data</h1>';
echo '<pre>' . print_r($devicesData, true) . '</pre>';

$devices = new Devices();
echo '<h1>Loaded Devices Data</h1>';
echo '<pre>' . print_r($devices->getDevicesData(), true) . '</pre>';

$devicesList = $devices->getDevicesList();
echo '<h1>Devices List</h1>';
echo '<pre>' . print_r($devicesList, true) . '</pre>';
Expand Down
48 changes: 25 additions & 23 deletions src/Devices.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ private function loadDevicesData() {
}

/**
* Get the loaded devices data.
* Get the stored devices data.
*
* @return array|null The devices data or null if not set.
*/
Expand All @@ -47,7 +47,7 @@ public function getDeviceById($deviceId) {
}

/**
* Create a list of devices containing name, deviceid, productModel, online status, and isSupportChannelSplit status.
* Create a list of devices containing name, deviceid, productModel, online status, and channel support.
* The list is an associative array with device names as keys.
*
* @return array The list of devices.
Expand All @@ -57,18 +57,34 @@ public function getDevicesList() {
if ($this->devicesData && isset($this->devicesData['thingList'])) {
foreach ($this->devicesData['thingList'] as $device) {
$itemData = $device['itemData'];
$deviceId = $itemData['deviceid'];
$devicesList[$itemData['name']] = [
'deviceid' => $deviceId,
'deviceid' => $itemData['deviceid'],
'productModel' => $itemData['productModel'],
'online' => $itemData['online'],
'isSupportChannelSplit' => $this->isMultiChannel($deviceId)
'isSupportChannelSplit' => $this->isMultiChannel($itemData['deviceid'])
];
}
}
return $devicesList;
}

/**
* Check if a device supports multiple channels.
*
* @param string $deviceId The ID of the device to check.
* @return bool True if the device supports multiple channels, false otherwise.
*/
public function isMultiChannel($deviceId) {
if ($this->devicesData && isset($this->devicesData['thingList'])) {
foreach ($this->devicesData['thingList'] as $device) {
if ($device['itemData']['deviceid'] === $deviceId && isset($device['itemData']['isSupportChannelSplit'])) {
return $device['itemData']['isSupportChannelSplit'] == 1;
}
}
}
return false;
}

/**
* Search for a specific parameter within a device's data.
*
Expand Down Expand Up @@ -98,13 +114,13 @@ public function searchDeviceParam($searchKey, $deviceId) {
/**
* Get live device parameter using the API.
*
* @param HttpClient $httpClient The HTTP client instance.
* @param HttpClient $httpClient The HttpClient instance.
* @param string $deviceId The ID of the device.
* @param string $param The parameter to get.
* @param int $type The type (default is 1).
* @return mixed The specific parameter value from the API response or null if not found.
*/
public function getDeviceParamLive(HttpClient $httpClient, $deviceId, $param, $type = 1) {
public function getDeviceParamLive($httpClient, $deviceId, $param, $type = 1) {
$endpoint = '/v2/device/thing/status';
$queryParams = [
'id' => $deviceId,
Expand All @@ -128,13 +144,13 @@ public function getDeviceParamLive(HttpClient $httpClient, $deviceId, $param, $t
/**
* Set the device status by updating a parameter.
*
* @param HttpClient $httpClient The HTTP client instance.
* @param HttpClient $httpClient The HttpClient instance.
* @param string $deviceId The ID of the device.
* @param array $params The parameters to update.
* @return string The result message.
* @throws Exception If the parameter update fails.
*/
public function setDeviceStatus(HttpClient $httpClient, $deviceId, $params) {
public function setDeviceStatus($httpClient, $deviceId, $params) {
// Check if the parameter exists and get the current value
foreach ($params as $param => $newValue) {
$currentValue = $this->getDeviceParamLive($httpClient, $deviceId, $param);
Expand Down Expand Up @@ -164,18 +180,4 @@ public function setDeviceStatus(HttpClient $httpClient, $deviceId, $params) {
}
}
}

/**
* Check if a device supports multiple channels.
*
* @param string $deviceId The ID of the device to check.
* @return bool True if the device supports multiple channels, false otherwise.
*/
public function isMultiChannel($deviceId) {
$device = $this->getDeviceById($deviceId);
if ($device && isset($device['isSupportChannelSplit'])) {
return $device['isSupportChannelSplit'] == 1;
}
return false;
}
}
48 changes: 8 additions & 40 deletions src/HttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ class HttpClient {
private $tokenData;
private $familyData;
private $currentFamilyId;
private $devicesData;

public function __construct($state) {
$utils = new Utils();
Expand Down Expand Up @@ -141,23 +140,21 @@ public function postRequest($endpoint, $data, $useTokenAuthorization = false) {
];

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = file_get_contents($url, false, $context);

if ($result === FALSE) {
if ($response === FALSE) {
throw new Exception('Error making POST request');
}



$response = json_decode($result, true);
if ($response['error'] !== 0) {
$errorCode = $response['error'];
$result = json_decode($response, true);

if ($result['error'] !== 0) {
$errorCode = $result['error'];
$errorMsg = Constants::ERROR_CODES[$errorCode] ?? 'Unknown error';
throw new Exception("Error $errorCode: $errorMsg");
}

return $response['data'];
return $result['data'];
}

/**
Expand All @@ -177,7 +174,7 @@ public function getRequest($endpoint, $params = []) {

$options = [
'http' => [
'header' => implode("\r\n", $headers) . "\r\n",
'header' => implode("\r\n", $headers),
'method' => 'GET',
],
];
Expand Down Expand Up @@ -274,26 +271,6 @@ public function getFamilyData($lang = 'en') {
return $this->familyData;
}

/**
* Get devices data.
*
* @param string $lang The language parameter (default: 'en').
* @return array The devices data.
* @throws Exception If the request fails.
*/
public function getDevicesData($lang = 'en') {
if (!$this->currentFamilyId) {
throw new Exception('Current family ID is not set. Please call getFamilyData first.');
}
$params = [
'lang' => $lang,
'familyId' => $this->currentFamilyId
];
$this->devicesData = $this->getRequest('/v2/device/thing', $params);
file_put_contents('devices.json', json_encode($this->devicesData));
return $this->devicesData;
}

/**
* Get the stored token data.
*
Expand All @@ -320,13 +297,4 @@ public function getFamilyDataFromStorage() {
public function getCurrentFamilyId() {
return $this->currentFamilyId;
}

/**
* Get the stored devices data.
*
* @return array|null The devices data or null if not set.
*/
public function getDevicesDataFromStorage() {
return $this->devicesData;
}
}

0 comments on commit a3ddcd0

Please sign in to comment.