From 146d7694054cf9862e6f5ed836cb7f75a5519185 Mon Sep 17 00:00:00 2001 From: Martin Donnelly Date: Thu, 8 Sep 2016 16:45:04 +0100 Subject: [PATCH] =?UTF-8?q?=E2=80=9D2016-09-08=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mDotServer.censis/app.js | 50 +++++++++- .../mDotServer.censis/app/js/mdot.js | 17 +++- .../mDotServer.censis/app/js/websocket.js | 79 ++++++++++++++++ .../mDotServer.censis/app/socket.html | 21 +++++ .../mDotServer.censis/lib/mdot/message.js | 34 ++----- .../lib/server/db-connector.js | 6 +- .../mDotServer.censis/lib/server/db-save.js | 2 +- .../mDotServer.censis/lib/sockethandler.js | 94 +++++++++++++++++++ .../mDotServer.censis/views/test.ejs | 1 + mdot/mqttArchiver/mqttArchiver/app.js | 3 +- .../mqttArchiver/lib/mqtt/mqttClient.js | 2 +- smartoffice/SODashServer/SODashServer/app.js | 2 +- 12 files changed, 269 insertions(+), 42 deletions(-) create mode 100644 mdot/mDotServer.censis/mDotServer.censis/app/js/websocket.js create mode 100644 mdot/mDotServer.censis/mDotServer.censis/app/socket.html create mode 100644 mdot/mDotServer.censis/mDotServer.censis/lib/sockethandler.js diff --git a/mdot/mDotServer.censis/mDotServer.censis/app.js b/mdot/mDotServer.censis/mDotServer.censis/app.js index 8b7d428..f3cda2f 100644 --- a/mdot/mDotServer.censis/mDotServer.censis/app.js +++ b/mdot/mDotServer.censis/mDotServer.censis/app.js @@ -1,7 +1,7 @@ /** * Created by Martin on 08/02/2016. */ -'use strict'; + var express = require('express'); var path = require('path'); var http = require('http'); @@ -16,10 +16,10 @@ var log4js = require('log4js'); var logger = log4js.getLogger(); var authentication = require('basic-authentication'); -var EventEmitter = require('events'); -var busEmitter = new EventEmitter(); +var Events = require('events'); +var busEmitter = new Events.EventEmitter(); -var socketHandler = require('./lib/socketeer')(busEmitter); +var SocketHandler = require('./lib/sockethandler'); // Var apn = require('apn'); @@ -42,6 +42,38 @@ if (process.env.NODE_ENV === 'production') { logger.warn('isProduction:', isProduction); +var heartBeat = function() { + this.pingTimer = 0; + this.count = 0; + this.rate = 20000; + + this.setupPing = function() { + logger.warn('Starting heartbeat...'); + + this.pingTimer = setTimeout(function() {this.ping();}.bind(this), 10000); + }; + + this.ping = function() { + var now = new Date; + var mod = this.rate - (now.getTime() % this.rate); + this.count++; + if (this.count > 5) { + this.count = 1; + } + + var _newDots = ['.','.','.','.','.']; + _newDots[this.count - 1] = 'O'; + logger.info(_newDots.join('')); + + busEmitter.emit('sendSocket',{tick:new Date().getTime()}); + this.pingTimer = setTimeout(function() {this.ping();}.bind(this), mod); + + }; + + this.setupPing(); +}; + + var app = express(); /*App.use(authentication(({ @@ -102,15 +134,21 @@ app.get('/meeting', function(req, res) { res.render('meeting',{delimiter: '^'}); }); +// **** + +var webSocket = new SocketHandler(busEmitter); + // Glue routes mdotApi(app); mdotApiV2(app); trackApi(app); meetingApi(app); -messageApi(app); +messageApi(app, busEmitter); + +heartBeat(); var port = (process.env.VCAP_APP_PORT || 3011); var host = (process.env.VCAP_APP_HOST || 'localhost'); @@ -123,3 +161,5 @@ app.listen(port, function() { logger.info('Express listening on ',host, port); }); + + diff --git a/mdot/mDotServer.censis/mDotServer.censis/app/js/mdot.js b/mdot/mDotServer.censis/mDotServer.censis/app/js/mdot.js index 14fbe7b..b26524d 100644 --- a/mdot/mDotServer.censis/mDotServer.censis/app/js/mdot.js +++ b/mdot/mDotServer.censis/mDotServer.censis/app/js/mdot.js @@ -17,7 +17,20 @@ |_| |_|\___/|___/|___|____|___/ */ - var MainModel = Backbone.Model.extend({}); + var SocketManager = Backbone.Model.extend({ + initialize: function() { + // _.bindAll(this, 'processAdded'); + this.webSocket = new WEBSOCKET(this); + + this.on('message', function(o) { + console.log('Message', o); + }); + } + }); + + var MainModel = Backbone.Model.extend({ + + }); var EventsModel = Backbone.Model.extend({ initialize: function() { @@ -451,6 +464,8 @@ notification.configProfile('global', { stacking: false }); + var webSocketModel = new SocketManager(); + var DeviceCollection = new Backbone.Collection; var mdotCollection = new mDotCollection(); diff --git a/mdot/mDotServer.censis/mDotServer.censis/app/js/websocket.js b/mdot/mDotServer.censis/mDotServer.censis/app/js/websocket.js new file mode 100644 index 0000000..040421f --- /dev/null +++ b/mdot/mDotServer.censis/mDotServer.censis/app/js/websocket.js @@ -0,0 +1,79 @@ +var WEBSOCKET = function(model) { + + var wsUrl = 'ws://localhost:3001'; + + this.socket = null; + this.retry = 0; + this.timer = 0; + + this.startWebSocket = function() { + 'use strict'; + console.log('Starting socket?'); + + var url = wsUrl; + + var wsCtor = window['MozWebSocket'] ? MozWebSocket : WebSocket; + this.socket = new wsCtor(url, 'stream'); + + this.socket.onopen = this.handleWebsocketOnOpen.bind(this); + this.socket.onmessage = this.handleWebsocketMessage.bind(this); + this.socket.onclose = this.handleWebsocketClose.bind(this); + this.socket.onerror = function(e) { + console.error(e); + }; + + }; + + + this.handleData = function(d) { + + + model.trigger('message',d); + switch (d.id) { +/* + case 'LightingDataReceived': + + // This.updateLighting(d.sensorData.d); + break; +*/ + + default: + console.log('Default:',d); + break; + } + }; + + this.handleWebsocketOnOpen = function() { + 'use strict'; + this.retry = 0; + + console.log('**** Websocket Connected ****'); + }; + + this.handleWebsocketMessage = function(message) { + + console.log('handleWebsocketMessage:',message); + var command; + try { + command = JSON.parse(message.data); + } + catch (e) { /* Do nothing */ + } + + + if (command) { + //This.dispatchCommand(command); + this.handleData.call(this,command); + } + }; + + this.handleWebsocketClose = function() { + console.error('WebSocket Connection Closed.'); + var self = this; + console.log('Waiting ', 5000); + this.timer = setTimeout(function() {self.startWebSocket();},5000); + }; + + this.startWebSocket(); + + }; diff --git a/mdot/mDotServer.censis/mDotServer.censis/app/socket.html b/mdot/mDotServer.censis/mDotServer.censis/app/socket.html new file mode 100644 index 0000000..0b2756a --- /dev/null +++ b/mdot/mDotServer.censis/mDotServer.censis/app/socket.html @@ -0,0 +1,21 @@ + + + + + Title + + + + + + + + diff --git a/mdot/mDotServer.censis/mDotServer.censis/lib/mdot/message.js b/mdot/mDotServer.censis/mDotServer.censis/lib/mdot/message.js index f62958a..2cd115f 100644 --- a/mdot/mDotServer.censis/mDotServer.censis/lib/mdot/message.js +++ b/mdot/mDotServer.censis/mDotServer.censis/lib/mdot/message.js @@ -8,7 +8,7 @@ var db = require('../server/db-connector').dbConnection; var dbSave = require('../server/db-save')(db); -module.exports = function(app) { +module.exports = function(app, events) { var express = require('express'); var messageRouter = express.Router(); @@ -26,7 +26,12 @@ module.exports = function(app) { .then(function(d) { 'use strict'; // Logger.info('Finished - Processed'); + logger.info('emiting sendSocket'); + events.emit('sendSocket',d); + //console.log(events); + res.status(200).json({}); + }) .catch(function(e) { 'use strict'; @@ -36,33 +41,6 @@ module.exports = function(app) { } - /* If (!req.params.id) { - logger.error('MDot','Missing required parameter'); - res.status(400).send({ - status: 'error', - error: 'missing required parameter' - }); - return; - } - - if (req.query.hasOwnProperty('start') && req.query.hasOwnProperty('end')) { - data.start = req.query.start; - data.end = req.query.end; - } - - if (req.params.hasOwnProperty('id')) { - data.id = req.params.id; - - dbMdot.doGet(data) - .then((d) => { - res.json({events:d}); - }) - .catch((e) => { - logger.error(e); - res.status(500).json({}); - }); - - }*/ }); diff --git a/mdot/mDotServer.censis/mDotServer.censis/lib/server/db-connector.js b/mdot/mDotServer.censis/mDotServer.censis/lib/server/db-connector.js index 02e24b2..e219a2e 100644 --- a/mdot/mDotServer.censis/mDotServer.censis/lib/server/db-connector.js +++ b/mdot/mDotServer.censis/mDotServer.censis/lib/server/db-connector.js @@ -9,7 +9,6 @@ var pgp = require('pg-promise')(); -/* var cn = { host: 'localhost', port: 5432, @@ -17,17 +16,16 @@ var cn = { user: 'postgres', password: '' }; -*/ // ElephantSql settings -var cn = { +/*var cn = { host: 'jumbo.db.elephantsql.com', port: 5432, database: 'amlrxqev', user: 'amlrxqev', password: 'K11cvCplk0--oNafsYj4ISN-rVQmVS3y' -}; +};*/ exports.dbConnection = pgp(cn); diff --git a/mdot/mDotServer.censis/mDotServer.censis/lib/server/db-save.js b/mdot/mDotServer.censis/mDotServer.censis/lib/server/db-save.js index 12d82b9..df4fb8d 100644 --- a/mdot/mDotServer.censis/mDotServer.censis/lib/server/db-save.js +++ b/mdot/mDotServer.censis/mDotServer.censis/lib/server/db-save.js @@ -93,7 +93,7 @@ module.exports = function(db) { self.sqlInsertDecoded(_data) .then((d)=> { // console.log('Postgres returns', d); - return resolve({reply: 'Processed event inserted'}); + return resolve({reply: 'Processed event inserted',data:_data}); }) .catch((err)=> { console.error(err); diff --git a/mdot/mDotServer.censis/mDotServer.censis/lib/sockethandler.js b/mdot/mDotServer.censis/mDotServer.censis/lib/sockethandler.js new file mode 100644 index 0000000..2f5c63d --- /dev/null +++ b/mdot/mDotServer.censis/mDotServer.censis/lib/sockethandler.js @@ -0,0 +1,94 @@ +/** + * + * User: Martin Donnelly + * Date: 2016-09-07 + * Time: 15:33 + * + */ + +var WebSocketServer = require('websocket').server; +var http = require('http'); + +var logger = require('log4js').getLogger(); + +var Sugar = require('sugar-date'); + +var server = http.createServer(function(request, response) { + logger.info((new Date()) + ' Received request for ' + request.url); + response.writeHead(404); + response.end(); +}); + +server.listen(3001, function() { + logger.info('Server is listening on port 3001'); +}); + +var wsServer = new WebSocketServer({ + httpServer: server, // You should not use autoAcceptConnections for production + // applications, as it defeats all standard cross-origin protection + // facilities built into the protocol and the browser. You should + // *always* verify the connection's origin and decide whether or not + // to accept it. + autoAcceptConnections: false + }); + +module.exports = function(events) { + 'use strict'; + logger.debug('creating with events', events); + + function originIsAllowed(origin) { + // Put logic here to detect whether the specified origin is allowed. + return true; + } + wsServer.on('request', function(request) { + + logger.info('Creating event for this connection'); + if (!originIsAllowed(request.origin)) { + // Make sure we only accept requests from an allowed origin + request.reject(); + logger.info((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); + return; + } + + var connection = request.accept('stream', request.origin); + logger.info((new Date()) + ' Connection accepted.'); + + var sendSocketHandler = (obj) => { + logger.debug('sendSocketHandler', obj); + try { + connection.sendUTF(JSON.stringify(obj)); + } + catch (err) { + logger.error(err); + logger.warn('Offending object: ', obj); + } + }; + + events.on('sendSocket', sendSocketHandler); +/* + events.on('sendSocket', function(o){ + logger.debug('sendSocket!!', o); + }); +*/ + + connection.on('message', function(message) { + if (message.type === 'utf8') { + logger.info('Received Message: ' + message.utf8Data); + connection.sendUTF(message.utf8Data); + } else if (message.type === 'binary') { + logger.info('Received Binary Message of ' + message.binaryData.length + ' bytes'); + connection.sendBytes(message.binaryData); + } + }); + + connection.on('close', function(reasonCode, description) { + logger.info((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); + events.removeListener('sendSocket', sendSocketHandler); + }); + + }); + + + + return module; +}; diff --git a/mdot/mDotServer.censis/mDotServer.censis/views/test.ejs b/mdot/mDotServer.censis/mDotServer.censis/views/test.ejs index 3cf7f41..5b16e26 100644 --- a/mdot/mDotServer.censis/mDotServer.censis/views/test.ejs +++ b/mdot/mDotServer.censis/mDotServer.censis/views/test.ejs @@ -227,6 +227,7 @@ + diff --git a/mdot/mqttArchiver/mqttArchiver/app.js b/mdot/mqttArchiver/mqttArchiver/app.js index 82a80a3..41a6506 100644 --- a/mdot/mqttArchiver/mqttArchiver/app.js +++ b/mdot/mqttArchiver/mqttArchiver/app.js @@ -15,7 +15,7 @@ var authentication = require('basic-authentication'); var cfenv = require('cfenv'); -var WebSocketServer = require('websocket').server; +// var WebSocketServer = require('websocket').server; var EventEmitter = require('events'); var busEmitter = new EventEmitter(); @@ -43,6 +43,7 @@ logger.warn('isProduction:', isProduction); var heartBeat = function() { + console.log(this); this.pingTimer = 0; this.count = 0; this.rate = 90000; diff --git a/mdot/mqttArchiver/mqttArchiver/lib/mqtt/mqttClient.js b/mdot/mqttArchiver/mqttArchiver/lib/mqtt/mqttClient.js index 4dd7db0..b72c314 100644 --- a/mdot/mqttArchiver/mqttArchiver/lib/mqtt/mqttClient.js +++ b/mdot/mqttArchiver/mqttArchiver/lib/mqtt/mqttClient.js @@ -65,7 +65,7 @@ var doInsertEntry = (obj) => { dbSave.addNewEvent(obj) .then(function(d) { 'use strict'; - //logger.info('Finished - Raw',d); + logger.info('Obj',obj.type); saveToDB(obj); if (obj.type === 'mDot') { busEmitter.emit('sendMessage', obj); diff --git a/smartoffice/SODashServer/SODashServer/app.js b/smartoffice/SODashServer/SODashServer/app.js index 2a0fa5a..75df06a 100644 --- a/smartoffice/SODashServer/SODashServer/app.js +++ b/smartoffice/SODashServer/SODashServer/app.js @@ -267,7 +267,7 @@ mdotApi(app); //app.get('/api/mdot/:id', mDot.getData); -app.listen(3000, function() { +app.listen(3002, function() { logger.info('Express listening on 3000'); restartTimer(); });