Add user friendly names (right now just usernames)
[matches/MCTX3420.git] / testing / MCTXWeb / public_html / static / mctx.gui.js
index e7dd167..8c6da7a 100644 (file)
@@ -3,15 +3,35 @@
  */
 
 mctx = {};
-mctx.api = location.protocol + "//" +  location.host + "/api/";
+//Don't use this in the final version
+mctx.location = window.location.pathname;
+mctx.location = mctx.location.substring(0, mctx.location.lastIndexOf('/')) + "/";
+//mctx.location = location.protocol + "//" + location.host + "/";
+mctx.api = location.protocol + "//" + location.host + "/" + "api/";
 mctx.expected_api_version = 0;
+mctx.has_control = false;
+//mctx.debug = true;
+
+mctx.statusCodes = {
+  STATUS_OK : 1
+}
+
+mctx.statusCodesDescription = {
+  "1" : "Ok",
+  "-1" : "General error",
+  "-2" : "Unauthorized",
+  "-3" : "Not running",
+  "-4" : "Already exists"
+};
+
 mctx.sensors = {
   0 : {name : "Strain gauge 1"},
   1 : {name : "Strain gauge 2"},
   2 : {name : "Strain gauge 3"},
   3 : {name : "Strain gauge 4"},
   4 : {name : "Pressure sensor 1"},
-  5 : {name : "Pressure sensor 2"}
+  5 : {name : "Pressure sensor 2"},
+  6 : {name : "Pressure sensor 3"}
 };
 
 mctx.actuators = {
@@ -25,39 +45,100 @@ mctx.strain_gauges = {};
 mctx.strain_gauges.ids = [0, 1, 2, 3];
 mctx.strain_gauges.time_limit = 20;
 
+function debugLog (msg) {
+  if (typeof console === "undefined" || typeof console.log === "undefined") {
+    alert(msg);
+  } else {
+    console.log(msg);
+  }
+}
+
+/**
+ * Writes the current date to wherever it's called.
+ */
 function getDate(){
        document.write((new Date()).toDateString());
 }
 
-/** 
- * Populates the navigation bar
+/**
+ * Should be run before the load of any GUI page.
+ * To hook events to be called after this function runs,
+ * use the 'always' method, e.g runBeforeLoad().always(function() {my stuff});
+ * @param {type} isLoginPage
+ * @returns The return value of calling $.ajax
  */
-$.fn.populateNavbar = function () {
-  var menu = $("<ul/>", {class : "menu"});
-  var sensorEntry = $("<li/>").append($("<a/>", {text : "Sensor data", href : "#"}));
-  var submenu = $("<ul/>", {class : "submenu"});
+function runBeforeLoad(isLoginPage) {
+  return $.ajax({
+    url : mctx.api + "identify"
+  }).done(function (data) {
+    if (data.logged_in && isLoginPage) {
+      if (mctx.debug) {
+        debugLog("Redirect disabled!");
+      } else {
+        window.location = mctx.location;
+      }
+    } else if (!data.logged_in && !isLoginPage) {
+      if (mctx.debug) {
+        debugLog("Redirect disabled!");
+      } else {
+        //Note: this only clears the nameless cookie
+        document.cookie = ""; 
+        window.location = mctx.location + "login.html";
+      }
+    } else {
+      mctx.friendlyName = data.friendly_name;
+    }
+  }).fail(function (jqHXR) {
+    if (mctx.debug) {
+      debugLog("Failed to ident server. Is API running?")
+    } else if (!isLoginPage) {
+      window.location = mctx.location + "login.html";
+    }
+  });
+}
+
+/**
+ * Populates a submenu of the navigation bar
+ * @param {string} header The header
+ * @param {object} items An object representing the submenu items
+ * @param {function} translator A function that translates an object item
+ *                              into a text and href.
+ * @returns {$.fn} Itself
+ */
+$.fn.populateSubmenu = function(header, items, translator) {
+  var submenuHeader = $("<li/>").append($("<a/>", {text : header, href : "#"}));
+  var submenu = $("<ul/>", {"class" : "submenu"});
   
-  for (sensor in mctx.sensors) {
-    var href = mctx.api + "sensors?start_time=0&format=tsv&id=" + sensor;
+  for (var item in items) {
+    var info = translator(item, items);
     submenu.append($("<li/>").append(
-          $("<a/>", {text : mctx.sensors[sensor].name
-                     href : href, target : "_blank"})
+          $("<a/>", {text : info.text
+                     href : info.href, target : "_blank"})
     ));
   }
-  menu.append(sensorEntry.append(submenu));
   
-  var actuatorEntry = $("<li/>").append($("<a/>", {text : "Actuator data", href : "#"}));
-  submenu = $("<ul/>", {class : "submenu"});
+  this.append(submenuHeader.append(submenu));
+  return this;
+};
+
+/** 
+ * Populates the navigation bar
+ */
+$.fn.populateNavbar = function () {
+  var menu = $("<ul/>", {"class" : "menu"});
+  var sensorTranslator = function(item, items) {
+    var href = mctx.api + "sensors?start_time=0&format=tsv&id=" + item;
+    return {text : items[item].name, href : href};
+  };
+  var actuatorTranslator = function(item, items) {
+    var href = mctx.api + "actuators?start_time=0&format=tsv&id=" + item;
+    return {text : items[item].name, href : href};
+  };
   
-  for (actuator in mctx.actuators) {
-    var href = mctx.api + "actuators?start_time=0&format=tsv&id=" + actuator;
-    submenu.append($("<li/>").append(
-          $("<a/>", {text : mctx.actuators[actuator].name, 
-                     href : href, target : "_blank"})
-    ));
-  }
-  menu.append(actuatorEntry.append(submenu));  
+  menu.populateSubmenu("Sensor data", mctx.sensors, sensorTranslator);
+  menu.populateSubmenu("Actuator data", mctx.actuators, actuatorTranslator);
   menu.appendTo(this);
+  return this;
 }
 
 /**
@@ -65,7 +146,7 @@ $.fn.populateNavbar = function () {
  * @returns {$.fn}
  */
 $.fn.setCamera = function () {
-  var url = mctx.api + "image";
+  var url = mctx.api + "image";  //http://beaglebone/api/image
   var update = true;
 
   //Stop updating if we can't retrieve an image!
@@ -84,7 +165,7 @@ $.fn.setCamera = function () {
     
     parent.attr("src", url + "#" + (new Date()).getTime());
     
-    setTimeout(updater, 500);
+    setTimeout(updater, 1000);
   };
   
   updater();
@@ -108,13 +189,86 @@ $.fn.setStrainGraphs = function () {
       var data = new Array(arguments.length);
       for (var i = 0; i < arguments.length; i++) {
         var raw_data = arguments[i][0].data;
-        data[i] = raw_data;
+        var pruned_data = [];
+        var step = ~~(raw_data.length/100);
+        for (var j = 0; j < raw_data.length; j += step)
+          pruned_data.push(raw_data[j]); 
+        data[i] = pruned_data;
       }
       $.plot(graphdiv, data);
       setTimeout(updater, 500);
-    }, function () {alert("boo");});
+    }, function () {alert("It crashed");});
   };
   
   updater();
   return this;
-};
\ No newline at end of file
+};
+
+$.fn.login = function () {
+  var username = this.find("input[name='username']").val();
+  var password = this.find("input[name='pass']").val();
+  var out = this.find("#result");
+  var redirect = function () {
+    window.location.href = mctx.location;
+  };
+  
+  out.removeAttr("class");
+  out.text("Logging in...");
+  
+  $.ajax({
+    url : mctx.api + "bind",
+    data : {user: username, pass : password}
+  }).done(function (data) {
+    if (data.status < 0) {
+      mctx.has_control = false;
+      out.attr("class", "fail");
+      out.text("Login failed: " + data.description);
+    } else {
+      //todo: error check
+      mctx.has_control = true;
+      out.attr("class", "pass");
+      out.text("Login ok!");
+      setTimeout(redirect, 800);      
+    }
+  }).fail(function (jqXHR) {
+    mctx.has_control = false;
+    out.attr("class", "fail");
+    out.text("Login request failed - connection issues.")
+  });
+};
+
+$.fn.logout = function () {
+  $.ajax({
+    url : mctx.api + "unbind"
+  }).always(function () {
+    //Note: this only clears the nameless cookie
+    document.cookie = ""; 
+    window.location = mctx.location + "login.html";
+  });
+}
+
+$.fn.setErrorLog = function () {
+  var url = mctx.api + "errorlog";
+  var outdiv = this;
+  
+  var updater = function () {
+    $.ajax({url : url}).done(function (data) {
+      outdiv.text(data);
+      outdiv.scrollTop(
+        outdiv[0].scrollHeight - outdiv.height()
+      );
+      setTimeout(updater, 1000);
+    }).fail(function (jqXHR) {
+      if (jqXHR.status === 502 || jqXHR.status === 0) {
+        outdiv.text("Failed to retrieve the error log.");
+      }
+      setTimeout(updater, 1500);
+    });
+  };
+  
+  updater();
+};
+
+$(document).ajaxError(function (event, jqXHR) {
+  //console.log("AJAX query failed with: " + jqXHR.status + " (" + jqXHR.statusText + ")");
+});
\ No newline at end of file

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