-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhue-controller.js
More file actions
110 lines (90 loc) · 2.31 KB
/
hue-controller.js
File metadata and controls
110 lines (90 loc) · 2.31 KB
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
var hueController = function() {
'use strict';
//get config from config.json
var fs = require('fs');
var configJson = JSON.parse(fs.readFileSync('./config.json', 'UTF-8'));
//create API base url from config
this.hueBaseUrl = 'http://' + configJson.ip + '/api/' + configJson.username + '/';
//get request handler
this.request = require('request');
};
hueController.prototype = {
getLights: function(callback) {
'use strict';
//list lights request url
var params = {
'url': this.hueBaseUrl + 'lights',
'json': true
};
this.request(params, function(error, response, body) {
if (!error && response.statusCode === 200) {
callback(body);
} else {
callback({'error':error, 'code': response.statusCode});
}
});
},
turnLightOn: function(lightId) {
'use strict';
//turn on light params
var params = {
'url': this.hueBaseUrl + 'lights/' + lightId + '/state',
'json': {"on":true},
'method': 'PUT'
};
this.request(params, function(error, response, body) {
if (error || response.statusCode !== 200) {
console.log('ERROR TURNING ON LIGHT [' + lightId + ']');
console.log('HTTP STATUS CODE :: ' + response.statusCode);
console.log(error);
} else {
console.log('Light ' + lightId + ' turned on');
}
});
},
turnLightOff: function(lightId) {
'use strict';
//turn on light params
var params = {
'url': this.hueBaseUrl + 'lights/' + lightId + '/state',
'json': {"on":false},
'method': 'PUT'
};
this.request(params, function(error, response, body) {
if (error || response.statusCode !== 200) {
console.log('ERROR TURNING OFF LIGHT [' + lightId + ']');
console.log('HTTP STATUS CODE :: ' + response.statusCode);
console.log(error);
} else {
console.log('Light ' + lightId + ' turned off');
}
});
},
turnAllOn: function() {
'use strict';
var self = this;
this.getLights(function(lights) {
if (!lights.error) {
for (var lightId in lights) {
if (parseInt(lightId)) {
self.turnLightOn(lightId);
}
}
}
});
},
turnAllOff: function() {
'use strict';
var self = this;
this.getLights(function(lights) {
if (!lights.error) {
for (var lightId in lights) {
if (parseInt(lightId)) {
self.turnLightOff(lightId);
}
}
}
});
}
};
module.exports = new hueController();