Skip to content

Commit

Permalink
1.35.31
Browse files Browse the repository at this point in the history
- removed forceGetDataMethod and forceUpdateDevice as they have been successfully replaced by getDataWebsocket and setDataWebsocket
- added forceWakeUp method that is using websocket connection to refresh some of parameters that http can not (energy, temperature etc).
- updated index.php to have a live example of new method
  • Loading branch information
PJanisio authored Jul 10, 2024
1 parent 7204198 commit 3201375
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 82 deletions.
29 changes: 15 additions & 14 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
* Description: API connector for Sonoff / ewelink devices
*/

ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
ini_set('max_execution_time', 0);
require_once __DIR__ . '/autoloader.php';

// User Inputs
// -----------------------------------------------
$devId = '100xxxxxxx'; // Single Device ID
$multiDevId = '100xxxxxxx'; // Multi-Channel Device ID
$singleDevId = '100xxxxxxx'; // Another Single Device ID
$devIdent = 'Name of device'; // Device Identifier for online check
$devIdent = 'Switch'; // Device Identifier for online check

$singleParams = ['switch' => 'off']; // Parameters for single-channel device
$multiParams = [
Expand All @@ -31,7 +31,6 @@
['colorB' => 0]
]; // Multiple parameters for single-channel device
$liveParam = ['voltage', 'current', 'power']; // Parameters to get live data
$forceParams = ['current', 'power', 'voltage']; // Parameters for force get data
$updateParams = ['switch' => 'on']; // Parameters for force update device
// -----------------------------------------------

Expand Down Expand Up @@ -71,6 +70,7 @@
$liveRes = $devs->getDeviceParamLive($devId, $liveParam);
echo '<h1>Live Device Parameter</h1>';
echo '<pre>' . print_r($liveRes, true) . '</pre>';


$allLiveParams = $devs->getAllDeviceParamLive($devId);
echo '<h1>Get All Device Parameters Live</h1>';
Expand All @@ -84,9 +84,9 @@
echo '<h1>Set Single-Channel Device Status Result</h1>';
echo '<pre>' . print_r($setSingleRes, true) . '</pre>';

$setSingleMultiRes = $devs->setDeviceStatus($singleDevId, $singleParamsMulti);
echo '<h1>Set Single-Channel Device Status Result (Multiple Parameters)</h1>';
echo '<pre>' . print_r($setSingleMultiRes, true) . '</pre>';
//$setSingleMultiRes = $devs->setDeviceStatus($singleDevId, $singleParamsMulti);
//echo '<h1>Set Single-Channel Device Status Result (Multiple Parameters)</h1>';
//echo '<pre>' . print_r($setSingleMultiRes, true) . '</pre>';

$onlineRes = $devs->isOnline($devIdent);
echo '<h1>Is Device Online?</h1>';
Expand All @@ -98,13 +98,15 @@
echo '<pre>' . print_r($familyData, true) . '</pre>';
echo '<p>Current Family ID: ' . htmlspecialchars($home->getCurrentFamilyId()) . '</p>';

$forceRes = $devs->forceGetData('Gniazdko biuro', $forceParams);
echo '<h1>Force Get Data Result</h1>';
echo '<pre>' . print_r($forceRes, true) . '</pre>';
$forceWakeUpRes = $devs->forceWakeUp($devIdent);
echo '<h1>Force Wake Up Result</h1>';
echo '<pre>' . print_r($forceWakeUpRes, true) . '</pre>';

$updateRes = $devs->forceUpdateDevice($devIdent, $updateParams, 3);
echo '<h1>Force Update Device Result</h1>';
echo '<pre>' . print_r($updateRes, true) . '</pre>';
if ($forceWakeUpRes) {
$allLiveParams = $devs->getAllDeviceParamLive($devIdent);
echo '<h1>Get All Device Parameters Live After Force Wake Up</h1>';
echo '<pre>' . print_r($allLiveParams, true) . '</pre>';
}

// Initialize WebSocket connection and get data
$wsClient = $devs->initializeWebSocketConnection($devId);
Expand All @@ -120,5 +122,4 @@
$loginUrl = $http->getLoginUrl();
echo '<a href="' . htmlspecialchars($loginUrl) . '">Authorize ewelinkApiPhp</a>';
}
}
?>
}
77 changes: 9 additions & 68 deletions src/Devices.php
Original file line number Diff line number Diff line change
Expand Up @@ -527,15 +527,15 @@ public function setDataWebSocket($identifier, $params) {
return $response['params'];
}


/**
* Force get data of a device using WebSocket.
* Force wake up the device by fetching all parameters and setting them back to their current values.
*
* @param string $identifier The device name or ID.
* @param array|string $params The parameters to query.
* @return array The response data.
* @return bool True if the operation was successful, false otherwise.
* @throws Exception If there is an error during the process.
*/
public function forceGetData($identifier, $params) {
public function forceWakeUp($identifier) {
$deviceId = $this->getDeviceIdByIdentifier($identifier);
if (!$deviceId) {
throw new Exception("Device not found.");
Expand All @@ -547,15 +547,9 @@ public function forceGetData($identifier, $params) {
throw new Exception($errorMsg);
}

// Check if the device has energy parameters
$energyParams = ['power', 'current', 'voltage'];
$deviceParams = array_keys($this->getAllDeviceParamLive($identifier) ?? []);
$hasEnergyParams = !empty(array_intersect($energyParams, $deviceParams));

// If the device has energy parameters, update 'current' to 0.50 before fetching data
if ($hasEnergyParams) {
$updateParams = ['current' => 0.50];
$this->forceUpdateDevice($identifier, $updateParams, 5);
$currentParams = $this->getAllDeviceParamLive($deviceId);
if ($currentParams === null) {
return false;
}

$wsClient = new WebSocketClient($this->httpClient);
Expand All @@ -567,7 +561,7 @@ public function forceGetData($identifier, $params) {
throw new Exception("Handshake Error: $errorMsg");
}

$data = $wsClient->createQueryData($device, $params);
$data = $wsClient->createUpdateData($device, $currentParams, $device['apikey']);
$wsClient->send(json_encode($data));
$response = json_decode($wsClient->receive(), true);

Expand All @@ -579,59 +573,6 @@ public function forceGetData($identifier, $params) {
throw new Exception("Error: $errorMsg");
}

return $response['params'];
}

/**
* Force update the status of a device using WebSocket.
*
* @param string $identifier The device name or ID.
* @param array $params The parameters to update.
* @param int $sleepSec The number of seconds to wait before verifying the update (default is 10 seconds).
* @return array The response data.
* @throws Exception If there is an error during the process.
*/
public function forceUpdateDevice($identifier, $params, $sleepSec = 5) {
$deviceId = $this->getDeviceIdByIdentifier($identifier);
if (!$deviceId) {
throw new Exception("Device not found.");
}
$device = $this->getDeviceById($deviceId);
if (!$device) {
$errorCode = 'DEVICE_NOT_FOUND'; // Example error code
$errorMsg = Constants::ERROR_CODES[$errorCode] ?? 'Unknown error';
throw new Exception($errorMsg);
}

$wsClient = new WebSocketClient($this->httpClient);
$handshakeResponse = $wsClient->handshake($device);

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

$data = $wsClient->createUpdateData($device, $params, $device['apikey']);
$wsClient->send(json_encode($data));

// Keep heartbeat running and verify changes
$response = json_decode($wsClient->receive(), true);

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

sleep($sleepSec); // Wait for a while to let the changes take effect

// Check if the parameters have been updated
$updatedParams = $this->forceGetData($deviceId, array_keys($params));

$wsClient->close();

return $updatedParams;
return true;
}
}
?>

0 comments on commit 3201375

Please sign in to comment.