hc-magichome/HCMHAddressableSubsection.js

102 lines
2.5 KiB
JavaScript

const {
HCColorLamp,
StateUpdateManager,
utils,
} = require('homecontrol-control-base');
class HCMHAddressableSubsection extends HCColorLamp {
constructor(config, registry) {
super(config);
if (!("parent" in this._configuration)) {
throw new Error(`Required configuration field "parent" is missing"`);
}
if (!("section_id" in this._configuration)) {
throw new Error(`Required configuration field "section_id" is missing"`);
}
if (!("section_start" in this._configuration)) {
throw new Error(`Required configuration field "section_start" is missing"`);
}
if (!("section_end" in this._configuration)) {
throw new Error(`Required configuration field "section_end" is missing"`);
}
this._registry = registry;
this._parent = null;
// the default state should be white and 100% brightness
this._state.brightness = 100;
this._state.color.l = 100;
}
async init() {
for (let i = 0; i < 20; i++) {
if (this._configuration.parent in this._registry) {
this._parent = this._registry[this._configuration.parent];
this._parent.on("state change", state => {
this.pullState();
});
return;
} else {
await utils.asyncTimeout(100);
}
}
throw new Error("Could not connect to parent after 2 seconds");
}
turnOn() {
let { red, green, blue } = utils.HSL_to_RGB(this.state.color);
red = Math.round(red * this.state.brightness / 100);
green = Math.round(green * this.state.brightness / 100);
blue = Math.round(blue * this.state.brightness / 100);
this._state.on = true;
this.emit("state change", this.state);
return this._parent.setSubsectionColor(
this._configuration.section_start,
this._configuration.section_end,
this._configuration.section_id,
{ red, green, blue }
);
}
turnOff() {
this._state.on = false;
this.emit("state change", this.state);
return this._parent.removeSubsection(this._configuration.section_id);
}
setColor(color) {
this._state.color = utils.fillPartialHSL(color, this._state.color);
return this.turnOn();
}
setBrightness(brightness) {
this._state.brightness = brightness;
return this.turnOn();
}
pullState() {
if (this._parent == null) return Promise.resolve();
const futureState = this.state;
futureState.on = this._parent.isSubsectionActive(this._configuration.section_id);
if (this.state.hash != futureState.hash) {
this._state = futureState;
this.emit("state change", futureState);
}
return Promise.resolve();
}
}
module.exports = HCMHAddressableSubsection;