Merge branch 'master' of linz:/srv/git/tricorder
[tricorder.git] / js / tricorder.js
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3  * You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 var gStardate, gSDBase;
6 var gSounds = {};
7
8 navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
9
10 window.onload = function() {
11   setTimeout(updateStardate, 0);
12   gSounds.scan = new Audio("sound/scan.opus");
13   gSounds.scan.loop = true;
14   gSounds.launch = new Audio("sound/launch.opus");
15   gSounds.shutdown = new Audio("sound/shutdown.opus");
16   gSounds.keyaction = new Audio("sound/key-action.opus");
17   gSounds.keypress = new Audio("sound/key-press.opus");
18
19   document.getElementById("fullScreenButton").addEventListener("click",
20       function(aEvent) { toggleFullscreen(); }, false);
21
22   var navItems = document.getElementById("navlist").children;
23   for (var i = 0; i <= navItems.length - 1; i++) {
24     navItems[i].addEventListener("click",
25         function(aEvent) {
26           switchModule(aEvent.target.id.replace("nav", ""));
27         }, false);
28   }
29
30   gSounds.launch.play();
31   window.addEventListener("beforeunload", function( event ) {
32     gSounds.shutdown.play();
33   }, false);
34 }
35
36 window.onresize = function() {
37   if (document.getElementById("sectSound").classList.contains("active")) {
38     gModSound.resize();
39   }
40 }
41
42 function updateStardate() {
43   // Stardate rules foggy at best. See http://en.wikipedia.org/wiki/Stardate
44   // and the Memory Alpha article linked there for more details.
45   // We roughly lean on TNG scale by splitting an Earth year into exactly 1000
46   // units, but we put the 0 point at the TV premiere of The Original Series.
47   if (!gStardate)
48     gStardate = document.getElementById("stardate");
49
50   var curDate = new Date();
51
52   // Star Trek famously premiered on Thursday, September 8, 1966, at 8:30 p.m.
53   // See http://www.startrek.com/article/what-if-the-original-star-trek-had-debuted-on-friday-nights
54   if (!gSDBase)
55     gSDBase = new Date("September 8, 1966 20:30:00 EST");
56
57   var sdateval = (curDate - gSDBase) / (86400 * 365.2425);
58   gStardate.textContent = sdateval.toFixed(1);
59
60   setTimeout(updateStardate, 5*60*1000);
61 }
62
63 function toggleFullscreen() {
64   gSounds.keyaction.play();
65   if ((document.fullScreenElement && document.fullScreenElement !== null) ||
66       (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
67       (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
68     if (document.cancelFullScreen) {
69       document.cancelFullScreen();
70     } else if (document.mozCancelFullScreen) {
71       document.mozCancelFullScreen();
72     } else if (document.webkitCancelFullScreen) {
73       document.webkitCancelFullScreen();
74     }
75   }
76   else {
77     var elem = document.getElementById("body");
78     if (elem.requestFullScreen) {
79       elem.requestFullScreen();
80     } else if (elem.mozRequestFullScreen) {
81       elem.mozRequestFullScreen();
82     } else if (elem.webkitRequestFullScreen) {
83       elem.webkitRequestFullScreen();
84     }
85   }
86 }
87
88 function switchModule(aModname) {
89   gSounds.keyaction.play();
90   var sections = document.getElementsByTagName('section');
91   for (var i = 0; i <= sections.length - 1; i++) {
92     if (sections[i].classList.contains("active")) {
93       window["gMod" + sections[i].id.replace("sect", "")].deactivate();
94       sections[i].classList.remove("active");
95     }
96   }
97   var navs = document.getElementById('navlist').children;
98   for (var i = 0; i <= navs.length - 1; i++) {
99     navs[i].classList.remove("active");
100   }
101
102   var navItem = document.getElementById("nav" + aModname);
103   navItem.classList.add("active");
104   document.getElementById("sect" + aModname).classList.add("active");
105   document.getElementById("mainHeader").textContent =
106       (aModname == "Other") ? "Web Tricorder" : navItem.textContent;
107
108   window["gMod" + aModname].activate();
109 }
110
111 var gModPos = {
112   activate: function() {
113     if (navigator.geolocation) {
114       gSounds.scan.play();
115       document.getElementById("posunavail").style.display = "none";
116       document.getElementById("posavail").style.display = "block";
117       this.watchID = navigator.geolocation.watchPosition(
118         function(position) {
119            document.getElementById("posLat").textContent =
120                position.coords.latitude + "°";
121            document.getElementById("posLong").textContent =
122                position.coords.longitude + "°";
123            document.getElementById("posAlt").textContent =
124                position.coords.altitude.toFixed(0) + " m";
125            document.getElementById("posAcc").textContent =
126                position.coords.accuracy.toFixed(0) + " m";
127            document.getElementById("posAltAcc").textContent =
128                position.coords.altitudeAccuracy.toFixed(0) + " m";
129            document.getElementById("posHead").textContent =
130                position.coords.heading ? position.coords.heading.toFixed(0) + "°" : "---";
131            document.getElementById("posSpd").textContent =
132                position.coords.speed ? position.coords.speed.toFixed(1) + " m/s" : "---";
133            var locTime = new Date(position.timestamp);
134            document.getElementById("posTime").textContent = locTime.toISOString();
135         },
136         function(error) {
137           // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
138           if (error.message) {
139             document.getElementById("posLat").textContent = error.message;
140             document.getElementById("posLong").textContent = "...";
141             document.getElementById("posAlt").textContent = "...";
142             document.getElementById("posAcc").textContent = "...";
143             document.getElementById("posAltAcc").textContent = "...";
144             document.getElementById("posHead").textContent = "...";
145             document.getElementById("posSpd").textContent = "...";
146             document.getElementById("posTime").textContent = "...";
147             setTimeout(function() { gModPos.deactivate(); }, 5000);
148           }
149           else {
150             document.getElementById("posunavail").style.display = "block";
151             document.getElementById("posavail").style.display = "none";
152           }
153           gSounds.scan.pause();
154         },
155         {enableHighAccuracy: true, maximumAge: 10000, timeout: 60000}
156       );
157     }
158     else {
159       document.getElementById("posunavail").style.display = "block";
160       document.getElementById("posavail").style.display = "none";
161     }
162   },
163   deactivate: function() {
164     gSounds.scan.pause();
165     if (this.watchID) {
166       navigator.geolocation.clearWatch(this.watchID);
167     }
168     document.getElementById("posunavail").style.display = "block";
169     document.getElementById("posavail").style.display = "none";
170     document.getElementById("posLat").textContent = "...";
171     document.getElementById("posLong").textContent = "...";
172     document.getElementById("posAlt").textContent = "...";
173     document.getElementById("posAcc").textContent = "...";
174     document.getElementById("posAltAcc").textContent = "...";
175     document.getElementById("posHead").textContent = "...";
176     document.getElementById("posSpd").textContent = "...";
177     document.getElementById("posTime").textContent = "...";
178   },
179   watchID: null,
180 }
181
182 var gModGrav = {
183   activate: function() {
184     gSounds.scan.play();
185     document.getElementById("gravunavail").style.display = "none";
186     document.getElementById("gravavail").style.display = "block";
187     window.addEventListener("deviceorientation", this.orientEvent, true);
188     window.addEventListener("devicemotion", this.motionEvent, true);
189     setTimeout(function() {
190       if ((document.getElementById("gravAlpha").textContent == "...") &&
191           (document.getElementById("gravX").textContent == "...")) {
192         gModGrav.deactivate();
193       }
194     }, 3000);
195   },
196   deactivate: function() {
197     gSounds.scan.pause();
198     window.removeEventListener("deviceorientation", this.orientEvent, true);
199     window.removeEventListener("devicemotion", this.motionEvent, true);
200     document.getElementById("gravunavail").style.display = "block";
201     document.getElementById("gravavail").style.display = "none";
202     //document.getElementById("gravAbs").textContent = "...";
203     document.getElementById("gravAlpha").textContent = "...";
204     document.getElementById("gravBeta").textContent = "...";
205     document.getElementById("gravGamma").textContent = "...";
206     document.getElementById("gravTotal").textContent = "...";
207     document.getElementById("gravX").textContent = "...";
208     document.getElementById("gravY").textContent = "...";
209     document.getElementById("gravZ").textContent = "...";
210     //document.getElementById("gravRot").textContent = "...";
211   },
212   orientEvent: function(orientData) {
213     //document.getElementById("gravAbs").textContent = orientData.absolute;
214     document.getElementById("gravAlpha").textContent = orientData.alpha.toFixed(1) + "°";
215     document.getElementById("gravBeta").textContent = orientData.beta.toFixed(1) + "°";
216     document.getElementById("gravGamma").textContent = orientData.gamma.toFixed(1) + "°";
217   },
218   motionEvent: function(event) {
219     var gravTotal = 
220         Math.sqrt(Math.pow(event.accelerationIncludingGravity.x, 2) +
221                   Math.pow(event.accelerationIncludingGravity.y, 2) +
222                   Math.pow(event.accelerationIncludingGravity.z, 2));
223     document.getElementById("gravTotal").textContent = gravTotal.toFixed(2) + " m/s²";
224     document.getElementById("gravX").textContent = event.accelerationIncludingGravity.x.toFixed(2) + " m/s²";
225     document.getElementById("gravY").textContent = event.accelerationIncludingGravity.y.toFixed(2) + " m/s²";
226     document.getElementById("gravZ").textContent = event.accelerationIncludingGravity.z.toFixed(2) + " m/s²";
227     //document.getElementById("gravRot").textContent = event.rotationRate;
228   },
229 }
230
231 var gModSound = {
232   activate: function() {
233     //gSounds.scan.play();
234     if (navigator.getUserMedia && (window.AudioContext || window.webkitAudioContext)) {
235       document.getElementById("soundunavail").style.display = "none";
236       document.getElementById("soundavail").style.display = "block";
237       navigator.getUserMedia({ audio: true },
238          function(aLocalMediaStream) {
239            gModSound.mAudio.stream = aLocalMediaStream;
240            gModSound.mAudio.context = new (window.AudioContext || window.webkitAudioContext)();
241            gModSound.mAudio.input = gModSound.mAudio.context.createMediaStreamSource(gModSound.mAudio.stream);
242            // Could put a filter in between like in http://webaudioapi.com/samples/microphone/
243            gModSound.mDisplay.canvas = document.getElementById("soundcanvas");
244            gModSound.mDisplay.context = gModSound.mDisplay.canvas.getContext("2d");
245            gModSound.rebuildCanvas();
246          },
247          function(err) {
248            document.getElementById("soundunavail").style.display = "block";
249            document.getElementById("soundavail").style.display = "none";
250            console.log(err);
251          }
252       );
253     }
254     else {
255       document.getElementById("soundunavail").style.display = "block";
256       document.getElementById("soundavail").style.display = "none";
257     }
258   },
259   rebuildCanvas: function() {
260     if (gModSound.mDisplay.AFRequestID) {
261       window.cancelAnimationFrame(gModSound.mDisplay.AFRequestID);
262       gModSound.mDisplay.AFRequestID = 0;
263     }
264     gModSound.mDisplay.canvas.height = document.getElementById("soundavail").clientHeight - 4;
265     gModSound.mDisplay.canvas.width = document.getElementById("soundavail").clientWidth;
266     gModSound.mAudio.frequencySlices = (gModSound.mDisplay.canvas.width > 512) ?
267                                       512 :
268                                       Math.pow(2, Math.floor(Math.log(gModSound.mDisplay.canvas.width) / Math.LN2));
269     //console.log("slices: " + gModSound.mAudio.frequencySlices);
270     gModSound.mAudio.analyzer = gModSound.mAudio.context.createAnalyser();
271     // Make the FFT four times as large as needed as the upper three quarters turn out to be useless.
272     gModSound.mAudio.analyzer.fftSize = gModSound.mAudio.frequencySlices * 4;
273     //console.log("FFT: " + gModSound.mAudio.analyzer.fftSize);
274     gModSound.mAudio.input.connect(gModSound.mAudio.analyzer);
275     gModSound.mDisplay.context.setTransform(1, 0, 0, -(gModSound.mDisplay.canvas.height/256), 0, gModSound.mDisplay.canvas.height);
276     gModSound.mDisplay.active = true;
277     gModSound.mDisplay.AFRequestID = window.requestAnimationFrame(gModSound.paintAnalyzerFrame);
278   },
279   mAudio: {
280     frequencySlices: 32, // Must be a multiple of 2 (see AnalyserNode.fftSize)
281   },
282   mDisplay: {
283     active: false,
284   },
285   paintAnalyzerFrame: function(aTimestamp) {
286     var data = new Uint8Array(gModSound.mAudio.frequencySlices);
287     gModSound.mAudio.analyzer.getByteFrequencyData(data);
288     gModSound.mDisplay.context.clearRect(0, 0, gModSound.mDisplay.canvas.width, gModSound.mDisplay.canvas.height);
289     // Out of experience, only the first half of the slices are actually useful.
290     var wid = gModSound.mDisplay.canvas.width / gModSound.mAudio.frequencySlices;
291     var fill = "#9C9CFF";
292     for (var i = 0; i < gModSound.mAudio.frequencySlices; ++i) {
293       var newFill = (data[i] > 200) ? "#FF0000" : ((data[i] > 100) ? "#FFCF00" : "#9C9CFF");
294       if (fill != newFill) { gModSound.mDisplay.context.fillStyle = newFill; fill = newFill; }
295       gModSound.mDisplay.context.fillRect(i*wid, 0, wid, data[i]);
296     }
297     if (gModSound.mDisplay.active)
298       gModSound.mDisplay.AFRequestID = window.requestAnimationFrame(gModSound.paintAnalyzerFrame);
299   },
300   resize: function() {
301     gModSound.rebuildCanvas();
302   },
303   deactivate: function() {
304     if (gModSound.mDisplay.active) {
305       gModSound.mAudio.stream.stop();
306       gModSound.mDisplay.active = false;
307     }
308     gSounds.scan.pause();
309   },
310 }
311
312 var gModEnv = {
313   activate: function() {
314     gSounds.scan.play();
315     document.getElementById("envunavail").style.display = "none";
316     document.getElementById("envavail").style.display = "block";
317     window.addEventListener("devicelight", this.lightEvent, true);
318     window.addEventListener("deviceproximity", this.proxEvent, true);
319     setTimeout(function() {
320       if ((document.getElementById("envLight").textContent == "...") &&
321           (document.getElementById("envDistance").textContent == "...")) {
322         gModEnv.deactivate();
323       }
324     }, 5000);
325     try {
326       for (var cameraId of window.navigator.mozCameras.getListOfCameras()) {
327         window.navigator.mozCameras.getCamera({camera: cameraId}, function(aCamera) {
328             if (aCamera.capabilities.flashModes.indexOf('torch') !== -1) {
329               this.flashCamera = aCamera;
330             }
331         });
332       }
333       if (this.flashCamera) {
334         document.getElementById("envFlashOn").onclick = gModEnv.switchFlashlight(true);
335         document.getElementById("envFlashOff").onclick = gModEnv.switchFlashlight(false);
336         document.getElementById("envFlashUnavail").style.display = "none";
337         document.getElementById("envFlashAvail").style.display = "block";
338       }
339     } catch (e) {
340       // camera api not supported
341       document.getElementById("envFlashUnavail").style.display = "block";
342       document.getElementById("envFlashAvail").style.display = "none";
343     }
344   },
345   deactivate: function() {
346     gSounds.scan.pause();
347     window.removeEventListener("devicelight", this.lightEvent, true);
348     window.removeEventListener("deviceproximity", this.proxEvent, true);
349     document.getElementById("envunavail").style.display = "block";
350     document.getElementById("envavail").style.display = "none";
351     document.getElementById("envLight").textContent = "...";
352     document.getElementById("envDistance").textContent = "...";
353   },
354   lightEvent: function(lightData) {
355     // See http://www.w3.org/TR/ambient-light/
356     document.getElementById("envLight").textContent = lightData.value + " lux";
357   },
358   proxEvent: function(proxData) {
359     // See http://www.w3.org/TR/2012/WD-proximity-20120712/
360     if (proxData.value >= proxData.max) {
361       document.getElementById("envDistance").textContent = "(maximum, >= " + proxData.value + " cm)";
362     }
363     else if (proxData.value <= proxData.min) {
364       document.getElementById("envDistance").textContent = "(minimum, <= " + proxData.value + " cm)";
365     }
366     else {
367       document.getElementById("envDistance").textContent = proxData.value + " cm";
368     }
369   },
370   flashCamera: null,
371   switchFlashlight: function(aEnabled) {
372     if (this.flashCamera) {
373       this.flashCamera.flashMode = aEnabled ? 'torch' : 'off';
374     }
375   }
376 }
377
378 var gModDev = {
379   activate: function() {
380     gSounds.scan.play();
381     this.batteryTimer =
382         setInterval(function () { gModDev.updateBattery(); }, 100);
383   },
384   deactivate: function() {
385     clearTimeout(this.batteryTimer);
386     gSounds.scan.pause();
387   },
388   updateBattery: function() {
389     document.getElementById("devBattLevel").textContent =
390         (navigator.battery.level * 100).toFixed(1) + "%";
391     if (navigator.battery.charging) {
392       if (navigator.battery.chargingTime == 0 ||
393           navigator.battery.chargingTime == Infinity) {
394         document.getElementById("devBattStatus").textContent = "charging";
395       }
396       else {
397         document.getElementById("devBattStatus").textContent = 
398             "charging, " + navigator.battery.chargingTime + "s remaining";
399       }
400     }
401     else {
402       if (navigator.battery.dischargingTime == 0 ||
403           navigator.battery.dischargingTime == Infinity) {
404         document.getElementById("devBattStatus").textContent = "discharging";
405       }
406       else {
407         document.getElementById("devBattStatus").textContent = 
408             navigator.battery.dischargingTime + "s usage remaining";
409       }
410     }
411   },
412   batteryTimer: null,
413 }
414
415 var gModOther = {
416   activate: function() {
417     //gSounds.scan.play();
418   },
419   deactivate: function() {
420     gSounds.scan.pause();
421   },
422 }
423
424 var gModNull = {
425   activate: function() {
426     //gSounds.scan.play();
427   },
428   deactivate: function() {
429     gSounds.scan.pause();
430   },
431 }