Skip to content

Instantly share code, notes, and snippets.

@adlerweb
Created October 1, 2022 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adlerweb/1ba6ac9fdbdc2748182e8a524303e9f0 to your computer and use it in GitHub Desktop.
Save adlerweb/1ba6ac9fdbdc2748182e8a524303e9f0 to your computer and use it in GitHub Desktop.
Homeassistant/PHP: Read sensor via REST API
<?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