hc-fogmachine-mqtt/HCFogmachineMQTT.js
2019-06-07 00:09:18 +02:00

63 lines
1.7 KiB
JavaScript

const {
HCFogmachine
} = require('homecontrol-control-base');
const mqtt = require('mqtt');
class HCFogmachineMQTT extends HCFogmachine {
constructor(config) {
super(config);
if (!("server" in this._configuration)) {
throw new Error(`Required configuration field "server" is missing"`);
}
if (!("control_topic" in this._configuration)) {
throw new Error(`Required configuration field "control_topic" is missing"`);
}
if (!("indicator_topic" in this._configuration)) {
throw new Error(`Required configuration field "indicator_topic" is missing"`);
}
this._client = null;
}
init() {
return new Promise((resolve, reject) => {
this._client = mqtt.connect(this._configuration.server);
this._client.on("connect", () => {
this._client.subscribe(this._configuration.indicator_topic, err => {
if (err) return reject(err);
resolve();
});
});
this._client.on("error", err => {
reject(err);
});
this._client.on("message", (topic, messageBuf) => {
let message = messageBuf.toString();
if (topic != this._configuration.indicator_topic) return;
this._state.ready = (message == "1");
this.emit("state change", this.state);
});
});
}
triggerFor(milliseconds) {
return new Promise((resolve, reject) => {
this._client.publish(this._configuration.control_topic, String(milliseconds), err => {
if (err) return reject(err);
resolve();
});
});
}
}
module.exports = HCFogmachineMQTT;