forked from jnovack/homebridge-better-http-rgb
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
707 lines (613 loc) · 26.5 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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
// ISC License - Copyright 2018, Sander van Woensel
// TODO: colorsys usage?
// enable coverage measurement.
// -----------------------------------------------------------------------------
// Constants
// -----------------------------------------------------------------------------
const PACKAGE_JSON = require('./package.json');
const MANUFACTURER = PACKAGE_JSON.author.name;
const SERIAL_NUMBER = '001';
const MODEL = PACKAGE_JSON.name;
const FIRMWARE_REVISION = PACKAGE_JSON.version;
const IDENTIFY_BLINK_DELAY_MS = 250; // [ms]
const DEFAULT_BRIGHTNESS_MAX = 100;
// -----------------------------------------------------------------------------
// Module variables
// -----------------------------------------------------------------------------
var Service, Characteristic;
var request = require('request');
var api;
var convert = require('color-convert');
// -----------------------------------------------------------------------------
// Exports
// -----------------------------------------------------------------------------
//! @module homebridge
//! @param {object} homebridge Export functions required to create a
//! new instance of this plugin.
module.exports = function(homebridge){
api = homebridge;
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory(MODEL, 'HttpPushRgb', HttpPushRgb);
};
// -----------------------------------------------------------------------------
// Module functions
// -----------------------------------------------------------------------------
/**
* Parse the config and instantiate the object.
*
* @constructor
* @param {function} log Logging function.
* @param {object} config The configuration object.
*/
function HttpPushRgb(log, config) {
this.log = log;
this.service = null;
this.serviceCategory = config.service;
this.name = config.name || 'RGB Light';
this.http_method = config.http_method || 'GET';
this.username = config.username || '';
this.password = config.password || '';
this.timeout = config.timeout || 10000;
// Handle the basic on/off
this.switch = { powerOn: {}, powerOff: {}, status: {} };
if (typeof config.switch === 'object') {
this.switch.status.bodyRegEx = new RegExp("1");
// Intelligently handle if config.switch.status is an object or string.
if (typeof config.switch.status === 'object') {
this.switch.status.url = config.switch.status.url;
// Verify type of body regular expression parameter.
if (typeof config.switch.status.bodyRegEx === "string") {
this.switch.status.bodyRegEx = new RegExp(config.switch.status.bodyRegEx);
}
else {
this.log("Property 'switch.status.bodyRegEx' was provided in an unsupported type. Using default one!");
}
} else {
this.switch.status.url = 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;
}
// Register notification server.
api.on('didFinishLaunching', function() {
// Check if notificationRegistration is set and user specified notificationID.
// if not 'notificationRegistration' is probably not installed on the system.
if (global.notificationRegistration && typeof global.notificationRegistration === "function" &&
config.switch.notificationID) {
try {
global.notificationRegistration(config.switch.notificationID, this.handleNotification.bind(this), config.switch.notificationPassword);
} catch (error) {
// notificationID is already taken.
}
}
}.bind(this));
}
// Local caching of HSB color space for RGB callback
this.cache = {};
this.cacheUpdated = false;
// Handle brightness
if (typeof config.brightness === 'object') {
this.brightness = {status: {}, set_url: {}};
if (typeof config.brightness.status === 'object') {
this.brightness.status.url = config.brightness.status.url;
this.brightness.status.bodyRegEx = new RegExp(config.brightness.status.bodyRegEx);
} else {
this.brightness.status.url = config.brightness.status;
}
if (typeof config.brightness.url === 'object') {
this.brightness.set_url.url = config.brightness.url.url || this.brightness.status.url;
this.brightness.set_url.body = config.brightness.url.body || '';
} else {
this.brightness.set_url.url = config.brightness.url || this.brightness.status.url;
this.brightness.set_url.body = '';
}
this.brightness.http_method = config.brightness.http_method || this.http_method;
this.brightness.max = config.brightness.max || DEFAULT_BRIGHTNESS_MAX;
this.cache.brightness = 0;
} else {
this.brightness = false;
this.cache.brightness = 100;
}
// Color handling
if (typeof config.color === 'object') {
this.color = {"set_url": {}, "get_url": {}};
if (typeof config.color.url === 'object') {
this.color.set_url.url = config.color.url.url || this.color.status;
this.color.set_url.body = config.color.url.body;
} else {
this.color.set_url.url = config.color.url || this.color.status;
this.color.set_url.body = '';
}
if (typeof config.color.status === 'object') {
this.color.get_url.url = config.color.status.url;
this.color.get_url.bodyRegEx = config.color.status.bodyRegEx || '';
} else {
this.color.get_url.url = config.color.status;
this.color.get_url.bodyRegEx = '';
}
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 HttpPushRgb
*/
HttpPushRgb.prototype = {
// Required Functions
/**
* Blink device to allow user to identify its location.
*/
identify: function(callback) {
this.log('Identify requested!');
this.getPowerState( (error, onState) => {
// eslint-disable-next-line no-unused-vars
this.setPowerState(!onState, (error, responseBody) => {
// Ignore any possible error, just continue as if nothing happened.
setTimeout(() => {
this.setPowerState(onState, callback);
}, IDENTIFY_BLINK_DELAY_MS);
});
});
},
getServices: function() {
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, MANUFACTURER)
.setCharacteristic(Characteristic.SerialNumber, SERIAL_NUMBER)
.setCharacteristic(Characteristic.Model, MODEL)
.setCharacteristic(Characteristic.FirmwareRevision, FIRMWARE_REVISION);
switch (this.serviceCategory) {
case 'Light':
this.log('Creating Lightbulb');
this.service = new Service.Lightbulb(this.name);
if (this.switch.status) {
this.service
.getCharacteristic(Characteristic.On)
.on('get', this.getPowerState.bind(this))
.on('set', this.setPowerState.bind(this));
} else {
this.service
.getCharacteristic(Characteristic.On)
.on('set', this.setPowerState.bind(this));
}
// Handle brightness
if (this.has.brightness) {
this.log('... adding brightness');
this.service
.addCharacteristic(new Characteristic.Brightness())
.on('get', this.getBrightness.bind(this))
.on('set', this.setBrightness.bind(this));
}
// Handle color
if (this.color) {
this.log('... adding color');
this.service
.addCharacteristic(new Characteristic.Hue())
.on('get', this.getHue.bind(this))
.on('set', this.setHue.bind(this));
this.service
.addCharacteristic(new Characteristic.Saturation())
.on('get', this.getSaturation.bind(this))
.on('set', this.setSaturation.bind(this));
}
return [informationService, this.service];
case 'Switch':
this.log('creating Switch');
this.service = new Service.Switch(this.name);
if (this.switch.status) {
this.service
.getCharacteristic(Characteristic.On)
.on('get', this.getPowerState.bind(this))
.on('set', this.setPowerState.bind(this));
} else {
this.service
.getCharacteristic(Characteristic.On)
.on('set', this.setPowerState.bind(this));
}
return [informationService, this.service];
default:
return [informationService];
} // end switch
},
//** Custom Functions **//
/**
* Called by homebridge-http-notification-server
* whenever an accessory sends a status update.
*
* @param {function} jsonRequest The characteristic and characteristic value to update.
*/
handleNotification: function (jsonRequest) {
const characteristic = jsonRequest.characteristic;
const value = jsonRequest.value;
let characteristicType;
switch (characteristic) {
case "On":
characteristicType = Characteristic.On;
break;
default:
this.log("Encountered unknown characteristic when handling notification: " + jsonRequest.characteristic);
return;
}
this.ignoreNextSetPowerState = true; // See method setPowerStatus().
this.service.setCharacteristic(characteristicType, value); // This will also call setPowerStatus() indirectly.
},
/**
* Gets power state of lightbulb.
*
* @param {function} callback The callback that handles the response.
*/
getPowerState: function(callback) {
if (!this.switch.status.url) {
this.log.warn('Ignoring request, switch.status not defined.');
callback(new Error('No switch.status url defined.'));
return;
}
var url = this.switch.status.url;
this._httpRequest(url, '', 'GET', function(error, response, responseBody) {
if (!this._handleHttpErrorResponse('getPowerState()', error, response, responseBody, callback)) {
var powerOn = this.switch.status.bodyRegEx.test(responseBody)
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;
}
// Prevent an infinite loop when setCharacteristic() from
// handleNotification() also indirectly calls setPowerState.
if (this.ignoreNextSetPowerState) {
this.ignoreNextSetPowerState = false;
callback();
return;
}
if (state) {
url = this.switch.powerOn.set_url;
body = this.switch.powerOn.body;
} else {
url = this.switch.powerOff.set_url;
body = this.switch.powerOff.body;
}
this._httpRequest(url, body, this.http_method, function(error, response, responseBody) {
if (!this._handleHttpErrorResponse('setPowerState()', error, response, responseBody, callback)) {
this.log('setPowerState() successfully set to %s', state ? 'ON' : 'OFF');
callback();
}
}.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.url, '', 'GET', function(error, response, responseBody) {
if (!this._handleHttpErrorResponse('getBrightness()', error, response, responseBody, callback)) {
var level;
if (typeof this.brightness.status.bodyRegEx === 'object') {
level = parseInt(responseBody.match(this.brightness.status.bodyRegEx)[1]);
} else {
level = parseInt(responseBody);
}
level = parseInt(100 / this.brightness.max * level);
this.log('brightness is currently at %s%', level);
callback(null, level);
}
}.bind(this));
} else {
if(this.color.brightness) {
var url = this.color.get_url.url;
this._httpRequest(url, '', 'GET', function(error, response, responseBody) {
if (!this._handleHttpErrorResponse('getBrightness()', error, response, responseBody, callback)) {
var rgb = responseBody;
var levels = this._rgbToHsl(
parseInt(rgb.substr(0,2),16),
parseInt(rgb.substr(2,2),16),
parseInt(rgb.substr(4,2),16)
);
var brightness = levels[2];
this.log('... brightness is currently %s. RGB: %s', brightness, rgb);
this.cache.brightness = brightness;
callback(null, brightness);
}
}.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.log('Caching Brightness as %s ...', level);
this.cache.brightness = level;
// If achromatic or color.brightness is false, update brightness, otherwise, update HSL as RGB
if (!this.color || !this.color.brightness) {
var calculatedLevel = Math.ceil(this.brightness.max / 100 * level);
var url = this.brightness.set_url.url.replace('%s', calculatedLevel);
var body = this.brightness.set_url.body.replace('%s', calculatedLevel);
this._httpRequest(url, body, this.brightness.http_method, function(error, response, responseBody) {
if (!this._handleHttpErrorResponse('setBrightness()', error, response, responseBody, callback)) {
this.log('setBrightness() successfully set to %s%', level);
callback();
}
}.bind(this));
} else {
this.log("Setting brightness via RGB.");
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.get_url.url !== 'string') {
this.log.warn("Ignoring getHue request; problem with 'color' variables.");
callback(new Error("There was a problem parsing the 'color.status' section of your configuration."));
return;
}
var url = this.color.get_url.url;
this._httpRequest(url, '', 'GET', function(error, response, responseBody) {
if (!this._handleHttpErrorResponse('getHue()', error, response, responseBody, callback)) {
var rgb = responseBody;
var levels = this._rgbToHsl(
parseInt(rgb.substr(0,2),16),
parseInt(rgb.substr(2,2),16),
parseInt(rgb.substr(4,2),16)
);
var hue = levels[0];
this.log('... hue is currently %s. RGB: %s', hue, rgb);
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.url!== 'string') {
this.log.warn("Ignoring setHue 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.get_url.url !== 'string') {
this.log.warn("Ignoring getSaturation request; problem with 'color' variables.");
callback(new Error("There was a problem parsing the 'color' section of your configuration."));
return;
}
var url = this.color.get_url.url;
this._httpRequest(url, '', 'GET', function(error, response, responseBody) {
if (!this._handleHttpErrorResponse('getSaturation()', error, response, responseBody, callback)) {
var rgb = responseBody;
var levels = this._rgbToHsl(
parseInt(rgb.substr(0,2),16),
parseInt(rgb.substr(2,2),16),
parseInt(rgb.substr(4,2),16)
);
var saturation = levels[1];
this.log('... saturation is currently %s. RGB: %s', saturation, rgb);
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.url !== 'string') {
this.log.warn("Ignoring setSaturation 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 rgbRequest = this._buildRgbRequest();
this.cacheUpdated = false;
this._httpRequest(rgbRequest.url, rgbRequest.body, this.color.http_method, function(error, response, responseBody) {
if (!this._handleHttpErrorResponse('_setRGB()', error, response, responseBody, callback)) {
this.log('... _setRGB() successfully set');
callback();
}
}.bind(this));
},
_buildRgbRequest: function() {
var rgb = convert.hsv.rgb([this.cache.hue, this.cache.saturation, this.cache.brightness]);
var xyz = convert.rgb.xyz(rgb);
var hex = convert.rgb.hex(rgb);
if(xyz == null || xyz.size == 0) {
this.log.error("Failed to convert HSB to xyz values. Cached values: H:%s S:%s B:%s", this.cache.hue, this.cache.saturation, this.cache.brightness);
return {url: '', body: ''};
}
var xy = {
x: (xyz[0] / 100 / (xyz[0] / 100 + xyz[1] / 100 + xyz[2] / 100)).toFixed(4),
y: (xyz[1] / 100 / (xyz[0] / 100 + xyz[1] / 100 + xyz[2] / 100)).toFixed(4)
};
var url = this.color.set_url.url;
var body = this.color.set_url.body;
var replaces = {
'%s': hex,
'%xy-x': xy.x,
'%xy-y': xy.y
};
for (var key in replaces) {
url = url.replace(key, replaces[key]);
body = body.replace(key, replaces[key]);
}
this.log('_buildRgbRequest converting H:%s S:%s B:%s to RGB:%s ...', this.cache.hue, this.cache.saturation, this.cache.brightness, hex);
return {url: url, body: body};
},
// 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,
timeout: this.timeout,
rejectUnauthorized: false,
auth: {
user: this.username,
pass: this.password
}},
function(error, response, body) {
callback(error, response, body);
});
},
/**
* Verify if response code equals '200', otherwise log error and callback
* with a new Error object.
* @param {String} functionStr Description used to create log and error message.
* @param {Object} error Received error from client.
* @param {Object} response Received reponse from client.
* @param {Function} callback Reply function to call when error ocurred.
* @return {Boolean} true: Error occurred, false otherwise
*/
_handleHttpErrorResponse: function(functionStr, error, response, responseBody, callback) {
var errorOccurred = false;
if (error) {
this.log(functionStr +' failed: %s', error.message);
callback(error);
errorOccurred = true;
} else if (response.statusCode != 200) {
this.log(functionStr + ' returned HTTP error code: %s: "%s"', response.statusCode, responseBody);
callback( new Error("Received HTTP error code " + response.statusCode + ': "' + responseBody + '"') );
errorOccurred = true;
}
return errorOccurred;
},
/**
* 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..255] 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){
r /= 255;
g /= 255;
b /= 255;
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 [parseInt(h), parseInt(s), parseInt(l)];
},
/**
* Converts a decimal number into a hexidecimal string, with optional
* padding (default 2 characters).
*
* @param {Number} d Decimal number
* @param {String} padding Padding for the string
* @return {String} '0' padded hexidecimal number
*/
_decToHex: function(d, padding) {
var hex = Number(d).toString(16).toUpperCase();
padding = typeof (padding) === 'undefined' || padding === null ? padding = 2 : padding;
while (hex.length < padding) {
hex = '0' + hex;
}
return hex;
}
};