diff --git a/app/css/today.css b/app/css/today.css
new file mode 100644
index 0000000..e5a552e
--- /dev/null
+++ b/app/css/today.css
@@ -0,0 +1,50 @@
+.datebox {
+ border:1px solid silver;
+margin-top: 15px;
+ }
+
+.section {
+ background-color: #f0f0f0;
+ text-transform: uppercase;
+ border-bottom:1px solid silver;
+ padding:5px;
+ }
+
+.date, .location {
+ text-transform: uppercase;
+ padding:5px;
+ font-size: 90%;
+ color: #707070;
+ }
+
+.location {
+ border-bottom:1px solid silver;
+ }
+
+.timearea {
+ padding-left: 5px;
+ }
+.time, .temp {
+ padding-left: 5px;
+ font-size: 250%;
+ line-height: 100%;
+
+ }
+
+.weatherIcon {
+ padding-left: 5px;
+ font-size: 200%;
+ line-height: 100%;
+
+ }
+.temp {
+ padding:5px;
+ }
+.seconds {
+ font-size: 175%;
+ }
+
+.temp, .weatherDescription, .weatherIcon {
+ display:table-cell;
+ width:33%;
+ }
diff --git a/app/js/modules/clock.js b/app/js/modules/clock.js
new file mode 100644
index 0000000..ae76a01
--- /dev/null
+++ b/app/js/modules/clock.js
@@ -0,0 +1,52 @@
+/**
+ *
+ * User: Martin Donnelly
+ * Date: 2016-10-03
+ * Time: 14:20
+ *
+ */
+var ClockModel = Backbone.Model.extend({
+ initialize: function() {
+ this.set('now',new Date);
+ this.update();
+ },
+ update: function() {
+ var now = new Date;
+ var mod = 60000 - (now.getTime() % 60000);
+ this.set('now',now);
+
+ var clockFn = function() {
+ this.update();
+ };
+
+ setTimeout(clockFn.bind(this), mod + 10);
+ }
+});
+
+var Clock = Backbone.View.extend({
+ tagName: 'div',
+ initialize: function() {
+ _.bindAll(this, 'render');
+ this.model.bind('change', this.render);
+ this.$date = $('#date');
+ this.$time = $('#time');
+ this.render();
+ },
+ render: function() {
+ var now = this.model.get('now');
+ //var curTime = now.format('{24hr}{mm}');
+ var curTime = now.format('{24hr} {mm}');
+
+ var curDate = now.format('{yyyy}-{MM}-{dd}');
+ if (this.prevTime !== curTime) {
+ this.$time.html(curTime);
+ this.prevTime = curTime;
+ }
+
+ if (this.prevDate !== curDate) {
+ this.$date.html(now.format(
+ '{Weekday} {Month} {dd} {yyyy}'));
+ this.prevDate = curDate;
+ }
+ }
+});
diff --git a/app/js/modules/train.js b/app/js/modules/train.js
new file mode 100644
index 0000000..630b05c
--- /dev/null
+++ b/app/js/modules/train.js
@@ -0,0 +1,45 @@
+/**
+ *
+ * User: Martin Donnelly
+ * Date: 2016-10-03
+ * Time: 14:20
+ *
+ */
+
+var TrainModel = Backbone.Model.extend({});
+
+var Train = Backbone.View.extend({
+ tagName: 'div',
+ initialize: function() {
+ _.bindAll(this, 'render');
+ this.model.bind('change', this.render);
+ this.$traininfo = $('#traininfo');
+ this.$traintext = $('#traintext');
+ },
+ render: function() {
+ console.log('Train:Render');
+ var ws ='';
+ var data = this.model.get('data');
+ console.log(this.model);
+
+ if (data.length > 0)
+ {
+ for (var i = 0; i < data.length; i++)
+ {
+ ws = ws + '
';
+ ws = ws + '' + data[i].description + '
';
+ }
+
+ this.$traintext.empty().html(ws);
+ this.$traininfo.removeClass('mui--hide').addClass('mui--show');
+
+ } else {
+ this.$traininfo.removeClass('mui--show').addClass('mui--hide');
+ }
+
+
+
+ }
+
+});
+
diff --git a/app/js/modules/weather.js b/app/js/modules/weather.js
new file mode 100644
index 0000000..a541963
--- /dev/null
+++ b/app/js/modules/weather.js
@@ -0,0 +1,76 @@
+/**
+ *
+ * User: Martin Donnelly
+ * Date: 2016-10-03
+ * Time: 14:20
+ *
+ */
+
+var WeatherModel = Backbone.Model.extend({
+ initialize: function() {
+ this.set('url','https://api.darksky.net/forecast/9ad2a41d420f3cf4960571bb886f710c/' + this.get('lat').toString() + ',' + this.get('long').toString() + '?units=uk2&exclude=minutely,hourly,daily,alerts,flags');
+
+ console.log(this.get('url'));
+ // this.update();
+ },
+ update: function() {
+ this.getWeather();
+ var now = new Date;
+ var mod = 1800000 - (now.getTime() % 1800000);
+ var weatherTrigger = function() {
+ this.update();
+ };
+ },
+ getWeather: function() {
+ var self = this;
+ $.ajax({
+ type: 'GET',
+ url: self.get('url'),
+ data: '',
+ dataType: 'jsonp',
+ timeout: 10000,
+ context: $('body'),
+ contentType: ('application/json'),
+ headers: {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
+ 'Access-Control-Allow-Headers': 'Content-Type'
+ },
+ success: function(data) {
+ var stored = {
+ temperature: data.currently.temperature,
+ icon: data.currently.icon,
+ summary: data.currently.summary
+ };
+ self.set(stored);
+ },
+ error: function(xhr, type) {
+ console.error('ajax error');
+ console.error(xhr);
+ console.error(type);
+ }
+ });
+ }
+});
+
+var Weather = Backbone.View.extend({
+ tagName: 'div',
+ initialize: function() {
+ _.bindAll(this, 'render');
+ this.model.bind('change', this.render);
+ this.$weatherText = $('#weatherDescription');
+ this.$weatherTemp = $('#temp');
+ this.$weatherIcon = $('#weatherIcon');
+ },
+ render: function() {
+ console.log('Weather:Render');
+
+ var ws = '';
+
+ this.$weatherTemp.empty().html(parseInt(this.model.get('temperature')) + '°c ');
+ this.$weatherText.empty().html(this.model.get('summary'));
+
+ this.$weatherIcon.empty().html(ws);
+ }
+
+});
diff --git a/app/js/parts/websocket.js b/app/js/parts/websocket.js
new file mode 100644
index 0000000..22d10d9
--- /dev/null
+++ b/app/js/parts/websocket.js
@@ -0,0 +1,80 @@
+var WEBSOCKET = function(model) {
+
+ var wsUrl = ['localhost','mdotserver.mybluemix.net','52.211.111.57'];
+ var wsPort = 3011;
+
+ if ('https:' === document.location.protocol) {
+ wsUrl = 'wss://' + wsUrl[2] + '/';
+ wsPort = '';
+ } else {
+ //wsUrl = 'ws://localhost:3001';
+ wsUrl = 'ws://' + wsUrl[2] + '/';
+ wsPort = '';
+ }
+
+ this.socket = null;
+ this.timer = 0;
+ this.clock = null;
+
+ 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);
+ };
+
+ };
+
+
+ this.send = function(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();
+
+ };
diff --git a/app/js/todaySocket.js b/app/js/todaySocket.js
new file mode 100644
index 0000000..e20583b
--- /dev/null
+++ b/app/js/todaySocket.js
@@ -0,0 +1,74 @@
+/**
+ *
+ * User: Martin Donnelly
+ * Date: 2016-09-09
+ * Time: 11:38
+ *
+ */
+/* global Backbone, _, WEBSOCKET */
+/* jshint browser: true , devel: true*/
+
+'use strict';
+
+var SOCKETMANAGER = (function() {
+
+ var 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 === 'weather') {
+ console.log('Setting weather');
+ this.weather.set(item.data);
+ }
+
+ if (item.id === 'trains') {
+ console.log(item);
+ this.train.set('data',item.data);
+
+ }
+
+ }
+
+
+ }
+ , setWeather: function(obj) {
+ this.weather = obj;
+ },
+ setTrain: function(obj) {
+ this.train = obj;
+ },
+ getUpdate: function() {
+ this.webSocket.send('update');
+ }
+ });
+
+ return SocketManager;
+}());
+
+
diff --git a/app/js/todayv2.js b/app/js/todayv2.js
index 9ead95b..d09286e 100644
--- a/app/js/todayv2.js
+++ b/app/js/todayv2.js
@@ -7,6 +7,32 @@
*/
(function($) {
- var clock = new Clock({model: new ClockModel()});
+ var TodayDataModel = Backbone.Model.extend({
+ initialize: function() {
+ this.set('url', '/today/data');
+
+ console.log(this.get('url'));
+ //this.update();
+ }
+ });
+
+
+ var webSocketModel = new SOCKETMANAGER();
+ webSocketModel.turnOn();
+
+ var clock = new Clock({model: new ClockModel()});
+ var weatherModel = new WeatherModel({lat: 55.95, long: -4.5666667});
+ var weather = new Weather({model: weatherModel});
+
+ var trainModel = new TrainModel();
+ var train = new Train({model: trainModel});
+
+ webSocketModel.setWeather(weatherModel);
+ webSocketModel.setTrain(trainModel);
+
+ setTimeout(function(){
+ console.log('request update');
+ webSocketModel.getUpdate();
+ }, 500);
})(jQuery);
diff --git a/app/js/weatherclock.js b/app/js/weatherclock.js
index 816fd4b..ba7554b 100644
--- a/app/js/weatherclock.js
+++ b/app/js/weatherclock.js
@@ -16,7 +16,7 @@
var WeatherModel = Backbone.Model.extend({
initialize: function() {
- this.set('url','https://api.forecast.io/forecast/0657dc0d81c037cbc89ca88e383b6bbf/' + this.get('lat').toString() + ',' + this.get('long').toString() + '?units=uk2&exclude=minutely,hourly,daily,alerts,flags');
+ this.set('url','https://api.darksky.net/forecast/9ad2a41d420f3cf4960571bb886f710c/' + this.get('lat').toString() + ',' + this.get('long').toString() + '?units=uk2&exclude=minutely,hourly,daily,alerts,flags');
console.log(this.get('url'));
this.update();
@@ -49,7 +49,8 @@ var WeatherModel = Backbone.Model.extend({
success: function(data) {
var stored = {
temperature: data.currently.temperature,
- icon: data.currently.icon
+ icon: data.currently.icon,
+ summary: data.currently.summary
};
self.set('data',stored);
},
@@ -113,14 +114,23 @@ var Weather = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
- this.$weatherText = $('#weatherText');
+ this.$weatherText = $('#weatherDescription');
+ this.$weatherTemp = $('#temp');
+ this.$weatherIcon = $('#weatherIcon');
},
render: function() {
console.log('Weather:Render');
var data = this.model.get('data');
- this.$weatherText.html(parseInt(data.temperature) + '°c ');
- skycons.remove('icon1');
- skycons.add('icon1', data.icon);
+ var ws = '';
+
+ this.$weatherTemp.empty().html(parseInt(data.temperature) + '°c ');
+ this.$weatherText.empty().html(data.summary);
+
+ this.$weatherIcon.empty().html(ws);
+
+
+
+ console.log(data);
}
});
diff --git a/app/js/websocket.js b/app/js/websocket.js
new file mode 100644
index 0000000..af9c6fb
--- /dev/null
+++ b/app/js/websocket.js
@@ -0,0 +1,81 @@
+var WEBSOCKET = function(model) {
+
+ var wsUrl = ['localhost','mdotserver.mybluemix.net','52.211.111.57'];
+ var wsPort = 9000;
+
+ if ('https:' === document.location.protocol) {
+ wsUrl = 'wss://' + wsUrl[0] + '';
+ //wsPort = '';
+ } else {
+ //wsUrl = 'ws://localhost:3001';
+ wsUrl = 'ws://' + wsUrl[0] + '';
+ //wsPort = '';
+ }
+
+ this.socket = null;
+ this.timer = 0;
+ this.clock = null;
+
+ 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);
+ };
+
+ };
+
+ 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();
+
+ };
diff --git a/lib/today.js b/lib/today.js
index b294a6c..cea5772 100644
--- a/lib/today.js
+++ b/lib/today.js
@@ -1,7 +1,8 @@
/**
* Created by marti on 30/01/2016.
*/
-var http = require('http'), request = require('request'), cheerio = require('cheerio'), util = require('util'), cron = require('node-cron');
+var http = require('http'), request = require('request'), cheerio = require(
+ 'cheerio'), util = require('util'), cron = require('node-cron');
var dateFormat = require('dateformat');
var jsonfile = require('jsonfile'), fs = require('fs');
var nano = require('nano')('http://martind2000:1V3D4m526i@localhost:5984');
@@ -20,30 +21,54 @@ var dbCouch = nano.use(db_name);
require('sugar-date');
+String.prototype.hashCode = function() {
+
+ if (Array.prototype.reduce) {
+ return this.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);
+ } else {
+
+ var hash = 0, i, chr, len;
+ if (this.length == 0) return hash;
+ for (i = 0, len = this.length; i < len; i++) {
+ chr = this.charCodeAt(i);
+ hash = ((hash << 5) - hash) + chr;
+ hash |= 0; // Convert to 32bit integer
+ }
+ return hash;
+ }
+};
+
var todayCache = {
last: 0, data: {
- trains: {last: 0, data: []}, weather: {}, history: [], today: '', tv: {entries: []}, cal: {today: [], tomorrow: [], week: []}, swedish: {}, fitbit: {}, ftse:{}
+ trains: {last: 0, data: []},
+ weather: {},
+ history: [],
+ today: '',
+ tv: {entries: []},
+ cal: {today: [], tomorrow: [], week: []},
+ swedish: {},
+ fitbit: {},
+ ftse: {}
}, expire: ((60 * 1000) * 60)
};
var file = __dirname + '/' + 'newdata.json';
var htmlfile = __dirname + '/' + 'today.html';
-
+var eventEmitter;
function runable() {
- try{
+ try {
var now = new Date().getTime();
-
- console.log('last updated',((now - todayCache.last) / 60000));
+ console.log('last updated', ((now - todayCache.last) / 60000));
if (now - todayCache.last < 3600000) {
return false;
- } else {
+ }
+ else {
todayCache.last = now;
return true;
}
}
- catch(e)
- {
+ catch (e) {
todayCache.last = new Date().getTime();
return true;
@@ -51,14 +76,25 @@ function runable() {
}
+function broadcastWeather() {
+ const wData = {
+ temperature: todayCache.data.weather.data.currently.temperature,
+ icon: todayCache.data.weather.data.currently.icon,
+ summary: todayCache.data.weather.data.currently.summary
+ };
+
+ if (todayCache.data.weather.data.hasOwnProperty('alerts')) {
+ wData.alerts = todayCache.data.weather.data.alerts;
+ }
+ eventEmitter.emit('sendSocket', {id: 'weather', data: wData});
+}
function loadData() {
console.log('Loading old data');
try {
todayCache = jsonfile.readFileSync(file);
}
- catch(e)
- {
+ catch (e) {
console.error('Could not load previous data');
}
}
@@ -69,6 +105,7 @@ function saveData() {
}
function saveToDB(data) {
saveData();
+
logger.debug('Inserting into couch...');
// Logger.info(util.inspect(obj));
dbCouch.insert(data, function(err, body, header) {
@@ -84,15 +121,7 @@ function nth(d) {
// If (d > 3 && d < 21) {return 'th';} // Thanks kennebec
// if (d % 10 === 1) {return 'st';} else if (d % 10 === 2) {return 'nd';} else if (d % 10 === 3) {return 'rd';} else {return 'th';}
var n = d;
- return Math.floor(n / 10) === 1
- ? 'th'
- : (n % 10 === 1
- ? 'st'
- : (n % 10 === 2
- ? 'nd'
- : (n % 10 === 3
- ? 'rd'
- : 'th')));
+ return Math.floor(n / 10) === 1 ? 'th' : (n % 10 === 1 ? 'st' : (n % 10 === 2 ? 'nd' : (n % 10 === 3 ? 'rd' : 'th')));
}
function dayNumber() {
@@ -105,9 +134,32 @@ function dayNumber() {
function breakDay() {
var now = new Date();
- return {year: now.getFullYear(), month: parseInt(now.getMonth()) + 1, day: now.getDate()}
+ return {
+ year: now.getFullYear(),
+ month: parseInt(now.getMonth()) + 1,
+ day: now.getDate()
+ };
}
+function reduceTrains(d){
+
+ var titles = [], ta = [];
+ console.log('reducetrains',d);
+ for (var items in d) {
+ if (typeof d[items].title !== 'undefined') {
+ var hash = d[items].title.hashCode();
+ if (titles.indexOf(hash) === -1)
+ {
+ titles.push(hash);
+ ta.push(d[items]);
+ }
+
+ }
+
+ }
+ return ta;
+ }
+
/**
* @return {number}
*/
@@ -127,7 +179,8 @@ Array.prototype.indexOfOld = Array.prototype.indexOf;
Array.prototype.indexOf = function(e, fn) {
if (!fn) {
return this.indexOfOld(e);
- } else {
+ }
+ else {
if (typeof fn === 'string') {
var att = fn;
fn = function(e) {
@@ -139,7 +192,10 @@ Array.prototype.indexOf = function(e, fn) {
};
module.exports = {
- getClock: function(req, res) {
+ setEmitter: function(newEmitter) {
+ console.log('Setting events', newEmitter);
+ eventEmitter = newEmitter;
+ }, getClock: function(req, res) {
// Console.log(todayCache);
res.render('pages/clock', todayCache);
}, getToday: function(req, res) {
@@ -157,29 +213,24 @@ module.exports = {
todayCache.data.history = [];
s = '' + d.format('{Weekday} {Month} {dd}, {yyyy}') + ' - ';
- /*
- S = s + 'The ' + dayNumber() + nth(dayNumber) + ' day of ' + dateFormat(d,
- 'yyyy') + ', and there are ' + DayDiff(d) + ' days left until the end of the year.';
-*/
- s = s + 'The ' + daysSinceStart + nth(daysSinceStart) + ' day of ' + dateFormat(d,
+ s = s + 'The ' + daysSinceStart + nth(daysSinceStart) + ' day of ' + dateFormat(
+ d,
'yyyy') + ', and there are ' + daysRemaining + ' days left until the end of the year.';
-
-
logger.debug(s);
todayCache.data.today = s;
- }, refreshTrainAndWeather: function() {
- weather.newDoGetWeather()
- .then((d) => {
- todayCache.data.weather = d;
- }).catch((e) => {
- logger.error(e);
- });
+ },
+ refreshTrain: function(){
+ var self = this;
trains.updateTrains()
.then((d) => {
'use strict';
+
+ d = reduceTrains(d);
console.log('Trains: ', d);
+
+ eventEmitter.emit('sendSocket', {id: 'trains', data: d});
todayCache.data.trains.data = d;
todayCache.data.trains.last = new Date();
})
@@ -187,9 +238,50 @@ module.exports = {
'use strict';
console.error(e);
});
+
+
+ },
+ refreshWeather: function(){
+ weather.newDoGetWeather()
+ .then((d) => {
+ todayCache.data.weather = d;
+ console.log('Updating weather');
+ broadcastWeather();
+ }).catch((e) => {
+ logger.error(e);
+ });
+
+ },
+
+ refreshTrainAndWeather: function() {
+ this.refreshTrain();
+ this.refreshWeather();
+/*
+ var self = this;
+ weather.newDoGetWeather()
+ .then((d) => {
+ todayCache.data.weather = d;
+ console.log('Updating weather');
+ broadcastWeather();
+ }).catch((e) => {
+ logger.error(e);
+ });
+ trains.updateTrains()
+ .then((d) => {
+ 'use strict';
+ console.log('Trains: ', d);
+ eventEmitter.emit('sendSocket', {id: 'trains', data: d});
+ todayCache.data.trains.data = d;
+ todayCache.data.trains.last = new Date();
+ })
+ .catch((e)=> {
+ 'use strict';
+ console.error(e);
+ });
+*/
}, preLoadToday: function() {
module.exports.getTodayDate();
- todayCache.data.cal={today: [], tomorrow:[], week:[]};
+ todayCache.data.cal = {today: [], tomorrow: [], week: []};
weather.newDoGetWeather()
.then((d)=> {
todayCache.data.weather = d;
@@ -219,7 +311,8 @@ module.exports = {
console.error(e);
});
- calHandler.getSimpleCalV3('http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc')
+ calHandler.getSimpleCalV3(
+ 'http://www.pogdesign.co.uk/cat/download_ics/60cfdff469d0490545d33d7e3b5c0bcc')
.then((d) => {
'use strict';
todayCache.data.tv = d;
@@ -237,22 +330,20 @@ module.exports = {
logger.error(e);
});
-
- for (var t = 0; t < calHandler.calendars.length;t++) {
+ for (var t = 0; t < calHandler.calendars.length; t++) {
calHandler.getAdvancedCalV3(calHandler.calendars[t])
- .then((d) => {
- 'use strict';
- todayCache.data.cal.today = todayCache.data.cal.today.concat(d.today);
- todayCache.data.cal.tomorrow = todayCache.data.cal.tomorrow.concat(d.tomorrow);
- todayCache.data.cal.week = todayCache.data.cal.week.concat(d.week);
- })
- .catch((e) => {
- 'use strict';
- logger.error(e);
- });
+ .then((d) => {
+ 'use strict';
+ todayCache.data.cal.today = todayCache.data.cal.today.concat(d.today);
+ todayCache.data.cal.tomorrow = todayCache.data.cal.tomorrow.concat(d.tomorrow);
+ todayCache.data.cal.week = todayCache.data.cal.week.concat(d.week);
+ })
+ .catch((e) => {
+ 'use strict';
+ logger.error(e);
+ });
}
-
swedishWord.getSwedishWord()
.then((d) => {
'use strict';
@@ -274,6 +365,11 @@ module.exports = {
});
todayCache.date = breakDay();
+ }, broadcast : function() {
+ console.log('BROADCAST');
+ broadcastWeather();
+ eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data});
+
}
};
@@ -289,9 +385,19 @@ setTimeout(function() {
setTimeout(function() {
// mdMailer.sendEmailV1(todayCache, __dirname);
// saveToDB(todayCache);
- saveData();
+ saveData();
}, 45000);
+setInterval(function() {
+
+ // eventEmitter.emit('sendSocket',{id:'weather',data:todayCache.data.weather});
+ // broadcastWeather();
+ // eventEmitter.emit('sendSocket', {id: 'trains', data: todayCache.data.trains.data});
+
+
+}, (60000));
+
+
cron.schedule('45 6 * * *', function() {
if (runable()) {
module.exports.preLoadToday();
@@ -299,10 +405,23 @@ cron.schedule('45 6 * * *', function() {
return -1;
});
+
cron.schedule('0 */1 * * *', function() {
- module.exports.refreshTrainAndWeather();
+// module.exports.refreshTrainAndWeather();
+// this.refreshTrain();
+ module.exports.refreshWeather();
+
return -1;
});
+
+cron.schedule('*/15 * * * *', function() {
+ module.exports.refreshTrain();
+
+// module.exports.refreshWeather();
+
+ return -1;
+});
+
cron.schedule('0 7 * * *', function() {
mdMailer.sendEmailV1(todayCache, __dirname);
saveToDB(todayCache);
@@ -310,3 +429,4 @@ cron.schedule('0 7 * * *', function() {
return -1;
});
+
diff --git a/lib/today/weather.js b/lib/today/weather.js
index 77ba518..17ebd39 100644
--- a/lib/today/weather.js
+++ b/lib/today/weather.js
@@ -17,8 +17,7 @@ module.exports = {
logger.info('New Retrieving weather..');
var j = {};
var forecast = new Forecast(forecastOptions);
- forecast.get(55.8582846,
- -4.2593033,
+ forecast.get(55.95, -4.566667,
{units: 'uk2'},
function(err, res, data) {
if (err) {
diff --git a/lib/wshandlerv2.js b/lib/wshandlerv2.js
new file mode 100644
index 0000000..bb72ef2
--- /dev/null
+++ b/lib/wshandlerv2.js
@@ -0,0 +1,54 @@
+/**
+ *
+ * User: Martin Donnelly
+ * Date: 2016-09-07
+ * Time: 15:33
+ *
+ */
+
+var url = require('url');
+var logger = require('log4js').getLogger();
+
+
+module.exports = function(events, wsServer) {
+ 'use strict';
+
+ wsServer.on('connection', function connection(ws) {
+ var location = url.parse(ws.upgradeReq.url, true);
+
+ logger.info('Creating event for this connection');
+
+ 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);
+ }
+ };
+
+ events.on('sendSocket', sendSocketHandler);
+
+ ws.on('message', function(message) {
+ console.log('received:', message);
+
+ if (message === 'update') {
+ events.emit('update');
+ }
+ });
+
+ ws.on('close', function(reasonCode, description) {
+ logger.info((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
+ events.removeListener('sendSocket', sendSocketHandler);
+ });
+
+ });
+
+
+
+ return module;
+};
diff --git a/views/pages/today-old.ejs b/views/pages/today-old.ejs
new file mode 100644
index 0000000..7dc3e84
--- /dev/null
+++ b/views/pages/today-old.ejs
@@ -0,0 +1,23 @@
+<% include ../partials/head %>
+
+
+
+
+
+
+ <% include ../partials/weather %>
+ <% include ../partials/trains %>
+ <% include ../partials/calendar %>
+ <% include ../partials/history %>
+ <% include ../partials/tv %>
+
+
+
+<% include ../partials/footer %>
diff --git a/views/pages/today.ejs b/views/pages/today.ejs
index 7dc3e84..16dd653 100644
--- a/views/pages/today.ejs
+++ b/views/pages/today.ejs
@@ -1,23 +1,55 @@
-<% include ../partials/head %>
-
-
+ <% include ../partials/date_weather %>
+
+
+
+
Train Info
+
+
-
- <% include ../partials/weather %>
- <% include ../partials/trains %>
- <% include ../partials/calendar %>
- <% include ../partials/history %>
- <% include ../partials/tv %>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
<% include ../partials/footer %>
+
+
+
diff --git a/views/partials/date_weather.ejs b/views/partials/date_weather.ejs
new file mode 100644
index 0000000..dac8294
--- /dev/null
+++ b/views/partials/date_weather.ejs
@@ -0,0 +1,17 @@
+
+
+
+
local time
+
+
Weather
+
+
diff --git a/web-server.js b/web-server.js
index 6b36f08..f6a6340 100644
--- a/web-server.js
+++ b/web-server.js
@@ -1,5 +1,6 @@
-var express = require('express'), path = require('path'), http = require('http'),
- fx = require('./lib/fx'), btc = require('./lib/btc'), train = require('./lib/train'),
+var express = require('express'), path = require('path'), server = require('http').createServer();
+
+var fx = require('./lib/fx'), btc = require('./lib/btc'), train = require('./lib/train'),
password = require('./lib/password') , clean = require('./lib/clean'), events = require('./lib/events'),
today = require('./lib/today'),
morgan = require('morgan'), cookieParser = require('cookie-parser'),session = require('express-session')
@@ -7,6 +8,21 @@ var express = require('express'), path = require('path'), http = require('http')
var jsonfile = require('jsonfile');
+var Events = require('events');
+var busEmitter = new Events.EventEmitter();
+
+busEmitter.on('update', today.broadcast);
+
+var WebSocketServer = require('ws').Server;
+var wss = new WebSocketServer({ server: server });
+
+var SocketHandler = require('./lib/wshandlerv2');
+
+var webSocket = new SocketHandler(busEmitter, wss);
+
+
+today.setEmitter(busEmitter);
+
//train = require('lib/train')
/* ,submit = require('./routes/mongo/submit') */
;
@@ -22,8 +38,11 @@ var app = express();
GLOBAL.lastcheck = 0;
var btcCache = {}, fxCache = {} , trainCache = {};
+var port = process.env.PORT || 9000;
+
+
//app.configure(function () {
- app.set('port', process.env.PORT || 9000);
+ app.set('port', port);
app.set('view engine', 'ejs');
app.use(morgan('dev'));
app.use(cookieParser('your secret here'));
@@ -166,7 +185,15 @@ jsonfile.readFile('./fb-token.json', function(err, obj) {
/**
* create the server
*/
+/*
http.createServer(app).listen(app.get('port'), function () {
logger.warn("Express server listening on port " + app.get('port'));
//console.log("Express server listening on port " + app.get('port'));
});
+*/
+
+
+
+server.on('request', app);
+server.listen(port, function() { logger.info('New server listening on ' + server.address().port); });
+