hc-tplink-smartplug/HCTPLink.js
2019-01-29 22:10:28 +01:00

79 lines
1.8 KiB
JavaScript

const {
HCSwitch
} = require('homecontrol-control-base');
const TPLink = require('tplink-smartplug-node');
class HCTPLink extends HCSwitch {
constructor(config) {
super(config);
if (!("address" in this._configuration)) {
throw new Error(`Required configuration field "address" is missing"`);
}
}
turnOn() {
return new Promise((resolve, reject) => {
let tp = new TPLink(this._configuration.address, (err) => {
if (err) return reject(err);
tp.turnOn((parsed, resp) => {
if (!parsed) return reject("Could not parse response");
if (resp.system.set_relay_state.err_code == 0) {
this._state.on = true;
this.emit("state change", this.state);
return resolve();
} else {
return reject("Could not parse response");
}
});
});
});
}
turnOff() {
return new Promise((resolve, reject) => {
let tp = new TPLink(this._configuration.address, (err) => {
if (err) return reject(err);
tp.turnOff((parsed, resp) => {
if (!parsed) return reject("Could not parse response");
if (resp.system.set_relay_state.err_code == 0) {
this._state.on = false;
this.emit("state change", this.state);
return resolve();
} else {
return reject("Could not parse response");
}
});
});
});
}
pullState() {
return new Promise((resolve, reject) => {
let tp = new TPLink(this._configuration.address, (err) => {
if (err) return reject(err);
tp.getInfo((parsed, resp) => {
if (parsed) {
let hashBefore = this.state.hash;
this._state.on = (resp.system.get_sysinfo.relay_state == 1);
if (this.state.hash != hashBefore) {
this.emit("state change", this.state);
}
}
return resolve();
});
});
});
}
}
module.exports = HCTPLink;