mirror of
https://gitlab.silvrtree.co.uk/martind2000/mdot_server.git
synced 2025-01-10 21:05:08 +00:00
Made it an app that can run on cloudfoundry
This commit is contained in:
parent
3eba4a4a70
commit
b9d035aa32
15
.project
Normal file
15
.project
Normal file
@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>mdotserver</name>
|
||||
<comment>mDot server with MQTT</comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.nodeclipse.ui.NodeNature</nature>
|
||||
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
22
app.js
22
app.js
@ -21,19 +21,17 @@ var WebSocketServer = require('websocket').server;
|
||||
var EventEmitter = require('events');
|
||||
var busEmitter = new EventEmitter();
|
||||
|
||||
var apn = require('apn');
|
||||
// var apn = require('apn');
|
||||
|
||||
require('sugar-date');
|
||||
|
||||
var isProduction = false;
|
||||
|
||||
|
||||
var mdotApi = require('./lib/mdot/api.js');
|
||||
var mdotApiV2 = require('./lib/mdot/apiv2.js');
|
||||
var trackApi = require('./lib/mdot/track.js');
|
||||
var meetingApi = require('./lib/mdot/meeting.js');
|
||||
|
||||
|
||||
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
@ -69,6 +67,8 @@ app.use(function(req, res, next) {
|
||||
// Run npm start --production to use dist
|
||||
var staticDir = isProduction ? 'dist' : 'app';
|
||||
|
||||
staticDir = 'app';
|
||||
|
||||
app.use(express.static(path.join(__dirname, staticDir)));
|
||||
app.use(errorhandler({dumpExceptions: true, showStack: true}));
|
||||
|
||||
@ -86,9 +86,19 @@ mdotApiV2(app);
|
||||
trackApi(app);
|
||||
meetingApi(app);
|
||||
|
||||
//app.get('/api/mdot/:id', mDot.getData);
|
||||
|
||||
app.listen(3010, function() {
|
||||
logger.info('Express listening on 3010');
|
||||
var mqttClient = require('./lib/mqtt/mqttClient');
|
||||
|
||||
var mqtt;
|
||||
|
||||
if (isProduction) {
|
||||
mqtt = new mqttClient.mqttClient(busEmitter);
|
||||
}
|
||||
|
||||
var port = (process.env.VCAP_APP_PORT || 3010);
|
||||
var host = (process.env.VCAP_APP_HOST || 'localhost');
|
||||
|
||||
app.listen(port, function() {
|
||||
logger.info('Express listening on ',host, port);
|
||||
|
||||
});
|
||||
|
@ -109,6 +109,7 @@
|
||||
|
||||
processAdded: function() {
|
||||
var skipOccupancy = false;
|
||||
console.time('processAdd');
|
||||
var tempCollection = new Backbone.Collection();
|
||||
|
||||
var events;
|
||||
|
130
lib/mqtt/IoTFconnector.js
Normal file
130
lib/mqtt/IoTFconnector.js
Normal file
@ -0,0 +1,130 @@
|
||||
|
||||
|
||||
|
||||
var IoTFconnector = function (orgId, api_key, auth_token, $rootScope) {
|
||||
|
||||
|
||||
//this.connected = '';
|
||||
this.clientId = "a:" + orgId + ":" + Date.now();
|
||||
|
||||
console.log("clientId: " + this.clientId);
|
||||
this.hostname = orgId + ".messaging.internetofthings.ibmcloud.com";
|
||||
this.client = '';
|
||||
|
||||
this.initialize = function () {
|
||||
|
||||
client = new Messaging.Client(this.hostname, 8883, this.clientId);
|
||||
|
||||
|
||||
client.onMessageArrived = function (msg) {
|
||||
console.log("Message from :" + msg.destinationName);
|
||||
};
|
||||
|
||||
var connectOptions = new Object();
|
||||
connectOptions.keepAliveInterval = 3600;
|
||||
connectOptions.useSSL = true;
|
||||
connectOptions.userName = api_key;
|
||||
connectOptions.password = auth_token;
|
||||
|
||||
connectOptions.onSuccess = function () {
|
||||
IoTFconnector.prototype.clientStatus.connected = true;
|
||||
// $rootScope.$broadcast("clientStatusUpdated", clientStatus);
|
||||
console.log("MQTT connected to host: " + client.host + " port : " + client.port + " at " + Date.now());
|
||||
|
||||
}
|
||||
|
||||
connectOptions.onFailure = function (e) {
|
||||
console.log("MQTT connection failed at " + Date.now() + "\nerror: " + e.errorCode + " : " + e.errorMessage);
|
||||
}
|
||||
|
||||
console.log("about to connect to " + client.host);
|
||||
client.connect(connectOptions);
|
||||
|
||||
//client = new Messaging.Client(this.hostname, 8883, this.clientId);
|
||||
|
||||
//// Initialize the Realtime Graph
|
||||
////var rtGraph = new RealtimeGraph();
|
||||
//client.onMessageArrived = function(msg) {
|
||||
// //var topic = msg.destinationName;
|
||||
|
||||
// //var payload = JSON.parse(msg.payloadString);
|
||||
// ////First message, instantiate the graph
|
||||
// //if (firstMessage) {
|
||||
// // $('#chart').empty();
|
||||
// // firstMessage = false;
|
||||
// // rtGraph.displayChart(null, payload);
|
||||
// //} else {
|
||||
// // rtGraph.graphData(payload);
|
||||
// //}
|
||||
// console.log("Message from :" + msg.destinationName);
|
||||
//};
|
||||
|
||||
//client.onConnectionLost = function(e) {
|
||||
// console.log("Connection Lost at " + Date.now() + " : " + e.errorCode + " : " + e.errorMessage);
|
||||
// this.connect(connectOptions);
|
||||
//}
|
||||
|
||||
//var connectOptions = new Object();
|
||||
//connectOptions.keepAliveInterval = 3600;
|
||||
//connectOptions.useSSL = true;
|
||||
//connectOptions.userName = api_key;
|
||||
//connectOptions.password = auth_token;
|
||||
|
||||
//connectOptions.onSuccess = function() {
|
||||
// IoTFconnector.prototype.connected = true;
|
||||
// console.log("MQTT connected to host: " + client.host + " port : " + client.port + " at " + Date.now());
|
||||
|
||||
//}
|
||||
|
||||
//connectOptions.onFailure = function(e) {
|
||||
// console.log("MQTT connection failed at " + Date.now() + "\nerror: " + e.errorCode + " : " + e.errorMessage);
|
||||
//}
|
||||
|
||||
//console.log("about to connect to " + client.host);
|
||||
//client.connect(connectOptions);
|
||||
}
|
||||
|
||||
|
||||
this.initialize();
|
||||
|
||||
//var imageHTML = '<div class="iotdashboardtext">The selected device is not currently sending events to the Internet of Things Foundation</div><br><div class="iotdashboardtext">Select to view historical data or select a different device.</div> <img class="iotimagesMiddle" align="middle" alt="Chart" src="../../images/IOT_Icons_Thing02.svg">';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
IoTFconnector.prototype.clientStatus = { connected: false, subscribeTopic: '' };;
|
||||
|
||||
IoTFconnector.prototype.disconnect = function disconnect() {
|
||||
client.disconnect();
|
||||
console.log("Connection closed");
|
||||
}
|
||||
|
||||
IoTFconnector.prototype.connect = function connect() {
|
||||
// this.initialize();
|
||||
}
|
||||
|
||||
|
||||
|
||||
IoTFconnector.prototype.subscribe = function subscribe(deviceId) {
|
||||
var subscribeOptions = {
|
||||
qos: 0,
|
||||
onSuccess: function () {
|
||||
console.log("subscribed to " + IoTFconnector.prototype.clientStatus.subscribeTopic);
|
||||
},
|
||||
onFailure: function () {
|
||||
console.log("Failed to subscribe to " + IoTFconnector.prototype.clientStatus.subscribeTopic);
|
||||
console.log("As messages are not available, visualization is not possible");
|
||||
}
|
||||
};
|
||||
|
||||
if (IoTFconnector.prototype.clientStatus.subscribeTopic != "") {
|
||||
console.log("Unsubscribing to " + IoTFconnector.prototype.clientStatus.subscribeTopic);
|
||||
client.unsubscribe(IoTFconnector.prototype.clientStatus.subscribeTopic);
|
||||
};
|
||||
|
||||
IoTFconnector.prototype.clientStatus.subscribeTopic = "iot-2/type/iotsample-ti-cc3200/id/" + deviceId + "/evt/+/fmt/json";
|
||||
|
||||
client.subscribe(IoTFconnector.prototype.clientStatus.subscribeTopic, subscribeOptions);
|
||||
}
|
150
lib/mqtt/mqttClient.js
Normal file
150
lib/mqtt/mqttClient.js
Normal file
@ -0,0 +1,150 @@
|
||||
var mqtt = require('mqtt');
|
||||
var logger = require('log4js').getLogger();
|
||||
|
||||
var EventEmitter = require('events');
|
||||
|
||||
var busEmitter = new EventEmitter();
|
||||
|
||||
var db = require('../server/db-connector').dbConnection;
|
||||
|
||||
var dbSave = require('../server/db-save')(db);
|
||||
|
||||
function dataBuilder(obj) {
|
||||
'use strict';
|
||||
var now = new Date();
|
||||
var newObj = {device_type: 'mDot', evt_type: 'update', timestamp: {}, evt: {}};
|
||||
|
||||
newObj.device_id = obj.topic.split('/')[4];
|
||||
|
||||
newObj.evt = obj;
|
||||
newObj.timestamp['$date'] = now.getTime();
|
||||
|
||||
return newObj;
|
||||
}
|
||||
|
||||
function insertEntry(obj) {
|
||||
|
||||
var newObj = dataBuilder(obj);
|
||||
|
||||
newObj.rtype = 1;
|
||||
|
||||
logger.debug('Inserting into couch...');
|
||||
// logger.info(util.inspect(newObj));
|
||||
dbCouch.insert(newObj, 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);
|
||||
|
||||
dbSave.addNewEvent(obj)
|
||||
.then(function(d) {
|
||||
'use strict';
|
||||
logger.info('Finished - Raw',d);
|
||||
})
|
||||
.catch(function(e) {
|
||||
'use strict';
|
||||
logger.error(e);
|
||||
});
|
||||
|
||||
|
||||
dbSave.addProcessedEvent(obj)
|
||||
.then(function(d) {
|
||||
'use strict';
|
||||
logger.info('Finished - Processed',d);
|
||||
})
|
||||
.catch(function(e) {
|
||||
'use strict';
|
||||
logger.error(e);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
var mqttClient = function() {
|
||||
|
||||
var subscribeTopic;
|
||||
var orgId = 'qz0da4';
|
||||
var userName = 'a-qz0da4-dfwwdkmkzr';
|
||||
var address = '.messaging.internetofthings.ibmcloud.com';
|
||||
var appKey = '9txJEf3Cjy7hkSOvkv';
|
||||
var prefix = 'iot-2/type/mDot/id/';
|
||||
//var deviceId = ['CENSIS-LoRa-1','CENSIS-LoRa-2','CENSIS-LoRa-3','CENSIS-LoRa-4','HIE-mobile-1','HIE-mobile-2','HIE-smart-campus-1','HIE-smart-campus-2','HIE-smart-campus-3','HIE-smart-campus-4','HIE-smart-campus-5','HIE-smart-campus-6','HIE-smart-campus-7','HIE-mDot-1'];
|
||||
|
||||
var deviceId = ['CENSIS-LoRa-1','CENSIS-LoRa-2','CENSIS-LoRa-3','CENSIS-LoRa-4','HIE-mobile-1----','HIE-mobile-2----','HIE-smart-campus-1','HIE-smart-campus-2','HIE-smart-campus-3','HIE-smart-campus-4','HIE-smart-campus-5','HIE-smart-campus-6','HIE-smart-campus-7','HIE-mDot-1'];
|
||||
|
||||
|
||||
//Var subscribeTopic = prefix + deviceId + '/evt/+/fmt/json';
|
||||
|
||||
|
||||
this.connected = false;
|
||||
|
||||
var options = {
|
||||
keepalive: 3600,
|
||||
clientId: 'a:' + orgId + ':' + Date.now(),
|
||||
username: userName,
|
||||
password: new Buffer(appKey)
|
||||
|
||||
};
|
||||
|
||||
this.client = mqtt.connect('mqtt://' + orgId + address, options);
|
||||
|
||||
this.client.on('connect', function() {
|
||||
connected = true;
|
||||
logger.info('Connected to ', address);
|
||||
}.bind(this));
|
||||
|
||||
|
||||
for (var t = 0;t < deviceId.length;t++) {
|
||||
subscribeTopic = prefix + deviceId[t] + '/evt/+/fmt/json';
|
||||
logger.info('Subscribing:', subscribeTopic);
|
||||
this.client.subscribe(subscribeTopic);
|
||||
}
|
||||
|
||||
|
||||
|
||||
this.client.on('message', function(topic, message) {
|
||||
console.log('onMessage',topic);
|
||||
|
||||
var json = JSON.parse(message.toString());
|
||||
|
||||
json.topic = topic;
|
||||
// logger.debug(JSON.stringify(json));
|
||||
|
||||
busEmitter.emit('saveData', json);
|
||||
|
||||
}.bind(this));
|
||||
|
||||
this.isConnected = function() {
|
||||
|
||||
return this.connected;
|
||||
};
|
||||
|
||||
this.client.on('connected', function() {
|
||||
logger.debug('mqttConnect - doConnection - Connected');
|
||||
|
||||
});
|
||||
this.client.on('disconnect', function(e) {
|
||||
logger.error('mqttConnect - doConnection - disconnect');
|
||||
logger.error(e);
|
||||
});
|
||||
this.client.on('error', function(e) {
|
||||
logger.error('mqttConnect - doConnection - disconnect');
|
||||
logger.error(e);
|
||||
});
|
||||
|
||||
|
||||
busEmitter.on('saveData', doInsertEntry);
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
module.exports.mqttClient = mqttClient;
|
353
lib/mqtt/mqttConnect.js
Normal file
353
lib/mqtt/mqttConnect.js
Normal file
@ -0,0 +1,353 @@
|
||||
/**
|
||||
* 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: 'martind2000',
|
||||
appKey: 'MPReoa43',
|
||||
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);
|
||||
}
|
||||
|
||||
/*
|
||||
Projector: 'ProjectorISP15',
|
||||
lighting: 'LightingISP15',
|
||||
heating: 'HeatingISP15',
|
||||
|
||||
*/
|
||||
var live = true;
|
||||
|
||||
logger.warn('!!! Live? ', live);
|
||||
module.exports = {
|
||||
restartTimer : 0,
|
||||
pingTimer: 0,
|
||||
statuses: {},
|
||||
sockets: null,
|
||||
wsClient: null,
|
||||
watches: {},
|
||||
client: null,
|
||||
projector: live ? 'Projector' : 'ProjectorISP15',
|
||||
lighting: live ? 'Lighting' : 'LightingISP15',
|
||||
heating: live ? 'Heating' : 'HeatingISP15',
|
||||
myID: 0,
|
||||
connected: false,
|
||||
options: {
|
||||
// Keepalive: 3600,
|
||||
keepalive: 60,
|
||||
clientId: 'a:' + mqttConfig.orgId + ':' + Date.now(),
|
||||
username: mqttConfig.userName,
|
||||
password: new Buffer(mqttConfig.appKey)
|
||||
|
||||
},
|
||||
lightList: {o: 'frontLight', f: 'frontLight',n: 'backLight', g: 'backLight'},
|
||||
updateStatus: function(id, packet) {
|
||||
this.statuses[id] = packet;
|
||||
logger.info('Statuses:', this.statuses);
|
||||
},
|
||||
|
||||
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://' + 'silvrtree.co.uk', this.options);
|
||||
|
||||
this.client.on('connect', function() {
|
||||
logger.info('Connected to SilvrBroker');
|
||||
self.connected = this.connected;
|
||||
});
|
||||
this.client.on('connected', function() {
|
||||
logger.debug('mqttConnect - doConnection - Connected');
|
||||
|
||||
});
|
||||
this.client.on('disconnect', function(e) {
|
||||
logger.error('mqttConnect - doConnection - disconnect');
|
||||
logger.error(e);
|
||||
});
|
||||
this.client.on('error', function(e) {
|
||||
logger.error('mqttConnect - doConnection - disconnect');
|
||||
logger.error(e);
|
||||
});
|
||||
|
||||
}
|
||||
return this;
|
||||
},
|
||||
isConnected: function() {
|
||||
return this.connected;
|
||||
},
|
||||
sendCommand: function(deviceID, command) {
|
||||
var payload = {
|
||||
id: 'd',
|
||||
text: command
|
||||
|
||||
};
|
||||
},
|
||||
projectorOn: function(callback) {
|
||||
var packet;
|
||||
console.log('projectorOn:');
|
||||
var _callback = callback || {};
|
||||
|
||||
if (!this.client) {
|
||||
return -1;
|
||||
}
|
||||
packet = {id: this.projector, status: true};
|
||||
var destinationName = mqttConfig.prefix + this.projector + '/cmd/' + 'ON' + '/fmt/json';
|
||||
this.client.publish(destinationName, 'ON', _callback);
|
||||
this.emitter.emit('sendSocket',packet);
|
||||
logger.debug('Storing status...');
|
||||
this.updateStatus('projector', packet);
|
||||
},
|
||||
projectorOff: function(callback) {
|
||||
var packet;
|
||||
var _callback = callback || {};
|
||||
if (!this.client) {
|
||||
return -1;
|
||||
}
|
||||
packet = {id: this.projector, status: false};
|
||||
var destinationName = mqttConfig.prefix + this.projector + '/cmd/' + 'OFF' + '/fmt/json';
|
||||
this.client.publish(destinationName, 'OFF', _callback);
|
||||
this.emitter.emit('sendSocket',packet);
|
||||
console.log('Storing status...');
|
||||
this.updateStatus('projector', packet);
|
||||
|
||||
},
|
||||
projectorCmd: function(id, callback) {
|
||||
var packet;
|
||||
var _callback = callback || {};
|
||||
if (!this.client) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
var destinationName = mqttConfig.prefix + this.projector + '/cmd/' + id + '/fmt/json';
|
||||
this.client.publish(destinationName, 'cmd', _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);
|
||||
this.emitter.emit('sendSocket',{id: this.heating, status: true});
|
||||
},
|
||||
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);
|
||||
this.emitter.emit('sendSocket',{id: this.heating, status: false});
|
||||
},
|
||||
lightingOn: function(id, callback) {
|
||||
var packet;
|
||||
|
||||
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);
|
||||
packet = {id: this.lighting, device: id, status: true};
|
||||
this.emitter.emit('sendSocket',packet);
|
||||
logger.debug('Storing status...');
|
||||
this.updateStatus(this.lightList[id], packet);
|
||||
},
|
||||
lightingOff: function(id, callback) {
|
||||
var packet;
|
||||
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);
|
||||
packet = {id: this.lighting, device: id, status: false};
|
||||
this.emitter.emit('sendSocket', packet);
|
||||
this.updateStatus(this.lightList[id], packet);
|
||||
},
|
||||
lightingCommand: function(id, callback) {
|
||||
var packet;
|
||||
var _callback = callback || null;
|
||||
if (!this.client) {
|
||||
return -1;
|
||||
}
|
||||
var destinationName = mqttConfig.prefix + this.lighting + '/cmd/' + id + '/fmt/json';
|
||||
this.client.publish(destinationName, 'cmd', _callback);
|
||||
},
|
||||
|
||||
setupEvents: function() {
|
||||
|
||||
this.emitter.on('lightingOn', this.lightingOn);
|
||||
this.emitter.on('lightingOff', this.lightingOff);
|
||||
this.emitter.on('heatingOn', this.heatingOn);
|
||||
this.emitter.on('heatingOff', this.heatingOff);
|
||||
this.emitter.on('projectorOn', this.projectorOn);
|
||||
this.emitter.on('projectorOff', this.projectorOff);
|
||||
},
|
||||
setupPing: function() {
|
||||
logger.warn('Starting ping timer...');
|
||||
|
||||
this.pingTimer = setTimeout(function() {this.ping();}.bind(this), 10000);
|
||||
},
|
||||
ping: function() {
|
||||
//Logger.error('Ping!');
|
||||
this.sendRefresh();
|
||||
var now = new Date;
|
||||
var mod = 10000 - (now.getTime() % 10000);
|
||||
|
||||
setTimeout(function() {this.ping();}.bind(this),mod + 10);
|
||||
|
||||
},
|
||||
sendRefresh: function() {
|
||||
// logger.debug('+ Send refresh', this.statuses);
|
||||
|
||||
for (var item in this.statuses) {
|
||||
if (this.statuses.hasOwnProperty(item)) {
|
||||
console.log(this.statuses[item]);
|
||||
this.emitter.emit('sendSocket', this.statuses[item]);
|
||||
}
|
||||
}
|
||||
// logger.debug('+ Send refresh');
|
||||
},
|
||||
preRestartConnection: function() {
|
||||
logger.debug('Restart connection...');
|
||||
//this.emitter.emit('restartMQTTSocket', this);
|
||||
//logger.debug(this);
|
||||
this.restartMQTTSocket();
|
||||
},
|
||||
startMQTTSocket:function() {
|
||||
logger.warn('Restarting socket?');
|
||||
this.connectWS();
|
||||
},
|
||||
restartMQTTSocket: function() {
|
||||
this.wsClient.disconnect();
|
||||
// setTimeout(this.startMQTTSocket.bind(this), 15000);
|
||||
},
|
||||
connectWS: function(connectCB) {
|
||||
|
||||
logger.debug('Going to connect WS');
|
||||
var self = this;
|
||||
var hostname = 'silvrtree.co.uk';
|
||||
var clientId = 'a:' + 'qz0da4' + ':' + Date.now();
|
||||
|
||||
var api_key = 'martind2000';
|
||||
var auth_token = 'MPReoa43';
|
||||
|
||||
this.wsClient =new Messaging.Client(hostname, 8883, clientId);
|
||||
//var wsClient = new Messaging.Client(hostname, 8883, clientId);
|
||||
var wsClient = this.wsClient;
|
||||
var clientStatus = {connected: false, subscribed: false, deviceConnected: false};
|
||||
var sensorData = {};
|
||||
|
||||
|
||||
this.restartTimer = setTimeout(this.preRestartConnection.bind(this), 60000);
|
||||
|
||||
wsClient.onMessageArrived = function(msg) {
|
||||
//logger.info("Message from :" + msg.destinationName);
|
||||
clearTimeout(self.restartTimer);
|
||||
self.restartTimer = setTimeout(self.preRestartConnection.bind(self), 60000);
|
||||
clientStatus.deviceConnected = true;
|
||||
sensorData = JSON.parse(msg.payloadString);
|
||||
// Logger.debug(sensorData);
|
||||
var temp = msg.destinationName.split('/');
|
||||
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});
|
||||
}
|
||||
|
||||
};
|
||||
wsClient.onConnectionLost = function(e) {
|
||||
logger.error('+ wsClient.onConnectionLost');
|
||||
logger.error(e);
|
||||
logger.warn('Going to force a restart of the Socket.. Hold on.');
|
||||
setTimeout(self.startMQTTSocket.bind(self), 15000);
|
||||
//self.emitter.emit('sendSocket',{id: 'deviceLost',data: e});
|
||||
//var wsReconnectTimer = setTimeout(function() {logger.debug('TRYING TO RECONNECT TO MQTT');self.emitter.emit('connectWS');}.bind(this),30000);
|
||||
logger.error('- wsClient.onConnectionLost');
|
||||
};
|
||||
|
||||
|
||||
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) {
|
||||
self.emitter.emit('sendSocket',{id: 'deviceNotConnecting'});
|
||||
logger.error('wsClient onFailure', e);
|
||||
logger.error('MQTT connection failed at ' + Date.now() + '\nerror: ' + e.errorCode + ' : ' + e.errorMessage);
|
||||
//var wsReconnectTimer = setTimeout(function() {logger.debug('TRYING TO RECONNECT TO MQTT');self.emitter.emit('connectWS');}.bind(this),30000);
|
||||
};
|
||||
|
||||
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() {
|
||||
logger.info('subscribed to ' + subscribeTopic);
|
||||
clientStatus.subscribed = true;
|
||||
// $rootScope.$broadcast("clientStatusUpdated", clientStatus);
|
||||
|
||||
self.emitter.emit('clientStatusUpdated', clientStatus);
|
||||
self.watches[deviceId] = emitterId;
|
||||
},
|
||||
onFailure: function() {
|
||||
logger.error('Failed to subscribe to ' + subscribeTopic);
|
||||
logger.error('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;
|
||||
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
7
lib/mqtt/mqttSocket.js
Normal file
7
lib/mqtt/mqttSocket.js
Normal file
@ -0,0 +1,7 @@
|
||||
/**
|
||||
*
|
||||
* User: Martin Donnelly
|
||||
* Date: 2016-07-28
|
||||
* Time: 14:48
|
||||
*
|
||||
*/
|
1791
lib/mqtt/mqttws31.js
Normal file
1791
lib/mqtt/mqttws31.js
Normal file
File diff suppressed because it is too large
Load Diff
@ -9,6 +9,7 @@
|
||||
|
||||
var pgp = require('pg-promise')();
|
||||
|
||||
/*
|
||||
var cn = {
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
@ -16,6 +17,17 @@ var cn = {
|
||||
user: 'postgres',
|
||||
password: ''
|
||||
};
|
||||
*/
|
||||
|
||||
// ElephantSql settings
|
||||
|
||||
var cn = {
|
||||
host: 'jumbo.db.elephantsql.com',
|
||||
port: 5432,
|
||||
database: 'amlrxqev',
|
||||
user: 'amlrxqev',
|
||||
password: 'K11cvCplk0--oNafsYj4ISN-rVQmVS3y'
|
||||
};
|
||||
|
||||
exports.dbConnection = pgp(cn);
|
||||
|
||||
|
@ -1,6 +1,5 @@
|
||||
'use strict';
|
||||
|
||||
var newId = require('uuid-pure').newId;
|
||||
var atob = require('atob');
|
||||
|
||||
module.exports = function(db) {
|
||||
@ -17,6 +16,7 @@ module.exports = function(db) {
|
||||
return resolve('ok');
|
||||
})
|
||||
.catch((err)=> {
|
||||
console.error(err);
|
||||
return reject(err);
|
||||
});
|
||||
});
|
||||
@ -26,8 +26,6 @@ module.exports = function(db) {
|
||||
let _data = data;
|
||||
|
||||
console.log('sqlInsertDecoded', _data.deviceid, _data.timestamp);
|
||||
console.log('insert_decoded',
|
||||
[_data.deviceid, _data.timestamp, _data.lux, _data.co2, _data.temp, _data.humidity, _data.sound]);
|
||||
return new Promise(function(resolve, reject) {
|
||||
db.func('insert_decoded',
|
||||
[_data.deviceid, _data.timestamp, _data.lux, _data.co2, _data.temp, _data.humidity, _data.sound])
|
||||
@ -35,6 +33,7 @@ module.exports = function(db) {
|
||||
return resolve('ok');
|
||||
})
|
||||
.catch((err)=> {
|
||||
console.error(err);
|
||||
return reject(err);
|
||||
});
|
||||
});
|
||||
@ -56,6 +55,7 @@ module.exports = function(db) {
|
||||
return resolve({reply: 'raw event inserted'});
|
||||
})
|
||||
.catch((err)=> {
|
||||
console.error(err);
|
||||
return reject(err);
|
||||
});
|
||||
});
|
||||
@ -68,14 +68,13 @@ module.exports = function(db) {
|
||||
|
||||
let _data = self.rawBreaker(data);
|
||||
|
||||
console.log(_data);
|
||||
|
||||
self.sqlInsertDecoded(_data)
|
||||
.then((d)=> {
|
||||
console.log('Postgres returns', d);
|
||||
return resolve({reply: 'Processed event inserted'});
|
||||
})
|
||||
.catch((err)=> {
|
||||
console.error(err);
|
||||
return reject(err);
|
||||
});
|
||||
|
||||
@ -96,6 +95,7 @@ module.exports = function(db) {
|
||||
_obj.humid = (parseInt(_data[12] + _data[13] + _data[14] + _data[15] + _data[16], 10) / 10);
|
||||
_obj.noise = parseInt('0x' + ('0' + bytes[17]).substr(-2) + ('0' + bytes[18]).substr(-2));
|
||||
_obj.binData = bytes;
|
||||
console.log(_obj);
|
||||
return _obj;
|
||||
};
|
||||
|
||||
@ -104,7 +104,9 @@ module.exports = function(db) {
|
||||
var workObj = {};
|
||||
|
||||
var device_name = data.topic.split('/')[4];
|
||||
console.log('Device_name', device_name);
|
||||
workObj.deviceid = self.deviceIds.indexOf(device_name);
|
||||
|
||||
if (data.hasOwnProperty('data')) {
|
||||
|
||||
var _data = self.decoder(data.data);
|
||||
@ -114,7 +116,7 @@ module.exports = function(db) {
|
||||
workObj.temp = _data.temp;
|
||||
workObj.humidity = _data.humid;
|
||||
workObj.sound = _data.noise;
|
||||
workObj.timestamp = new Date(data.gateway_info['0'].gw_time);
|
||||
workObj.timestamp = new Date();
|
||||
|
||||
return workObj;
|
||||
} else {
|
||||
|
8
manifest.yml
Normal file
8
manifest.yml
Normal file
@ -0,0 +1,8 @@
|
||||
applications:
|
||||
- path: .
|
||||
memory: 256M
|
||||
instances: 1
|
||||
domain: mybluemix.net
|
||||
name: mdotmqtt
|
||||
host: mdotmqtt
|
||||
disk_quota: 1024M
|
10
package.json
10
package.json
@ -2,7 +2,7 @@
|
||||
"name": "mdotserver",
|
||||
"version": "0.0.1",
|
||||
"description": "mDot Dashboard Server",
|
||||
"main": "index.js",
|
||||
"main": "app.js",
|
||||
"directories": {
|
||||
"test": "test"
|
||||
},
|
||||
@ -10,12 +10,15 @@
|
||||
"atob": "^2.0.3",
|
||||
"body-parser": "^1.15.1",
|
||||
"btoa": "^1.1.2",
|
||||
"cfenv": "1.0.x",
|
||||
"cookie-parser": "*",
|
||||
"ejs": "*",
|
||||
"errorhandler": "*",
|
||||
"events": "^1.1.1",
|
||||
"express": "^4.13.4",
|
||||
"express-session": "*",
|
||||
"htmlparser": "^1.7.7",
|
||||
"log4js": "^0.6.36",
|
||||
"method-override": "*",
|
||||
"minibus": "^3.1.0",
|
||||
"morgan": "*",
|
||||
@ -25,8 +28,9 @@
|
||||
"pg-promise": "^5.2.7",
|
||||
"request": "^2.74.0",
|
||||
"request-promise": "^4.1.1",
|
||||
"sugar-date": "^2.0.0",
|
||||
"uuid-pure": "^1.0.10",
|
||||
"websocket": "^1.0.22"
|
||||
"websocket": "^1.0.23"
|
||||
},
|
||||
"devDependencies": {
|
||||
"after": "^0.8.1",
|
||||
@ -73,7 +77,7 @@
|
||||
},
|
||||
"scripts": {
|
||||
"test": "mocha --recursive --reporter spec --bail --check-leaks --timeout 3000",
|
||||
"start": "node app"
|
||||
"start": "node app.js"
|
||||
},
|
||||
"author": "Martin Donnelly",
|
||||
"license": "ISC",
|
||||
|
@ -11,9 +11,9 @@ var exec = require('child_process').exec;
|
||||
|
||||
function run_script() {
|
||||
'use strict';
|
||||
exec('psql -Upostgres -d mdot -h localhost -f ../mdot.sql', function(err) {
|
||||
exec('psql postgres://amlrxqev:K11cvCplk0--oNafsYj4ISN-rVQmVS3y@jumbo.db.elephantsql.com:5432/amlrxqev -f ../sql/mdot.sql', function(err) {
|
||||
if (err !== null) {
|
||||
console.log('exec error: ' + err);
|
||||
console.log('exec error: ', err);
|
||||
return -1;
|
||||
} else {
|
||||
// addUsers();
|
||||
|
Loading…
Reference in New Issue
Block a user