SODashServer/lib/mqtt/mqttConnect.js

226 lines
7.6 KiB
JavaScript
Raw Normal View History

2016-04-13 09:01:28 +00:00
/**
* Created by Martin on 08/02/2016.
*/
"use strict";
var mqtt = require('mqtt');
var Messaging = require("mqtt_over_websockets");
var log4js = require('log4js');
var logger = log4js.getLogger();
var mqttConfig = {
orgId: 'qz0da4',
userName: 'a-qz0da4-dfwwdkmkzr',
appKey: '9txJEf3Cjy7hkSOvkv',
prefix: 'iot-2/type/Ti-CC3200/id/'
};
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
module.exports = {
sockets : null,
watches : {},
client: null,
projector: 'ProjectorISP15',
lighting: 'LightingISP15',
heating: 'HeatingISP15',
myID: 0,
connected: false,
options: {
keepalive: 3600,
clientId: 'a:' + mqttConfig.orgId + ':' + Date.now(),
username: mqttConfig.userName,
password: new Buffer(mqttConfig.appKey)
},
setEmitter: function(newEmitter)
{
this.emitter = newEmitter;
},
doConnection: function (cb) {
console.log('Do connection');
var self = this;
if (this.client === null) {
this.client = mqtt.connect('mqtt://' + mqttConfig.orgId + '.messaging.internetofthings.ibmcloud.com', this.options);
this.client.on('connect', function () {
console.log('Connected to IBM');
self.connected = this.connected;
});
}
return this;
},
isConnected: function () {
return this.connected;
},
sendCommand: function (deviceID, command) {
var payload = {
id: "d",
text: command
};
},
projectorOn: function (callback) {
var _callback = callback || {};
if (!this.client) {
return -1;
}
var destinationName = mqttConfig.prefix + this.projector + "/cmd/" + 'ON' + "/fmt/json";
this.client.publish(destinationName, 'ON', _callback);
},
projectorOff: function (callback) {
var _callback = callback || {};
if (!this.client) {
return -1;
}
var destinationName = mqttConfig.prefix + this.projector + "/cmd/" + 'OFF' + "/fmt/json";
this.client.publish(destinationName, 'OFF', _callback);
},
heatingOn: function (callback) {
console.log('Turn heating on...');
var _callback = callback || null;
if (!this.client) {
return -1;
}
var destinationName = mqttConfig.prefix + this.heating + "/cmd/" + 'on' + "/fmt/json";
this.client.publish(destinationName, 'ON', _callback);
},
heatingOff: function (callback) {
var _callback = callback || {};
if (!this.client) {
return -1;
}
var destinationName = mqttConfig.prefix + this.heating + "/cmd/" + 'off' + "/fmt/json";
this.client.publish(destinationName, 'OFF', _callback);
},
lightingOn: function (id, callback) {
console.log('lightingOn:' + id);
var _callback = callback || null;
if (!this.client) {
return -1;
}
var destinationName = mqttConfig.prefix + this.lighting + "/cmd/" + id + "/fmt/json";
this.client.publish(destinationName, 'ON', _callback);
},
lightingOff: function (id, callback) {
var _callback = callback || null;
if (!this.client) {
return -1;
}
var destinationName = mqttConfig.prefix + this.lighting + "/cmd/" + id + "/fmt/json";
this.client.publish(destinationName, 'OFF', _callback);
},
connectWS: function (connectCB) {
logger.debug("Going to connect WS");
var self = this;
var hostname = "qz0da4" + ".messaging.internetofthings.ibmcloud.com";
var clientId = "a:" + "qz0da4" + ":" + Date.now();
var api_key = "a-qz0da4-dfwwdkmkzr";
var auth_token = "9txJEf3Cjy7hkSOvkv";
var wsClient = new Messaging.Client(hostname, 8883, clientId);
var clientStatus = {connected: false, subscribed: false, deviceConnected: false};
var sensorData = {};
var watches ={};
wsClient.onMessageArrived = function (msg) {
// console.log("Message from :" + msg.destinationName);
clientStatus.deviceConnected = true;
// $rootScope.$broadcast("clientStatusUpdated", clientStatus);
//logger.debug("clientStatusUpdated", clientStatus);
sensorData = JSON.parse(msg.payloadString);
var temp = msg.destinationName.split("/");
//console.log(temp[4]);
//console.log(sensorData);
if (self.watches.hasOwnProperty(temp[4]))
{
// logger.info('Emit: ' + JSON.stringify({id:self.watches[temp[4]],sensorData:sensorData}));
self.emitter.emit('sendSocket',{id:self.watches[temp[4]],sensorData:sensorData});
}
/* if (temp[4] == lighting) {
// $rootScope.$broadcast("LightingDataReceived", sensorData);
}
if (temp[4] == projector) {
// $rootScope.$broadcast("ProjectorDataReceived", sensorData);
}
if (temp[4] == heating) {
// $rootScope.$broadcast("HeatingISP15DataReceived", sensorData);
}*/
};
var connectOptions = {};
connectOptions.keepAliveInterval = 3600;
connectOptions.useSSL = true;
connectOptions.userName = api_key;
connectOptions.password = auth_token;
connectOptions.onSuccess = function () {
clientStatus.connected = true;
logger.info("MQTT connected to host: " + wsClient.host + " port : " + wsClient.port + " at " + Date.now());
self.emitter.emit("clientStatusUpdated", clientStatus);
self.emitter.emit("clientConnected", self.sockets);
};
connectOptions.onFailure = function (e) {
logger.error("MQTT connection failed at " + Date.now() + "\nerror: " + e.errorCode + " : " + e.errorMessage);
};
logger.debug("about to connect to " + wsClient.host);
wsClient.connect(connectOptions);
this.sockets = {
getClientStatus: function () {
return clientStatus;
},
subscribe: function( deviceId, emitterId) {
logger.debug("trying to subscribe");
var subscribeTopic = "iot-2/type/Ti-CC3200/id/" + deviceId + "/evt/+/fmt/json";
logger.debug(subscribeTopic);
var subscribeOptions = {
qos: 0,
onSuccess: function () {
console.log("subscribed to " + subscribeTopic);
clientStatus.subscribed = true;
// $rootScope.$broadcast("clientStatusUpdated", clientStatus);
self.emitter.emit("clientStatusUpdated", clientStatus);
self.watches[deviceId] = emitterId;
},
onFailure: function () {
console.log("Failed to subscribe to " + subscribeTopic);
console.log("As messages are not available, visualization is not possible");
}
};
/*if (IoTFconnector.prototype.clientStatus.subscribeTopic != "") {
console.log("Unsubscribing to " + subscribeTopic);
wsClient.unsubscribe(IoTFconnector.prototype.clientStatus.subscribeTopic);
};*/
wsClient.subscribe(subscribeTopic, subscribeOptions);
}
};
return this.sockets;
}
};