I am just starting HA integration into a project using the REST API. First test was a simple light on which appears to work (e.g. no error response from API) however light does not turn on. On HA web it then shows icon of light as on but minus usual brightness slider and then will not change state clicking on it, I have to goto Hue to turn light on/off again for it to work again in HA.
Any ideas what I am missing?
Code…
<?php
require("include/config.php");
class HAApi {
public $url;
public $token;
function __construct() {
global $_CONFIG;
$this->url = $_CONFIG['ha_api_url'];
$this->token = $_ENV['HA_TOKEN'];
}
function curl($url,$post = false,$type = "GET") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($post) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer '.$this->token
));
$output = json_decode(curl_exec($ch),true);
curl_close($ch);
return $output;
}
function changeState($device,$state) {
$apiURL = $this->url.'states/'.$device;
$postRequest = array(
'state' => $state
);
return $this->curl($apiURL,$postRequest,"POST");
}
}
$ha = New HAApi;
print_r($ha->changeState("light.living_room_light","on"));
response
Array
(
[entity_id] => light.living_room_light
[state] => on
[attributes] => Array
(
)
[last_changed] => 2023-01-30T12:18:34.101977+00:00
[last_updated] => 2023-01-30T12:18:34.101977+00:00
[context] => Array
(
[id] => 01GR19TRFN2RM68ZCY3P50Y26Q
[parent_id] =>
[user_id] => 354b0fab875d41ae95cb0e29e1bb8777
)
)