import http , { IncomingMessage , Server , ServerResponse } from "http" ; import { API , APIEvent , CharacteristicEventTypes , CharacteristicSetCallback , CharacteristicValue , DynamicPlatformPlugin , HAP , Logging , PlatformAccessory , PlatformAccessoryEvent , PlatformConfig , } from "homebridge" ; const PLUGIN_NAME = "homebridge-dynamic-platform-example" ; const PLATFORM_NAME = "ExampleDynamicPlatform" ; let hap ; let Accessory ; export = ( api ) => { hap = api . hap ; Accessory = api . platformAccessory ; api . registerPlatform ( PLATFORM_NAME , ExampleDynamicPlatform ) ; } ; class ExampleDynamicPlatform implements DynamicPlatformPlugin { private readonly log : Logging ; private readonly api : API ; private requestServer ? : Server ; private readonly accessories : PlatformAccessory [ ] = [ ] ; constructor ( log , config , api ) { this . log = log ; this . api = api ; log . info ( "Example platform finished initializing!" ) ; api . on ( APIEvent . DID_FINISH_LAUNCHING , ( ) => { log . info ( "Example platform 'didFinishLaunching'" ) ; this . createHttpService ( ) ; } ) ; } configureAccessory ( accessory ) { this . log ( "Configuring accessory %s" , accessory . displayName ) ; accessory . on ( PlatformAccessoryEvent . IDENTIFY , ( ) => { this . log ( "%s identified!" , accessory . displayName ) ; } ) ; accessory . getService ( hap . Service . Lightbulb ) ! . getCharacteristic ( hap . Characteristic . On ) . on ( CharacteristicEventTypes . SET , ( value , callback ) => { this . log . info ( "%s Light was set to: " + value ) ; callback ( ) ; } ) ; this . accessories . push ( accessory ) ; } addAccessory ( name ) { this . log . info ( "Adding new accessory with name %s" , name ) ; const uuid = hap . uuid . generate ( name ) ; const accessory = new Accessory ( name , uuid ) ; accessory . addService ( hap . Service . Lightbulb , "Test Light" ) ; this . configureAccessory ( accessory ) ; this . api . registerPlatformAccessories ( PLUGIN_NAME , PLATFORM_NAME , [ accessory ] ) ; } removeAccessories ( ) { this . log . info ( "Removing all accessories" ) ; this . api . unregisterPlatformAccessories ( PLUGIN_NAME , PLATFORM_NAME , this . accessories ) ; this . accessories . splice ( 0 , this . accessories . length ) ; } createHttpService ( ) { this . requestServer = http . createServer ( this . handleRequest . bind ( this ) ) ; this . requestServer . listen ( 18081 , ( ) => this . log . info ( "Http server listening on 18081..." ) ) ; } private handleRequest ( request , response ) { if ( request . url === "/add" ) { this . addAccessory ( new Date ( ) . toISOString ( ) ) ; } else if ( request . url === "/remove" ) { this . removeAccessories ( ) ; } response . writeHead ( 204 ) ; response . end ( ) ; } }