const em = require('events').EventEmitter; const util = require('util'); const logger = require('log4js').getLogger('BedroomRecipe'); logger.level = 'debug'; const BedroomRecipe = function(devices) { const _this = this; this.mqtt = devices.mqtt; this.wemo = devices.wemo; this.globalMode = 'FanOff'; this.bedroom = { 'temp': 0, 'last': 0, 'data': [] }; this.ranges = { 'day': { 'low': 20.2, 'high': 22.0, 'max': 22.7 }, 'night': { 'low': 20.2, 'high': 22.0, 'max': 22.7 } }; logger.debug('Setting up bedroom recipe'); this.fanTimer = function() { let n; const onTime = 900000; const now = new Date; const mod = onTime - (now.getTime() % onTime); const day = now.getDay(); const daytimeLimits = { 'low': 27900000, 'high': 63000000 }; const nowMS = (now.getHours() * 3600000) + (now.getMinutes() * 60000); const curRange = (nowMS < 25200000) ? this.ranges.night : this.ranges.day; if (this.globalMode === 'FanOff') { logger.info(`Fans off, temp should be <= ${curRange.low}`); mode = (parseFloat(this.bedroom.temp) <= curRange.low) ? 'FanOn' : 'FanOff'; } else { logger.info(`Fans on, temp should not be less than ${curRange.high}`); mode = (parseFloat(this.bedroom.temp) <= curRange.high) ? 'FanOn' : 'FanOff'; } if ((this.globalMode !== 'FanOff' || mode !== 'FanOff') && ((day >= 1 && day <= 5) && (nowMS >= daytimeLimits.low && nowMS <= daytimeLimits.high))) { logger.info('Week day'); mode = 'FanOff'; } n = now.getTime() - this.lastMsg; logger.info('Last msg', n); if (n >= 600000) { logger.error('No message received for over 10 minutes'); mode = 'FanOff'; logger.warn('Setting quit for 15 seconds.'); setTimeout(() => { throw new error('Ejecting for restart'); }, 15000); } logger.info('LR temp:', this.bedroom.temp); // const data = { 'id': 'temperature', 'data': { 'mode': this.globalMode, 'temp': this.bedroom.temp } }; logger.debug('Mode', mode); if (this.bedroom.temp !== 0) { logger.debug('trying to turn fann off'); _this.wemo.emit('wemo', mode); } setTimeout(this.fanTimer.bind(this), mod + 500); }; const updateTemp = (temp) => { const now = new Date; const nowMS = (now.getHours() * 3600000) + (now.getMinutes() * 60000); const curRange = (nowMS < 25200000) ? this.ranges.night : this.ranges.day; this.bedroom.temp = parseFloat(temp); logger.info(this.bedroom.temp, this.bedroom.temp >= curRange.max); if (this.bedroom.temp >= curRange.max) { logger.warn('Max temp reached, turn off'); _this.wemo.emit('wemo', 'fanOff'); } }; this.mqtt.on('bedroomTemp', (d) => { updateTemp(d); }); setTimeout(this.fanTimer.bind(this), 10000); }; util.inherits(BedroomRecipe, em); module.exports = { BedroomRecipe };