Created
October 1, 2022 17:45
-
-
Save adlerweb/1ba6ac9fdbdc2748182e8a524303e9f0 to your computer and use it in GitHub Desktop.
Homeassistant/PHP: Read sensor via REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?PHP | |
function getHA($id) { //ID to read - for example sensor.foo | |
$key = ''; //Long-lived access token, can be obtained in HomeAssistant UI→Profile | |
$url = 'http://127.0.0.1:8123/'; //URL to your HA including trailing / | |
$opts = [ | |
"http" => [ | |
"method" => "GET", | |
"header" => | |
"Content-Type: application/json\r\n" . | |
"Authorization: Bearer ".$key."\r\n" | |
] | |
]; | |
$ctx = stream_context_create($opts); | |
$data = @file_get_contents($url.'api/states/'.$id, false, $ctx); | |
if(!$data) return false; | |
$data = json_decode($data); | |
if(!$data) return false; | |
if(!isset($data->state)) return false; | |
return [$data->state, $data->last_updated]; | |
} | |
/* | |
Usage: | |
$data = getHA('sensor.foo'); | |
if($data) { | |
echo 'Value: '.$data[0].PHP_EOL; | |
echo 'Last Update: '.$data[2].PHP_EOL; | |
}else{ | |
echo 'Sensor not found'.PHP_EOL; | |
} | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment