-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathThingSpeakMultichannel001.html
452 lines (433 loc) · 19.1 KB
/
ThingSpeakMultichannel001.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!--<script src="https://www.thingspeak.com/assets/application-927d1479ab2235e91ae25cb56d33b211.js"
type="text/javascript"></script>-->
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://rawgithub.com/highslide-software/export-csv/master/export-csv.js"></script>
<script type="text/javascript">
// Webpage Javascript to chart multiple ThingSpeak channels on two axis with navigator, load historical data, and export cvs data.
// Public Domain, by turgo.
// The charting library is called HighStock. It is awesome! HighSoft, the owners say,
// "Do you want to use Highstock for a personal or non-profit project? Then you can use Highchcarts for
// free under the Creative Commons Attribution-NonCommercial 3.0 License. "
// http://forum.arduino.cc/index.php?topic=213058.msg1560990#msg1560990
var dynamicChart;
var channelsLoaded = 0;
// put your ThingSpeak Channel#, Channel Name, and API keys here.
// fieldList shows which field you want to load, and which axis to display that field on,
// the 'T' Temperature left axis, or the 'O' Other right axis.
var channelKeys =[];
//Change TO: display two fields from the same channel from a Rain gauge - 15min counts, and total counts
// src="http://api.thingspeak.com/channels/8652/charts/3?width=1300&height=520&results=1000&dynamic=false&title=15minTotals%20(0.5mm)" ></iframe>
channelKeys.push({channelNumber:8652, name:'RainGauge',key:'EAEX6922YVUKP3IP',
fieldList:[{field:3,axis:'C'},{field:7,axis:'R'}]});
// user's timezone offset
var myOffset = new Date().getTimezoneOffset();
// converts date format from JSON
function getChartDate(d) {
// get the data using javascript's date object (year, month, day, hour, minute, second)
// months in javascript start at 0, so remember to subtract 1 when specifying the month
// offset in minutes is converted to milliseconds and subtracted so that chart's x-axis is correct
return Date.UTC(d.substring(0,4), d.substring(5,7)-1, d.substring(8,10), d.substring(11,13), d.substring(14,16), d.substring(17,19)) - (myOffset * 60000);
}
// Hide all series, via 'Hide All' button. Then user can click on serries name in legent to show series of interest.
function HideAll(){
for (var index=0; index<dynamicChart.series.length; index++) // iterate through each series
{
if (dynamicChart.series[index].name == 'Navigator')
continue;
dynamicChart.series[index].hide();
//window.console && console.log('Series Number:',index,' Name:',dynamicChart.series[index].name);
}
//});
}
// This is where the chart is generated.
$(document).ready(function()
{
//Add Channel Load Menu
var menu=document.getElementById("Channel Select");
for (var channelIndex=0; channelIndex<channelKeys.length; channelIndex++) // iterate through each channel
{
window.console && console.log('Name',channelKeys[channelIndex].name);
var menuOption =new Option(channelKeys[channelIndex].name,channelIndex);
menu.options.add(menuOption,channelIndex);
}
var last_date; // variable for the last date added to the chart
window.console && console.log('Testing console');
//make series numbers for each field
var seriesCounter=0
for (var channelIndex=0; channelIndex<channelKeys.length; channelIndex++) // iterate through each channel
{
for (var fieldIndex=0; fieldIndex<channelKeys[channelIndex].fieldList.length; fieldIndex++) // iterate through each channel
{
channelKeys[channelIndex].fieldList[fieldIndex].series = seriesCounter;
seriesCounter++;
}
}
//make calls to load data from each channel into channelKeys array now
// draw the chart when all the data arrives, later asyncronously add history
for (var channelIndex=0; channelIndex<channelKeys.length; channelIndex++) // iterate through each channel
{
channelKeys[channelIndex].loaded = false;
loadThingSpeakChannel(channelIndex,channelKeys[channelIndex].channelNumber,channelKeys[channelIndex].key,channelKeys[channelIndex].fieldList);
}
//window.console && console.log('Channel Keys',channelKeys);
// load the most recent 2500 points (fast initial load) from a ThingSpeak channel into a data[] array and return the data[] array
function loadThingSpeakChannel(sentChannelIndex,channelNumber,key,sentFieldList) {
var fieldList= sentFieldList;
var channelIndex = sentChannelIndex;
// get the Channel data with a webservice call
$.getJSON('https://api.thingspeak.com/channels/'+channelNumber+'/feed.json?&offset=0&results=2500;api_key='+key, function(data)
{
// if no access
if (data == '-1') {
$('#chart-container').append('This channel is not public. To embed charts, the channel must be public or a read key must be specified.');
window.console && console.log('Thingspeak Data Loading Error');
}
for (var fieldIndex=0; fieldIndex<fieldList.length; fieldIndex++) // iterate through each field
{
fieldList[fieldIndex].data =[];
for (var h=0; h<data.feeds.length; h++) // iterate through each feed (data point)
{
var p = []//new Highcharts.Point();
var fieldStr = "data.feeds["+h+"].field"+fieldList[fieldIndex].field;
var v = eval(fieldStr);
p[0] = getChartDate(data.feeds[h].created_at);
p[1] = parseFloat(v);
// if a numerical value exists add it
if (!isNaN(parseInt(v))) { fieldList[fieldIndex].data.push(p); }
}
fieldList[fieldIndex].name = eval("data.channel.field"+fieldList[fieldIndex].field);
}
window.console && console.log('getJSON field name:',fieldList[0].name);
channelKeys[channelIndex].fieldList=fieldList;
channelKeys[channelIndex].loaded=true;
channelsLoaded++;
window.console && console.log('channels Loaded:',channelsLoaded);
window.console && console.log('channel index:',channelIndex);
if (channelsLoaded==channelKeys.length){createChart();}
})
.fail(function() { alert('getJSON request failed! '); });
}
// create the chart when all data is loaded
function createChart() {
// specify the chart options
var chartOptions = {
chart:
{
renderTo: 'chart-container',
zoomType:'y',
events:
{
load: function()
{
if ('true' === 'true' && (''.length < 1 && ''.length < 1 && ''.length < 1 && ''.length < 1 && ''.length < 1))
{
// If the update checkbox is checked, get latest data every 15 seconds and add it to the chart
setInterval(function()
{
if (document.getElementById("Update").checked)
{
for (var channelIndex=0; channelIndex<channelKeys.length; channelIndex++) // iterate through each channel
{
(function(channelIndex)
{
// get the data with a webservice call
$.getJSON('https://api.thingspeak.com/channels/'+channelKeys[channelIndex].channelNumber+'/feed/last.json?offset=0&location=false;api_key='+channelKeys[channelIndex].key, function(data)
{
for (var fieldIndex=0; fieldIndex<channelKeys[channelIndex].fieldList.length; fieldIndex++)
{
// if data exists
var fieldStr = "data.field"+channelKeys[channelIndex].fieldList[fieldIndex].field;
var chartSeriesIndex=channelKeys[channelIndex].fieldList[fieldIndex].series;
if (data && eval(fieldStr))
{
var p = []//new Highcharts.Point();
var v = eval(fieldStr);
p[0] = getChartDate(data.created_at);
p[1] = parseFloat(v);
// get the last date if possible
if (dynamicChart.series[chartSeriesIndex].xData.length > 0)
{
last_date = dynamicChart.series[chartSeriesIndex].xData[dynamicChart.series[chartSeriesIndex].xData.length-1];
}
var shift = false ; //default for shift
// if a numerical value exists and it is a new date, add it
if (!isNaN(parseInt(v)) && (p[0] != last_date))
{
dynamicChart.series[chartSeriesIndex].addPoint(p, true, shift);
}
}
//window.console && console.log('channelKeys:',channelKeys);
//window.console && console.log('chartSeriesIndex:',chartSeriesIndex);
//window.console && console.log('channel index:',channelIndex);
//window.console && console.log('field index:',fieldIndex);
//window.console && console.log('update series name:',dynamicChart.series[chartSeriesName].name);
//window.console && console.log('channel keys name:',channelKeys[channelIndex].fieldList[fieldIndex].name);
}
});
})(channelIndex);
}
}
}, 15000);
}
}
}
},
rangeSelector: {
buttons: [{
count: 30,
type: 'minute',
text: '30M'
}, {
count: 12,
type: 'hour',
text: '12H'
}, {
count: 1,
type: 'day',
text: 'D'
}, {
count: 1,
type: 'week',
text: 'W'
}, {
count: 1,
type: 'month',
text: 'M'
}, {
count: 1,
type: 'year',
text: 'Y'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: true,
selected: 4 //Change to 4th button as default
},
title: {
text: ''
},
plotOptions: {
line: {
gapSize:5
//color: '#d62020'
// },
// bar: {
//color: '#d52020'
// },
// column: {
},
series: {
marker: {
radius: 2
},
animation: true,
step: false,
turboThrehold:1000,
borderWidth: 0
}
},
tooltip: {
valueDecimals: 1,
valueSuffix: '(0.01")',
xDateFormat:'%Y-%m-%d<br/>%H:%M:%S %p' //bug fix
// reformat the tooltips so that local times are displayed
//formatter: function() {
//var d = new Date(this.x + (myOffset*60000));
//var n = (this.point.name === undefined) ? '' : '<br/>' + this.point.name;
//return this.series.name + ':<b>' + this.y + '</b>' + n + '<br/>' + d.toDateString() + '<br/>' + d.toTimeString().replace(/\(.*\)/, "");
//}
},
xAxis: {
type: 'datetime',
ordinal:false,
min: Date.UTC(2013,02,28),
dateTimeLabelFormats : {
hour: '%l %p',
minute: '%l:%M %p'
},
title: {
text: 'LeftAxis'
}
},
yAxis: [{
title: {
text: 'RainGauge Total (0.01")'
},
id: 'R'
}, {
title: {
text: '15min counts (0.01")'
},
opposite: true,
id: 'C'
}],
exporting: {
enabled: true,
csv: {
dateFormat: '%d/%m/%Y %I:%M:%S %p'
}
},
legend: {
enabled: true
},
navigator: {
baseSeries: 0, //select which series to show in history navigator, First series is 0
series: {
includeInCSVExport: false
}
},
series: []
//series: [{data:[[getChartDate("2013-06-16T00:32:40Z"),75]]}]
};
// add all Channel data to the chart
for (var channelIndex=0; channelIndex<channelKeys.length; channelIndex++) // iterate through each channel
{
for (var fieldIndex=0; fieldIndex<channelKeys[channelIndex].fieldList.length; fieldIndex++) // add each field
{
window.console && console.log('Channel '+channelIndex+' field '+fieldIndex);
chartOptions.series.push({data:channelKeys[channelIndex].fieldList[fieldIndex].data,
index:channelKeys[channelIndex].fieldList[fieldIndex].series,
yAxis:channelKeys[channelIndex].fieldList[fieldIndex].axis,
//visible:false,
name: channelKeys[channelIndex].fieldList[fieldIndex].name});
}
}
// set chart labels here so that decoding occurs properly
//chartOptions.title.text = data.channel.name;
chartOptions.xAxis.title.text = 'Date';
// draw the chart
dynamicChart = new Highcharts.StockChart(chartOptions);
// update series number to account for the navigator series (The historical series at the bottom) which is the first series.
for (var channelIndex=0; channelIndex<channelKeys.length; channelIndex++) // iterate through each channel
{
for (var fieldIndex=0; fieldIndex<channelKeys[channelIndex].fieldList.length; fieldIndex++) // and each field
{
for (var seriesIndex=0; seriesIndex<dynamicChart.series.length; seriesIndex++) // compare each series name
{
if (dynamicChart.series[seriesIndex].name == channelKeys[channelIndex].fieldList[fieldIndex].name)
{
channelKeys[channelIndex].fieldList[fieldIndex].series = seriesIndex;
}
}
}
}
// add all history
//dynamicChart.showLoading("Loading History..." );
window.console && console.log('Channels: ',channelKeys.length);
for (var channelIndex=0; channelIndex<channelKeys.length; channelIndex++) // iterate through each channel
{
window.console && console.log('channelIndex: ',channelIndex);
(function(channelIndex)
{
//load only 1 set of 8000 points
loadChannelHistory(channelIndex,channelKeys[channelIndex].channelNumber,channelKeys[channelIndex].key,channelKeys[channelIndex].fieldList,0,1);
}
)(channelIndex);
}
}
});
function loadOneChannel(){
// load a channel selected in the popUp menu.
var selectedChannel=document.getElementById("Channel Select");
var maxLoads=document.getElementById("Loads").value ;
var channelIndex = selectedChannel.selectedIndex;
loadChannelHistory(channelIndex,channelKeys[channelIndex].channelNumber,channelKeys[channelIndex].key,channelKeys[channelIndex].fieldList,0,maxLoads);
}
// load next 8000 points from a ThingSpeak channel and addPoints to a series
function loadChannelHistory(sentChannelIndex,channelNumber,key,sentFieldList,sentNumLoads,maxLoads) {
var numLoads=sentNumLoads
var fieldList= sentFieldList;
var channelIndex = sentChannelIndex;
var first_Date = new Date();
if (typeof fieldList[0].data[0] != "undefined") first_Date.setTime(fieldList[0].data[0][0]+7*60*60*1000);//adjust for 7 hour difference from GMT (Zulu time)
else if (typeof fieldList[1].data[0] != "undefined") first_Date.setTime(fieldList[1].data[0][0]+7*60*60*1000);
else if (typeof fieldList[2].data[0] != "undefined") first_Date.setTime(fieldList[2].data[0][0]+7*60*60*1000);
else if (typeof fieldList[3].data[0] != "undefined") first_Date.setTime(fieldList[3].data[0][0]+7*60*60*1000);
else if (typeof fieldList[4].data[0] != "undefined") first_Date.setTime(fieldList[4].data[0][0]+7*60*60*1000);
else if (typeof fieldList[5].data[0] != "undefined") first_Date.setTime(fieldList[5].data[0][0]+7*60*60*1000);
else if (typeof fieldList[6].data[0] != "undefined") first_Date.setTime(fieldList[6].data[0][0]+7*60*60*1000);
else if (typeof fieldList[7].data[0] != "undefined") first_Date.setTime(fieldList[7].data[0][0]+7*60*60*1000);
var end = first_Date.toJSON();
window.console && console.log('earliest date:',end);
window.console && console.log('sentChannelIndex:',sentChannelIndex);
window.console && console.log('numLoads:',numLoads);
// get the Channel data with a webservice call
$.getJSON('https://api.thingspeak.com/channels/'+channelNumber+'/feed.json?offset=0&start=2013-01-20T00:00:00;end='+end+';api_key='+key, function(data)
{
// if no access
if (data == '-1') {
$('#chart-container').append('This channel is not public. To embed charts, the channel must be public or a read key must be specified.');
window.console && console.log('Thingspeak Data Loading Error');
}
for (var fieldIndex=0; fieldIndex<fieldList.length; fieldIndex++) // iterate through each field
{
//fieldList[fieldIndex].data =[];
for (var h=0; h<data.feeds.length; h++) // iterate through each feed (data point)
{
var p = []//new Highcharts.Point();
var fieldStr = "data.feeds["+h+"].field"+fieldList[fieldIndex].field;
var v = eval(fieldStr);
p[0] = getChartDate(data.feeds[h].created_at);
p[1] = parseFloat(v);
// if a numerical value exists add it
if (!isNaN(parseInt(v))) { fieldList[fieldIndex].data.push(p); }
}
fieldList[fieldIndex].data.sort(function(a,b){return a[0]-b[0]});
dynamicChart.series[fieldList[fieldIndex].series].setData(fieldList[fieldIndex].data,false);
//dynamicChart.series[fieldList[fieldIndex].series].addPoint(fieldList[fieldIndex].data,false);
//fieldList[fieldIndex].name = eval("data.channel.field"+fieldList[fieldIndex].field);
//window.console && console.log('data added to series:',fieldList[fieldIndex].series,fieldList[fieldIndex].data);
}
channelKeys[channelIndex].fieldList=fieldList;
dynamicChart.redraw()
window.console && console.log('channel index:',channelIndex);
numLoads++;
if (numLoads<maxLoads) {loadChannelHistory(channelIndex,channelNumber,key,fieldList,numLoads,maxLoads);}
});
}
</script>
<title>Rain Gauge - rain intentsity - experimental</title>
</head>
<body style=" background-color: white;">
<div id="chart-container" style="height: 600px;"><br>
Highstock Chart Here<br>
</div>
<div id="below chart"> <button style="width: 89px; margin-top: -18px;" value="Hide All"
name="Hide All Button"
onclick="HideAll();">Hide
All</button><button style="width: 162px; margin-top: -18px;" value="Load More Data"
name="Load More Data"
onclick="loadOneChannel();">Load
More Historical Data </button>
<select id="Channel Select">
</select>
<select id="Loads">
<option value="1">1 Load</option>
<option value="2">2 Loads</option>
<option value="3">3 Loads</option>
<option value="4">4 Loads</option>
<option value="5" selected="selected">5 Loads</option>
<option value="6">6 Loads</option>
<option value="7">7 Loads</option>
<option value="8">8 Loads</option>
<option value="9">9 Loads</option>
<option value="10">10 Loads</option>
<option value="15">15 Loads</option>
<option value="20">20 Loads</option>
<option value="25">25 Loads</option>
<option value="30">30 Loads</option>
<option value="40">40 Loads</option>
<option value="50">50 Loads</option>
</select>
<input id="Update" name="Update" type="checkbox"><span style="font-family: Lucida Grande;">Update
Chart</span> <span id="Latency" style="font-family: Lucida Grande;">(Latency)</span>
</div>
</body>
</html>