Successfully controlling wiz bulbs

This commit is contained in:
Brandon Watson 2022-09-06 18:25:38 -05:00
parent c3a6882413
commit d73dead5d4
6 changed files with 2351 additions and 351 deletions

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"tabWidth": 4,
"useTabs": false
}

3
.vscode/launch.json vendored
View File

@ -11,7 +11,8 @@
"preLaunchTask": "build", "preLaunchTask": "build",
"program": "/Users/brandonwatson/.nvm/versions/node/v14.15.0/lib/node_modules/homebridge/bin/homebridge", "program": "/Users/brandonwatson/.nvm/versions/node/v14.15.0/lib/node_modules/homebridge/bin/homebridge",
"env": { "env": {
"HOMEBRIDGE_OPTS": "/Users/brandonwatson/.homebridge" "HOMEBRIDGE_OPTS": "/Users/brandonwatson/.homebridge",
"LOG_LEVEL": "debug"
}, },
"sourceMaps": true "sourceMaps": true
} }

1950
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -29,6 +29,7 @@
"dependencies": { "dependencies": {
"@types/node-cron": "^2.0.3", "@types/node-cron": "^2.0.3",
"@types/suncalc": "^1.8.0", "@types/suncalc": "^1.8.0",
"@watsonb8/wiz-lib": "^1.0.1-62427.0",
"node-cron": "^2.0.3", "node-cron": "^2.0.3",
"node-hue-api": "^4.0.5", "node-hue-api": "^4.0.5",
"suncalc": "^1.8.0" "suncalc": "^1.8.0"

View File

@ -8,6 +8,8 @@ import { IConfig } from "./models/iConfig";
import { GetTimesResult, getTimes } from "suncalc"; import { GetTimesResult, getTimes } from "suncalc";
import HueError = require("node-hue-api/lib/HueError"); import HueError = require("node-hue-api/lib/HueError");
import cron from "node-cron"; import cron from "node-cron";
import { WizBulb } from "@watsonb8/wiz-lib/build/wizBulb";
import { colorTemperature2rgb, Pilot, RGB } from "@watsonb8/wiz-lib";
let Service: HAPNodeJS.Service; let Service: HAPNodeJS.Service;
let Characteristic: HAPNodeJS.Characteristic; let Characteristic: HAPNodeJS.Characteristic;
@ -20,6 +22,7 @@ export interface IFluxProps {
log: any; log: any;
homebridge: any; homebridge: any;
hue: Api; hue: Api;
wizBulbs: Array<WizBulb>;
config: IConfig; config: IConfig;
} }
@ -37,6 +40,7 @@ export class FluxAccessory implements IAccessory {
private _hue: Api; private _hue: Api;
private _lights: Array<Light> = []; private _lights: Array<Light> = [];
private _wizLights: Array<WizBulb> = [];
private _times: GetTimesResult; private _times: GetTimesResult;
@ -49,6 +53,7 @@ export class FluxAccessory implements IAccessory {
Characteristic = props.api.hap.Characteristic; Characteristic = props.api.hap.Characteristic;
this._homebridge = props.homebridge; this._homebridge = props.homebridge;
this._isActive = false; this._isActive = false;
this._wizLights = props.wizBulbs;
this._times = getTimes( this._times = getTimes(
new Date(), new Date(),
@ -57,8 +62,7 @@ export class FluxAccessory implements IAccessory {
); );
//Schedule job to refresh times //Schedule job to refresh times
cron cron.schedule(
.schedule(
"0 12 * * *", "0 12 * * *",
() => { () => {
this._times = getTimes( this._times = getTimes(
@ -71,8 +75,7 @@ export class FluxAccessory implements IAccessory {
{ {
scheduled: true, scheduled: true,
} }
) ).start();
.start();
this._hue = props.hue; this._hue = props.hue;
this.name = this._config.name; this.name = this._config.name;
@ -159,9 +162,7 @@ export class FluxAccessory implements IAccessory {
} }
}; };
private colorTempToRgb = ( private colorTempToRgb = (kelvin: number): RGB => {
kelvin: number
): { red: number; green: number; blue: number } => {
var temp = kelvin / 100; var temp = kelvin / 100;
var red, green, blue; var red, green, blue;
if (temp <= 66) { if (temp <= 66) {
@ -185,9 +186,9 @@ export class FluxAccessory implements IAccessory {
blue = 255; blue = 255;
} }
return { return {
red: this.clamp(red, 0, 255), r: this.clamp(red, 0, 255),
green: this.clamp(green, 0, 255), g: this.clamp(green, 0, 255),
blue: this.clamp(blue, 0, 255), b: this.clamp(blue, 0, 255),
}; };
}; };
@ -205,7 +206,7 @@ export class FluxAccessory implements IAccessory {
return "_hueError" in object; return "_hueError" in object;
}; };
private setLights = async (state: LightState) => { private setHueLights = async (state: LightState) => {
const promises: Array<Promise<unknown> | PromiseLike<unknown>> = []; const promises: Array<Promise<unknown> | PromiseLike<unknown>> = [];
this._lights.map(async (light: Light) => { this._lights.map(async (light: Light) => {
try { try {
@ -226,6 +227,16 @@ export class FluxAccessory implements IAccessory {
await Promise.all(promises); await Promise.all(promises);
}; };
private setWizLights = async (rgb: RGB, fade: number): Promise<void> => {
await Promise.all(
this._wizLights.map(async (bulb) => {
const pilot = await bulb.get();
bulb.set(rgb, pilot?.dimming, fade);
})
);
return;
};
/** /**
* Helper function to generate a UUID * Helper function to generate a UUID
*/ */
@ -259,7 +270,8 @@ export class FluxAccessory implements IAccessory {
) => { ) => {
const now = this.getNow().getTime(); const now = this.getNow().getTime();
const percentComplete = const percentComplete =
(now - startTime.getTime()) / (endTime.getTime() - startTime.getTime()); (now - startTime.getTime()) /
(endTime.getTime() - startTime.getTime());
const tempRange = Math.abs(startTemp - endTemp); const tempRange = Math.abs(startTemp - endTemp);
const tempOffset = tempRange * percentComplete; const tempOffset = tempRange * percentComplete;
return startTemp - tempOffset; return startTemp - tempOffset;
@ -332,20 +344,25 @@ export class FluxAccessory implements IAccessory {
} }
//Set lights //Set lights
const rgb = this.colorTempToRgb(newTemp); const hueRGB = this.colorTempToRgb(newTemp);
if (rgb && newTemp !== 0) { const wizRGB = colorTemperature2rgb(newTemp);
if (hueRGB && newTemp !== 0) {
const lightState = new LightState(); const lightState = new LightState();
lightState lightState
.transitionInMillis( .transitionInMillis(
this._config.transition ? this._config.transition : 5000 this._config.transition ? this._config.transition : 5000
) )
.rgb( .rgb(hueRGB.r ?? 0, hueRGB.g ?? 0, hueRGB.b ?? 0);
rgb.red ? rgb.red : 0, await this.setHueLights(lightState);
rgb.green ? rgb.green : 0, await this.setWizLights(
rgb.blue ? rgb.blue : 0 wizRGB,
this._config.transition ? this._config.transition / 1000 : 5
);
this._log(
`Adjusting light temp to ${newTemp}, ${JSON.stringify(
hueRGB
)}`
); );
await this.setLights(lightState);
this._log(`Adjusting light temp to ${newTemp}, ${JSON.stringify(rgb)}`);
} }
await Sleep(this._config.delay ? this._config.delay : 60000); await Sleep(this._config.delay ? this._config.delay : 60000);

View File

@ -1,10 +1,12 @@
import { IConfig } from "./models/iConfig"; import { IConfig } from "./models/iConfig";
import { v3 } from 'node-hue-api'; import { v3 } from "node-hue-api";
import LocalBootstrap = require("node-hue-api/lib/api/http/LocalBootstrap"); import LocalBootstrap = require("node-hue-api/lib/api/http/LocalBootstrap");
import Api = require("node-hue-api/lib/api/Api"); import Api = require("node-hue-api/lib/api/Api");
import { Sleep } from "./sleep"; import { Sleep } from "./sleep";
import { IAccessory } from "./models/iAccessory"; import { IAccessory } from "./models/iAccessory";
import { FluxAccessory } from "./fluxAccessory"; import { FluxAccessory } from "./fluxAccessory";
import { WizBulb } from "@watsonb8/wiz-lib/build/wizBulb";
import discover from "@watsonb8/wiz-lib/build/discovery";
let Accessory: any; let Accessory: any;
let Homebridge: any; let Homebridge: any;
@ -16,13 +18,8 @@ let Homebridge: any;
export default function (homebridge: any) { export default function (homebridge: any) {
Homebridge = homebridge; Homebridge = homebridge;
Accessory = homebridge.platformAccessory; Accessory = homebridge.platformAccessory;
homebridge.registerPlatform( homebridge.registerPlatform("homebridge-flux", "Flux", FluxPlatform, true);
'homebridge-flux', }
'Flux',
FluxPlatform,
true
);
};
class FluxPlatform { class FluxPlatform {
log: any = {}; log: any = {};
@ -31,50 +28,76 @@ class FluxPlatform {
config: IConfig; config: IConfig;
hue: Api | undefined; hue: Api | undefined;
constructor(log: any, config: any, api: any) { constructor(log: any, config: any, api: any) {
this.log = log; this.log = log;
this.api = api; this.api = api;
this.config = config; this.config = config;
this.log('INFO - Registering Flux platform'); this.log("INFO - Registering Flux platform");
this.api.on('didFinishLaunching', this.didFinishLaunching.bind(this)); this.api.on("didFinishLaunching", this.didFinishLaunching.bind(this));
} }
private connectWiz = async () => {
if (!this.config) {
return;
}
return await discover();
};
private connectHue = async () => { private connectHue = async () => {
if (!this.config) { if (!this.config) {
return; return;
} }
if (this.config.userName && this.config.clientKey) { if (this.config.userName && this.config.clientKey) {
this.hue = await v3.api.createLocal(this.config.ipAddress).connect(this.config.userName, this.config.clientKey, undefined); this.hue = await v3.api
.createLocal(this.config.ipAddress)
.connect(
this.config.userName,
this.config.clientKey,
undefined
);
this.log("Using existing connection info"); this.log("Using existing connection info");
} else { } else {
const unauthenticatedApi = await v3.api.createLocal(this.config.ipAddress).connect(undefined, undefined, undefined); const unauthenticatedApi = await v3.api
.createLocal(this.config.ipAddress)
.connect(undefined, undefined, undefined);
let createdUser; let createdUser;
let connected = false let connected = false;
while (!connected) { while (!connected) {
try { try {
this.log("Creating hue user. Push link button") this.log("Creating hue user. Push link button");
createdUser = await unauthenticatedApi.users.createUser("homebridge", "HueChase"); createdUser = await unauthenticatedApi.users.createUser(
"homebridge",
"HueChase"
);
this.hue = await v3.api.createLocal(this.config.ipAddress).connect(createdUser.username, createdUser.clientKey, undefined); this.hue = await v3.api
.createLocal(this.config.ipAddress)
.connect(
createdUser.username,
createdUser.clientKey,
undefined
);
this.log("Connected to Hue Bridge"); this.log("Connected to Hue Bridge");
this.log(`UserName: ${createdUser.username}, ClientKey: ${createdUser.clientkey}`) this.log(
`UserName: ${createdUser.username}, ClientKey: ${createdUser.clientkey}`
);
connected = true; connected = true;
} catch (err: any) { } catch (err: any) {
if (err.getHueErrorType() === 101) { if (err.getHueErrorType() === 101) {
this.log('The Link button on the bridge was not pressed. Please press the Link button and try again.'); this.log(
"The Link button on the bridge was not pressed. Please press the Link button and try again."
);
Sleep(5000); Sleep(5000);
} else { } else {
this.log(`Unexpected Error: ${err.message}`); this.log(`Unexpected Error: ${err.message}`);
break; break;
} }
}
} }
} }
} }
};
/** /**
* Handler for didFinishLaunching * Handler for didFinishLaunching
@ -88,18 +111,24 @@ class FluxPlatform {
* Called by homebridge to gather accessories. * Called by homebridge to gather accessories.
* @param callback * @param callback
*/ */
public accessories = async (callback: (accessories: Array<IAccessory>) => void) => { public accessories = async (
callback: (accessories: Array<IAccessory>) => void
) => {
//Connect to hue bridge //Connect to hue bridge
await this.connectHue(); await this.connectHue();
const wizBulbs = await this.connectWiz();
this.accessoryList.push(new FluxAccessory({ this.accessoryList.push(
new FluxAccessory({
api: this.api, api: this.api,
log: this.log, log: this.log,
homebridge: Homebridge, homebridge: Homebridge,
hue: this.hue!, hue: this.hue!,
config: this.config wizBulbs: wizBulbs ?? [],
})); config: this.config,
})
);
callback(this.accessoryList); callback(this.accessoryList);
} };
} }