SODashServer/app/js/appv2.js

348 lines
8.4 KiB
JavaScript

/*
SO App v2
*/
var skycons = new Skycons({color: '#e5f7fd'});
var SOController = (function() {
'use strict';
var path;
var wsUrl;
var local = true;
var bus = {};
var prevDate;
var prevTime;
var weatherTimer = 0;
var weatherStore = null;
var lastWeatherRequest = 0;
var soWebSocket;
var lightsList = {
off: ['frontLightOff', 'backLightOff'], on: ['frontLightOn', 'backLightOn']
};
if (local) {
path = 'http://localhost:3000/';
wsUrl = 'ws://localhost:3001';
} else {
wsUrl = 'ws://ec2-52-50-147-81.eu-west-1.compute.amazonaws.com:8080';
path = 'http://ec2-52-50-147-81.eu-west-1.compute.amazonaws.com/';
}
MicroEvent.mixin(bus);
var iOS = ['iPad', 'iPhone', 'iPod'].indexOf(navigator.platform) >= 0;
if (iOS) {
$('#iosTaskbar').show();
path = 'http://localhost:3000/';
}
var module = {lights: lightsList};
var storage = {};
storage.supportsLocalStorage = function() {
try {
return !localStorage ? false : true;
}
catch (e) {
return false;
}
};
storage._localStorage = storage.supportsLocalStorage();
if (storage._localStorage) {
storage.LocalStorage = {
save: function(i, v) {
localStorage[i] = v;
}, load: function(i) {
return localStorage[i];
}
};
} else {
storage.LocalStorage = {
save: function(i, v) {
document.cookie = (i) + '=' + encodeURIComponent(v);
}, load: function(i) {
var s;
var p;
s = '; ' + document.cookie + ';';
p = s.indexOf('; ' + i + '=');
if (p < 0) {
return '';
}
p = p + i.length + 3;
var p2 = s.indexOf(';', p + 1);
return decodeURIComponent(s.substring(p, p2));
}
};
}
function updateCalendar(d) {
var $calendar = $('#calendar');
if (d.current !== null && d.current.hasOwnProperty('dtstart')) {
var calString = [
'<div class="mui--text-subhead">', d.current.summary,
'</div>'
].join('');
$('#caltext').html(calString);
$calendar.slideDown();
} else {
$calendar.slideUp();
}
}
function updateDateTime() {
var now = Date.create(new Date());
var $date = $('#date');
var $time = $('#time');
var curTime = now.format('<span class="hour">{24hr}</span>{mm}');
var curDate = now.format('{yyyy}-{MM}-{dd}');
if (prevTime !== curTime) {
$time.html(curTime);
// UpdateCalendar();
prevTime = curTime;
}
if (prevDate !== curDate) {
$date.html(now.format(
'<span class="wd-{do}">{Weekday}</span><br><span class="mo mo-{M}">{Month} {dd}</span><br>{yyyy}'));
prevDate = curDate;
}
}
function turnOnLights(id) {
console.log(id);
$.post(path + 'api/v1/lighting/on', {light: id}, function() {});
}
function turnOffLights(id) {
$.post(path + 'api/v1/lighting/off', {light: id}, function() {});
}
function turnOnHeating() {
$.post(path + 'api/v1/heating/on', {}, function() {});
}
function turnOffHeating() {
$.post(path + 'api/v1/heating/off', {}, function() {});
}
function turnOnProjector() {
$.post(path + 'api/v1/projector/on', {}, function() {});
}
function turnOffProjector() {
$.post(path + 'api/v1/projector/off', {}, function() {});
}
function attachClicks() {
$('#projectorOn').on('click', function() {
turnOnProjector();
});
$('#projectorOff').on('click', function() {
turnOffProjector();
});
$('#heatingOn').on('click', function() {
turnOnHeating();
});
$('#heatingOff').on('click', function() {
turnOffHeating();
});
$('#frontLightOn').on('click', function() {
// 1 for board lights
turnOnLights('o');
});
$('#middleLightOn').on('click', function() {
turnOnLights(2);
});
$('#backLightOn').on('click', function() {
// 3 for board lights
turnOnLights('n');
});
$('#frontLightOff').on('click', function() {
// A for board lights
turnOffLights('f');
});
$('#middleLightOff').on('click', function() {
turnOffLights('b');
});
$('#backLightOff').on('click', function() {
turnOffLights('g');
});
}
function clock() {
updateDateTime();
var now = new Date;
var mod = 60000 - (now.getTime() % 60000);
setTimeout(function() {clock();}, mod + 10);
}
var get_weather = function() {
navigator.geolocation.getCurrentPosition(show_weather,
function(e) {alert(e.code + ' / ' + e.message);});
};
bus.bind('displayWeather', function(data) {
console.log(data.currently);
$('#weatherText').html(parseInt(data.currently.temperature) + '&deg;c&nbsp;');
skycons.add('icon1', data.currently.icon);
});
var weatherClock = function() {
get_weather();
var now = new Date;
var mod = 1800000 - (now.getTime() % 1800000);
weatherTimer = setTimeout(function() {weatherClock();}, mod + 10);
};
var show_weather = function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
// Show cached first before doing a long request.
// forecast.io is a bit slow.
var doRefresh = false;
if (weatherStore === null) {
var w = storage.LocalStorage.load('weather');
if (typeof w !== 'undefined') {
w = JSON.parse(w);
weatherStore = w;
bus.trigger('displayWeather', w);
} else {
doRefresh = true;
}
} else {
doRefresh = true;
}
// Let's show a map or do something interesting!
if (doRefresh) {
var now = new Date();
if (now.getTime() - lastWeatherRequest < 10000) {
// Sometimes when the app loses focus, and then returns the weather requests queue up
// this ensures that we don't do multiple requests within a ten second window
return -1;
}
lastWeatherRequest = now.getTime();
$.ajax({
type: 'GET',
url: 'https://api.forecast.io/forecast/0657dc0d81c037cbc89ca88e383b6bbf/' + latitude.toString() + ',' + longitude.toString() + '?units=uk2',
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) {
storage.LocalStorage.save('weather', JSON.stringify(data));
weatherStore = data;
console.log('fresh..');
bus.trigger('displayWeather', data);
},
error: function(xhr, type) {
console.error('ajax error');
console.error(xhr);
console.error(type);
}
});
}
};
var browserNotify = function(d) {
console.log('BrowserNotify:', d);
if (Notification.permission !== 'granted')
Notification.requestPermission();
else {
var notification = new Notification('SmartOffice Console', {
icon: '/fav/favicon-96x96.png',
body: d.msg
});
notification.onclick = function() {
//window.open("http://stackoverflow.com/a/13328397/1269037");
console.log('click');
};
}
};
var notifyConfirm = function(r) {
console.log(r);
};
var cordovaNotify = function(d) {
navigator.notification.confirm(
d.msg, // message
notifyConfirm, // callback to invoke with index of button pressed
'Smartoffice Console', // title
['Extend','Ignore'] // buttonLabels
);
};
//
module.init = function() {
attachClicks();
clock();
weatherClock();
soWebSocket = new SOWEBSOCKET(this);
};
module.updateCalendar = function(data) {
updateCalendar(data);
};
module.webSocketURL = function() {
return wsUrl;
};
module.notify = function(d) {
if (window.cordova && !(window.cordova instanceof HTMLElement)) {
document.addEventListener('deviceready', onDeviceReady, false);
} else {
browserNotify(d);
}
};
return module;
})();
function onDeviceReady() {
SOController.init();
}
;(function() {
if (window.cordova && !(window.cordova instanceof HTMLElement)) {
document.addEventListener('deviceready', onDeviceReady, false);
} else {
onDeviceReady();
Notification.requestPermission();
}
})();