/* 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 calendarData; var extendTimer; var lightsList = { off: ['frontLightOff', 'backLightOff'], on: ['frontLightOn', 'backLightOn'], aux: ['auxFront','auxBack'] }; 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/';*/ /*wsUrl = 'ws://13.80.9.55:8080'; path = 'http://13.80.9.55/';*/ wsUrl = 'ws://smartofficehost.cloudapp.net:8080'; path = 'http://smartofficehost.cloudapp.net/'; } 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 actualEnd; var now; calendarData = d; console.log('+ UpdateCalendar'); if (d.current !== null && Object.has(d.current, 'dtstart') && !Object.has(d.current,'done')) { var calString = [ '
', d.current.summary, '
' ].join(''); $('#caltext').html(calString); console.log('SlideDown'); $('#calendar:hidden').slideDown(); } else { console.log('SlideUp'); $('#calendar:visible').slideUp(); } // if (Object.has(calendarData.current, 'actualEnd')) { now = new Date(); actualEnd = new Date(calendarData.current.actualEnd); var timerDistance = actualEnd.rewind({ minutes: 5 }).getTime() - now.getTime(); if ((timerDistance > 5000) && (timerDistance < 300000)) { extendTimer = setTimeout(function() {$('#extender:hidden').slideDown();},timerDistance); } else if (timerDistance <= 5000) { $('#extender:hidden').slideDown(); } else if (timerDistance > 300000) { $('#extender:visible').slideUp(); } } else { clearTimeout(extendTimer); extendTimer = 0; $('#extender:visible').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 lightCommand(id) { console.log('lightCommand',path + 'api/v1/lighting/cmd'); $.post(path + 'api/v1/lighting/cmd', {id: id}, function() {}); } 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 extendMeetingBy(extendBy) { console.log('+ extendMeetingBy', extendBy); var payload = {extendBy: extendBy}; if (Object.has(calendarData.current, 'actualEnd')) { payload.uid = calendarData.current.uid; } $.post(path + 'api/v1/extend', payload, function() {}); console.log('+ extendMeetingBy', extendBy); } 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'); }); $('#extend05').on('click', function() { extendMeetingBy(5); }); $('#extend10').on('click', function() { extendMeetingBy(10); }); $('#extend15').on('click', function() { extendMeetingBy(15); }); $('#extend30').on('click', function() { extendMeetingBy(30); }); $('#frontUp').on('click', function(event) { var target = $(event.target); lightCommand('9'); delayButton(target); }); $('#frontDown').on('click', function(event) { var target = $(event.target); lightCommand('1'); delayButton(target); }); $('#backUp').on('click', function(event) { var target = $(event.target); lightCommand('8'); delayButton(target); }); $('#backDown').on('click', function(event) { var target = $(event.target); lightCommand('2'); delayButton(target); }); } function delayButton($button) { $button.attr('disabled', true);//.removeAttr("disabled"); setTimeout(function() { $button.prop('disabled', false); },3000); } 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) { $('#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) { if (Notification.permission !== 'granted') { Notification.requestPermission(); } else { var notification = new Notification('SmartOffice Console', { icon: '/fav/favicon-96x96.png', body: d.msg }); notification.onclick = function() { 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() { attachClicks(); clock(); weatherClock(); soWebSocket = new SOWEBSOCKET(this); // Setup iOS notifications if (window.cordova && !(window.cordova instanceof HTMLElement)) { if (device.platform === 'iOS' || device.platform === 'ios') { setupPushNotifications(); } } }; 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); } else { } */ ;(function() { if (window.cordova && !(window.cordova instanceof HTMLElement)) { document.addEventListener('deviceready', onDeviceReady, false); } else { onDeviceReady(); Notification.requestPermission(); } })();