UNPKG

homebridge-hatch-baby-rest

Version:
60 lines (59 loc) 3.03 kB
import { hap } from "./hap.js"; import { debounceTime, map, startWith } from 'rxjs/operators'; import { Subject } from 'rxjs'; import { logInfo } from "./util.js"; import { SoundMachineAccessory } from "./sound-machine.js"; export class LightAndSoundMachineAccessory extends SoundMachineAccessory { constructor(light, accessory) { super(light, accessory); const { Service, Characteristic } = hap, { name } = light, lightService = this.getService(Service.Lightbulb, 'Light'), onOffService = this.getService(Service.Switch), onHsbSet = new Subject(), context = accessory.context, onBrightness = light.onBrightness.pipe(startWith(context.b || 0)); context.h = context.h || 0; context.s = context.s || 0; context.b = context.b || 0; light.onHue.subscribe((h) => (context.h = h)); light.onSaturation.subscribe((s) => (context.s = s)); onBrightness.subscribe((b) => { context.b = b; if (b > 0) { context.previousBrightness = b; } }); onHsbSet.pipe(debounceTime(100)).subscribe(() => { light.setHsb(context); }); this.registerCharacteristic(onOffService.getCharacteristic(Characteristic.On), light.onIsPowered, (on) => { logInfo(`Turning ${on ? 'on' : 'off'} ${name}`); light.setPower(on); }); this.registerCharacteristic(lightService.getCharacteristic(Characteristic.On), onBrightness.pipe(map((brightness) => Boolean(brightness))), (on) => { if (on) { context.b = context.previousBrightness || 100; } else { context.b = 0; } onHsbSet.next(null); }); this.registerCharacteristic(lightService.getCharacteristic(Characteristic.Hue), light.onHue, (hue) => { context.h = hue; onHsbSet.next(null); }); this.registerCharacteristic(lightService.getCharacteristic(Characteristic.Saturation), light.onSaturation, (saturation) => { context.s = saturation; onHsbSet.next(null); }); this.registerCharacteristic(lightService.getCharacteristic(Characteristic.Brightness), onBrightness, (brightness) => { context.b = brightness; onHsbSet.next(null); }); if (light.onBatteryLevel) { const batteryService = this.getService(Service.Battery, name); this.registerCharacteristic(batteryService.getCharacteristic(Characteristic.BatteryLevel), light.onBatteryLevel); this.registerCharacteristic(batteryService.getCharacteristic(Characteristic.StatusLowBattery), light.onBatteryLevel.pipe(map((batteryLevel) => (batteryLevel < 20 ? 1 : 0)))); batteryService .getCharacteristic(Characteristic.ChargingState) .updateValue(2); // "not chargeable". no way to detect if it is plugged in. } onOffService.setPrimaryService(true); } }