@switchbot/homebridge-switchbot
Version:
The SwitchBot plugin allows you to access your SwitchBot device(s) from HomeKit.
892 lines • 45 kB
JavaScript
/*
* For Testing Locally:
* import { SwitchBotBLEModel, SwitchBotBLEModelName } from '/Users/Shared/GitHub/OpenWonderLabs/node-switchbot/dist/index.js';
*/
import { SwitchBotBLEModel, SwitchBotBLEModelName } from 'node-switchbot';
import { debounceTime, interval, skipWhile, Subject, take, tap } from 'rxjs';
import { formatDeviceIdAsMac, hs2rgb, m2hs, rgb2hs } from '../utils.js';
import { deviceBase } from './device.js';
/**
* Platform Accessory
* An instance of this class is created for each accessory your platform registers
* Each accessory may expose multiple services of different service types.
*/
export class ColorBulb extends deviceBase {
platform;
// Services
LightBulb;
// OpenAPI
deviceStatus;
// Webhook
webhookContext;
// BLE
serviceData;
// Adaptive Lighting
adaptiveLighting;
adaptiveLightingShift;
AdaptiveLightingController;
// Updates
colorBulbUpdateInProgress;
doColorBulbUpdate;
constructor(platform, accessory, device) {
super(platform, accessory, device);
this.platform = platform;
// Set category
accessory.category = 5 /* this.hap.Categories.LIGHTBULB */;
// default placeholders
this.getAdaptiveLightingSettings(accessory, device);
// this is subject we use to track when we need to POST changes to the SwitchBot API
this.doColorBulbUpdate = new Subject();
this.colorBulbUpdateInProgress = false;
// Initialize LightBulb property
accessory.context.LightBulb = accessory.context.LightBulb ?? {};
this.LightBulb = {
Name: accessory.displayName,
Service: accessory.getService(this.hap.Service.Lightbulb) ?? accessory.addService(this.hap.Service.Lightbulb),
On: accessory.context.On ?? false,
Hue: accessory.context.Hue ?? 0,
Saturation: accessory.context.Saturation ?? 0,
Brightness: accessory.context.Brightness ?? 0,
ColorTemperature: accessory.context.ColorTemperature ?? 140,
};
accessory.context.LightBulb = this.LightBulb;
// Initialize LightBulb Characteristics
this.LightBulb.Service.setCharacteristic(this.hap.Characteristic.Name, this.LightBulb.Name).getCharacteristic(this.hap.Characteristic.On).onGet(() => {
return this.LightBulb.On;
}).onSet(this.OnSet.bind(this));
this.LightBulb.Service.getCharacteristic(this.hap.Characteristic.Brightness).setProps({
minStep: device?.set_minStep ?? 1,
minValue: 0,
maxValue: 100,
validValueRanges: [0, 100],
}).onGet(() => {
return this.LightBulb.Brightness;
}).onSet(this.BrightnessSet.bind(this));
this.LightBulb.Service.getCharacteristic(this.hap.Characteristic.ColorTemperature).setProps({
minValue: 140,
maxValue: 500,
validValueRanges: [140, 500],
}).onGet(() => {
return this.LightBulb.ColorTemperature;
}).onSet(this.ColorTemperatureSet.bind(this));
this.LightBulb.Service.getCharacteristic(this.hap.Characteristic.Hue).setProps({
minValue: 0,
maxValue: 360,
validValueRanges: [0, 360],
}).onGet(() => {
return this.LightBulb.Hue;
}).onSet(this.HueSet.bind(this));
this.LightBulb.Service.getCharacteristic(this.hap.Characteristic.Saturation).setProps({
minValue: 0,
maxValue: 100,
validValueRanges: [0, 100],
}).onGet(() => {
return this.LightBulb.Saturation;
}).onSet(this.SaturationSet.bind(this));
if (this.adaptiveLighting && this.adaptiveLightingShift === -1 && this.LightBulb) {
accessory.removeService(this.LightBulb.Service);
this.LightBulb.Service = accessory.addService(this.hap.Service.Lightbulb);
accessory.context.adaptiveLighting = false;
this.debugLog(`adaptiveLighting: ${this.adaptiveLighting}`);
}
else if (this.adaptiveLighting && this.adaptiveLightingShift >= 0 && this.LightBulb) {
this.AdaptiveLightingController = new platform.api.hap.AdaptiveLightingController(this.LightBulb.Service, {
controllerMode: 1 /* this.hap.AdaptiveLightingControllerMode.AUTOMATIC */,
customTemperatureAdjustment: this.adaptiveLightingShift,
});
accessory.configureController(this.AdaptiveLightingController);
accessory.context.adaptiveLighting = true;
this.debugLog(`adaptiveLighting: ${this.adaptiveLighting}, adaptiveLightingShift: ${this.adaptiveLightingShift}`);
}
else {
accessory.context.adaptiveLighting = false;
this.debugLog(`adaptiveLighting: ${accessory.context.adaptiveLighting}`);
}
// Retrieve initial values and updateHomekit
try {
this.debugLog('Retrieve initial values and update Homekit');
this.refreshStatus();
}
catch (e) {
this.errorLog(`failed to retrieve initial values and update Homekit, Error: ${e.message ?? e}`);
}
// regisiter webhook event handler if enabled
try {
this.debugLog('Registering Webhook Event Handler');
this.registerWebhook();
}
catch (e) {
this.errorLog(`failed to registerWebhook, Error: ${e.message ?? e}`);
}
// regisiter platform BLE event handler if enabled
try {
this.debugLog('Registering Platform BLE Event Handler');
this.registerPlatformBLE();
}
catch (e) {
this.errorLog(`failed to registerPlatformBLE, Error: ${e.message ?? e}`);
}
// Start an update interval
interval(this.deviceRefreshRate * 1000)
.pipe(skipWhile(() => this.colorBulbUpdateInProgress))
.subscribe(async () => {
await this.refreshStatus();
});
// Watch for Bulb change events
// We put in a debounce of 100ms so we don't make duplicate calls
this.doColorBulbUpdate
.pipe(tap(() => {
this.colorBulbUpdateInProgress = true;
}), debounceTime(this.devicePushRate * 1000))
.subscribe(async () => {
try {
await this.pushChanges();
}
catch (e) {
await this.apiError(e);
this.errorLog(`failed pushChanges with ${device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`);
}
this.colorBulbUpdateInProgress = false;
});
}
/**
* Parse the device status from the SwitchBotBLE API
*/
async BLEparseStatus() {
this.debugLog('BLEparseStatus');
// On
this.LightBulb.On = this.serviceData.power;
this.debugLog(`On: ${this.LightBulb.On}`);
// Brightness
this.LightBulb.Brightness = this.serviceData.brightness;
this.debugLog(`Brightness: ${this.LightBulb.Brightness}`);
// Color, Hue & Brightness
this.debugLog(`red: ${this.serviceData.red}, green: ${this.serviceData.green}, blue: ${this.serviceData.blue}`);
if (this.serviceData.red !== undefined && this.serviceData.green !== undefined && this.serviceData.blue !== undefined) {
const [hue, saturation] = rgb2hs(this.serviceData.red, this.serviceData.green, this.serviceData.blue);
this.debugLog(`hs: ${JSON.stringify(rgb2hs(this.serviceData.red, this.serviceData.green, this.serviceData.blue))}`);
// Hue
this.LightBulb.Hue = hue;
this.debugLog(`Hue: ${this.LightBulb.Hue}`);
// Saturation
this.LightBulb.Saturation = saturation;
this.debugLog(`Saturation: ${this.LightBulb.Saturation}`);
}
else {
this.errorLog(`Invalid color data: red=${this.serviceData.red}, green=${this.serviceData.green}, blue=${this.serviceData.blue}`);
}
// ColorTemperature
const miredColorTemperature = Math.round(1000000 / this.serviceData.color_temperature);
this.LightBulb.ColorTemperature = Math.max(Math.min(miredColorTemperature, 500), 140);
this.debugLog(`ColorTemperature: ${this.LightBulb.ColorTemperature}`);
}
/**
* Parse the device status from the SwitchBot OpenAPI
*/
async openAPIparseStatus() {
this.debugLog('openAPIparseStatus');
// On
this.LightBulb.On = this.deviceStatus.power === 'on';
this.debugLog(`On: ${this.LightBulb.On}`);
// Brightness
this.LightBulb.Brightness = this.deviceStatus.brightness;
this.debugLog(`Brightness: ${this.LightBulb.Brightness}`);
// Color, Hue & Brightness
if (typeof this.deviceStatus.color === 'string') {
this.debugLog(`color: ${JSON.stringify(this.deviceStatus.color)}`);
const [red, green, blue] = this.deviceStatus.color.split(':');
this.debugLog(`red: ${JSON.stringify(red)}, green: ${JSON.stringify(green)}, blue: ${JSON.stringify(blue)}`);
const [hue, saturation] = rgb2hs(red, green, blue);
this.debugLog(`hs: ${JSON.stringify(rgb2hs(red, green, blue))}`);
// Hue
this.LightBulb.Hue = hue;
this.debugLog(`Hue: ${this.LightBulb.Hue}`);
// Saturation
this.LightBulb.Saturation = saturation;
this.debugLog(`Saturation: ${this.LightBulb.Saturation}`);
}
else {
this.errorLog(`Invalid color format: ${JSON.stringify(this.deviceStatus.color)}`);
}
// ColorTemperature
const miredColorTemperature = Math.round(1000000 / this.deviceStatus.colorTemperature);
this.LightBulb.ColorTemperature = Math.max(Math.min(miredColorTemperature, 500), 140);
this.debugLog(`ColorTemperature: ${this.LightBulb.ColorTemperature}`);
// Firmware Version
if (this.deviceStatus.version) {
const version = this.deviceStatus.version.toString();
this.debugLog(`Firmware Version: ${version.replace(/^V|-.*$/g, '')}`);
const deviceVersion = version.replace(/^V|-.*$/g, '') ?? '0.0.0';
this.accessory
.getService(this.hap.Service.AccessoryInformation)
.setCharacteristic(this.hap.Characteristic.HardwareRevision, deviceVersion)
.setCharacteristic(this.hap.Characteristic.FirmwareRevision, deviceVersion)
.getCharacteristic(this.hap.Characteristic.FirmwareRevision)
.updateValue(deviceVersion);
this.accessory.context.version = deviceVersion;
this.debugSuccessLog(`version: ${this.accessory.context.version}`);
}
}
async parseStatusWebhook() {
this.debugLog('parseStatusWebhook');
this.debugLog(`(powerState, brightness, color, colorTemperature) = Webhook:(${this.webhookContext.powerState}, ${this.webhookContext.brightness}, ${this.webhookContext.color}, ${this.webhookContext.colorTemperature}), current:(${this.LightBulb.On}, ${this.LightBulb.Brightness}, ${this.LightBulb.Hue}, ${this.LightBulb.Saturation}, ${this.LightBulb.ColorTemperature})`);
// On
this.LightBulb.On = this.webhookContext.powerState === 'ON';
this.debugLog(`On: ${this.LightBulb.On}`);
// Brightness
this.LightBulb.Brightness = this.webhookContext.brightness;
this.debugLog(`Brightness: ${this.LightBulb.Brightness}`);
// Color, Hue & Brightness
if (typeof this.webhookContext.color === 'string') {
this.debugLog(`color: ${JSON.stringify(this.webhookContext.color)}`);
const [red, green, blue] = this.webhookContext.color.split(':');
this.debugLog(`red: ${JSON.stringify(red)}, green: ${JSON.stringify(green)}, blue: ${JSON.stringify(blue)}`);
const [hue, saturation] = rgb2hs(red, green, blue);
this.debugLog(`hs: ${JSON.stringify(rgb2hs(red, green, blue))}`);
// Hue
this.LightBulb.Hue = hue;
this.debugLog(`Hue: ${this.LightBulb.Hue}`);
// Saturation
this.LightBulb.Saturation = saturation;
this.debugLog(`Saturation: ${this.LightBulb.Saturation}`);
}
else {
this.errorLog(`Invalid color format: ${JSON.stringify(this.webhookContext.color)}`);
}
// ColorTemperature
const miredColorTemperature = Math.round(1000000 / this.webhookContext.colorTemperature);
this.LightBulb.ColorTemperature = Math.max(Math.min(miredColorTemperature, 500), 140);
this.debugLog(`ColorTemperature: ${this.LightBulb.ColorTemperature}`);
}
/**
* Asks the SwitchBot API for the latest device information
*/
async refreshStatus() {
if (!this.device.enableCloudService && this.OpenAPI) {
this.errorLog(`refreshStatus enableCloudService: ${this.device.enableCloudService}`);
}
else if (this.BLE) {
await this.BLERefreshStatus();
}
else if (this.OpenAPI && this.platform.config.credentials?.token) {
await this.openAPIRefreshStatus();
}
else {
await this.offlineOff();
this.debugWarnLog(`Connection Type: ${this.device.connectionType}, refreshStatus will not happen.`);
}
}
async BLERefreshStatus() {
this.debugLog('BLERefreshStatus');
const switchBotBLE = await this.switchbotBLE();
if (switchBotBLE === undefined) {
await this.BLERefreshConnection(switchBotBLE);
}
else {
// Start to monitor advertisement packets
(async () => {
// Start to monitor advertisement packets
const serviceData = await this.monitorAdvertisementPackets(switchBotBLE);
// Update HomeKit
if (serviceData.model === SwitchBotBLEModel.ColorBulb && serviceData.modelName === SwitchBotBLEModelName.ColorBulb) {
this.serviceData = serviceData;
if (serviceData !== undefined || serviceData !== null) {
await this.BLEparseStatus();
await this.updateHomeKitCharacteristics();
}
else {
this.errorLog(`serviceData is either undefined or null, serviceData: ${JSON.stringify(serviceData)}`);
await this.BLERefreshConnection(switchBotBLE);
}
}
else {
this.errorLog(`failed to get serviceData, serviceData: ${JSON.stringify(serviceData)}`);
await this.BLERefreshConnection(switchBotBLE);
}
})();
}
}
async registerPlatformBLE() {
this.debugLog('registerPlatformBLE');
if (this.config.options?.BLE && !this.device.disablePlatformBLE) {
this.debugLog('is listening to Platform BLE.');
try {
const formattedDeviceId = formatDeviceIdAsMac(this.device.deviceId);
this.device.bleMac = formattedDeviceId;
this.debugLog(`bleMac: ${this.device.bleMac}`);
this.platform.bleEventHandler[this.device.bleMac] = async (context) => {
try {
this.serviceData = context;
if (context !== undefined || context !== null) {
this.debugLog(`received BLE: ${JSON.stringify(context)}`);
await this.BLEparseStatus();
await this.updateHomeKitCharacteristics();
}
else {
this.errorLog(`context is either undefined or null, context: ${JSON.stringify(context)}`);
await this.BLERefreshConnection(context);
}
}
catch (e) {
this.errorLog(`failed to handle BLE. Received: ${JSON.stringify(context)} Error: ${e.message ?? e}`);
}
};
}
catch (error) {
this.errorLog(`failed to format device ID as MAC, Error: ${error}`);
}
}
else {
this.debugLog('is not listening to Platform BLE');
}
}
async openAPIRefreshStatus() {
this.debugLog('openAPIRefreshStatus');
try {
const response = await this.deviceRefreshStatus();
const deviceStatus = response.body;
this.debugLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`);
if (await this.successfulStatusCodes(deviceStatus)) {
this.debugSuccessLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`);
this.deviceStatus = deviceStatus.body;
await this.openAPIparseStatus();
await this.updateHomeKitCharacteristics();
}
else {
this.debugWarnLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`);
}
}
catch (e) {
await this.apiError(e);
this.errorLog(`failed openAPIRefreshStatus with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`);
}
}
async registerWebhook() {
if (this.device.webhook) {
this.debugLog('is listening webhook.');
this.platform.webhookEventHandler[this.device.deviceId] = async (context) => {
try {
this.webhookContext = context;
if (context !== undefined || context !== null) {
this.debugLog(`received Webhook: ${JSON.stringify(context)}`);
await this.parseStatusWebhook();
await this.updateHomeKitCharacteristics();
}
else {
this.errorLog(`context is either undefined or null, context: ${JSON.stringify(context)}`);
}
}
catch (e) {
this.errorLog(`failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e.message ?? e}`);
}
};
}
else {
this.debugLog('is not listening webhook.');
}
}
/**
* Pushes the requested changes to the SwitchBot API
* deviceType commandType Command command parameter Description
* Color Bulb - "command" "turnOff" "default" = set to OFF state
* Color Bulb - "command" "turnOn" "default" = set to ON state
* Color Bulb - "command" "toggle" "default" = toggle state
* Color Bulb - "command" "setBrightness" "{1-100}" = set brightness
* Color Bulb - "command" "setColor" "{0-255}:{0-255}:{0-255}" = set RGB color value
* Color Bulb - "command" "setColorTemperature" "{2700-6500}" = set color temperature
*
*/
async pushChanges() {
if (!this.device.enableCloudService && this.OpenAPI) {
this.errorLog(`pushChanges enableCloudService: ${this.device.enableCloudService}`);
}
else if (this.BLE) {
await this.BLEpushChanges();
if (this.LightBulb.On) {
// Push Brightness Update
this.debugLog(`Brightness: ${this.LightBulb.Brightness}`);
await this.BLEpushBrightnessChanges();
// Push ColorTemperature Update
this.debugLog(`ColorTemperature: ${this.LightBulb.ColorTemperature}`);
await this.BLEpushColorTemperatureChanges();
// Push Hue & Saturation Update
this.debugLog(`Hue: ${this.LightBulb.Hue}, Saturation: ${this.LightBulb.Saturation}`);
await this.BLEpushRGBChanges();
}
else {
this.debugLog('BLE (Brightness), (ColorTemperature), (Hue), & (Saturation) changes will not happen, as the device is OFF.');
}
}
else if (this.OpenAPI && this.platform.config.credentials?.token) {
await this.openAPIpushChanges();
if (this.LightBulb.On) {
// Push Brightness Update
this.debugLog(`Brightness: ${this.LightBulb.Brightness}`);
await this.pushBrightnessChanges();
// Push ColorTemperature Update
this.debugLog(`ColorTemperature: ${this.LightBulb.ColorTemperature}`);
await this.pushColorTemperatureChanges();
// Push Hue & Saturation Update
this.debugLog(`Hue: ${this.LightBulb.Hue}, Saturation: ${this.LightBulb.Saturation}`);
await this.pushHueSaturationChanges();
}
else {
this.debugLog('openAPI (Brightness), (ColorTemperature), (Hue), & (Saturation) changes will not happen, as the device is OFF.');
}
}
else {
await this.offlineOff();
this.debugWarnLog(`Connection Type: ${this.device.connectionType}, pushChanges will not happen.`);
}
// Refresh the status from the API
interval(15000)
.pipe(skipWhile(() => this.colorBulbUpdateInProgress))
.pipe(take(1))
.subscribe(async () => {
await this.refreshStatus();
});
}
async BLEpushChanges() {
this.debugLog('BLEpushChanges');
if (this.LightBulb.On !== this.accessory.context.On) {
this.debugLog(`BLEpushChanges On: ${this.LightBulb.On}, OnCached: ${this.accessory.context.On}`);
const switchBotBLE = await this.platform.connectBLE(this.accessory, this.device);
try {
const formattedDeviceId = formatDeviceIdAsMac(this.device.deviceId);
this.device.bleMac = formattedDeviceId;
this.debugLog(`bleMac: ${this.device.bleMac}`);
if (switchBotBLE !== false) {
switchBotBLE
.discover({ model: this.device.bleModel, id: this.device.bleMac })
.then(async (device_list) => {
this.infoLog(`On: ${this.LightBulb.On}`);
return await this.retryBLE({
max: this.maxRetryBLE(),
fn: async () => {
if (this.LightBulb.On) {
return await device_list[0].turnOn();
}
else {
return await device_list[0].turnOff();
}
},
});
})
.then(async () => {
this.successLog(`On: ${this.LightBulb.On} sent over SwitchBot BLE, sent successfully`);
await this.updateHomeKitCharacteristics();
})
.catch(async (e) => {
await this.apiError(e);
this.errorLog(`failed BLEpushChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`);
await this.BLEPushConnection();
});
}
else {
this.errorLog(`wasn't able to establish BLE Connection, node-switchbot: ${JSON.stringify(switchBotBLE)}`);
await this.BLEPushConnection();
}
}
catch (error) {
this.errorLog(`failed to format device ID as MAC, Error: ${error}`);
}
}
else {
this.debugLog(`No changes (BLEpushChanges), On: ${this.LightBulb.On}, OnCached: ${this.accessory.context.On}`);
}
}
async BLEpushBrightnessChanges() {
this.debugLog('BLEpushBrightnessChanges');
if (this.LightBulb.Brightness !== this.accessory.context.Brightness) {
const switchBotBLE = await this.platform.connectBLE(this.accessory, this.device);
try {
const formattedDeviceId = formatDeviceIdAsMac(this.device.deviceId);
this.device.bleMac = formattedDeviceId;
this.debugLog(`bleMac: ${this.device.bleMac}`);
if (switchBotBLE !== false) {
switchBotBLE
.discover({ model: this.device.bleModel, id: this.device.bleMac })
.then(async (device_list) => {
const deviceList = device_list;
this.infoLog(`Target Brightness: ${this.LightBulb.Brightness}`);
return await deviceList[0].setBrightness(Number(this.LightBulb.Brightness));
})
.then(async () => {
this.successLog(`Brightness: ${this.LightBulb.Brightness} sent over SwitchBot BLE, sent successfully`);
await this.updateHomeKitCharacteristics();
})
.catch(async (e) => {
await this.apiError(e);
this.errorLog(`failed BLEpushChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`);
await this.BLEPushConnection();
});
}
else {
this.errorLog(`wasn't able to establish BLE Connection, node-switchbot: ${JSON.stringify(switchBotBLE)}`);
await this.BLEPushConnection();
}
}
catch (error) {
this.errorLog(`failed to format device ID as MAC, Error: ${error}`);
}
}
else {
this.debugLog(`No changes (BLEpushBrightnessChanges), Brightness: ${this.LightBulb.Brightness}, BrightnessCached: ${this.accessory.context.Brightness}`);
}
}
async BLEpushColorTemperatureChanges() {
this.debugLog('BLEpushColorTemperatureChanges');
if (this.LightBulb.ColorTemperature !== this.accessory.context.ColorTemperature) {
const kelvin = Math.round(1000000 / Number(this.LightBulb.ColorTemperature));
this.accessory.context.kelvin = kelvin;
const switchBotBLE = await this.platform.connectBLE(this.accessory, this.device);
try {
const formattedDeviceId = formatDeviceIdAsMac(this.device.deviceId);
this.device.bleMac = formattedDeviceId;
this.debugLog(`bleMac: ${this.device.bleMac}`);
if (switchBotBLE !== false) {
switchBotBLE
.discover({ model: this.device.bleModel, id: this.device.bleMac })
.then(async (device_list) => {
const deviceList = device_list;
this.infoLog(`ColorTemperature: ${this.LightBulb.ColorTemperature}`);
return await deviceList[0].setColorTemperature(kelvin);
})
.then(async () => {
this.successLog(`ColorTemperature: ${this.LightBulb.ColorTemperature} sent over SwitchBot BLE, sent successfully`);
await this.updateHomeKitCharacteristics();
})
.catch(async (e) => {
await this.apiError(e);
this.errorLog(`failed BLEpushRGBChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`);
await this.BLEPushConnection();
});
}
else {
this.errorLog(`wasn't able to establish BLE Connection, node-switchbot: ${JSON.stringify(switchBotBLE)}`);
await this.BLEPushConnection();
}
}
catch (error) {
this.errorLog(`failed to format device ID as MAC, Error: ${error}`);
}
}
else {
this.debugLog(`No changes (BLEpushColorTemperatureChanges), ColorTemperature: ${this.LightBulb.ColorTemperature}, ColorTemperatureCached: ${this.accessory.context.ColorTemperature}`);
}
}
async BLEpushRGBChanges() {
this.debugLog('BLEpushRGBChanges');
if ((this.LightBulb.Hue !== this.accessory.context.Hue) || (this.LightBulb.Saturation !== this.accessory.context.Saturation)) {
this.debugLog(`Hue: ${JSON.stringify(this.LightBulb.Hue)}, Saturation: ${JSON.stringify(this.LightBulb.Saturation)}`);
const [red, green, blue] = hs2rgb(this.LightBulb.Hue, this.LightBulb.Saturation);
this.debugLog(`rgb: ${JSON.stringify([red, green, blue])}`);
const switchBotBLE = await this.platform.connectBLE(this.accessory, this.device);
try {
const formattedDeviceId = formatDeviceIdAsMac(this.device.deviceId);
this.device.bleMac = formattedDeviceId;
this.debugLog(`bleMac: ${this.device.bleMac}`);
if (switchBotBLE !== false) {
switchBotBLE
.discover({ model: this.device.bleModel, id: this.device.bleMac })
.then(async (device_list) => {
const deviceList = device_list;
this.infoLog(`RGB: ${(this.LightBulb.Brightness, red, green, blue)}`);
return await deviceList[0].setRGB(Number(this.LightBulb.Brightness), red, green, blue);
})
.then(async () => {
this.successLog(`RGB: ${(this.LightBulb.Brightness, red, green, blue)} sent over SwitchBot BLE, sent successfully`);
await this.updateHomeKitCharacteristics();
})
.catch(async (e) => {
await this.apiError(e);
this.errorLog(`failed BLEpushRGBChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`);
await this.BLEPushConnection();
});
}
else {
this.errorLog(`wasn't able to establish BLE Connection, node-switchbot: ${JSON.stringify(switchBotBLE)}`);
await this.BLEPushConnection();
}
}
catch (error) {
this.errorLog(`failed to format device ID as MAC, Error: ${error}`);
}
}
else {
this.debugLog(`No changes (BLEpushRGBChanges), Hue: ${this.LightBulb.Hue}, HueCached: ${this.accessory.context.Hue}, Saturation: ${this.LightBulb.Saturation}, SaturationCached: ${this.accessory.context.Saturation}`);
}
}
async openAPIpushChanges() {
this.debugLog('openAPIpushChanges');
if (this.LightBulb.On !== this.accessory.context.On) {
const command = this.LightBulb.On ? 'turnOn' : 'turnOff';
const bodyChange = {
command: `${command}`,
parameter: 'default',
commandType: 'command',
};
this.debugLog(`SwitchBot OpenAPI bodyChange: ${JSON.stringify(bodyChange)}`);
try {
const response = await this.pushChangeRequest(bodyChange);
const deviceStatus = response.body;
this.debugLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`);
if (await this.successfulStatusCodes(deviceStatus)) {
this.debugSuccessLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`);
await this.updateHomeKitCharacteristics();
}
else {
await this.statusCode(deviceStatus.statusCode);
}
}
catch (e) {
await this.apiError(e);
this.errorLog(`failed openAPIpushChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`);
}
}
else {
this.debugLog(`No changes (openAPIpushChanges), On: ${this.LightBulb.On}, OnCached: ${this.accessory.context.On}`);
}
}
async pushHueSaturationChanges() {
this.debugLog('pushHueSaturationChanges');
if ((this.LightBulb.Hue !== this.accessory.context.Hue) || (this.LightBulb.Saturation !== this.accessory.context.Saturation)) {
this.debugLog(`Hue: ${JSON.stringify(this.LightBulb.Hue)}, Saturation: ${JSON.stringify(this.LightBulb.Saturation)}`);
const [red, green, blue] = hs2rgb(this.LightBulb.Hue, this.LightBulb.Saturation);
this.debugLog(`rgb: ${JSON.stringify([red, green, blue])}`);
const bodyChange = {
command: 'setColor',
parameter: `${red}:${green}:${blue}`,
commandType: 'command',
};
this.debugLog(`SwitchBot OpenAPI bodyChange: ${JSON.stringify(bodyChange)}`);
try {
const response = await this.pushChangeRequest(bodyChange);
const deviceStatus = response.body;
this.debugLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`);
if (await this.successfulStatusCodes(deviceStatus)) {
this.debugSuccessLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`);
await this.updateHomeKitCharacteristics();
}
else {
await this.statusCode(deviceStatus.statusCode);
}
}
catch (e) {
await this.apiError(e);
this.errorLog(`failed pushHueSaturationChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`);
}
}
else {
this.debugLog(`No changes (pushHueSaturationChanges), Hue: ${this.LightBulb.Hue}, HueCached: ${this.accessory.context.Hue}, Saturation: ${this.LightBulb.Saturation}, SaturationCached: ${this.accessory.context.Saturation}`);
}
}
async pushColorTemperatureChanges() {
this.debugLog('pushColorTemperatureChanges');
if (this.LightBulb.ColorTemperature !== this.accessory.context.ColorTemperature) {
const kelvin = Math.round(1000000 / Number(this.LightBulb.ColorTemperature));
this.accessory.context.kelvin = kelvin;
const bodyChange = {
command: 'setColorTemperature',
parameter: `${kelvin}`,
commandType: 'command',
};
this.debugLog(`SwitchBot OpenAPI bodyChange: ${JSON.stringify(bodyChange)}`);
try {
const response = await this.pushChangeRequest(bodyChange);
const deviceStatus = response.body;
this.debugLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`);
if (await this.successfulStatusCodes(deviceStatus)) {
this.debugSuccessLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`);
await this.updateHomeKitCharacteristics();
}
else {
await this.statusCode(deviceStatus.statusCode);
}
}
catch (e) {
await this.apiError(e);
this.errorLog(`failed pushColorTemperatureChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`);
}
}
else {
this.debugLog(`No changes (pushColorTemperatureChanges), ColorTemperature: ${this.LightBulb.ColorTemperature}, ColorTemperatureCached: ${this.accessory.context.ColorTemperature}`);
}
}
async pushBrightnessChanges() {
this.debugLog('pushBrightnessChanges');
if (this.LightBulb.Brightness !== this.accessory.context.Brightness) {
const bodyChange = {
command: 'setBrightness',
parameter: `${this.LightBulb.Brightness}`,
commandType: 'command',
};
this.debugLog(`SwitchBot OpenAPI bodyChange: ${JSON.stringify(bodyChange)}`);
try {
const response = await this.pushChangeRequest(bodyChange);
const deviceStatus = response.body;
this.debugLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`);
if (await this.successfulStatusCodes(deviceStatus)) {
this.debugSuccessLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`);
await this.updateHomeKitCharacteristics();
}
else {
await this.statusCode(deviceStatus.statusCode);
}
}
catch (e) {
await this.apiError(e);
this.errorLog(`failed pushBrightnessChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`);
}
}
else {
this.debugLog(`No changes (pushBrightnessChanges), Brightness: ${this.LightBulb.Brightness}, BrightnessCached: ${this.accessory.context.Brightness}`);
}
}
/**
* Handle requests to set the value of the "On" characteristic
*/
async OnSet(value) {
if (this.LightBulb.On !== this.accessory.context.On) {
this.infoLog(`Set On: ${value}`);
}
else {
this.debugLog(`No Changes, On: ${value}`);
}
this.LightBulb.On = value;
this.doColorBulbUpdate.next();
}
/**
* Handle requests to set the value of the "Brightness" characteristic
*/
async BrightnessSet(value) {
if (this.LightBulb.On && (this.LightBulb.Brightness !== this.accessory.context.Brightness)) {
this.infoLog(`Set Brightness: ${value}`);
}
else {
if (this.LightBulb.On) {
this.debugLog(`No Changes, Brightness: ${value}`);
}
else {
this.debugLog(`Brightness: ${value}, On: ${this.LightBulb.On}`);
}
}
this.LightBulb.Brightness = value;
this.doColorBulbUpdate.next();
}
/**
* Handle requests to set the value of the "ColorTemperature" characteristic
*/
async ColorTemperatureSet(value) {
if (this.LightBulb.On && (this.LightBulb.ColorTemperature !== this.accessory.context.ColorTemperature)) {
this.infoLog(`Set ColorTemperature: ${value}`);
}
else {
if (this.LightBulb.On) {
this.debugLog(`No Changes, ColorTemperature: ${value}`);
}
else {
this.debugLog(`Set ColorTemperature: ${value}, On: ${this.LightBulb.On}`);
}
}
const minKelvin = 2000;
const maxKelvin = 9000;
// Convert mired to kelvin to nearest 100 (SwitchBot seems to need this)
const kelvin = Math.round(1000000 / Number(value) / 100) * 100;
// Check and increase/decrease kelvin to range of device
const k = Math.min(Math.max(kelvin, minKelvin), maxKelvin);
if (!this.accessory.context.On || this.accessory.context.kelvin === k) {
return;
}
// Updating the hue/sat to the corresponding values mimics native adaptive lighting
const hs = m2hs(value);
this.LightBulb.Service.updateCharacteristic(this.hap.Characteristic.Hue, hs[0]);
this.LightBulb.Service.updateCharacteristic(this.hap.Characteristic.Saturation, hs[1]);
this.LightBulb.ColorTemperature = value;
this.doColorBulbUpdate.next();
}
/**
* Handle requests to set the value of the "Hue" characteristic
*/
async HueSet(value) {
if (this.LightBulb.On && (this.LightBulb.Hue !== this.accessory.context.Hue)) {
this.infoLog(`Set Hue: ${value}`);
}
else {
if (this.LightBulb.On) {
this.debugLog(`No Changes, Hue: ${value}`);
}
else {
this.debugLog(`Set Hue: ${value}, On: ${this.LightBulb.On}`);
}
}
this.LightBulb.Service.updateCharacteristic(this.hap.Characteristic.ColorTemperature, 140);
this.LightBulb.Hue = value;
this.doColorBulbUpdate.next();
}
/**
* Handle requests to set the value of the "Saturation" characteristic
*/
async SaturationSet(value) {
if (this.LightBulb.On && (this.LightBulb.Saturation !== this.accessory.context.Saturation)) {
this.infoLog(`Set Saturation: ${value}`);
}
else {
if (this.LightBulb.On) {
this.debugLog(`No Changes, Saturation: ${value}`);
}
else {
this.debugLog(`Set Saturation: ${value}, On: ${this.LightBulb.On}`);
}
}
this.LightBulb.Service.updateCharacteristic(this.hap.Characteristic.ColorTemperature, 140);
this.LightBulb.Saturation = value;
this.doColorBulbUpdate.next();
}
async updateHomeKitCharacteristics() {
// On
await this.updateCharacteristic(this.LightBulb.Service, this.hap.Characteristic.On, this.LightBulb.On, 'On');
// Brightness
await this.updateCharacteristic(this.LightBulb.Service, this.hap.Characteristic.Brightness, this.LightBulb.Brightness, 'Brightness');
// ColorTemperature
await this.updateCharacteristic(this.LightBulb.Service, this.hap.Characteristic.ColorTemperature, this.LightBulb.ColorTemperature, 'ColorTemperature');
// Hue
await this.updateCharacteristic(this.LightBulb.Service, this.hap.Characteristic.Hue, this.LightBulb.Hue, 'Hue');
// Saturation
await this.updateCharacteristic(this.LightBulb.Service, this.hap.Characteristic.Saturation, this.LightBulb.Saturation, 'Saturation');
}
async getAdaptiveLightingSettings(accessory, device) {
// Adaptive Lighting
this.adaptiveLighting = accessory.context.adaptiveLighting ?? true;
this.debugLog(`adaptiveLighting: ${this.adaptiveLighting}`);
// Adaptive Lighting Shift
this.adaptiveLightingShift = device.adaptiveLightingShift ?? 0;
this.debugLog(`adaptiveLightingShift: ${this.adaptiveLightingShift}`);
}
async BLEPushConnection() {
if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
this.warnLog('Using OpenAPI Connection to Push Changes');
await this.openAPIpushChanges();
}
}
async BLERefreshConnection(switchbot) {
this.errorLog(`wasn't able to establish BLE Connection, node-switchbot: ${switchbot}`);
if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
this.warnLog('Using OpenAPI Connection to Refresh Status');
await this.openAPIRefreshStatus();
}
}
async offlineOff() {
if (this.device.offline) {
this.LightBulb.Service.updateCharacteristic(this.hap.Characteristic.On, false);
}
}
async apiError(e) {
this.LightBulb.Service.updateCharacteristic(this.hap.Characteristic.On, e);
this.LightBulb.Service.updateCharacteristic(this.hap.Characteristic.Hue, e);
this.LightBulb.Service.updateCharacteristic(this.hap.Characteristic.Brightness, e);
this.LightBulb.Service.updateCharacteristic(this.hap.Characteristic.Saturation, e);
this.LightBulb.Service.updateCharacteristic(this.hap.Characteristic.ColorTemperature, e);
}
}
//# sourceMappingURL=colorbulb.js.map