From 30ae80262854e6f74473024fd8465cb0f29d4257 Mon Sep 17 00:00:00 2001 From: Oliver Vogt Date: Mon, 24 Aug 2026 19:52:09 +0200 Subject: [PATCH] ha-client.js: HA-API-Client als eigenes Modul ausgelagert --- home-assistant-skill/ha-client.js | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 home-assistant-skill/ha-client.js diff --git a/home-assistant-skill/ha-client.js b/home-assistant-skill/ha-client.js new file mode 100644 index 0000000..65a3023 --- /dev/null +++ b/home-assistant-skill/ha-client.js @@ -0,0 +1,48 @@ +// ---- Home Assistant API Client ---- +require('dotenv').config(); + +const https = require('https'); + +const HA_URL = process.env.HA_URL; // z.B. "https://haos.vogt.de.com" +const HA_TOKEN = process.env.HA_TOKEN; // Long-Lived Access Token aus HA + +/** + * Fragt den aktuellen Zustand einer Home-Assistant-Entity ab. + * @param {string} entityId - z.B. "sensor.wohnzimmer_temperatur" + * @returns {Promise<{state: string, attributes: object}>} + */ +function getHaState(entityId) { + return new Promise((resolve, reject) => { + const url = new URL(`${HA_URL}/api/states/${entityId}`); + const options = { + hostname: url.hostname, + path: url.pathname, + method: 'GET', + headers: { + Authorization: `Bearer ${HA_TOKEN}`, + 'Content-Type': 'application/json', + }, + }; + + const req = https.request(options, (res) => { + let data = ''; + res.on('data', (chunk) => (data += chunk)); + res.on('end', () => { + if (res.statusCode !== 200) { + reject(new Error(`HA API Fehler: ${res.statusCode} - ${data}`)); + return; + } + try { + resolve(JSON.parse(data)); + } catch (e) { + reject(e); + } + }); + }); + + req.on('error', reject); + req.end(); + }); +} + +module.exports = { getHaState };