-
Notifications
You must be signed in to change notification settings - Fork 0
/
cheerlights.js
51 lines (39 loc) · 1.31 KB
/
cheerlights.js
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
// CheerLights client library for connecting to thingspeak.com
// namespace for cheerlights
var CheerLights = {
// base domain of thingspeak
domainThingSpeak: 'https://api.thingspeak.com/',
// thingspeak channel for cheerlights
channelThingSpeak: 1417
};
// get the latest color value
CheerLights.getColor = function(callback) {
// contruct URL for thingspeak
var url = CheerLights.domainThingSpeak + 'channels/' + CheerLights.channelThingSpeak + '/feeds/last.json';
// send color request to thingspeak
CheerLights.ajaxColorFromThingSpeak(url, callback);
}
// get channel data from thingspeak
CheerLights.ajaxColorFromThingSpeak = function(url, callback) {
// set up new request
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.send();
// callback when the response is received
request.onload = function() {
// successful response
if (request.status >= 200 && request.status < 400) {
// get response text
response = request.responseText;
// parse response
response = JSON.parse(response);
// set color values
const color = {
htmlName: response.field1,
hexValue: response.field2
};
// execute the callback if it is a function
if (typeof callback === 'function') { callback(color); }
}
};
}