089e93c1bac42549396faea100bfefb73e8daf2e
[matches/MCTX3420.git] / testing / MCTXWeb / public_html / static / mctx.gui.js
1 /**
2  * MCTX3420 2013 GUI stuff.
3  */
4
5 mctx = {};
6 mctx.location = location.protocol + "//" + location.host + "/";
7 mctx.api = mctx.location + "/api/";
8 mctx.expected_api_version = 0;
9 mctx.has_control = false;
10
11 mctx.return_codes = {
12   "1" : "Ok",
13   "-1" : "General error",
14   "-2" : "Unauthorized",
15   "-3" : "Not running",
16   "-4" : "Already exists"
17 };
18
19 mctx.sensors = {
20   0 : {name : "Strain gauge 1"},
21   1 : {name : "Strain gauge 2"},
22   2 : {name : "Strain gauge 3"},
23   3 : {name : "Strain gauge 4"},
24   4 : {name : "Pressure sensor 1"},
25   5 : {name : "Pressure sensor 2"},
26   6 : {name : "Pressure sensor 3"}
27 };
28
29 mctx.actuators = {
30   0 : {name : "Solenoid 1"},
31   1 : {name : "Solenoid 2"},
32   2 : {name : "Solenoid 3"},
33   3 : {name : "Pressure regulator"}
34 };
35
36 mctx.strain_gauges = {};
37 mctx.strain_gauges.ids = [0, 1, 2, 3];
38 mctx.strain_gauges.time_limit = 20;
39
40 function debugLog (msg) {
41   if (typeof console === "undefined" || typeof console.log === "undefined") {
42     alert(msg);
43   } else {
44     console.log(msg);
45   }
46 }
47
48 /**
49  * Writes the current date to wherever it's called.
50  */
51 function getDate(){
52         document.write((new Date()).toDateString());
53 }
54
55 function runBeforeLoad(isLoginPage) {
56   $.ajax({
57     url : mctx.api + "identify"
58   }).done(function (data) {
59     if (data.logged_in && isLoginPage) {
60         window.location = mctx.location;
61     } else if (!data.logged_in && !isLoginPage) {
62       //Note: this only clears the nameless cookie
63       document.cookie = ""; 
64       window.location = mctx.location + "login.html";
65     } else {
66       mctx.friendlyName = data.friendly_name;
67     }
68   }).fail(function (jqHXR) {
69     if (!isLoginPage) {
70       window.location = mctx.location + "login.html";
71     } else {
72       debugLog("Failed to ident server. Is API running?")
73     }
74   });
75 }
76
77 /**
78  * Populates a submenu of the navigation bar
79  * @param {string} header The header
80  * @param {object} items An object representing the submenu items
81  * @param {function} translator A function that translates an object item
82  *                              into a text and href.
83  * @returns {$.fn} Itself
84  */
85 $.fn.populateSubmenu = function(header, items, translator) {
86   var submenuHeader = $("<li/>").append($("<a/>", {text : header, href : "#"}));
87   var submenu = $("<ul/>", {"class" : "submenu"});
88   
89   for (var item in items) {
90     var info = translator(item, items);
91     submenu.append($("<li/>").append(
92           $("<a/>", {text : info.text, 
93                      href : info.href, target : "_blank"})
94     ));
95   }
96   
97   this.append(submenuHeader.append(submenu));
98   return this;
99 };
100
101 /** 
102  * Populates the navigation bar
103  */
104 $.fn.populateNavbar = function () {
105   var menu = $("<ul/>", {"class" : "menu"});
106   var sensorTranslator = function(item, items) {
107     var href = mctx.api + "sensors?start_time=0&format=tsv&id=" + item;
108     return {text : items[item].name, href : href};
109   };
110   var actuatorTranslator = function(item, items) {
111     var href = mctx.api + "actuators?start_time=0&format=tsv&id=" + item;
112     return {text : items[item].name, href : href};
113   };
114   
115   menu.populateSubmenu("Sensor data", mctx.sensors, sensorTranslator);
116   menu.populateSubmenu("Actuator data", mctx.actuators, actuatorTranslator);
117   menu.appendTo(this);
118   return this;
119 }
120
121 /**
122  * Sets the camera autoupdater
123  * @returns {$.fn}
124  */
125 $.fn.setCamera = function () {
126   var url = mctx.api + "image";  //http://beaglebone/api/image
127   var update = true;
128
129   //Stop updating if we can't retrieve an image!
130   this.error(function() {
131     update = false;
132   });
133   
134   var parent = this;
135   
136   var updater = function() {
137     if (!update) {
138       alert("Cam fail");
139       parent.attr("src", "");
140       return;
141     }
142     
143     parent.attr("src", url + "#" + (new Date()).getTime());
144     
145     setTimeout(updater, 1000);
146   };
147   
148   updater();
149   return this;
150 };
151
152 $.fn.setStrainGraphs = function () {
153   var sensor_url = mctx.api + "sensors";
154   var graphdiv = this;
155   
156   var updater = function () {
157     var time_limit = mctx.strain_gauges.time_limit;
158     var responses = new Array(mctx.strain_gauges.ids.length);
159     
160     for (var i = 0; i < mctx.strain_gauges.ids.length; i++) {
161       var parameters = {id : i, start_time: -time_limit};
162       responses[i] = $.ajax({url : sensor_url, data : parameters});
163     }
164     
165     $.when.apply(this, responses).then(function () {
166       var data = new Array(arguments.length);
167       for (var i = 0; i < arguments.length; i++) {
168         var raw_data = arguments[i][0].data;
169         var pruned_data = [];
170         var step = ~~(raw_data.length/100);
171         for (var j = 0; j < raw_data.length; j += step)
172           pruned_data.push(raw_data[j]); 
173         data[i] = pruned_data;
174       }
175       $.plot(graphdiv, data);
176       setTimeout(updater, 500);
177     }, function () {alert("It crashed");});
178   };
179   
180   updater();
181   return this;
182 };
183
184 $.fn.login = function () {
185   var username = this.find("input[name='username']").val();
186   var password = this.find("input[name='pass']").val();
187   var out = this.find("#result");
188   var redirect = function () {
189     window.location.href = mctx.location;
190   };
191   
192   out.removeAttr("class");
193   out.text("Logging in...");
194   
195   $.ajax({
196     url : mctx.api + "bind",
197     data : {user: username, pass : password}
198   }).done(function (data) {
199     //todo: error check
200     mctx.has_control = true;
201     out.attr("class", "pass");
202     out.text("Login ok!");
203     setTimeout(redirect, 1000);
204   }).fail(function (jqXHR) {
205     mctx.has_control = false;
206     out.attr("class", "fail");
207     out.text("Login request failed - connection issues.")
208   });
209 };
210
211 $.fn.logout = function () {
212   $.ajax({
213     url : mctx.api + "unbind"
214   }).always(function () {
215     //Note: this only clears the nameless cookie
216     document.cookie = ""; 
217     window.location = mctx.location + "login.html";
218   });
219 }
220
221 $.fn.setErrorLog = function () {
222   var url = mctx.api + "errorlog";
223   var outdiv = this;
224   
225   var updater = function () {
226     $.ajax({url : url}).done(function (data) {
227       outdiv.text(data);
228       outdiv.scrollTop(
229         outdiv[0].scrollHeight - outdiv.height()
230       );
231       setTimeout(updater, 1000);
232     }).fail(function (jqXHR) {
233       if (jqXHR.status === 502 || jqXHR.status === 0) {
234         outdiv.text("Failed to retrieve the error log.");
235       }
236       setTimeout(updater, 1500);
237     });
238   };
239   
240   updater();
241 };
242
243 $(document).ajaxError(function (event, jqXHR) {
244   //console.log("AJAX query failed with: " + jqXHR.status + " (" + jqXHR.statusText + ")");
245 });

UCC git Repository :: git.ucc.asn.au