forked from Jey-Cee/ioBroker.deconz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
executable file
·2342 lines (2136 loc) · 83.6 KB
/
main.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 utils = require('@iobroker/adapter-core'); // Get common adapter utils
const request = require('request');
let SSDP = require('./lib/ssdp.js');
let adapter;
let hue_factor = 182.041666667;
let ws = null;
let alive_ts = 0;
let reconnect = null;
async function startAdapter(options) {
options = options || {};
Object.assign(options, {
name: 'deconz',
stateChange: (id, state) => {
let tmp = id.split('.');
let dp = tmp.pop();
id = tmp.slice(2).join('.');
if (!id || !state || state.ack) {
if (dp === 'alive') {
if (state === null) {
adapter.setState(id, {val: false, ack: true});
if (ws !== null) {
ws.terminate();
adapter.setState('info.connection', {val: false, ack: true});
}
} else if (state.val === true) {
if (state.lc !== alive_ts) {
alive_ts = state.lc;
if(reconnect !== null){
clearTimeout(reconnect);
}
getAutoUpdates();
}
}
}
return;
}
adapter.log.debug('stateChange ' + id + ' ' + JSON.stringify(state));
adapter.log.debug('dp: ' + dp + '; id:' + id + ' tmp: ' + tmp);
/**
* @param {any} err
* @param {string | null} transitionTime
*/
adapter.getState(adapter.name + '.' + adapter.instance + '.' + id + '.transitiontime', async (err, transitionTime) => {
let parameters = {};
let action = '';
let stateId = '';
let method = '';
if (err) {
transitionTime = 'none';
} else if (transitionTime === null) {
transitionTime = 'none';
} else {
transitionTime = transitionTime.val;
}
let obj = await adapter.getObjectAsync(adapter.name + '.' + adapter.instance + '.' + id);
let controlId = obj.native.id;
switch (dp) {
case 'bri':
if (state.val > 0 && transitionTime === 'none') {
parameters = '{"bri": ' + JSON.stringify(state.val) + ', "on": true}';
} else if (state.val > 0) {
parameters = '{"transitiontime": ' + JSON.stringify(transitionTime) + ', "bri": ' + JSON.stringify(state.val) + ', "on": true}';
} else {
parameters = '{"bri": ' + JSON.stringify(state.val) + ', "on": false}';
}
new SetObjectAndState(tmp[3], '', tmp[2], 'level', Math.floor((100/255) * state.val));
break;
case 'level':
if (state.val > 0 && transitionTime === 'none') {
parameters = '{"bri": ' + Math.floor((255/100) * state.val) + ', "on": true}';
} else if (state.val > 0) {
parameters = '{"transitiontime": ' + JSON.stringify(transitionTime) + ', "bri": ' + Math.floor((255/100) * state.val) + ', "on": true}';
} else {
parameters = '{"bri": ' + Math.floor((255/100) * state.val) + ', "on": false}';
}
break;
case 'on':
if (transitionTime === 'none') {
parameters = '{"on": ' + JSON.stringify(state.val) + '}';
} else {
parameters = '{"transitiontime": ' + JSON.stringify(transitionTime) + ', "on": ' + JSON.stringify(state.val) + '}';
}
break;
case 'hue':
if (transitionTime === 'none') {
parameters = '{"hue": ' + Math.round(parseInt(JSON.stringify(state.val)) * hue_factor) + '}';
} else {
parameters = '{"transitiontime": ' + JSON.stringify(transitionTime) + ', "hue": ' + Math.round(parseInt(JSON.stringify(state.val)) * hue_factor) + '}';
}
break;
case 'sat':
if (transitionTime === 'none') {
parameters = '{"sat": ' + JSON.stringify(state.val) + '}';
} else {
parameters = '{"transitiontime": ' + JSON.stringify(transitionTime) + ', "sat": ' + JSON.stringify(state.val) + '}';
}
break;
case 'ct':
if (transitionTime === 'none') {
parameters = '{"ct": ' + JSON.stringify(state.val) + '}';
} else {
parameters = '{"transitiontime": ' + JSON.stringify(transitionTime) + ', "ct": ' + JSON.stringify(state.val) + '}';
}
break;
case 'xy':
if (transitionTime === 'none') {
parameters = '{"xy": [' + state.val + ']}';
} else {
parameters = '{"transitiontime": ' + JSON.stringify(transitionTime) + ', "xy": [' + state.val + ']}';
}
break;
case 'alert':
if (transitionTime === 'none') {
parameters = '{"alert": ' + JSON.stringify(state.val) + '}';
} else {
parameters = '{"transitiontime": ' + JSON.stringify(transitionTime) + ', "alert": ' + JSON.stringify(state.val) + '}';
}
break;
case 'effect':
if (state.val === 'colorloop') {
let speed = await adapter.getStateAsync(adapter.name + '.' + adapter.instance + '.' + id + '.colorspeed');
adapter.log.info(JSON.stringify(speed));
if (speed.val === null || speed.val === undefined) {
speed = 1;
}
parameters = '{"colorspeed": ' + JSON.stringify(speed) + ', "effect": ' + JSON.stringify(state.val) + '}';
} else {
parameters = '{"effect": ' + JSON.stringify(state.val) + '}';
}
break;
case 'colormode':
parameters = `{ "${dp}": "${state.val}" }`;
break;
case 'dimup':
case 'dimdown':
let dimspeed = await adapter.getStateAsync(adapter.name + '.' + adapter.instance + '.' + id + '.dimspeed');
if (dimspeed === null || dimspeed === undefined || dimspeed.val === 0) {
dimspeed = 10;
adapter.setState(adapter.name + '.' + adapter.instance + '.' + id + '.dimspeed', 10, true);
}
let speed = dp === 'dimup' ? dimspeed.val : dimspeed.val * -1;
if (transitionTime !== 'none') {
parameters = `{ "transitiontime": ${JSON.stringify(transitionTime)} , "bri_inc": ${speed} }`;
} else {
parameters = `{ "bri_inc": ${speed} }`;
}
break;
case 'action':
if (state.val === null || state.val === undefined || state.val === 0) {
return;
}
parameters = `{ ${state.val} }`;
break;
case 'createscene':
if (obj.common.role === 'group') {
let controlId = obj.native.id;
let parameters = `{ "name": "${state.val}" }`;
setGroupScene(parameters, controlId, 0, '', '', 'POST');
getAllGroups();
}
break;
case 'delete':
method = 'DELETE';
await adapter.delObjectAsync(adapter.name + '.' + adapter.instance + '.' + id);
break;
case 'store':
action = 'store';
method = 'PUT';
break;
case 'recall':
action = 'recall';
method = 'PUT';
break;
case 'name':
parameters = `{ "name": "${state.val}" }`;
method = 'PUT';
adapter.extendObject(adapter.name + '.' + adapter.instance + '.' + id, {
common: {
name: state.val
}
});
break;
case 'offset':
case 'sensitivity':
case 'usertest':
case 'ledindication':
case 'duration':
case 'delay':
case 'locked':
case 'boost':
case 'off':
case 'mode':
parameters = `{ "${dp}": "${state.val}" }`;
break;
case 'heatsetpoint':
case 'temperature':
let val = Math.floor(state.val * 100);
parameters = `{ "${dp}": "${val}" }`;
break;
case 'network_open':
let opentime;
await adapter.getObjectAsync('Gateway_info')
.then(async results => {
opentime = results.native.networkopenduration;
}, reject => {
adapter.log.error(JSON.stringify(reject));
});
parameters = `{"permitjoin": ${opentime}}`;
await modifyConfig(parameters);
break;
default:
action = 'none';
break;
}
if(action !== 'none'){
if(typeof parameters === 'object'){
parameters = JSON.stringify(parameters);
}
switch (obj.common.role) {
case 'light':
setLightState(parameters, controlId, adapter.name + '.' + adapter.instance + '.' + id + '.' + dp);
break;
case 'group':
if (dp !== 'createscene') {
setGroupState(parameters, controlId, adapter.name + '.' + adapter.instance + '.' + id + '.' + dp);
}
break;
case 'sensor':
setSensorParameters(parameters, controlId, adapter.name + '.' + adapter.instance + '.' + id + '.' + dp);
break;
case 'scene':
let parentDeviceId = id.split(".")[1];
//let parent = await adapter.getObjectAsync(adapter.name + '.' + adapter.instance + '.Groups.' + parentDeviceId);
setGroupScene(parameters, parentDeviceId, controlId, action, stateId, method);
break;
}
}
});
},
//END on StateChange
// New message arrived. obj is array with current messages
message: async function (obj) {
let wait = false;
if (obj) {
switch (obj.command) {
case 'createAPIkey':
createAPIkey(obj.message.host, obj.message.credentials, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, JSON.stringify(res), obj.callback);
});
wait = true;
break;
case 'deleteAPIkey':
await deleteAPIkey();
wait = true;
break;
case 'getConfig':
await getConfig();
wait = true;
break;
case 'openNetwork':
let openTime;
await adapter.getObjectAsync('Gateway_info')
.then(async results => {
openTime = results.native.networkopenduration;
}, reject => {
adapter.log.error(JSON.stringify(reject));
});
let parameters = `{"permitjoin": ${openTime}}`;
await modifyConfig(parameters);
wait = true;
break;
case 'deleteLight':
await deleteLight(obj.message, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, JSON.stringify(res), obj.callback);
});
wait = true;
break;
case 'deleteSensor':
await deleteSensor(obj.message, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, JSON.stringify(res), obj.callback);
});
wait = true;
break;
case 'createGroup':
await createGroup(obj.message, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, JSON.stringify(res), obj.callback);
});
wait = true;
break;
case 'deleteGroup':
await deleteGroup(obj.message, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, JSON.stringify(res), obj.callback);
});
wait = true;
break;
case 'saveConfig':
adapter.extendObject('Gateway_info', {
native: obj.message
});
break;
default:
adapter.log.warn("Unknown command: " + obj.command);
return false;
}
}
if (!wait && obj.callback) {
adapter.sendTo(obj.from, obj.command, obj.message, obj.callback);
}
return true;
},
unload: stop,
ready: main
});
adapter = new utils.Adapter(options);
return adapter;
}
async function stop() {
ws.terminate();
adapter.setState('info.connection', {val: false, ack: true});
adapter.setState('Gateway_info.alive', {val: false, ack: true});
}
async function main() {
adapter.subscribeStates('*');
heartbeat();
await adapter.getObjectAsync('Gateway_info')
.then(async results => {
if (results.native.ipaddress === undefined) { //only on first start
autoDiscovery();
} else {
if (results.native.user === '' || results.native.user === null) {
adapter.log.warn('No API Key found');
} else {
getConfig();
getAutoUpdates();
}
}
}), (reject => {
adapter.log.error(JSON.stringify(reject));
});
}
//search for Gateway
let discovery = new SSDP.Discovery();
let found_deconz = false;
let wait;
function autoDiscovery() {
adapter.log.info('auto discovery');
discovery.on('message', (msg, rinfo, iface) => {
if (msg.headers.st === 'urn:schemas-upnp-org:device:basic:1') {
adapter.log.debug(`M-SEARCH from ${rinfo.address} for "${msg.headers.st}"`);
if (msg.headers['gwid.phoscon.de'] !== undefined) {
let loc = msg.headers.location.replace('/description.xml', '');
loc = loc.replace('http://', '');
loc = loc.split(':');
adapter.log.debug('autodiscovery: ' + loc);
adapter.extendObject('Gateway_info', {
native: {
ipaddress: loc[0],
port: loc[1]
}
});
found_deconz = true;
clearTimeout(wait);
discovery.close();
}
}
});
discovery.listen('',(error) => {
if (error) {
adapter.log.error(error);
}
discovery.search({st: 'ssdp:all'});
wait = setTimeout( () => {
adapter.log.warn('Could not found deConz by broadcast, establishing Websocket without monitoring the connection state. This is happen if you are using VLAN or installed deConz in an container.')
getAutoUpdates();
}, 10 * 1000)
});
}
function heartbeat() {
discovery.on('notify', (msg, rinfo, iface) => {
if (msg.headers.nt === 'urn:schemas-upnp-org:device:basic:1') {
if (msg.headers['gwid.phoscon.de']) {
let time = parseInt(msg.headers['cache-control'].replace('max-age=', ''));
adapter.setState('Gateway_info.alive', {val: true, ack: true, expire: time});
//adapter.log.debug('NOTIFY ' + JSON.stringify(msg))
}
}
});
discovery.listen((error) => {
if (error) {
adapter.log.error(error);
}
});
}
function createAPIkey(host, credentials, callback) {
let auth;
if (credentials !== null) {
auth = Buffer.from(credentials).toString('base64');
} else {
auth = 'ZGVsaWdodDpkZWxpZ2h0';
}
let options = {
url: 'http://' + host + '/api',
method: 'POST',
headers: {
'Content-Type': 'text/plain;charset=UTF-8',
'Authorization': `Basic ${auth}`,
'Content-Length': Buffer.byteLength('{"devicetype": "ioBroker"}')
}
};
adapter.log.debug(host + ' auth: ' + auth);
try {
let req = request(options, async (error, res, body) => {
if (!error) {
adapter.log.info('STATUS: ' + JSON.stringify(res));
if (res.statusCode === 403) {
callback({error: 101, message: 'Unlock Key not pressed'});
} else if ( await logging(res, body, 'create API key') ) {
let apiKey = JSON.parse(body);
adapter.log.info(JSON.stringify(apiKey[0]['success']['username']));
callback({error: 0, message: apiKey[0]['success']['username']});
getConfig();
}
} else {
adapter.log.error('Could not connect to deConz/Phoscon. ' + error);
}
});
req.write('{"devicetype": "ioBroker"}');
} catch (err) {
adapter.log.error(err)
}
}
async function deleteAPIkey() {
adapter.log.info('deleteAPIkey');
let ip, port, user;
await adapter.getObjectAsync('Gateway_info')
.then(async results => {
ip = results.native.ipaddress;
port = results.native.port;
user = results.native.user;
});
let options = {
url: 'http://' + ip + ':' + port + '/api/' + user + '/config/whitelist/' + user,
method: 'DELETE',
headers: {
'Content-Type': 'text/plain;charset=UTF-8'
}
};
request(options, async (error, res, body) => {
let response;
try {
response = JSON.parse(body);
} catch (err) {
}
if ( await logging(res, body, 'delete API key') ) {
if (response[0]['success']) {
adapter.extendObject('Gateway_info', {
native: {
user: ''
}
});
adapter.log.info('API key deleted');
} else if (response[0]['error']) {
adapter.log.warn(JSON.stringify(response[0]['error']));
}
} else if (res.statusCode === 403) {
adapter.log.warn('You do not have the permission to do this! ');
} else if (res.statusCode === 404) {
adapter.log.warn('Error 404 Not Found ')
}
});
}
//Make Abo using websocket
const WebSocket = require('ws');
function autoReconnect(host, port){
reconnect = setTimeout(() => {
ws.terminate();
getAutoUpdates();
}, 60 * 1000);
}
async function getAutoUpdates() {
let host, port, user;
await adapter.getObjectAsync('Gateway_info')
.then(async results => {
host = results.native.ipaddress;
port = results.native.websocketport;
user = results.native.user;
}, reject => {
adapter.log.warn('Object Gateway_info access error: ' + JSON.stringify(reject))
});
if (user) {
ws = new WebSocket('ws://' + host + ':' + port);
ws.on('open', () => {
adapter.setState('info.connection', {val: true, ack: true});
adapter.log.debug('Subscribed to updates...');
autoReconnect();
});
ws.on('close', () => {
adapter.log.debug('Websocket connection closed');
//getAutoUpdates();
});
ws.on('error', (err) => {
adapter.log.warn('Could not connect to websocket instance of deConz/Phoscon. ' + err);
adapter.setState('info.connection', {val: false, ack: true});
});
ws.onmessage = async (msg) => {
clearTimeout(reconnect);
autoReconnect(host, port);
let data = JSON.parse(msg.data);
let id = data['id'];
let type = data['r'];
let state = data['state'];
let config = data['config'];
adapter.log.debug('Websocket message: ' + JSON.stringify(data));
let thing;
let object;
switch (type) {
case 'lights':
await getLightState(id);
break;
case 'groups':
await getGroupAttributes(id);
break;
case 'sensors':
object = await getObjectByDeviceId(id, 'Sensors');
thing = 'Sensor';
if (object === undefined) {
await getSensor(id);
} else {
if (typeof state == 'object') {
for (let obj in state) {
if (obj === 'lastupdated') {
adapter.setObjectNotExists(`Sensors.${id}` + '.lastupdated', {
type: 'state',
common: {
name: 'lastupdated',
type: 'string',
role: 'state',
read: true,
write: false
},
native: {}
});
}
adapter.getState(`${adapter.name}.${adapter.instance}.Sensors.${id}.lastupdated`, (err, lupdate) => {
if (lupdate === null) {
new SetObjectAndState(id, object.value.common.name, 'Sensors', obj, state[obj]);
} else if (lupdate.val !== state[obj]) {
if (obj === 'buttonevent') {
new SetObjectAndState(id, object.value.common.name, 'Sensors', obj, state[obj]);
adapter.setObjectNotExists(`Sensors.${id}` + '.' + "buttonpressed", {
type: 'state',
common: {
name: 'Sensor' + id + ' ' + 'buttonpressed',
type: 'number',
role: 'state',
read: true,
write: false
},
native: {}
});
adapter.setState(`Sensors.${id}` + '.' + 'buttonpressed', {
val: state[obj],
ack: true
});
setTimeout(() => {
adapter.setState(`Sensors.${id}` + '.' + 'buttonpressed', {
val: 0,
ack: true
})
}, 800);
} else {
new SetObjectAndState(id, object.value.common.name, 'Sensors', obj, state[obj]);
}
}
})
}
}
if (typeof config == 'object') {
for (let obj in config) {
new SetObjectAndState(id, object.value.common.name, 'Sensors', obj, config[obj]);
}
}
}
break;
}
}
}
}
//START deConz config --------------------------------------------------------------------------------------------------
async function modifyConfig(parameters) {
let ip, port, user, ot;
await adapter.getObjectAsync('Gateway_info')
.then(async results => {
ip = results.native.ipaddress;
port = results.native.port;
user = results.native.user;
ot = results.native.networkopenduration;
});
let options = {
url: 'http://' + ip + ':' + port + '/api/' + user + '/config',
method: 'PUT',
headers: 'Content-Type" : "application/json',
body: parameters
};
request(options, async (error, res, body) => {
let response;
try {
response = JSON.parse(body);
} catch (err) {
}
if ( await logging(res, body, 'modify config') ) {
if (response[0]['success']) {
switch (JSON.stringify(response[0]['success'])) {
case `{"/config/permitjoin":${ot}}`:
adapter.log.info(`Network is now open for ${ot} seconds to register new devices.`);
adapter.setState('Gateway_info.network_open', {ack: true, expire: ot});
break;
}
} else if (response[0]['error']) {
adapter.log.warn(JSON.stringify(response[0]['error']));
}
} else if (res.statusCode === 403) {
adapter.log.warn('You do not have the permission to do this! ' + parameters);
} else if (res.statusCode === 400) {
adapter.log.warn('Error 404 Not Found ' + parameters)
}
});
}
async function getConfig() {
let ip, port, user;
await adapter.getObjectAsync('Gateway_info')
.then(async results => {
ip = results.native.ipaddress;
port = results.native.port;
user = results.native.user;
});
let options = {
url: 'http://' + ip + ':' + port + '/api/' + user + '/config',
method: 'GET'
};
request(options, async (error, res, body) => {
if (error) {
adapter.log.error('Could not connect to deConz/Phoscon. ' + error);
} else if ( await logging(res, body, ' get config') ) {
let gateway = JSON.parse(body);
adapter.log.info('deConz Version: ' + gateway['swversion'] + '; API version: ' + gateway['apiversion']);
adapter.extendObject('Gateway_info', {
type: 'device',
common: {
name: gateway['name'],
role: 'gateway'
},
native: {
apiversion: gateway['apiversion'],
bridgeid: gateway['bridgeid'],
datastoreversion: gateway['datastoreversion'],
devicename: gateway['devicename'],
dhcp: gateway['dhcp'],
factorynew: gateway['factorynew'],
gateway: gateway['gateway'],
//ipaddress: gateway['ipaddress'],
linkbutton: gateway['linkbutton'],
mac: gateway['mac'],
modelid: gateway['modelid'],
netmask: gateway['netmask'],
networkopenduration: gateway['networkopenduration'],
panid: gateway['panid'],
portalconnection: gateway['portalconnection'],
portalservices: gateway['portalservices'],
proxyaddress: gateway['proxyaddress'],
proxyport: gateway['proxyport'],
replacesbridgeid: gateway['replacesbridgeid'],
starterkitid: gateway['starterkitid'],
swversion: gateway['swversion'],
timeformat: gateway['timeformat'],
timezone: gateway['timezone'],
uuid: gateway['uuid'],
websocketnotifyall: gateway['websocketnotifyall'],
websocketport: gateway['websocketport'],
zigbeechannel: gateway['zigbeechannel']
}
});
getAllLights();
getAllSensors();
getAllGroups();
getDevices();
}
});
} //END getConfig
//END deConz config ----------------------------------------------------------------------------------------------------
//START Group functions -----------------------------------------------------------------------------------------------
async function getAllGroups() {
let ip, port, user;
await adapter.getObjectAsync('Gateway_info')
.then(async results => {
ip = results.native.ipaddress;
port = results.native.port;
user = results.native.user;
});
let options = {
url: 'http://' + ip + ':' + port + '/api/' + user + '/groups',
method: 'GET'
};
request(options, async (error, res, body) => {
let list = JSON.parse(body);
let count = Object.keys(list).length - 1;
if ( await logging(res, body, 'get all groups') && body !== '{}') {
for (let i = 0; i <= count; i++) {
let keyName = Object.keys(list)[i];
//create object for group
let objectName = list[keyName]['name'];
let groupID = list[keyName]['id'];
//Changed check if is helper group, if skip it
let regex = new RegExp("helper[0-9]+ for group [0-9]+");
if (!regex.test(objectName)) {
adapter.setObjectNotExists(`Groups.${groupID}`, {
type: 'device',
common: {
name: list[keyName]['name'],
role: 'group'
},
native: {
devicemembership: list[keyName]['devicemembership'],
etag: list[keyName]['etag'],
id: list[keyName]['id'],
hidden: list[keyName]['hidden'],
type: 'group'
}
}, () => {
getGroupAttributes(list[keyName]['id']);
getGroupScenes(`Groups.${groupID}`, list[keyName]['scenes']);
});
}
}
}
});
} //END getAllGroups
async function getGroupAttributes(groupId) {
let ip, port, user;
await adapter.getObjectAsync('Gateway_info')
.then(async results => {
ip = results.native.ipaddress;
port = results.native.port;
user = results.native.user;
});
let options = {
url: 'http://' + ip + ':' + port + '/api/' + user + '/groups/' + groupId,
method: 'GET'
};
request(options, async (error, res, body) => {
let list = JSON.parse(body);
if ( await logging(res, body, 'get group attributes ' + groupId) ) {
//create object for group with attributes
let groupID = list['id'];
//Changed check if helper, if skip it (cause it also dont exists)
let regex = new RegExp("helper[0-9]+ for group [0-9]+");
if (!regex.test(list['name'])) {
adapter.setObjectNotExists(`Groups.${groupId}`, {
type: 'device',
common: {
name: list['name'],
role: 'group'
},
native: {
devicemembership: list['devicemembership'],
etag: list['etag'],
hidden: list['hidden'],
id: groupId,
lights: list['lights'],
lightsequence: list['lightsequence'],
multideviceids: list['multideviceids']
}
});
let count2 = Object.keys(list['action']).length - 1;
//create states for light device
for (let z = 0; z <= count2; z++) {
let stateName = Object.keys(list['action'])[z];
new SetObjectAndState(groupId, list['name'], 'Groups', stateName, list['action'][stateName]);
new SetObjectAndState(groupId, list['name'], 'Groups', 'transitiontime', null);
}
let count3 = Object.keys(list['state']).length - 1;
//create states for light device
for (let z = 0; z <= count3; z++) {
let stateName = Object.keys(list['state'])[z];
new SetObjectAndState(groupId, list['name'], 'Groups', stateName, list['state'][stateName]);
new SetObjectAndState(groupId, list['name'], 'Groups', 'transitiontime', null);
}
new SetObjectAndState(groupId, list['name'], 'Groups', 'level', null);
adapter.setObjectNotExists(`Groups.${groupId}.dimspeed`, {
type: 'state',
common: {
name: list['name'] + ' ' + 'dimspeed',
type: 'number',
role: 'level.dimspeed',
min: 0,
max: 254,
read: false,
write: true
},
native: {}
});
adapter.setObjectNotExists(`Groups.${groupId}.dimup`, {
type: 'state',
common: {
name: list['name'] + ' ' + 'dimup',
role: 'button'
}
});
adapter.setObjectNotExists(`Groups.${groupId}.dimdown`, {
type: 'state',
common: {
name: list['name'] + ' ' + 'dimdown',
role: 'button'
}
});
adapter.setObjectNotExists(`Groups.${groupId}.action`, {
type: 'state',
common: {
name: list['name'] + ' ' + 'action',
role: 'argument',
type: 'string',
read: false,
write: true
}
});
}
getGroupScenes(`Groups.${groupID}`, list['scenes']);
}
})
} //END getGroupAttributes
function getGroupScenes(group, sceneList) {
//Changed check if group exists, if not skip it
adapter.getObject(adapter.name + '.' + adapter.instance + '.' + group, (err, obj) => {
if (obj !== undefined) {
adapter.setObjectNotExists(`${group}.createscene`, {
type: 'state',
common: {
name: "createscene",
role: 'button'
}
});
if (sceneList.length === 0) {
return;
}
sceneList.forEach((scene) => {
if (scene.lightcount > 0) {
adapter.setObjectNotExists(`${group}.Scene_${scene.id}`, {
type: 'device',
common: {
name: scene.name,
role: 'scene'
},
native: {
type: 'scene',
id: scene.id
}
});
adapter.setObjectNotExists(`${group}.Scene_${scene.id}.recall`, {
type: 'state',
common: {
name: "recall",
role: 'button',
type: 'boolean',
read: false,
write: true
}
});
adapter.setObjectNotExists(`${group}.Scene_${scene.id}.store`, {
type: 'state',
common: {
name: "store",
role: 'button',
type: 'boolean',
read: false,
write: true
}
});
adapter.setObjectNotExists(`${group}.Scene_${scene.id}.delete`, {
type: 'state',
common: {
name: "delete",
role: 'button',
type: 'boolean',
read: false,
write: true
}
});
adapter.setObjectNotExists(`${group}.Scene_${scene.id}.lightcount`, {
type: 'state',
common: {
name: "lightcount",
role: 'state',
type: 'number',
read: true,
write: false
}
});
adapter.setState(`${group}.Scene_${scene.id}.lightcount`, scene.lightcount, true);
adapter.setObjectNotExists(`${group}.Scene_${scene.id}.transitiontime`, {
type: 'state',
common: {
name: "transitiontime",
role: 'argument',
type: 'number',
read: true,
write: false