import { Chase } from "./chase"; import { IConfig, ISequence } from "./models/iConfig"; import { v3 } from 'node-hue-api'; import LocalBootstrap = require("node-hue-api/lib/api/http/LocalBootstrap"); import Api = require("node-hue-api/lib/api/Api"); import { Sleep } from "./sleep"; let Accessory: any; let Homebridge: any; /** * Main entry. * @param homebridge */ export default function (homebridge: any) { Homebridge = homebridge; Accessory = homebridge.platformAccessory; homebridge.registerPlatform( 'homebridge-hue-chase', 'HueChase', HueChasePlatform, true ); }; class HueChasePlatform { log: any = {}; api: any; chaseList: Array = []; config: IConfig; hue: Api | undefined; constructor(log: any, config: any, api: any) { this.log = log; this.api = api; this.config = config; this.log('INFO - Registering Hue Chase platform'); this.api.on('didFinishLaunching', this.didFinishLaunching.bind(this)); } private connectHue = async () => { if (!this.config) { return; } if (this.config.userName && this.config.clientKey) { this.hue = await v3.api.createLocal(this.config.ipAddress).connect(this.config.userName, this.config.clientKey, null); this.log("Using existing connection info"); } else { const unauthenticatedApi = await v3.api.createLocal(this.config.ipAddress).connect(null, null, null); let createdUser; let connected = false while (!connected) { try { this.log("Creating hue user. Push link button") createdUser = await unauthenticatedApi.users.createUser("homebridge", "HueChase"); this.hue = await v3.api.createLocal(this.config.ipAddress).connect(createdUser.username, createdUser.clientKey, null); this.log("Connected to Hue Bridge"); this.log(`UserName: ${createdUser.username}, ClientKey: ${createdUser.clientkey}`) connected = true; } catch (err) { if (err.getHueErrorType() === 101) { this.log('The Link button on the bridge was not pressed. Please press the Link button and try again.'); Sleep(5000); } else { this.log(`Unexpected Error: ${err.message}`); break; } } } } } /** * Handler for didFinishLaunching * Happens after constructor */ private didFinishLaunching() { this.log(`INFO - Done registering Hue Chase platform`); } /** * Called by homebridge to gather accessories. * @param callback */ public accessories = async (callback: (accessories: Array) => void) => { //Connect to hue bridge await this.connectHue(); this.config.sequences.forEach((sequence: ISequence) => { this.chaseList.push(new Chase({ name: sequence.name, api: this.api, log: this.log, homebridge: Homebridge, sequence: sequence, hue: this.hue!, })) }) callback(this.chaseList); } }