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