var mqtt = require('mqtt'); var request = require('request'); var util = require('util'); var logger = require('log4js').getLogger(); var EventEmitter = require('events'); var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984'); //var nano = require('nano')('http://localhost:5984'); var busEmitter = new EventEmitter(); var db_name = 'mqtt'; var dbCouch = nano.use(db_name); function insertEntry(obj) { logger.debug('Inserting into couch...'); logger.info(util.inspect(obj)); dbCouch.insert(obj, function(err, body, header) { if (err) { logger.error('Error inserting into couch'); return; } }); logger.debug('Insert done..'); } var doInsertEntry = (obj) => { // Logger.info('sendSocket: ' + JSON.stringify(obj)); insertEntry(obj); }; var mqttClient = function() { var orgId = ''; var userName = ''; var appKey = 'bob'; this.livingRoom = { temp: 0, last: 0 }; this.fanTimer = function() { 'use strict'; var now = new Date; var mod = 300000 - (now.getTime() % 300000); var mode = (this.livingRoom.temp > 22.0) ? 'FanOn' : 'FanOff'; var url = ['https://maker.ifttt.com/trigger/',mode,'/with/key/cWvECkeiyAPwmiOPBkXL2D'].join(''); logger.info('LR temp:', this.livingRoom.temp); request(url, function(error, response, body) { if (!error && response.statusCode === 200) { console.log(body); } }); setTimeout(this.fanTimer.bind(this),mod + 10); }; this.lighting = 'lights'; this.connected = false; var 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() { connected = true; logger.info('Connected to SIlvr Broker'); this.fanTimer(); }.bind(this)); this.client.subscribe('livingroomTemp'); this.client.on('message', function(topic, message) { var json = JSON.parse(message.toString()); logger.debug(json); logger.debug(json.temp); this.livingRoom.temp = json.temp; busEmitter.emit('saveData', json); }.bind(this)); this.isConnected = function() { return this.connected; }; busEmitter.on('saveData', doInsertEntry); }; /* Client = mqtt.connect(); client.subscribe('presence'); client.on('message', function(topic, message) { console.log(message); }); */ mqttClient.prototype.lightsIn = function() { var destinationName = 'lightsIn'; this.client.publish(destinationName, '0'); var destinationName = 'lightsIn'; this.client.publish(destinationName, '1'); }; mqttClient.prototype.lightsOut = function() { var destinationName = 'lightsOut'; this.client.publish(destinationName, 'f'); destinationName = 'lightsOut'; this.client.publish(destinationName, 'g'); }; module.exports.mqttClient = mqttClient;