forked from jnovack/homebridge-better-http-rgb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
575 lines (501 loc) · 20.1 KB
/
index.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
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
var Service, Characteristic;
var request = require('request');
/**
* @module homebridge
* @param {object} homebridge Export functions required to create a
* new instance of this plugin.
*/
module.exports = function(homebridge){
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory('homebridge-better-http-rgb', 'HTTP-RGB', HTTP_RGB);
};
/**
* Parse the config and instantiate the object.
*
* @summary Constructor
* @constructor
* @param {function} log Logging function
* @param {object} config Your configuration object
*/
function HTTP_RGB(log, config) {
// The logging function is required if you want your function to output
// any information to the console in a controlled and organized manner.
this.log = log;
this.service = 'Light';
this.name = config.name;
this.http_method = config.http_method || 'GET';
this.username = config.username || '';
this.password = config.password || '';
// Handle the basic on/off
this.switch = { powerOn: {}, powerOff: {} };
if (typeof config.switch === 'object') {
this.switch.status = config.switch.status;
// Intelligently handle if config.switch.powerOn is an object or string.
if (typeof config.switch.powerOn === 'object') {
this.switch.powerOn.set_url = config.switch.powerOn.url;
this.switch.powerOn.body = config.switch.powerOn.body;
} else {
this.switch.powerOn.set_url = config.switch.powerOn;
}
// Intelligently handle if config.switch.powerOff is an object or string.
if (typeof config.switch.powerOff === 'object') {
this.switch.powerOff.set_url = config.switch.powerOff.url;
this.switch.powerOff.body = config.switch.powerOff.body;
} else {
this.switch.powerOff.set_url = config.switch.powerOff;
}
}
// Local caching of HSB color space for RGB callback
this.cache = {};
this.cacheUpdated = false;
// Handle brightness
if (typeof config.brightness === 'object') {
this.brightness = {};
this.brightness.status = config.brightness.status;
this.brightness.set_url = config.brightness.url || this.brightness.status;
this.brightness.http_method = config.brightness.http_method || this.http_method;
this.cache.brightness = 0;
} else {
this.brightness = false;
this.cache.brightness = 100;
}
// Color handling
if (typeof config.color === 'object') {
this.color = {};
this.color.status = config.color.status;
this.color.set_url = config.color.url || this.color.status;
this.color.http_method = config.color.http_method || this.http_method;
this.color.brightness = config.color.brightness;
this.cache.hue = 0;
this.cache.saturation = 0;
} else {
this.color = false;
}
this.has = { brightness: this.brightness || (typeof this.color === 'object' && this.color.brightness) };
}
/**
*
* @augments HTTP_RGB
*/
HTTP_RGB.prototype = {
/** Required Functions **/
identify: function(callback) {
this.log('Identify requested!');
callback();
},
getServices: function() {
// You may OPTIONALLY define an information service if you wish to override
// default values for devices like serial number, model, etc.
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, 'HTTP Manufacturer')
.setCharacteristic(Characteristic.Model, 'homebridge-better-http-rgb')
.setCharacteristic(Characteristic.SerialNumber, 'HTTP Serial Number');
switch (this.service) {
case 'Light':
this.log('creating Lightbulb');
var lightbulbService = new Service.Lightbulb(this.name);
if (this.switch.status) {
lightbulbService
.getCharacteristic(Characteristic.On)
.on('get', this.getPowerState.bind(this))
.on('set', this.setPowerState.bind(this));
} else {
lightbulbService
.getCharacteristic(Characteristic.On)
.on('set', this.setPowerState.bind(this));
}
// Handle brightness
if (this.has.brightness) {
this.log('... adding Brightness');
lightbulbService
.addCharacteristic(new Characteristic.Brightness())
.on('get', this.getBrightness.bind(this))
.on('set', this.setBrightness.bind(this));
}
// Handle color
if (this.color) {
this.log('... Ted Turnerizing(tm)');
lightbulbService
.addCharacteristic(new Characteristic.Hue())
.on('get', this.getHue.bind(this))
.on('set', this.setHue.bind(this));
lightbulbService
.addCharacteristic(new Characteristic.Saturation())
.on('get', this.getSaturation.bind(this))
.on('set', this.setSaturation.bind(this));
}
return [lightbulbService];
/*
These are included here as an example of what other
HomeKit-compatible devices can be.
*/
/*
case 'Switch':
this.log('creating Switch');
var switchService = new Service.Switch(this.name);
if (this.switch.powerOn.status) {
switchService
.getCharacteristic(Characteristic.On)
.on('get', this.getPowerState.bind(this))
.on('set', this.setPowerState.bind(this));
} else {
switchService
.getCharacteristic(Characteristic.On)
.on('set', this.setPowerState.bind(this));
}
return [switchService];
case 'Lock':
var lockService = new Service.LockMechanism(this.name);
lockService
.getCharacteristic(Characteristic.LockCurrent)
.on('get', this.getLockCurrent.bind(this))
.on('set', this.setLockCurrent.bind(this));
lockService
.getCharacteristic(Characteristic.LockTarget)
.on('get', this.getLockTarget.bind(this))
.on('set', this.setLockTarget.bind(this));
return [lockService];
case 'Smoke':
var smokeService = new Service.SmokeSensor(this.name);
smokeService
.getCharacteristic(Characteristic.SmokeDetected)
.on('set', this.getSmokeDetected.bind(this));
return [smokeService];
case 'Motion':
var motionService = new Service.MotionSensor(this.name);
motionService
.getCharacteristic(Characteristic.MotionDetected)
.on('get', this.getMotionDetected.bind(this));
return [motionService];
case 'Temp':
var temperatureService = new Service.TemperatureSensor(this.name);
temperatureService
.getCharacteristic(Characteristic.CurrentTemperature)
.on('get', this.getTemperature.bind(this));
var humidityService = new Service.HumiditySensor(this.name);
humidityService
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.on('get', this.getHumidity.bind(this));
return [temperatureService, humidityService];
*/
default:
return [informationService];
} // end switch
},
//** Custom Functions **//
/**
* Gets power state of lightbulb.
*
* @param {function} callback The callback that handles the response.
*/
getPowerState: function(callback) {
if (!this.switch.status) {
this.log.warn('Ignoring request, switch.status not defined.');
callback(new Error('No switch.status url defined.'));
return;
}
var url = this.switch.status;
this._httpRequest(url, '', 'GET', function(error, response, responseBody) {
if (error) {
this.log('getPowerState() failed: %s', error.message);
callback(error);
} else {
var stateObj = JSON.parse(responseBody);
var powerOn = stateObj.channel.red > 0 || stateObj.channel.green > 0 || stateObj.channel.blue > 0;
this.log('power is currently %s', powerOn ? 'ON' : 'OFF');
callback(null, powerOn);
}
}.bind(this));
},
/**
* Sets the power state of the lightbulb.
*
* @param {function} callback The callback that handles the response.
*/
setPowerState: function(state, callback) {
var url;
var body;
if (!this.switch.powerOn.set_url || !this.switch.powerOff.set_url) {
this.log.warn('Ignoring request, powerOn.url or powerOff.url is not defined.');
callback(new Error("The 'switch' section in your configuration is incorrect."));
return;
}
var rgb = this._hsvToRgb(this.cache.hue, this.cache.saturation, this.cache.brightness)
if (state) {
url = this.switch.powerOn.set_url.replace('{{RED}}', rgb.r).replace('{{GREEN}}', rgb.g).replace('{{BLUE}}', rgb.b);
body = this.switch.powerOn.body;
} else {
url = this.switch.powerOn.set_url.replace('{{RED}}', 0).replace('{{GREEN}}', 0).replace('{{BLUE}}', 0);
body = this.switch.powerOff.body;
}
this._httpRequest(url, body, this.http_method, function(error, response, responseBody) {
if (error) {
this.log('setPowerState() failed: %s', error.message);
callback(error);
} else {
this.log('setPowerState() successfully set to %s', state ? 'ON' : 'OFF');
callback(undefined, responseBody);
}
}.bind(this));
},
/**
* Gets brightness of lightbulb.
*
* @param {function} callback The callback that handles the response.
*/
getBrightness: function(callback) {
if (!this.has.brightness) {
this.log.warn("Ignoring request; No 'brightness' defined.");
callback(new Error("No 'brightness' defined in configuration"));
return;
}
if (this.brightness) {
this._httpRequest(this.brightness.status, '', 'GET', function(error, response, responseBody) {
if (error) {
this.log('getBrightness() failed: %s', error.message);
callback(error);
} else {
var responseObj = JSON.parse(responseBody);
var hsl = this._rgbToHsl(responseObj.channel.red, responseObj.channel.green, responseObj.channel.blue);
var level = hsl.l;
this.log('brightness is currently at %s %', level);
callback(null, level);
}
}.bind(this));
} else {
callback(null, this.cache.brightness);
}
},
/**
* Sets the brightness of the lightbulb.
*
* @param {function} callback The callback that handles the response.
*/
setBrightness: function(level, callback) {
if (!this.has.brightness) {
this.log.warn("Ignoring request; No 'brightness' defined.");
callback(new Error("No 'brightness' defined in configuration"));
return;
}
this.cache.brightness = level;
// If achromatic, then update brightness, otherwise, update HSL as RGB
if (!this.color) {
var url = this.brightness.set_url.replace('%s', level);
this._httpRequest(url, '', this.brightness.http_method, function(error, response, body) {
if (error) {
this.log('setBrightness() failed: %s', error);
callback(error);
} else {
this.log('setBrightness() successfully set to %s %', level);
callback();
}
}.bind(this));
} else {
this._setRGB(callback);
}
},
/**
* Gets the hue of lightbulb.
*
* @param {function} callback The callback that handles the response.
*/
getHue: function(callback) {
if (this.color && typeof this.color.status !== 'string') {
this.log.warn("Ignoring request; problem with 'color' variables.");
callback(new Error("There was a problem parsing the 'color' section of your configuration."));
return;
}
var url = this.color.status;
this._httpRequest(url, '', 'GET', function(error, response, responseBody) {
if (error) {
this.log('... getHue() failed: %s', error.message);
callback(error);
} else {
var stateObj = JSON.parse(responseBody);
var hsl = this._rgbToHsl(
stateObj.channel.red,
stateObj.channel.green,
stateObj.channel.blue
);
var hue = hsl.h;
this.log('... hue is currently %s', hue);
this.cache.hue = hue;
callback(null, hue);
}
}.bind(this));
},
/**
* Sets the hue of the lightbulb.
*
* @param {function} callback The callback that handles the response.
*/
setHue: function(level, callback) {
if (this.color && typeof this.color.set_url !== 'string') {
this.log.warn("Ignoring request; problem with 'color' variables.");
callback(new Error("There was a problem parsing the 'color' section of your configuration."));
return;
}
this.log('Caching Hue as %s ...', level);
this.cache.hue = level;
if (this.cacheUpdated) {
this._setRGB(callback);
} else {
this.cacheUpdated = true;
callback();
}
},
/**
* Gets the saturation of lightbulb.
*
* @param {function} callback The callback that handles the response.
*/
getSaturation: function(callback) {
if (this.color && typeof this.color.status !== 'string') {
this.log.warn("Ignoring request; problem with 'color' variables.");
callback(new Error("There was a problem parsing the 'color' section of your configuration."));
return;
}
var url = this.color.status;
this._httpRequest(url, '', 'GET', function(error, response, responseBody) {
if (error) {
this.log('... getSaturation() failed: %s', error.message);
callback(error);
} else {
var stateObj = JSON.parse(responseBody);
var hsl = this._rgbToHsl(
stateObj.channel.red,
stateObj.channel.green,
stateObj.channel.blue
);
var saturation = hsl.s;
this.log('... saturation is currently %s', saturation);
this.cache.saturation = saturation;
callback(null, saturation);
}
}.bind(this));
},
/**
* Sets the saturation of the lightbulb.
*
* @param {number} level The saturation of the new call.
* @param {function} callback The callback that handles the response.
*/
setSaturation: function(level, callback) {
if (this.color && typeof this.color.set_url !== 'string') {
this.log.warn("Ignoring request; problem with 'color' variables.");
callback(new Error("There was a problem parsing the 'color' section of your configuration."));
return;
}
this.log('Caching Saturation as %s ...', level);
this.cache.saturation = level;
if (this.cacheUpdated) {
this._setRGB(callback);
} else {
this.cacheUpdated = true;
callback();
}
},
/**
* Sets the RGB value of the device based on the cached HSB values.
*
* @param {function} callback The callback that handles the response.
*/
_setRGB: function(callback) {
var rgb = this._hsvToRgb(this.cache.hue, this.cache.saturation, this.cache.brightness);
var r = rgb.r;
var g = rgb.g;
var b = rgb.b;
var url = this.color.set_url.replace('{{RED}}', r).replace('{{GREEN}}', g).replace('{{BLUE}}', b);
this.cacheUpdated = false;
this._httpRequest(url, '', 'GET', callback);
},
/** Utility Functions **/
/**
* Perform an HTTP request.
*
* @param {string} url URL to call.
* @param {string} body Body to send.
* @param {method} method Method to use.
* @param {function} callback The callback that handles the response.
*/
_httpRequest: function(url, body, method, callback) {
request({
url: url,
body: body,
method: method,
rejectUnauthorized: false,
auth: {
user: this.username,
pass: this.password
}
},
function(error, response, body) {
callback(error, response, body);
});
},
/**
* Converts an HSV color value to RGB. Conversion formula
* adapted from http://stackoverflow.com/a/17243070/2061684
* Assumes h in [0..360], and s and l in [0..100] and
* returns r, g, and b in [0..1].
*
* @param {Number} h The hue
* @param {Number} s The saturation
* @param {Number} l The lightness
* @return {Array} The RGB representation
*/
_hsvToRgb: function(h, s, v) {
var r, g, b, i, f, p, q, t;
h /= 360;
s /= 100;
v /= 100;
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
var rgb = { r: r, g: g, b: b };
return rgb;
},
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are in [0..1] and
* returns h in [0..360], and s and l in [0..100].
*
* @param {Number} r The red color value
* @param {Number} g The green color value
* @param {Number} b The blue color value
* @return {Array} The HSL representation
*/
_rgbToHsl: function(r, g, b){
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if(max == min){
h = s = 0; // achromatic
}else{
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
h *= 360; // return degrees [0..360]
s *= 100; // return percent [0..100]
l *= 100; // return percent [0..100]
return {h: parseInt(h), s: parseInt(s), l: parseInt(l)};
},
};