ha-client.js: HA-API-Client als eigenes Modul ausgelagert
This commit is contained in:
@@ -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 };
|
||||
Reference in New Issue
Block a user