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

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