const LifxClient = require('node-lifx').Client; const client = new LifxClient(); const em = require('events').EventEmitter; const util = require('util'); const logger = require('log4js').getLogger('Lights'); logger.level = 'debug'; const LightController = function() { const _this = this; const devices = []; client.on('light-new', light => { _this.emit('found', light); devices.push(light); logger.debug('New light found.'); logger.debug(`ID: ${ light.id}`); logger.debug(`IP: ${ light.address }:${ light.port}`); light.getState((err, info) => { if (err) logger.debug(err); logger.debug(`Label: ${ info.label}`); logger.debug('Power:', (info.power === 1) ? 'on' : 'off'); logger.debug('Color:', info.color); logger.debug('info', info); // _this.emit(info.label.replace(' ',''), ) }); light.getHardwareVersion((err, info) => { if (err) logger.debug(err); logger.debug(`Device Info: ${ info.vendorName } - ${ info.productName}`); logger.debug('Features: ', info.productFeatures, '\n'); }); }); client.on('listening', () => { const address = client.address(); logger.debug( `Started LIFX listening on ${ address.address }:${ address.port }\n` ); }); client.on('light-offline', light => { logger.debug(`Light: ${light.label} has gone offline`); _this.emit(light.label.replace(' ', ''), light.status); }); client.on('light-online', light => { logger.debug(`Light: ${light.label} has come online`); logger.debug(light.label.replace(' ', ''), light.status); _this.emit(light.label.replace(' ', ''), { 'status':light.status, 'id':light.id }); }); client.on('message', msg => { // logger.debug('>> msg', msg); }); client.init({ 'lightOfflineTolerance': 3, // A light is offline if not seen for the given amount of discoveries 'messageHandlerTimeout': 45000, // in ms, if not answer in time an error is provided to get methods 'startDiscovery': true, // start discovery after initialization 'resendPacketDelay': 150, // delay between packages if light did not receive a packet (for setting methods with callback) 'resendMaxTimes': 3, // resend packages x times if light did not receive a packet (for setting methods with callback) 'debug': false, // logs all messages in console if turned on 'address': '0.0.0.0', // the IPv4 address to bind the udp connection to 'broadcast': '255.255.255.255', // set's the IPv4 broadcast address which is addressed to discover bulbs 'lights': [] // Can be used provide a list of known light IPv4 ip addresses if broadcast packets in network are not allowed // For example: ['192.168.0.112', '192.168.0.114'], this will then be addressed directly }); this.on('newListener', listener => { logger.info(`Event Listener: ${ listener}`); }); this.on('setColour', (data) => { for(const light of devices) { if (light.id === data.id) { logger.info('Setting color of ', light.label); light.color(data.color.hue, data.color.saturation, data.color.brightness, data.color.kelvin); } } }); return this; }; util.inherits(LightController, em); module.exports = LightController;