/* SO App v2 */ var skycons = new Skycons({color: '#e5f7fd'}); var SOController = (function() { 'use strict'; var path; var wsUrl; var local = false; var bus = {}; var prevDate; var prevTime; var weatherTimer = 0; var weatherStore = null; var lastWeatherRequest = 0; var soWebSocket; var iosConfig = { badge: true, sound: true, alert: true, }; var lightsList = { off: ['frontLightOff', 'backLightOff'], on: ['frontLightOn', 'backLightOn'] }; console.log('Localmode',local); if (local) { console.log('Using local urls'); path = 'http://localhost:3000/'; wsUrl = 'ws://localhost:3001'; } else { console.log('Using remote urls'); 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 = [ '
', d.current.summary, '
' ].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('{24hr}{mm}'); var curDate = now.format('{yyyy}-{MM}-{dd}'); if (prevTime !== curTime) { $time.html(curTime); // UpdateCalendar(); prevTime = curTime; } if (prevDate !== curDate) { $date.html(now.format( '{Weekday}
{Month} {dd}
{yyyy}')); prevDate = curDate; } } function turnOnLights(id) { console.log('turnonlights',path + 'api/v1/lighting/on'); $.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) + '°c '); 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('notifyConfirm', r); }; var cordovaNotify = function(d) { console.log('+++ CORDOVA NOTIFY +++'); try { navigator.notification.beep(1); } catch (e) { console.log(e); } try { navigator.notification.confirm( d.msg, // Message notifyConfirm, // Callback to invoke with index of button pressed 'Smartoffice Console', // Title ['Extend','Ignore'] // ButtonLabels ); } catch (e) { console.log(e); } }; var setupPushNotifications = function() { console.log('Setting up iOS push notifications..'); var push = PushNotification.init({android: {},ios: iosConfig,windows: {}}); push.on('registration', function(d) { console.log('*PUSH* Registration: ', JSON.stringify(d)); $.post(path + 'api/v1/register/ios', d, function() {}); }); push.on('notification', function(d) { console.log('*PUSH* Notification: ', JSON.stringify(d)); }); push.on('error', function(e) { console.error('*PUSH* Push error:', e); }); }; // module.init = function() { console.log('-=# A #=-'); attachClicks(); console.log('-=# B #=-'); clock(); console.log('-=# C #=-'); weatherClock(); console.log('-=# D #=-'); soWebSocket = new SOWEBSOCKET(this); console.log('-=# E #=-'); // Setup iOS notifications console.log('device.platform', device.platform); console.log('-=# F #=-'); if (device.platform === 'iOS' || device.platform === 'ios') { console.log('-=# F.2 #=-'); setupPushNotifications(); } console.log('-=# G #=-'); }; module.updateCalendar = function(data) { updateCalendar(data); }; module.webSocketURL = function() { return wsUrl; }; module.notify = function(d) { if (window.cordova && !(window.cordova instanceof HTMLElement)) { if (device.platform === 'android' || device.platform === 'Android') { cordovaNotify(d); } } else { browserNotify(d); } }; return module; })(); function onDeviceReady() { SOController.init(); } if (window.cordova && !(window.cordova instanceof HTMLElement)) { document.addEventListener('deviceready', onDeviceReady, false); } /*;(function() { if (window.cordova && !(window.cordova instanceof HTMLElement)) { document.addEventListener('deviceready', onDeviceReady, false); } else { onDeviceReady(); Notification.requestPermission(); } })();*/