homebridge-lookin-http-ac
Version:
79 lines • 2.68 kB
JavaScript
import { EventEmitter } from 'events';
import http from 'http';
export class SensorPoller extends EventEmitter {
ip;
name;
log;
intervalMs;
temperature = 24;
humidity = 50;
contactDetected = false;
intervalHandle;
contactIntervalHandle;
constructor(ip, name, log, intervalMs = 30000) {
super();
this.ip = ip;
this.name = name;
this.log = log;
this.intervalMs = intervalMs;
this.startPolling();
}
startPolling() {
this.intervalHandle = setInterval(() => this.fetchSensorData(), this.intervalMs);
this.contactIntervalHandle = setInterval(() => this.fetchContactState(), this.intervalMs);
this.fetchSensorData();
this.fetchContactState();
}
fetchSensorData() {
const url = `http://${this.ip}/sensors/meteo`;
http.get(url, res => {
let rawData = '';
res.on('data', chunk => rawData += chunk);
res.on('end', () => {
try {
const parsed = JSON.parse(rawData);
const temp = parseFloat(parsed.Temperature);
const hum = parseFloat(parsed.Humidity);
if (!isNaN(temp)) {
this.temperature = temp;
}
if (!isNaN(hum)) {
this.humidity = hum;
}
this.emit('update');
}
catch (err) {
this.log.warn(`[${this.name}] Sensor update failed: ${err}`);
}
});
}).on('error', err => {
this.log.warn(`[${this.name}] Sensor update failed: ${err}`);
});
}
fetchContactState() {
const url = `http://${this.ip}`;
http.get(url, res => {
let rawData = '';
res.on('data', chunk => rawData += chunk);
res.on('end', () => {
const text = rawData.trim();
const detected = res.statusCode === 200 && text === 'OK';
this.contactDetected = detected;
this.emit('contactUpdate', detected);
});
}).on('error', err => {
this.contactDetected = false;
this.emit('contactUpdate', false);
this.log.error(`[${this.name}] Contact poll failed: ${err}`);
});
}
stop() {
if (this.intervalHandle) {
clearInterval(this.intervalHandle);
}
if (this.contactIntervalHandle) {
clearInterval(this.contactIntervalHandle);
}
}
}
//# sourceMappingURL=sensorPoller.js.map