const { promisify } = require('util'); const Wemo = require('wemo-client'); const wemo = new Wemo(); const em = require('events').EventEmitter; const util = require('util'); const logger = require('log4js').getLogger('Wemo'); // const getBinaryStateAsync = promisify(wemo.getBinaryState); logger.level = 'debug'; const WemoController = function() { const _this = this; wemo.discover(function(err, deviceInfo) { logger.debug('Wemo Device Found: %j', deviceInfo); _this.emit('found', deviceInfo); // Get the client for the found device _this.client = wemo.client(deviceInfo); // You definitely want to listen to error events (e.g. device went offline), // Node will throw them as an exception if they are left unhandled _this.client.on('error', function(err) { logger.error('Error: %s', err.code); }); // Handle BinaryState events _this.client.on('binaryState', function(value) { _this.emit('changeState', value); logger.info('Binary State changed to: %s', value); }); // Turn the switch off _this.client.setBinaryState(0); }); this.on('newListener', listener => { logger.info(`Event Listener: ${ listener}`); }); this.on('wemo-off', function() { _this.client.setBinaryState(0); }); this.on('wemo-on', function() { _this.client.setBinaryState(1); }); this.on('wemo', function(d) { logger.debug('onWemo msg', d); if (d === 'FanOn') this.emit('wemo-on'); else this.emit('wemo-off'); }); return this; }; util.inherits(WemoController, em); module.exports = WemoController;