mqtt_server/lib/mqtt/mqttClient.js
2016-06-24 14:44:21 +01:00

104 lines
2.2 KiB
JavaScript

var mqtt = require('mqtt');
var request = require('request');
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('');
console.log('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;
console.log('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());
console.log(json);
console.log(json.temp);
this.livingRoom.temp = json.temp;
}.bind(this));
this.isConnected = function() {
return this.connected;
};
};
/*
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;