Tidying other modules, fixing password and fx

This commit is contained in:
Martin Donnelly 2017-09-11 15:50:21 +01:00
parent 0976c58a6e
commit e2d788685c
5 changed files with 181 additions and 104 deletions

59
app/js/slackSocket.js Normal file
View File

@ -0,0 +1,59 @@
/**
*
* User: Martin Donnelly
* Date: 2016-09-09
* Time: 11:38
*
*/
/* global Backbone, _, WEBSOCKET */
/* jshint browser: true , devel: true*/
'use strict';
const SOCKETMANAGER = (function () {
const SocketManager = Backbone.Model.extend({
'initialize': function () {
_.bindAll(this, 'turnOn', 'turnOff');
this.listeningID = null;
this.listening = false;
this.webSocket = new WEBSOCKET(this);
this.on('message', function (o) {
console.log('On message', this.listening);
if (this.listening)
this.checkItem(o);
});
},
'turnOn': function () {
console.log('Socket now listening');
this.listening = true;
},
'turnOff': function () {
this.listening = false;
},
'listenFor': function (id) {
this.listeningID = this.deviceId.indexOf(id);
},
'checkItem': function (item) {
if (item.hasOwnProperty('id')) {
console.log('id:', item.id);
if (item.id === 'btc' && this.btc !== undefined) this.btc.btcFromSocket(item.data);
if (item.id === 'balance' && this.btc !== undefined) this.btc.balanceFromSocket(item.data);
}
},
'setBTC': function (obj) {
this.btc = obj;
},
'setTrain': function (obj) {
this.train = obj;
},
'getUpdate': function () {
this.webSocket.send('update');
}
});
return SocketManager;
}());

View File

@ -1,82 +1,81 @@
var WEBSOCKET = function(model) {
const WEBSOCKET = function (model) {
let wsUrl = ['localhost', 'silvrtree.co.uk'];
let wsPort = '9000';
const useUrl = 0;
var wsUrl = ['localhost','silvrtree.co.uk'];
var wsPort = '9000';
let useUrl = 0;
if ('https:' === document.location.protocol) {
wsUrl = `wss://${ wsUrl[useUrl] }`;
wsPort = '';
}
else {
// wsUrl = 'ws://localhost:3001';
wsUrl = `ws://${ wsUrl[useUrl] }`;
wsPort = '9000';
}
if ('https:' === document.location.protocol) {
wsUrl = 'wss://' + wsUrl[useUrl] + '';
wsPort = '';
} else {
//wsUrl = 'ws://localhost:3001';
wsUrl = 'ws://' + wsUrl[useUrl] + '';
wsPort = '';
}
console.log('>> wsUrl', wsUrl);
this.socket = null;
this.timer = 0;
this.clock = null;
this.socket = null;
this.timer = 0;
this.clock = null;
this.startWebSocket = function () {
'use strict';
this.startWebSocket = function() {
'use strict';
var url = (wsPort === '') ? wsUrl : wsUrl + ':' + wsPort;
console.log('Starting socket', url);
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);
};
const url = (wsPort === '') ? wsUrl : `${wsUrl }:${ wsPort}`;
console.log('Starting socket', url);
const 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.send = function(msg) {
this.send = function (msg) {
console.log('Sending', msg);
this.socket.send(msg);
};
this.handleData = function(d) {
model.trigger('message',d);
};
this.handleWebsocketOnOpen = function() {
'use strict';
this.retry = 0;
console.log('**** Websocket Connected ****');
this.clock = new Date();
};
this.handleWebsocketMessage = function(message) {
var command;
try {
command = JSON.parse(message.data);
}
catch (e) { /* Do nothing */
}
if (command) {
this.handleData.call(this,command);
}
};
this.handleWebsocketClose = function() {
console.error('WebSocket Connection Closed.');
var now = new Date();
var uptime = now.getTime() - this.clock.getTime();
console.log('Socket alive for', uptime / 1000);
var self = this;
console.log('Waiting ', 5000);
this.timer = setTimeout(function() {self.startWebSocket();},5000);
};
this.startWebSocket();
this.handleData = function (d) {
model.trigger('message', d);
};
this.handleWebsocketOnOpen = function () {
'use strict';
this.retry = 0;
console.log('**** Websocket Connected ****');
this.clock = new Date();
};
this.handleWebsocketMessage = function (message) {
let command;
try {
command = JSON.parse(message.data);
}
catch (e) { /* Do nothing */
}
if (command)
this.handleData.call(this, command);
};
this.handleWebsocketClose = function () {
console.error('WebSocket Connection Closed.');
const now = new Date();
// const uptime = now.getTime() - this.clock.getTime();
const uptime = 1;
console.log('Socket alive for', uptime / 1000);
const self = this;
console.log('Waiting ', 15000);
this.timer = setTimeout(function () {
self.startWebSocket();
}, 15000);
};
this.startWebSocket();
};

View File

@ -5,6 +5,8 @@ const trend = require('trend');
const logger = require('log4js').getLogger('btc');
let btcCache = {};
let balanceCache = {};
let eventEmitter;
let lastUpdated;
const history = new LimitedArray(288); // one days worth in 5 minute chunks
function getBitcoin () {
@ -55,11 +57,14 @@ function getBitcoin () {
logger.info('Got btc data. Storing it');
logger.debug('>> btc', a);
console.log(a.time.updatedISO);
btcCache = a;
history.push(a.bpi.USD.rate_float);
btcCache.history = history.get();
btcCache.trend = trend(btcCache.history, { 'avgPoints': 12 });
GLOBAL.lastcheck = new Date();
btcCache.lastcheck = GLOBAL.lastcheck.toISOString();
eventEmitter.emit('sendSocket', { 'id': 'btc', 'data': btcCache });
});
}
@ -97,6 +102,7 @@ function getBalance() {
balanceQuery(a => {
logger.info('Got balance data. Storing it');
balanceCache = a;
eventEmitter.emit('sendSocket', { 'id': 'balance', 'data': balanceCache });
});
}
@ -135,5 +141,11 @@ function updateBalance() {
};
setTimeout(balanceUpdateFn.bind(this), mod + 10);
}
exports.setEmitter = (newEmitter) => {
logger.debug('Setting events', newEmitter);
eventEmitter = newEmitter;
};
updateBitcoin();
updateBalance();

View File

@ -5,50 +5,45 @@
* Time: 15:33
*
*/
var url = require('url');
var logger = require('log4js').getLogger();
const url = require('url');
const logger = require('log4js').getLogger();
module.exports = function(events, wsServer) {
'use strict';
logger.debug('>> new WS', wsServer);
wsServer.on('connection', function connection(ws) {
var location = url.parse(ws.upgradeReq.url, true);
const location = url.parse(ws.upgradeReq.url, true);
logger.info('Creating event for this connection');
logger.info((new Date()) + ' Connection accepted.');
logger.info(`${new Date() } Connection accepted.`);
var sendSocketHandler = (obj) => {
logger.debug('sendSocketHandler', obj);
try {
ws.send(JSON.stringify(obj));
}
catch (err) {
logger.error(err);
logger.warn('Offending object: ', obj);
}
};
const sendSocketHandler = (obj) => {
logger.debug('sendSocketHandler', obj);
try {
ws.send(JSON.stringify(obj));
}
catch (err) {
logger.error(err);
logger.warn('Offending object: ', obj);
}
};
events.on('sendSocket', sendSocketHandler);
ws.on('message', function(message) {
console.log('received:', message);
console.log('received:', message);
if (message === 'update') {
if (message === 'update')
events.emit('update');
}
});
ws.on('close', function(reasonCode, description) {
logger.info((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
events.removeListener('sendSocket', sendSocketHandler);
});
ws.on('close', function(reasonCode, description) {
logger.info(`${new Date() } Peer ${ connection.remoteAddress } disconnected.`);
events.removeListener('sendSocket', sendSocketHandler);
});
});
return module;
};

View File

@ -31,6 +31,8 @@
<script src="libs/moment.js"></script>
<script src="libs/underscore.js"></script>
<script src="libs/backbone.js"></script>
<script src="js/websocket.js"></script>
<script src="js/slackSocket.js"></script>
<script src="js/modules/events.js"></script>
<script src="js/modules/bitcoin.js"></script>
<script src="js/modules/fx.js"></script>
@ -44,17 +46,27 @@
navigator.geolocation.getCurrentPosition((show_weather) => {
w.weather = new WeatherSlim({model: new WeatherModel({geo:show_weather})});
});
w.contractEnds = new EventView({model:new EventModel({event:new Date(2017, 8, 29), label: 'Contract Ends:'})});
w.bitcoin = new Bitcoin({model: new BitcoinModel()});
w.fx = new FxView({model: new FxModel()});
w.dbqglqView = new TrainView({model: new TrainModel({from: 'dbe', to: 'glq'})});
w.glqdbeView = new TrainView({model: new TrainModel({from: 'glq', to: 'dbe'})});
w.glqhymView = new TrainView({model: new TrainModel({from: 'glq', to: 'hym'})});
w.hymglqView = new TrainView({model: new TrainModel({from: 'hym', to: 'glq'})});
console.log(PasswordView);
const webSocketModel = new SOCKETMANAGER();
const btcModel = new BitcoinModel();
webSocketModel.setBTC(btcModel);
w.contractEnds = new EventView({model:new EventModel({event:new Date(2017, 8, 29), label: 'Contract Ends:'})});
/*w.bitcoin = new Bitcoin({model: new BitcoinModel()});*/
w.bitcoin = new Bitcoin({model: btcModel});
w.fx = new FxView({model: new FxModel()});
// w.dbqglqView = new TrainView({model: new TrainModel({from: 'dbe', to: 'glq'})});
//w.glqdbeView = new TrainView({model: new TrainModel({from: 'glq', to: 'dbe'})});
//w.glqhymView = new TrainView({model: new TrainModel({from: 'glq', to: 'hym'})});
//w.hymglqView = new TrainView({model: new TrainModel({from: 'hym', to: 'glq'})});
// console.log(PasswordView);
w.passwords = new PasswordView();
webSocketModel.turnOn();
})(window);
</script>