This repository has been archived by the owner on Dec 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
hue-extended.js
1284 lines (1083 loc) · 43 KB
/
hue-extended.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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const adapterName = require('./io-package.json').common.name;
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const _fs = require('fs');
const _request = require('request-promise');
const _color = require('color-convert');
const _hueColor = require('./lib/node-hue-api');
const _ctColor = require('./lib/ct-color-converter');
/*
* internal libraries
*/
const Library = require(__dirname + '/lib/library.js');
const _NODES = require(__dirname + '/_NODES.js').STATES;
const _MAPPING = require(__dirname + '/_NODES.js').MAPPING;
const _SUBSCRIPTIONS = require(__dirname + '/_NODES.js').SUBSCRIPTIONS;
const _MAPPING_BRIDGE = Object.keys(_MAPPING);
const _MAPPING_STATES = Object.values(_MAPPING);
/*
* variables initiation
*/
let adapter;
let library;
let unloaded, delay = 0, retry = 0;
let garbageCollector, refreshCycle;
let REQUEST_OPTIONS = { 'json': true };
let MAX_ATTEMPTS = 3;
let bridge, device;
let DEVICES = {};
let QUEUE = {};
/*
* ADAPTER
*
*/
function startAdapter(options)
{
options = options || {};
adapter = new utils.Adapter({ ...options, name: adapterName });
/*
* ADAPTER READY
*
*/
adapter.on('ready', function()
{
unloaded = false;
library = new Library(adapter, { nodes: _NODES, updatesInLog: adapter.config.debug || false });
// Check Node.js Version
let version = parseInt(process.version.substr(1, process.version.indexOf('.')-1));
if (version <= 6)
return library.terminate('This Adapter is not compatible with your Node.js Version ' + process.version + ' (must be >= Node.js v7).', true);
// Check Configuration
library.set(Library.CONNECTION, true);
if (!adapter.config.bridgeIp || !adapter.config.bridgeUser)
return library.terminate('Please provide connection settings for Hue Bridge!');
//
MAX_ATTEMPTS = adapter.config.maxAttempts || MAX_ATTEMPTS;
// Secure connection
REQUEST_OPTIONS.secureConnection = false;
if (adapter.config.secureConnection)
{
adapter.log.info('Establishing secure connection to bridge..');
try
{
REQUEST_OPTIONS = {
...REQUEST_OPTIONS,
'cert': adapter.config.certPublicPath.indexOf('.') === -1 ? adapter.config.certPublicPath : _fs.readFileSync(adapter.config.certPublicPath),
'key': adapter.config.certPrivatePath.indexOf('.') === -1 ? adapter.config.certPrivatePath : _fs.readFileSync(adapter.config.certPrivatePath),
'rejectUnauthorized': false,
'secureConnection': true
};
if (adapter.config.certChainedPath)
REQUEST_OPTIONS.ca = adapter.config.certChainedPath.indexOf('.') === -1 ? adapter.config.certChainedPath : _fs.readFileSync(adapter.config.certChainedPath);
if (REQUEST_OPTIONS.key.indexOf('ENCRYPTED') > -1)
REQUEST_OPTIONS.passphrase = adapter.config.passphrase;
}
catch(err)
{
adapter.log.warn('Establishing secure connection failed! Falling back to unsecure connection to bridge..');
adapter.log.debug(err.message);
REQUEST_OPTIONS.secureConnection = false;
}
}
else
adapter.log.info('Establishing connection to bridge..');
// Bridge connection
adapter.config.bridgePort = REQUEST_OPTIONS.secureConnection ? 443 : (adapter.config.bridgePort || 80);
bridge = (REQUEST_OPTIONS.secureConnection ? 'https://' : 'http://') + adapter.config.bridgeIp + ':' + adapter.config.bridgePort + '/api/' + adapter.config.bridgeUser + '/';
// retrieve all values from states to avoid message "Unsubscribe from all states, except system's, because over 3 seconds the number of events is over 200 (in last second 0)"
adapter.getStates(adapterName + '.' + adapter.instance + '.*', (err, states) =>
{
library.set(Library.CONNECTION, true);
// set current states from objects
for (let state in states)
library.setDeviceState(state.replace(adapterName + '.' + adapter.instance + '.', ''), states[state] && states[state].val);
// retrieve payload from Hue Bridge
getPayload(adapter.config.refresh || 30);
// add states for last action
readData(
'info',
{
'lastAction': {
'timestamp': library.getDeviceState('info.lastAction.timestamp'),
'datetime': library.getDeviceState('info.lastAction.datetime'),
'lastCommand': library.getDeviceState('info.lastAction.lastCommand'),
'lastResult': library.getDeviceState('info.lastAction.lastResult'),
'error': library.getDeviceState('info.lastAction.error')
}
},
''
);
// delete old states (which were not updated recently)
garbageCollector = setTimeout(function runGarbageCollector()
{
if (!unloaded && adapter.config.garbageCollector)
{
library.runGarbageCollector(adapterName + '.' + adapter.instance, true, 24*60*60); // delete states older than 24h
garbageCollector = setTimeout(runGarbageCollector, 60*60*1000); // run every hour
}
}, 1*60*1000);
});
// start listening for events in the queue
queue();
});
/*
* STATE CHANGE
*
*/
adapter.on('stateChange', function(id, state)
{
if (state === undefined || state === null || state.ack === true || state.val === undefined || state.val === null) return;
adapter.log.debug('State of ' + id + ' has changed ' + JSON.stringify(state) + '.');
// get params & action
let params = id.replace(adapterName + '.' + adapter.instance + '.', '').split('.');
let action = params.pop();
let path = params.join('.');
// appliance data
let appliance = {};
appliance.path = path.substr(0, path.lastIndexOf('.'));
appliance.type = params.splice(0,1).toString();
appliance.name = library.getDeviceState(appliance.path + '.name');
appliance.uid = library.getDeviceState(appliance.path + '.uid');
appliance.trigger = appliance.type + '/' + appliance.uid + '/' + (appliance.type == 'groups' ? 'action' : (appliance.type == 'sensors' ? 'config' : 'state'));
// no uid
if (!appliance.uid) {
adapter.log.warn('Command can not be send to device due to error (no UID)!');
return false;
}
// reset if scene was set
if (action == 'scene') {
library._setValue(id, '');
}
// build command
let commands = { [action]: state.val };
// override with provided commands
if (action == '_commands') {
try {
library._setValue(id, '');
commands = JSON.parse(state.val);
}
catch(err) {
adapter.log.warn('Commands supplied in wrong format! Format shall be {"command": value}, e.g. {"on": true} (with parenthesis).');
adapter.log.debug(err.message);
return false;
}
}
// handle sccene
if (appliance.type == 'scenes') {
// set scene
let scene = {
'uid': library.getDeviceState(appliance.path + '.uid'),
'name': library.getDeviceState(appliance.path + '.name'),
'type': library.getDeviceState(appliance.path + '.type'),
'groupId': library.getDeviceState(appliance.path + '.group'),
'lights': library.getDeviceState(appliance.path + '.lights')
};
// modify transitiontime
if (action == 'transitiontime') {
// get current lightstates
_request({ ...REQUEST_OPTIONS, 'uri': bridge + 'scenes/' + scene.uid }).then(s => {
if (s.lightstates && typeof s.lightstates == 'object') {
// set lightstates including transitiontime
for (let key in s.lightstates) {
let lightstate = s.lightstates[key];
lightstate.transitiontime = state.val;
_request({
...REQUEST_OPTIONS,
uri: bridge + 'scenes/' + scene.uid + '/lightstates/' + key,
method: 'PUT',
body: s.lightstates[key]
})
.then(function(res) {
adapter.log.info('Set transitiontime of scene ' + scene.name + ' (' + scene.uid + ') to ' + state.val + '.');
});
}
}
});
library._setValue(id, '');
return false;
}
// GroupScene
if (scene.type == 'GroupScene')
{
appliance.trigger = 'groups/' + scene.groupId + '/action';
appliance.name = DEVICES['groups'][scene.groupId].name + ' (' + scene.name + ')';
commands = { 'scene': appliance.uid };
}
// LightScene
else if (scene.type == 'LightScene')
{
appliance.trigger = 'groups/0/action';
appliance.name = 'lights (' + scene.name + ')';
commands = { 'scene': appliance.uid };
}
// LabScene
else if (scene.type == 'LabScene')
{
let options = null;
try
{
options = JSON.parse(library.getDeviceState(appliance.path + '.action.options'));
appliance.method = options.method;
appliance.trigger = 'sensors/' + options.address;
commands = options.body;
}
catch(err)
{
adapter.log.warn('Invalid scene data given!');
adapter.log.debug(err.message);
return false;
}
}
// Error
else
{
adapter.log.warn('Invalid scene type given! Must bei either GroupScene, LightScene or LabScene.');
return false;
}
}
// handle schedules
else if (appliance.type == 'schedules' || appliance.type == 'rules')
{
let options = null;
try
{
options = JSON.parse(library.getDeviceState(appliance.path + '.action.options'));
appliance.method = options.method;
appliance.trigger = options.address;
commands = options.body;
}
catch(err)
{
adapter.log.warn('Invalid schedules data given!');
adapter.log.debug(err.message);
return false;
}
}
// handle lights or groups
else if (appliance.type == 'lights' || appliance.type == 'groups')
{
let lights = appliance.type == 'lights' ? [appliance.uid] : DEVICES['groups'][appliance.uid].lights;
// handle color spaces
let value = commands[action];
let rgb = null, hsv = null;
if (action == 'rgb')
{
rgb = value.split(',');
hsv = _color.rgb.hsv(rgb);
}
else if (action == 'hsv')
hsv = value.split(',');
else if (action == 'cmyk')
hsv = _color.cmyk.hsv(value.split(','));
else if (action == 'xyz')
hsv = _color.xyz.hsv(value.split(','));
else if (action == 'hex')
hsv = _color.hex.hsv(value.split(','));
if (hsv !== null)
{
delete commands[action];
commands = {
'hue': hsv[0],
'sat': Math.max(Math.min(Math.round(hsv[1]*2.54), 254), 0),
'bri': Math.max(Math.min(Math.round(hsv[2]*2.54), 254), 0),
...commands
};
}
// check for each light, if hue lab scene is activated
//
// this has to be done for each light, because hue labs scenes might be activated for multiple groups
// and multiple groups are reflected by a single virtual group in the Hue API
//
let xySupported = [];
let manufacturers = [];
let hueLabScene;
for (let index in lights)
{
// light identifier
let light = lights[index];
let lightId = library.clean(DEVICES['lights'][light].name, true, '_').replace(/\./g, '-');
let lightUid = adapter.config.nameId == 'append' ? light : ('00' + light).substr(-3);
// check for activated hue lab scene
hueLabScene = library.getDeviceState('lights.' + (adapter.config.nameId == 'append' ? lightId + '-' + lightUid : lightUid + '-' + lightId) + '.action.hueLabScene');
if (hueLabScene)
{
// turn off hue lab scene
let command = DEVICES['scenes'][hueLabScene].command;
if (command.body && command.body.status === 0)
{
library.setDeviceState(appliance.path + '.action.hueLabScene', '');
sendCommand({ 'type': 'scenes', 'path': DEVICES['scenes'][hueLabScene].path, 'name': DEVICES['scenes'][hueLabScene].name, 'trigger': command.address, 'method': command.method }, command.body);
}
}
// get manufacturers
manufacturers.push(library.getDeviceState('lights.' + (adapter.config.nameId == 'append' ? lightId + '-' + lightUid : lightUid + '-' + lightId) + '.manufacturername'));
xySupported.push(library.getDeviceState('lights.' + (adapter.config.nameId == 'append' ? lightId + '-' + lightUid : lightUid + '-' + lightId) + '.action.xy'));
}
// go through commands and modify if required
let obj;
for (action in commands)
{
value = commands[action];
obj = action;
// remap states back due to standardization
let remapped = _MAPPING_STATES.indexOf(action);
if (remapped > -1)
{
let key = _MAPPING_BRIDGE[remapped];
commands[key] = commands[action];
delete commands[action];
action = key;
}
// if device is turned off, set brightness to 0
// NOTE: Brightness is a scale from 1 (the minimum the light is capable of) to 254 (the maximum).
if (action == 'on' && value == false && library.getDeviceState(appliance.path + '.action.brightness') !== null && commands.level === undefined && commands.bri === undefined && adapter.config.briWhenOff)
{
library.setDeviceState(appliance.path + '.action.real_brightness', library.getDeviceState(appliance.path + '.action.brightness') || 0);
library._setValue(appliance.path + '.action.brightness', 0);
library._setValue(appliance.path + '.action.level', 0);
}
// if device is turned on, make sure brightness is not 0
if (action == 'on' && value == true && library.getDeviceState(appliance.path + '.action.brightness') !== null && commands.level === undefined && commands.bri === undefined)
{
let bri = adapter.config.briWhenOff ? library.getDeviceState(appliance.path + '.action.real_brightness') : library.getDeviceState(appliance.path + '.action.brightness');
commands.bri = !bri || bri == 0 ? 254 : bri;
}
// if .level is changed the change will be applied to .brightness instead
if (action == 'level' && value > 0)
{
delete commands[action];
Object.assign(commands, { on: true, bri: Math.max(Math.min(Math.round(value*2.54), 254), 0) });
}
// if .bri is changed, make sure light is on
if (action == 'bri' && value > 0)
{
library.setDeviceState(appliance.path + '.action.real_brightness', value);
Object.assign(commands, { on: true, bri: value });
}
// if .bri is changed to 0, turn off
if ((action == 'bri' || action == 'level') && value <= 0)
{
delete commands['level'];
Object.assign(commands, { on: false }); // , bri: 0
}
// convert value ranges
if (action == 'hue' && value <= 360)
commands.hue = Math.max(Math.min(Math.round(value / 360 * 65535), 65535), 0);
if (action == 'ct' && value > 500)
commands.ct = Math.max(Math.min(Math.round(1 / value * 1000000), 500), 153);
}
// convert HUE / CT to XY
if (adapter.config.hueToXY && (commands.hue !== undefined || commands.ct !== undefined))
adapter.log.debug('Converting ' + JSON.stringify(commands) + ' to xy: ' + JSON.stringify(lights) + ' - ' + JSON.stringify(manufacturers) + ' - ' + JSON.stringify(xySupported));
if (((commands.hue !== undefined && adapter.config.hueToXY) || (commands.ct !== undefined && adapter.config.ctToXY)) && manufacturers.filter(manufacturer => manufacturer.indexOf('Philips') === -1 && manufacturer.indexOf('Signify') === -1).length > 0 && xySupported.indexOf(null) == -1)
{
if (!rgb)
{
if (commands.ct !== undefined && adapter.config.ctToXY)
{
rgb = _ctColor.convertCTtoRGB(Math.max(Math.min(Math.round(1 / commands.ct * 1000000), 6500), 2000));
delete commands.ct;
}
else if (commands.hue !== undefined && adapter.config.hueToXY)
{
rgb = hsv ? _color.hsv.rgb(hsv) : _color.hsv.rgb([commands.hue, (commands.sat || library.getDeviceState(appliance.path + '.action.saturation')), commands.bri || library.getDeviceState(appliance.path + '.action.brightness')]);
delete commands.hue;
}
}
if (rgb === null || rgb[0] === undefined || rgb[0] === null)
adapter.log.warn('Invalid RGB given (' + JSON.stringify(rgb) + ')!');
else
commands.xy = _hueColor.convertRGBtoXY(rgb);
}
// if .on is not off, be sure device is on (except for alerts)
if (commands.on === undefined && commands.alert === undefined)
commands.on = true; // A light cannot have its hue, saturation, brightness, effect, ct or xy modified when it is turned off. Doing so will return 201 error.
}
// queue commands
if (adapter.config.useQueue)
addToQueue(appliance, commands);
else
sendCommand(appliance, commands);
});
/*
* HANDLE MESSAGES
*
*/
adapter.on('message', function(msg)
{
adapter.log.debug('Message: ' + JSON.stringify(msg));
switch(msg.command)
{
case 'getUser':
getUser(msg.message.bridgeIp, msg.message.bridgePort || 80, username =>
{
adapter.log.debug('Retrieved user from Hue Bridge: ' + JSON.stringify(username));
library.msg(msg.from, msg.command, {result: true, user: username}, msg.callback);
}, error =>
{
adapter.log.warn('Failed retrieving user (' + error + ')!');
library.msg(msg.from, msg.command, {result: false, error: error}, msg.callback);
});
break;
}
});
/*
* ADAPTER UNLOAD
*
*/
adapter.on('unload', function(callback)
{
try
{
adapter.log.info('Adapter stopped und unloaded.');
unloaded = true;
library.resetStates();
clearTimeout(refreshCycle);
clearTimeout(garbageCollector);
callback();
}
catch(e)
{
callback();
}
});
return adapter;
};
/*
* COMPACT MODE
* If started as allInOne/compact mode => returnfunction to create instance
*
*/
if (module && module.parent)
module.exports = startAdapter;
else
startAdapter(); // or start the instance directly
/**
*
*
*/
function getPayload(refresh)
{
// get data from bridge
_request({ ...REQUEST_OPTIONS, 'uri': bridge }).then(payload =>
{
if (!payload || (payload[0] && payload[0].error))
{
adapter.log.error('Error retrieving payload from Hue Bridge' + (payload[0] && payload[0].error ? ': ' + payload[0].error.description : '!'));
return false;
}
// add meta data
library.set({ ...library.getNode('datetime'), 'node': 'info.datetime' }, library.getDateTime(Date.now()));
library.set({ ...library.getNode('timestamp'), 'node': 'info.timestamp' }, Math.floor(Date.now()/1000));
library.set({ ...library.getNode('syncing'), 'node': 'info.syncing' }, true);
// read hue labs from payload
if (adapter.config.syncScenes && adapter.config.syncHueLabsScenes)
{
// find "huelabs" in resourcelinks
let formulas = [];
for (let key in payload['resourcelinks'])
{
let resourcelink = payload['resourcelinks'][key];
if (resourcelink && resourcelink.name == 'HueLabs 2.0')
{
// get formulas
formulas = resourcelink.links.map(formula => payload['resourcelinks'][formula.substr(formula.lastIndexOf('/')+1)]);
break;
}
}
// get formula trigger
formulas.forEach((formula, i) =>
{
for (let index in formula.links)
{
let link = formula.links[index];
let id = link.substr(link.lastIndexOf('/')+1);
// add sensor data to scene
if (link && link.indexOf('sensors') > -1)
{
let sensor = payload['sensors'][id];
if (sensor && sensor.manufacturername == 'Philips' && sensor.modelid == 'HUELABSVTOGGLE')
{
formulas[i].state = { 'on': (sensor.state.status == 1), ...sensor.state };
formulas[i].command = { 'address': '/sensors/' + id + '/state', 'body': {"status": (1-sensor.state.status)}, 'method': 'PUT' };
}
}
// add group data to scene
else if (link && link.indexOf('groups') > -1)
{
formulas[i].group = id;
formulas[i].type = 'LabScene';
}
}
// add huelab scene to ordinary scenes
if (formulas[i].group && formulas[i].command)
payload['scenes'][library.clean(formula.description)] = formulas[i];
});
}
// go through channels
for (let channel in payload)
{
// create channel
library.set({
'node': channel,
'role': 'channel',
'description': library.ucFirst(channel.substr(channel.lastIndexOf('.')+1))
});
// sync all groups
if (channel == 'groups')
{
_request({ ...REQUEST_OPTIONS, 'uri': bridge + channel + '/0' }).then(pl =>
{
pl.name = 'All Lights';
// index
DEVICES[channel] = JSON.parse(JSON.stringify(payload[channel]));
DEVICES[channel][0] = JSON.parse(JSON.stringify(pl));
// only write if syncing is on
if (adapter.config['sync' + library.ucFirst(channel)])
addBridgeData(channel, { '0': pl });
}).catch(err => {});
}
else
DEVICES[channel] = JSON.parse(JSON.stringify(payload[channel])); // copy and index payload
// only write if syncing is on
if (adapter.config['sync' + library.ucFirst(channel)])
{
// update overall syncing information
library.set({ ...library.getNode('datetime'), 'node': 'info.datetime' }, library.getDateTime(Date.now()));
library.set({ ...library.getNode('timestamp'), 'node': 'info.timestamp' }, Math.floor(Date.now()/1000));
library.set({ ...library.getNode('syncing'), 'node': 'info.syncing' }, true);
library.set({ ...library.getNode('syncing'), 'node': 'info.syncing' + library.ucFirst(channel) }, true);
library.set({ ...library.getNode('syncing'), 'node': channel + '.syncing' }, true);
// add to states
addBridgeData(channel, payload[channel]);
}
else
{
library.set({ ...library.getNode('syncing'), 'node': channel + '.syncing' }, false);
library.set({ ...library.getNode('syncing'), 'node': 'info.syncing' + library.ucFirst(channel) }, false);
}
}
// refresh interval
retry = 0;
const maxRefresh = 2;
if (refresh > 0 && refresh < maxRefresh)
{
adapter.log.warn('Due to performance reasons, the refresh rate can not be set to less than ' + maxRefresh + ' seconds. Using ' + maxRefresh + ' seconds now.');
refresh = maxRefresh;
}
if (refresh > 0 && !unloaded)
refreshCycle = setTimeout(getPayload, refresh*1000, refresh);
}).catch(err =>
{
// Indicate that tree is not synchronized anymore
library.set({ ...library.getNode('syncing'), 'node': 'info.syncing' }, false);
//library.set({ ...library.getNode('syncing'), 'node': 'info.syncing' + library.ucFirst(channel) }, false);
//library.set({ ...library.getNode('syncing'), 'node': channel + '.syncing' }, false);
// ERROR
let error = err.message;
// ERROR: HTTP 500
if (err.message.substr(0, 3) == 500)
error = 'Hue Bridge is busy';
// ERROR: HTTP 502
else if (err.message.substr(0, 3) == 502)
error = '502 Bad Gateway';
// ERROR: ECONNREFUSED
else if (err.message.indexOf('ECONNREFUSED') > -1)
error = 'Connection refused';
// ERROR: EHOSTUNREACH
else if (err.message.indexOf('EHOSTUNREACH') > -1)
error = 'Host not reachable';
// ERROR: SOCKET HANG UP
else if (err.message.indexOf('socket hang up') > -1)
error = 'Socket hang up';
// TRY AGAIN OR STOP ADAPTER
if (!retry || retry < 10)
{
adapter.log.debug('Error connecting to Hue Bridge: ' + error + '. ' + (retry > 0 ? 'Already retried ' + retry + 'x so far. ' : '') + 'Try again in 10 seconds..');
//adapter.log.debug(err.message);
//adapter.log.debug(JSON.stringify(err.stack));
retry = !retry ? 1 : retry+1;
refreshCycle = setTimeout(getPayload, 10*1000, refresh);
}
else
{
library.terminate('Error connecting to Hue Bridge: ' + error + '. ' + (retry > 0 ? 'Already retried ' + retry + 'x in total, thus connection closed now.' : 'Connection closed.') + ' See debug log for details.');
adapter.log.debug(err.message);
adapter.log.debug(JSON.stringify(err.stack));
}
});
}
/**
*
*/
function addBridgeData(channel, data)
{
// add meta data
library.set({ ...library.getNode('datetime'), 'node': channel + '.datetime' }, library.getDateTime(Date.now()));
library.set({ ...library.getNode('timestamp'), 'node': channel + '.timestamp' }, Math.floor(Date.now()/1000));
library.set({ ...library.getNode('syncing'), 'node': channel + '.syncing' }, true);
// loop through payload
device = null;
readData(channel, data, channel);
}
/**
*
*/
function readData(key, data, channel)
{
// only proceed if data is given
if (data === undefined || data === 'undefined')
return false;
// skip recycled
if (channel && !adapter.config['sync' + library.ucFirst(channel) + 'Recycled'] && data && data.recycle === true && !(channel == 'scenes' && adapter.config.syncHueLabsScenes && data.type == 'LabScene'))
{
adapter.log.silly('Skipping device ' + data['name'] + ' in channel ' + channel + '.');
return false;
}
// set current device name
if (data && data.name)
device = data.name;
// get node details
key = key.replace(/ /g, '_');
let node = get(key.split('.'));
// loop nested data
if (data !== null && typeof data == 'object' && !(Array.isArray(data) && (key.substr(-2) == 'xy' || key.substr(-6) == 'lights' || key.substr(-7) == 'sensors' || key.substr(-5) == 'links')))
{
// create channel
if (Object.keys(data).length > 0)
{
let description = false;
// add last seen date
if (data.name) {
data.lastSeen = library.getDateTime(Date.now());
}
// use uid and name instead of only uid
let id = false;
if (data.name && channel != 'config' && channel != 'scenes' && channel != 'resourcelinks')
{
data.uid = key.substr(key.lastIndexOf('.')+1);
id = library.clean(data.name, true, '_').replace(/\./g, '-');
let uid = ('00' + data.uid).substr(-3);
// append UID
if (adapter.config.nameId == 'append')
key = key.replace('.' + data.uid, '.' + id + '-' + data.uid);
// prepend UID
else
key = key.replace('.' + data.uid, '.' + uid + '-' + id);
}
// add uid to scenes
else if (data.name && channel == 'scenes') {
data.uid = key.substr(key.lastIndexOf('.')+1);
}
// change state for groups
if (data.any_on) {
data.on = data.any_on;
}
// change state for resourcelinks
if (data.name && channel == 'resourcelinks')
{
data.uid = key.substr(key.lastIndexOf('.')+1);
id = library.clean(data.name, true, '_').replace(/\./g, '-');
key = key.replace('.' + data.uid, '.' + id);
}
// change state for rules
if (channel == 'rules' && key.substr(-7) == 'actions')
{
key = key.replace('.actions', '.action');
let states = {};
let action;
data.forEach(trigger =>
{
action = Object.keys(trigger.body).join('-');
states[library.clean(action, true, '-')] = { 'trigger': false, 'options': JSON.stringify(trigger) };
});
data = states;
}
// change state for scenes
if (data.type == 'GroupScene' || data.type == 'LightScene')
data.action = {
'trigger': false,
'transitiontime': ''
};
// change state for schedules / scenes
if ((channel == 'schedules' || channel == 'scenes') && key.substr(-7) == 'command')
{
key = key.replace('.command', '') + '.action';
data.address = data.address.substr(data.address.indexOf('/', 5)+1, data.address.length);
data = channel == 'schedules' ? { 'trigger': false, 'options': JSON.stringify(data) } : { 'options': JSON.stringify(data) };
}
// add additional states level, scene, _commands and lastAction
if (data.bri !== undefined)
{
data.level = data.bri > 0 ? Math.max(Math.min(Math.round(data.bri/2.54), 100), 0) : 0;
data.scene = '';
data._commands = '';
// add states for last action
readData(
key.replace('.state', '.action'),
{
'lastAction': {
'timestamp': library.getDeviceState(key.replace('.state', '.action') + '.lastAction.timestamp'),
'datetime': library.getDeviceState(key.replace('.state', '.action') + '.lastAction.datetime'),
'lastCommand': library.getDeviceState(key.replace('.state', '.action') + '.lastAction.lastCommand'),
'lastResult': library.getDeviceState(key.replace('.state', '.action') + '.lastAction.lastResult'),
'error': library.getDeviceState(key.replace('.state', '.action') + '.lastAction.error')
}
},
channel
);
}
// convert value ranges
if (data.hue !== undefined)
data.hue = Math.max(Math.min(Math.round(data.hue / 65535 * 360), 360), 0);
if (data.ct !== undefined && typeof data.ct !== 'object')
data.ct = Math.max(Math.min(Math.round(1 / data.ct * 1000000), 6500), 2000);
// add additional color spaces
if (data.bri !== undefined && data.sat !== undefined && data.hue !== undefined)
{
data.transitiontime = data.transitiontime || 4;
data.hsv = data.hue + ','+ (data.sat > 0 ? Math.max(Math.min(Math.round(data.sat/2.54), 100), 0) : 0) + ',' + data.level;
data.rgb = _color.hsv.rgb(data.hsv.split(',')).toString();
//data.cmyk = _color.rgb.cmyk(data.rgb.split(',')).toString();
//data.xyz = _color.rgb.xyz(data.rgb.split(',')).toString();
data.hex = _color.rgb.hex(data.rgb.split(','));
}
// set brightness to 0 when device is off
let real_bri = library.getDeviceState(key.replace('.state', '.action') + '.real_brightness');
if (data.bri !== undefined && data.on == false && adapter.config.briWhenOff)
{
data.bri = 0;
data.level = 0;
}
else if (data.bri !== undefined && data.on == true && real_bri != data.bri && adapter.config.briWhenOff)
library.setDeviceState(key.replace('.state', '.action') + '.real_brightness', data.bri);
// remap states for standardization (see https://github.com/Zefau/ioBroker.hue-extended/issues/1 and https://forum.iobroker.net/post/298019)
for (let state in _MAPPING)
{
if (data[state] !== undefined && typeof data[state] !== 'object')
{
data[_MAPPING[state]] = data[state];
delete data[state];
}
}
// create sub channel for scenes
let pathKey = '';
if (channel == 'scenes' && (((data.type == 'GroupScene' || data.type == 'LabScene') && data.group) || (data.type == 'LightScene' && data.lights && data.lights[0])))
{
// skips if groups are not indexed so far
if ((data.type == 'GroupScene' || data.type == 'LabScene') && (!DEVICES['groups'] || !DEVICES['groups'][data.group]))
{
adapter.log.silly('Groups not yet given, thus scene ' + data.name + ' (' + data.uid + ') skipped for now.');
return false;
}
// LightScene
let pathDescription = '';
if (data.type == 'LightScene')
{
key = key.replace('.' + data.uid, adapter.config.sceneNaming == 'scene' ? '.' + id : '.LightScenes');
pathKey = '.' + library.clean(data.name, true, '_').replace(/\./g, '-') + '_' + data.lights.join('-');
description = 'Light Scenes';
pathDescription = 'Scene ' + data.name + ' for ' + (data.lights.length > 1 ? 'lights ' + data.lights.join(', ') : 'light ' + data.lights[0]);
}
// GroupScene or LabScene
else
{
let groupId = library.clean(DEVICES['groups'][data.group].name, true, '_').replace(/\./g, '-');
let groupUid = adapter.config.nameId == 'append' ? data.group : ('00' + data.group).substr(-3);
let group = data.type == 'LabScene' && (!adapter.config.groupHueLabs || adapter.config.groupHueLabs == 'extra') ? 'HueLabsScenes' : adapter.config.nameId == 'append' ? groupId + '-' + groupUid : groupUid + '-' + groupId;
let scene = library.clean(data.name, true, '_').replace(/\./g, '-');
// update state
if (data.type == 'LabScene')
{
library.setDeviceState('groups.' + (adapter.config.nameId == 'append' ? groupId + '-' + groupUid : groupUid + '-' + groupId) + '.action.hueLabScene', library.getDeviceState('groups.' + (adapter.config.nameId == 'append' ? groupId + '-' + groupUid : groupUid + '-' + groupId) + '.action.on') ? data.uid : '');
DEVICES['groups'][data.group].lights.forEach(light =>
{
let lightId = library.clean(DEVICES['lights'][light].name, true, '_').replace(/\./g, '-');
let lightUid = adapter.config.nameId == 'append' ? light : ('00' + light).substr(-3);
library.setDeviceState('lights.' + (adapter.config.nameId == 'append' ? lightId + '-' + lightUid : lightUid + '-' + lightId) + '.action.hueLabScene', library.getDeviceState('lights.' + (adapter.config.nameId == 'append' ? lightId + '-' + lightUid : lightUid + '-' + lightId) + '.action.on') ? data.uid : '');
});
}
// scene.group
if (adapter.config.sceneNaming == 'scene')
{
key = key.replace('.' + data.uid, '.' + scene);
pathKey = '.' + group;
description = 'Scene ' + data.name;
pathDescription = 'Group ' + DEVICES['groups'][data.group].name;
}
// group.scene
else
{
key = key.replace('.' + data.uid, '.' + group);
pathKey = '.' + scene;
description = data.type == 'LabScene' ? 'Hue Lab Scenes' : 'Scenes for Group ' + DEVICES['groups'][data.group].name;
pathDescription = 'Scene ' + data.name;
}
}
// Duplicates
let uid = library.getDeviceState(key + pathKey + '.uid');
if (uid && uid != data.uid && adapter.config.syncScenesDuplicates)
pathKey += '_' + data.uid;
// update path
DEVICES['scenes'][data.uid].path = key + pathKey;
// create channel for group and scene
library.set({
'node': key + pathKey,
'role': 'channel',
'description': pathDescription
});
}
// read nested data
for (let nestedKey in data)
readData(key + pathKey + '.' + nestedKey, data[nestedKey], channel);
// create channel
library.set({
'node': key,
'role': 'channel',
'description': description || id && data.name || library.ucFirst(key.substr(key.lastIndexOf('.')+1))
});
}
}
// write to states
else
{