61 lines
1.6 KiB
PHP
61 lines
1.6 KiB
PHP
<?php
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
|
|
// Token/URL aus externer Config laden
|
|
require_once __DIR__ . '/config.local.php';
|
|
|
|
// Entity-ID (Standard: dein Sensor aus der Liste)
|
|
$entityId = isset($_GET['entity_id']) ? $_GET['entity_id'] : 'sensor.temp_temperatur';
|
|
|
|
$url = rtrim(HA_BASE_URL, '/') . '/api/states/' . urlencode($entityId);
|
|
|
|
$ch = curl_init($url);
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_HTTPHEADER => [
|
|
'Authorization: Bearer ' . HA_TOKEN,
|
|
'Content-Type: application/json'
|
|
],
|
|
CURLOPT_CONNECTTIMEOUT => 3,
|
|
CURLOPT_TIMEOUT => 5,
|
|
]);
|
|
$response = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$error = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
if ($response === false || $httpCode < 200 || $httpCode >= 300) {
|
|
http_response_code(502);
|
|
echo json_encode([
|
|
'error' => 'Home Assistant request failed',
|
|
'details' => $error ?: ('HTTP ' . $httpCode)
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
$data = json_decode($response, true);
|
|
if (!is_array($data) || !isset($data['state'])) {
|
|
http_response_code(500);
|
|
echo json_encode(['error' => 'Unexpected HA response']);
|
|
exit;
|
|
}
|
|
|
|
$val = $data['state'];
|
|
$unit = $data['attributes']['unit_of_measurement'] ?? '°C';
|
|
|
|
$CALIBRATION_OFFSET = +0;
|
|
|
|
if (is_numeric($val)) {
|
|
$number = round((float)$val + $CALIBRATION_OFFSET, 1);
|
|
} else {
|
|
$number = $val;
|
|
}
|
|
|
|
echo json_encode([
|
|
'entity_id' => $entityId,
|
|
'value' => $number,
|
|
'unit' => $unit,
|
|
'friendly_name' => $data['attributes']['friendly_name'] ?? null,
|
|
'last_changed' => $data['last_changed'] ?? null,
|
|
]);
|