mqtt_server/lib/mqtt/mqttClient.js
2017-02-28 23:49:17 +00:00

202 lines
5.4 KiB
JavaScript

'use strict';
const mqtt = require('mqtt');
const request = require('request');
let util = require('util');
const logger = require('log4js').getLogger();
// Var db = require('../server/db-connector').dbConnection;
// var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984');
// var nano = require('nano')('http://localhost:5984');
// let db_name = 'mqtt';
// var dbCouch = nano.use(db_name);
let globalMode = 'FanOff';
let lastDispatch = 0;
const mqttClient = function(events) {
const orgId = '';
const userName = '';
const appKey = 'bob';
this.livingRoom = {
temp: 0,
last: 0,
data: []
};
this.ranges = {
day: {low: 19.5, high: 22.5, max: 22.7},
night: {low: 18.5, high: 20.5, max: 20.7}
};
this.first = false;
this.maxLength = 540;
let mode = 'FanOff';
const d = new Date();
this.lastMsg = d.getTime();
events.on('sendIFTTT', function(mode) {
let d;
const url = ['https://maker.ifttt.com/trigger/', mode, '/with/key/cWvECkeiyAPwmiOPBkXL2D'].join('');
if (mode !== globalMode) {
logger.info('Go for change state', mode);
globalMode = mode;
logger.debug('Global Mode now A:', globalMode);
/* Request(url, function (error, response, body) {
logger.debug(response, body);
}); */
events.emit('changeState', mode === 'FanOn' ? 1:0);
d = new Date();
lastDispatch = d.getTime();
} else {
logger.warn('Not sent...');
}
});
this.updateGlobal = function(newStatus) {
globalMode = (newStatus === 0) ? 'FanOff' : 'FanOn';
logger.info('updateGlobal changed to: ', globalMode);
};
this.storeData = function(data, alt) {
if (!this.first) {
this.first = true;
return [];
}
let target = alt || this.livingRoom.data;
if (target.length === this.maxLength) {
target = target.slice(1);
}
target.push(data);
if (alt) {
return target;
}
this.livingRoom.data = target;
};
this.logTemp = function() {
const now = new Date;
const mod = 60000 - (now.getTime() % 60000);
this.storeData(this.livingRoom.temp);
const data = {id: 'graph', data: this.livingRoom.data};
events.emit('sendSocket', data);
setTimeout(this.logTemp.bind(this), mod + 10);
};
this.fanTimer = function() {
let n;
const now = new Date;
const mod = 900000 - (now.getTime() % 900000);
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 (globalMode === 'FanOff') {
logger.info(`Fans off, temp should be <= ${curRange.low}`);
mode = (parseFloat(this.livingRoom.temp) <= curRange.low) ? 'FanOn' : 'FanOff';
} else {
logger.info(`Fans on, temp should not be less than ${curRange.high}`);
mode = (parseFloat(this.livingRoom.temp) <= curRange.high) ? 'FanOn' : 'FanOff';
}
if ((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.livingRoom.temp);
const data = {id: 'temperature', data: {mode: globalMode, temp: this.livingRoom.temp}};
if (this.livingRoom.temp !== 0) {
events.emit('sendIFTTT', mode);
events.emit('sendSocket', data);
}
setTimeout(this.fanTimer.bind(this), mod + 500);
};
this.lighting = 'lights';
this.connected = false;
const options = {
keepalive: 3600,
clientId: 'a:' + orgId + ':' + Date.now(),
username: userName,
password: new Buffer(appKey)
};
this.client = mqtt.connect('mqtt://' + orgId + 'silvrtree.co.uk', options);
this.client.on('connect', function() {
this.connected = true;
logger.info('Connected to Silvr Broker');
this.fanTimer();
this.logTemp();
}.bind(this));
this.client.subscribe('livingroomTemp');
this.client.on('updateState', function(newStatus) {
globalMode = (newStatus === 0) ? 'FanOff' : 'FanOn';
logger.info('updateState changed to: ', globalMode);
});
this.client.on('message', function(topic, message) {
const now = new Date;
const nowMS = (now.getHours() * 3600000) + (now.getMinutes() * 60000);
const curRange = (nowMS < 25200000) ? this.ranges.night : this.ranges.day;
const json = JSON.parse(message.toString());
logger.debug(json);
logger.debug(json.temp);
this.livingRoom.temp = parseFloat(json.temp);
logger.info('lr:', this.livingRoom.temp, this.livingRoom.temp >= curRange.max);
if (this.livingRoom.temp >= curRange.max) {
logger.warn('Max temp reached, turn off');
events.emit('sendIFTTT', 'FanOff');
}
const d = new Date();
this.lastMsg = d.getTime();
const data = {id: 'temperature', data: {mode: globalMode, temp: this.livingRoom.temp}};
events.emit('sendSocket', data);
}.bind(this));
this.isConnected = function() {
return this.connected;
};
};
module.exports.mqttClient = mqttClient;