Fix two bugs in mctx.gui.js ++
[matches/MCTX3420.git] / testing / MCTXWeb / public_html / static / mctx.graph.js
1 /**
2  * Graph sensor and/or actuator values
3  */
4
5 //TODO: Clean this file up, I bow to Jeremy's superior JavaScript knowledge
6
7
8 mctx.graph = {};
9 mctx.graph.api = {};
10 mctx.graph.api.sensors = mctx.api + "sensors";
11 mctx.graph.api.actuators = mctx.api + "actuators";
12 mctx.sensors = {};
13 mctx.actuators = {};
14 mctx.graph.dependent = null;
15 mctx.graph.independent = null;
16 mctx.graph.timer = null;
17 mctx.graph.running = false;
18 mctx.graph.chart = null;
19
20 /**
21  * Helper - Calculate pairs of (dependent, independent) values
22  * Given input as (time, value) pairs for dependent and independent
23  * Appends each value pair to the result
24  * @returns result
25  */
26 /**
27  * Helper - Calculate pairs of (dependent, independent) values
28  * Given input as (time, value) pairs for dependent and independent
29  * Appends each value pair to the result
30  * @param {array[][]} dependent Dependent data to be correlated with independent
31  * @param {array[][]} independent Independent data
32  * @param {array[][]} result Storage location
33  * @returns {dataMerge.result}
34  */
35 function dataMerge(dependent, independent, result) {
36         var j = 0;
37         for (var i = 0; i < dependent.length-1; ++i) {
38                 var start = dependent[i][0];
39                 var end = dependent[i+1][0];
40                 var average = 0, n = 0;
41                 for (; j < independent.length; ++j) {
42                         if (independent[j][0] < start)
43                                 continue;
44                         else if (independent[j][0] >= end)
45                                 break;
46                         average += independent[j][1];
47                         n += 1;
48                 }
49                 if (n > 0) {
50                         average /= n;
51                         result.push([dependent[i][1], average]);
52                 }
53         }
54         return result;
55 }
56
57 /**
58  * Helper function adds the sensors and actuators to a form
59  * @param input_type is it a radio? or is it a checkbox?
60  * @param check_first determines whether the first item is checked or not
61  * @param group which group this input belongs to (name field)
62  */
63 $.fn.deployDevices = function(input_type, check_first, group) {
64   var container = this;
65   var apply = function(dict, prefix) {
66     $.each(dict, function(key, val) {
67       var attributes = {
68           'type' : input_type, 'value' : key, 'alt' : val,
69           'class' : prefix, 'name' : group, 
70           'id' : prefix + '_' + val //Unique id (name mangling)
71       };
72       var entry = $("<input/>", attributes);
73       var label = $("<label/>", {'for' : prefix + '_' + val, 'text' : val}); 
74       entry.prop("checked", check_first);
75       check_first = false;
76       container.append(entry).append(label);
77     });
78   }
79   
80   apply(mctx.sensors, 'sensors');
81   apply(mctx.actuators, 'actuators');
82 };
83
84 /**
85  * Identify sensors/actuators
86  * @returns itself (Is this right?)
87  */
88 $.fn.setDevices = function() {
89   // Query for sensors and actuators
90   return $.ajax({
91     url : mctx.api + 'identify', 
92     data : {'sensors' : 1, 'actuators' : 1}
93   }).done(function (data) {
94     mctx.sensors = $.extend(mctx.sensors, data.sensors);
95     mctx.actuators = $.extend(mctx.actuators, data.actuators);
96     
97     //Always set the 'time' option to be checked
98     $("#xaxis input").prop('checked', true);  
99     $("#xaxis").deployDevices("radio", false, 'xaxis');
100     $("#yaxis").deployDevices("checkbox", true, 'yaxis');
101     $("#current_time").val(data.running_time);
102     //Add event listeners for when the
103     $(".change input").change(function () {
104       $("#graph").setGraph();
105     });
106   });
107 };
108
109 function setGraphStatus(on, failText) {
110   if (on) {
111     mctx.graph.running = true;
112     $("#status-text").html("&nbsp;");
113     $("#graph-run").text("Pause");
114   } else {
115     mctx.graph.running = false;
116     if (failText) {
117       $("#status-text").text(failText).addClass("fail");
118     } else {
119       $("#status-text").text("Graph stopped").removeClass("fail");
120     }
121     $("#graph-run").text("Run");
122   }
123 }
124
125 function graphUpdater() {
126   var urls = {
127     'sensors' : mctx.graph.api.sensors,
128     'actuators' : mctx.graph.api.actuators
129   }
130   
131   var updater = function () {
132     var responses = [];
133     var ctime =  $("#current_time");
134     
135     var xaxis = mctx.graph.xaxis;
136     var yaxis = mctx.graph.yaxis;
137     var start_time = mctx.graph.start_time;
138     var end_time = mctx.graph.end_time;
139     var devices = mctx.graph.devices;
140     
141     if (xaxis.size() < 1 || yaxis.size() < 1) {
142       setGraphStatus(false, "No x or y axis selected.");
143       return;
144     }
145     
146     $.each(devices, function(key, val) {
147       if (val.urltype in urls) {
148         var parameters = {id : val.id};
149         if (start_time !== null) {
150           parameters.start_time = start_time;
151         }
152         if (end_time !== null) {
153           parameters.end_time = end_time;
154         }
155         responses.push($.ajax({url : urls[val.urltype], data : parameters})
156         .done(function(json) {
157           //alert("Hi from " + json.name);
158           var dev = val.data;
159           for (var i = 0; i < json.data.length; ++i) {
160             if (dev.length <= 0 || json.data[i][0] > dev[dev.length-1][0]) {
161               dev.push(json.data[i]);
162             }
163           }
164           ctime.val(json.running_time);
165           //alert(devices[json.name].data);
166         }));
167       }
168     });
169
170     //... When the response is received, then() will happen (I think?)
171     $.when.apply(this, responses).then(function () {
172       var plot_data = [];
173       yaxis.each(function() {
174         //alert("Add " + $(this).val() + " to plot");
175         if (xaxis.attr("alt") === "time") {
176           //alert("Against time");
177           plot_data.push(devices[$(this).attr("alt")].data);
178         } else {
179           var result = []
180           dataMerge(devices[xaxis.attr("alt")].data, 
181                     devices[$(this).attr("alt")].data, result);
182           plot_data.push(result);
183         }
184       });
185       
186       //$.plot("#graph", plot_data);
187       if (mctx.graph.chart !== null) {
188         mctx.graph.chart.setData(plot_data);
189         mctx.graph.chart.setupGrid(); 
190         mctx.graph.chart.draw();
191       } else {
192         mctx.graph.chart = $.plot("#graph", plot_data);
193       }
194       if (mctx.graph.running) {
195         mctx.graph.timer = setTimeout(updater, 1000);
196       }
197     }, function () {
198       setGraphStatus("Connection issue - graph stopped.");
199       //This will always happen when a user closes the page
200       //alert("Graph crashed"); 
201     });
202   };
203   
204   setGraphStatus(true);
205   updater();
206   return this;
207 }
208
209 /**
210  * Sets the graphs to graph stuff.
211  * @returns {$.fn}
212  */
213 $.fn.setGraph = function () {
214   // Determine which actuator/sensors to plot
215   var xaxis = $("#xaxis input[name=xaxis]:checked");
216   var yaxis = $("#yaxis input[name=yaxis]:checked");
217   if (xaxis.size() < 1 || yaxis.size() < 1) {
218     //nothing to plot...
219     setGraphStatus(false, "No x or y axis selected.");
220     return;
221   }
222   
223   var start_time = $("#start_time").val();
224   var end_time = $("#end_time").val();
225   if (!$.isNumeric(start_time)) {
226     start_time = null;
227   }
228   if (!$.isNumeric(end_time)) {
229     end_time = null;
230   }
231
232   var devices = {};
233   var populateDict = function () {
234     var dict = {};
235     dict['urltype'] = $(this).attr("class");
236     dict['id'] = $(this).attr("value");
237     dict['data'] = [];
238     dict['start_time'] = start_time;
239     dict['end_time'] = end_time;
240     devices[$(this).attr("alt")] = dict;
241   };
242   xaxis.each(populateDict);
243   yaxis.each(populateDict);
244   
245   mctx.graph.xaxis = xaxis;
246   mctx.graph.yaxis = yaxis;
247   mctx.graph.start_time = start_time;
248   mctx.graph.end_time = end_time;
249   mctx.graph.devices = devices;
250   
251   if (!mctx.graph.running) {
252     $("#graph-run").val("Pause");
253     $("#status-text").text("")
254     graphUpdater();
255   }
256   
257   return this;
258 };
259
260 $.fn.runButton = function() {
261   if (mctx.graph.running) {
262     setGraphStatus(false);
263     clearTimeout(mctx.graph.timer);
264   } else {
265     $("#graph").setGraph();
266   }
267 };

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