homebridge-vesync-v2
Version:
A Homebridge plugin for controlling VeSync smart devices including outlets, air purifiers, and humidifiers
90 lines (80 loc) • 3.14 kB
JavaScript
"use strict";
class BaseDevice {
constructor(accessory, client, log, debug, Service, Characteristic) {
log("[4] BaseDevice: constructor");
log("[5] BaseDevice: params=" + JSON.stringify({
acc: !!accessory,
ctx: !!accessory?.context,
name: accessory?.context?.name,
type: accessory?.context?.type
}));
this.accessory = accessory;
this.client = client;
this.log = log;
this.debug = debug;
this.Service = Service;
this.Characteristic = Characteristic;
log("[6] BaseDevice: initialized");
}
configureService() {
// To be overridden by subclasses which add services
// Then set On characteristic handlers
}
getPowerState(callback) {
if (this.accessory.context && this.accessory.context.id) {
this.client.login(this.accessory.platformConfig?.username, this.accessory.platformConfig?.password)
.then(() => this.client.getDevices())
.then(devices => {
return devices.find((device) => {
return device.name.includes(this.accessory.context.name);
});
}).then((device) => {
if (typeof device === 'undefined') {
if (this.debug) this.log("Removing undefined device", this.accessory.context.name);
// The platform handles removal, but we can log here
callback(new Error("Device not found"));
} else {
this.accessory.context.status = device.status;
callback(null, device.status == 'on');
}
}).catch(err => {
this.log(err);
callback(err);
});
} else {
callback(new Error("Device not found"));
}
}
setPowerState(powerState, callback) {
if (this.debug) this.log("Sending device status change");
this.client.login(this.accessory.platformConfig?.username, this.accessory.platformConfig?.password)
.then(() => this.client.getDevices())
.then(devices => {
return devices.find((device) => {
return device.name.includes(this.accessory.context.name);
});
}).then((device) => {
if (!device) {
throw new Error("Device not found");
}
this.accessory.context.status = device.status;
if (device.status == 'on' && powerState == false) {
return this.client.turnDevice(device, "off");
}
if (device.status == 'off' && powerState == true) {
return this.client.turnDevice(device, "on");
}
}).then(() => {
callback();
}).catch((err) => {
if (err == 'Error: No Content') {
callback();
return;
}
this.log(err);
this.log("Failed to set power state to", powerState);
callback(err);
});
}
}
module.exports = BaseDevice;