-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
2031 lines (1778 loc) · 84.8 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');
const twinkly = require('./lib/twinkly');
const apiObjectsMap = require('./lib/twinklyApi2Objects').apiObjectsMap;
const twinklyMovies = require('./lib/twinklyMovies');
const stateTools = require('./lib/stateTools');
const tools = require('./lib/tools');
// TODO: uploadMovie, LEDMovieConfig, sendRealtimeFrame, Summary, Mic, Music
/**
* The adapter instance
* @type {ioBroker.Adapter}
*/
let adapter;
/**
* Interval für das Polling
*/
let pollingInterval = null;
/**
* Twinkly-Verbindungen
* @type {{[x: string]: {enabled: Boolean, paused: Boolean, modeOn: String, lastModeOn: String, connected: Boolean, twinkly: Twinkly}}}
*/
const connections = {};
/**
* Sentry Messages
* @type {string[]}}
*/
const sentryMessages = [];
/**
* Liste aller States
* @type {{[x: string]: {connection: String, group: String, command: String}}}
*/
const subscribedStates = {};
/**
* Let commands only run once at startup
* @type {boolean}
*/
let initializing = true;
/**
* Anzulegende States
* @type {String[]}
*/
const statesConfig = [
apiObjectsMap.connected.id,
apiObjectsMap.firmware.parent.id,
apiObjectsMap.ledBri.parent.id,
apiObjectsMap.ledColor.parent.id,
// apiObjectsMap.ledConfig.id,
apiObjectsMap.ledEffect.parent.id,
// apiObjectsMap.ledLayout.parent.id, //Prüfen, weshalb es nicht klappt
apiObjectsMap.ledMode.parent.id,
apiObjectsMap.ledMovie.parent.id,
apiObjectsMap.ledSat.parent.id,
apiObjectsMap.name.parent.id,
apiObjectsMap.on.id,
apiObjectsMap.paused.id,
apiObjectsMap.ledPlaylist.parent.id,
apiObjectsMap.timer.parent.id
];
/**
* Starts the adapter instance
* @param {Partial<utils.AdapterOptions>} [options]
*/
function startAdapter(options) {
options = options || {};
Object.assign(options, {name: 'twinkly'});
adapter = new utils.Adapter(options)
.on('ready', main)
.on('stateChange', stateChange)
.on('message', processMessage)
.on('unload', onStop);
return adapter;
}
async function stateChange(id, state) {
if (state) {
if (state.ack) return;
// The state was changed
adapter.log.debug(`[stateChange] state ${id} changed: ${state.val} (ack = ${state.ack})`);
// Ist der state bekannt?
if (!Object.keys(subscribedStates).includes(id)) {
adapter.log.warn(`State ${id} is not writable, will not be processed!`);
return;
}
const connectionName = subscribedStates[id].connection;
const group = subscribedStates[id].group;
const command = subscribedStates[id].command;
let connection;
try {
if (command === apiObjectsMap.paused.id) {
connection = await getConnection(connectionName, {checkPaused: false, ignoreConnected: true});
if (connection.paused !== state.val) {
connection.paused = state.val;
if (!connection.paused)
startInterval(1000, connectionName);
return;
}
}
connection = await getConnection(connectionName, {checkConnected: true});
} catch (e) {
adapter.log.debug(`[stateChange] ${e.message}`);
return;
}
const pollFilter = [];
// LED Brightness
if (!group && command === apiObjectsMap.ledBri.parent.id) {
pollFilter.push(command);
if (state.val === -1) {
try {
await connection.twinkly.setBrightnessDisabled();
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not disable! ${e}`);
}
} else {
try {
await connection.twinkly.setBrightnessAbsolute(state.val);
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not set ${state.val}! ${e}`);
}
}
// LED Color (mode = color)
} else if (group && group === apiObjectsMap.ledColor.parent.id) {
pollFilter.push(group);
let changeMode = false;
try {
if ([apiObjectsMap.ledColor.child.hue.id, apiObjectsMap.ledColor.child.saturation.id, apiObjectsMap.ledColor.child.value.id].includes(command)) {
/** @type {{hue: Number, saturation: Number, value: Number}} */
const json = {hue: 0, saturation: 0, value: 0};
await getJSONStates(connectionName, connectionName + '.' + group, json, apiObjectsMap.ledColor.child, {
id: command,
val: state.val
});
await connection.twinkly.setLEDColorHSV(json.hue, json.saturation, json.value);
changeMode = connection.twinkly.ledMode !== twinkly.lightModes.value.color;
} else if ([apiObjectsMap.ledColor.child.red.id, apiObjectsMap.ledColor.child.green.id, apiObjectsMap.ledColor.child.blue.id, apiObjectsMap.ledColor.child.white.id, apiObjectsMap.ledColor.child.hex.id].includes(command)) {
/** @type {{red: Number, green: Number, blue: Number, white: Number}} */
const json = {red: 0, green: 0, blue: 0, white: -1};
if ([apiObjectsMap.ledColor.child.red.id, apiObjectsMap.ledColor.child.green.id, apiObjectsMap.ledColor.child.blue.id, apiObjectsMap.ledColor.child.white.id].includes(command)) {
await getJSONStates(connectionName, connectionName + '.' + group, json, apiObjectsMap.ledColor.child, {
id: command,
val: state.val
});
} else {
const hexRgb = tools.hexToRgb(state.val);
json.red = hexRgb.r;
json.green = hexRgb.g;
json.blue = hexRgb.b;
}
await connection.twinkly.setLEDColorRGBW(json.red, json.green, json.blue, json.white);
changeMode = connection.twinkly.ledMode !== twinkly.lightModes.value.color;
}
} catch (e) {
adapter.log.error(`[${connectionName}.${group}.${command}] Could not set ${state.val}! ${e}`);
}
try {
if (changeMode && adapter.config.switchMode) {
pollFilter.push(apiObjectsMap.ledMode.parent.id);
await connection.twinkly.setLEDMode(twinkly.lightModes.value.color);
}
} catch (e) {
adapter.log.error(`[${connectionName}.${group}.${command}] Could not change Mode! ${e}`);
}
// LED Config
} else if (!group && command === apiObjectsMap.ledConfig.id) {
pollFilter.push(command);
try {
await connection.twinkly.setLEDConfig(state.val);
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not set ${state.val}! ${e}`);
}
// LED Effect
} else if (!group && command === apiObjectsMap.ledEffect.parent.id) {
pollFilter.push(command);
let changeMode = false;
try {
if (!Object.keys(connection.twinkly.ledEffects).includes(typeof state.val === 'number' ? String(state.val) : state.val)) {
adapter.log.warn(`[${connectionName}.${command}] Effect ${state.val} does not exist!`);
} else {
await connection.twinkly.setCurrentLEDEffect(state.val);
changeMode = connection.twinkly.ledMode !== twinkly.lightModes.value.effect;
}
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not set ${state.val}! ${e}`);
}
try {
if (changeMode && adapter.config.switchMode) {
pollFilter.push(apiObjectsMap.ledMode.parent.id);
await connection.twinkly.setLEDMode(twinkly.lightModes.value.effect);
}
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not change Mode! ${e}`);
}
// LED Layout
} else if (group && group === apiObjectsMap.ledLayout.parent.id) {
pollFilter.push(group);
/** @type {{aspectXY: Number, aspectXZ: Number, coordinates: {x: Number, y: Number, z: Number}[], source: String, synthesized: Boolean}} */
const json = {aspectXY: 0, aspectXZ: 0, coordinates: [], source: '', synthesized: false};
await getJSONStates(connectionName, connectionName + '.' + group, json, apiObjectsMap.ledLayout.child, {id: command, val: state.val});
try {
await connection.twinkly.uploadLayout(json.aspectXY, json.aspectXZ, json.coordinates, json.source, json.synthesized);
} catch (e) {
adapter.log.error(`[${connectionName}.${group}.${command}] Could not set ${state.val}! ${e}`);
}
// LED Mode
} else if (!group && command === apiObjectsMap.ledMode.child.mode.id) {
pollFilter.push(apiObjectsMap.ledMode.parent.id);
try {
if (!Object.values(twinkly.lightModes.value).includes(state.val)) {
adapter.log.warn(`[${connectionName}.${command}] Could not set ${state.val}! Mode does not exist!`);
} else if (state.val === twinkly.lightModes.value.movie && Object.keys(connection.twinkly.ledMovies).length === 0) {
adapter.log.warn(`[${connectionName}.${command}] Could not set Mode ${twinkly.lightModes.text.movie}! No movie available! Is a Effect/Playlist selected?`);
pollFilter.push(apiObjectsMap.ledMovie.parent.id);
} else if (state.val === twinkly.lightModes.value.playlist && Object.keys(connection.twinkly.playlist).length === 0) {
adapter.log.warn(`[${connectionName}.${command}] Could not set Mode ${twinkly.lightModes.text.playlist}! No movie available! Is a Playlist created?`);
pollFilter.push(apiObjectsMap.ledPlaylist.parent.id);
} else {
await connection.twinkly.setLEDMode(state.val);
}
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not set ${state.val}! ${e}`);
}
// LED Saturation
} else if (!group && command === apiObjectsMap.ledSat.parent.id) {
pollFilter.push(command);
if (state.val === -1) {
try {
await connection.twinkly.setSaturationDisabled();
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not disable! ${e}`);
}
} else {
try {
await connection.twinkly.setSaturationAbsolute(state.val);
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not set ${state.val}! ${e}`);
}
}
// LED Movie
} else if (!group && command === apiObjectsMap.ledMovie.parent.id) {
pollFilter.push(command);
let changeMode = false;
try {
if (!Object.keys(connection.twinkly.ledMovies).includes(typeof state.val === 'number' ? String(state.val) : state.val)) {
adapter.log.warn(`[${connectionName}.${command}] Movie ${state.val} does not exist!`);
} else {
await connection.twinkly.setCurrentMovie(state.val);
changeMode = connection.twinkly.ledMode !== twinkly.lightModes.value.movie;
}
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not set ${state.val}! ${e}`);
}
try {
if (changeMode && adapter.config.switchMode) {
pollFilter.push(apiObjectsMap.ledMode.parent.id);
await connection.twinkly.setLEDMode(twinkly.lightModes.value.movie);
}
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not change Mode! ${e}`);
}
// LED Playlist
} else if (!group && command === apiObjectsMap.ledPlaylist.parent.id) {
pollFilter.push(command);
let changeMode = false;
try {
if (!Object.keys(connection.twinkly.playlist).includes(typeof state.val === 'number' ? String(state.val) : state.val)) {
adapter.log.warn(`[${connectionName}.${command}] Playlist ${state.val} does not exist!`);
} else {
await connection.twinkly.setCurrentPlaylistEntry(state.val);
changeMode = connection.twinkly.ledMode !== twinkly.lightModes.value.playlist;
}
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not set ${state.val}! ${e}`);
}
try {
if (changeMode && adapter.config.switchMode) {
pollFilter.push(apiObjectsMap.ledMode.parent.id);
await connection.twinkly.setLEDMode(twinkly.lightModes.value.playlist);
}
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not change Mode! ${e}`);
}
// MQTT anpassen
} else if (group && group === apiObjectsMap.mqtt.parent.id) {
pollFilter.push(group);
/** @type {{broker_host: String, broker_port: Number, client_id: String, user: String, keep_alive_interval : Number, encryption_key_set: Boolean}} */
const json = {broker_host: '', broker_port: 0, client_id: '', user: '', keep_alive_interval: 0, encryption_key_set: false};
await getJSONStates(connectionName, connectionName + '.' + group, json, apiObjectsMap.mqtt.child, {id: command, val: state.val});
try {
await connection.twinkly.setMqttConfiguration(json);
} catch (e) {
adapter.log.error(`[${connectionName}.${group}.${command}] Could not set ${state.val}! ${e}`);
}
// Namen anpassen
} else if (!group && command === apiObjectsMap.name.parent.id) {
pollFilter.push(command, apiObjectsMap.details.parent.id);
try {
await connection.twinkly.setDeviceName(state.val);
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not set ${state.val}! ${e}`);
}
// NetworkStatus anpassen
} else if (!group && command === apiObjectsMap.networkStatus.parent.id) {
pollFilter.push('');
// connection.twinkly.set_network_status(state.val)
// .catch(error => {
// adapter.log.error(`Could not set ${connectionName}.${command} ${error}`);
// });
} else if (group && group === apiObjectsMap.networkStatus.parent.id) {
pollFilter.push('');
// const json = {};
// await getJSONStates(connectionName, connectionName + '.' + group, json, apiObjectsMap.mqtt.child, {id: command, val: state.val});
//
// connection.twinkly.set_mqtt_str(JSON.stringify(json))
// .catch(error => {
// adapter.log.error(`Could not set ${connectionName}.${command} ${error}`);
// });
// Gerät ein-/ausschalten
} else if (!group && command === apiObjectsMap.on.id) {
pollFilter.push(apiObjectsMap.ledMode.parent.id);
try {
let newMode;
if (state.val) {
if (connection.modeOn === twinkly.STATE_ON_LASTMODE) {
newMode = connection.lastModeOn;
} else {
newMode = connection.modeOn;
}
} else {
newMode = twinkly.lightModes.value.off;
}
await connection.twinkly.setLEDMode(newMode);
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not set ${state.val}! ${e}`);
}
// Reset
} else if (!group && command === apiObjectsMap.reset.id) {
try {
await connection.twinkly.resetLED();
} catch (e) {
adapter.log.error(`[${connectionName}.${command}] Could not set ${state.val}! ${e}`);
}
// Timer anpassen
} else if (group && group === apiObjectsMap.timer.parent.id) {
pollFilter.push(group);
/** @type {{time_now: Number, time_on: Number, time_off: Number, tz: String}} */
const json = {time_now: -1, time_on: -1, time_off: -1, tz: ''};
await getJSONStates(connectionName, connectionName + '.' + group, json, apiObjectsMap.timer.child, {id: command, val: state.val});
try {
// Prüfen ob Daten gesendet werden können
if ((json.time_on > -1 && json.time_off > -1) || (json.time_on === -1 && json.time_off === -1)) {
await connection.twinkly.setTimer(json);
} else
adapter.log.debug(`[stateChange] Timer kann noch nicht übermittelt werden: (${json.time_on} > -1 && ${json.time_off} > -1) || (${json.time_on} === -1 && ${json.time_off} === -1)`);
} catch (e) {
adapter.log.error(`[${connectionName}.${group}.${command}] Could not set ${state.val}! ${e.message}`);
}
}
startInterval(1000, connectionName, pollFilter);
} else {
// The state was deleted
adapter.log.debug(`[stateChange] state ${id} deleted`);
}
}
/**
* Polling auf alle Verbindungen ausführen
* @param {string} specificConnection
* @param {string[]} filter
* @returns {Promise<void>}
*/
async function poll(specificConnection = '', filter = []) {
clearInterval();
/**
* Check if Command can be executed
* @param command
* @return {boolean}
*/
function canExecuteCommand(command) {
return statesConfig.includes(command) && (filter.length === 0 || filter.includes(command));
}
let deviceConnected = false;
adapter.log.debug(`[poll] Start polling...`);
adapter.log.silly(`[poll] specificConnection: ${specificConnection}, filter: ${filter}`);
try {
for (const connectionName of Object.keys(connections)) {
// Falls gefüllt nur bestimmte Connection abfragen...
if (specificConnection !== '' && connectionName !== specificConnection) continue;
let connection;
try {
connection = await getConnection(connectionName, {checkConnected: true});
} catch (e) {
adapter.log.debug(`[poll] ${e.message}`);
continue;
}
deviceConnected = true;
await connection.twinkly.interview();
// Only load at startup
if (initializing) {
await updateEffects(connectionName);
}
if (canExecuteCommand(apiObjectsMap.details.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.details.parent.id}`);
try {
const response = await connection.twinkly.getDeviceDetails();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.details);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.details);
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.details.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.firmware.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.firmware.parent.id}`);
try {
const response = await connection.twinkly.getFirmwareVersion();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.firmware);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.firmware);
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.firmware.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.ledBri.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.ledBri.parent.id}`);
try {
const response = await connection.twinkly.getBrightness();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.ledBri);
try {
await adapter.setStateAsync(connectionName + '.' + apiObjectsMap.ledBri.child.value.id,
response.mode !== 'disabled' ? response.value : -1, true);
} catch (e) {
this.adapter.log.silly(`[poll.${connectionName}]: ${e}`);
}
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.ledBri.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.ledColor.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.ledColor.parent.id}`);
try {
const response = await connection.twinkly.getLEDColor();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.ledColor);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.ledColor);
try {
// Hex Version
await adapter.setStateAsync(connectionName + '.' + apiObjectsMap.ledColor.parent.id + '.' + apiObjectsMap.ledColor.child.hex.id,
tools.rgbToHex(response.red, response.green, response.blue, false), true);
} catch (e) {
this.adapter.log.silly(`[poll.${connectionName}]: ${e}`);
}
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.ledColor.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.ledConfig.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.ledConfig.id}`);
try {
const response = await connection.twinkly.getLEDConfig();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.ledConfig);
try {
await adapter.setStateAsync(connectionName + '.' + apiObjectsMap.ledConfig.id, JSON.stringify(response.strings), true);
} catch (e) {
this.adapter.log.silly(`[poll.${connectionName}]: ${e}`);
}
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.ledConfig.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.ledEffect.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.ledEffect.parent.id}`);
try {
const response = await connection.twinkly.getCurrentLEDEffect();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.ledEffect);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.ledEffect);
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.ledEffect.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.ledLayout.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.ledLayout.parent.id}`);
try {
const response = await connection.twinkly.getLayout();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.ledLayout);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.ledLayout);
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.ledLayout.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.ledMode.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.ledMode.parent.id}`);
try {
const response = await connection.twinkly.getLEDMode();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.ledMode);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.ledMode);
try {
await adapter.setStateAsync(connectionName + '.' + apiObjectsMap.on.id, response.mode !== twinkly.lightModes.value.off, true);
} catch (e) {
this.adapter.log.silly(`[poll.${connectionName}]: ${e}`);
}
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.ledMode.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.ledMovie.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.ledMovie.parent.id}`);
try {
// First update existing Movies...
await updateMovies(connectionName);
// ... then get current Movie
const response = await connection.twinkly.getCurrentMovie();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.ledMovie);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.ledMovie);
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.ledMovie.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.ledPlaylist.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.ledPlaylist.parent.id}`);
try {
// First update existing Playlist...
await updatePlaylist(connectionName);
// ... then get current Playlist Entry
const response = await connection.twinkly.getCurrentPlaylistEntry();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.ledPlaylist);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.ledPlaylist);
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.ledPlaylist.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.ledSat.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.ledSat.parent.id}`);
try {
const response = await connection.twinkly.getSaturation();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.ledSat);
try {
await adapter.setStateAsync(connectionName + '.' + apiObjectsMap.ledSat.child.value.id,
response.mode !== 'disabled' ? response.value : -1, true);
} catch (e) {
this.adapter.log.silly(`[poll.${connectionName}]: ${e}`);
}
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.ledSat.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.mqtt.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.mqtt.parent.id}`);
try {
const response = await connection.twinkly.getMqttConfiguration();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.mqtt);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.mqtt);
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.mqtt.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.name.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.name.parent.id}`);
try {
const response = await connection.twinkly.getDeviceName();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.name);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.name);
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.name.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.networkStatus.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.networkStatus.parent.id}`);
try {
const response = await connection.twinkly.getNetworkStatus();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.networkStatus);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.networkStatus);
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.networkStatus.parent.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.status.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.status.id}`);
try {
const response = await connection.twinkly.getStatus();
await checkTwinklyResponse(connectionName, response.status, apiObjectsMap.status);
await saveJSONinState(connectionName, connectionName, response.status, apiObjectsMap.status);
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.status.id} ${e}`);
}
}
if (canExecuteCommand(apiObjectsMap.timer.parent.id)) {
adapter.log.debug(`[poll.${connectionName}] Polling ${apiObjectsMap.timer.parent.id}`);
try {
const response = await connection.twinkly.getTimer();
if (response.code === twinkly.HTTPCodes.values.ok) {
await checkTwinklyResponse(connectionName, response, apiObjectsMap.timer);
await saveJSONinState(connectionName, connectionName, response, apiObjectsMap.timer);
}
} catch (e) {
adapter.log.error(`Could not get ${connectionName}.${apiObjectsMap.timer.parent.id} ${e}`);
}
}
}
} catch (e) {
adapter.log.error(e);
}
adapter.log.debug(`[poll] Finished polling...`);
// Set Connection Status, at least one connection is active
if (specificConnection === '') {
adapter.setState('info.connection', deviceConnected, true);
}
startInterval(adapter.config.interval * 1000);
}
async function main() {
adapter.subscribeStates('*');
adapter.getState('info.connection', (err, state) => {
if (state) {
adapter.setState('info.connection', false, true);
}
});
// Set Config Default Values
adapter.config.interval = adapter.config.interval < 15 ? 15 : adapter.config.interval;
if (adapter.config.devices === undefined)
adapter.config.devices = [];
if (adapter.config.details === undefined)
adapter.config.details = false;
if (adapter.config.mqtt === undefined)
adapter.config.mqtt = false;
if (adapter.config.network === undefined)
adapter.config.network = false;
if (adapter.config.usePing === undefined)
adapter.config.usePing = true;
if (adapter.config.switchMode === undefined)
adapter.config.switchMode = false;
// States/Objekte anlegen...
try {
if (await syncConfig()) {
await poll();
initializing = false;
adapter.log.info('Startup complete');
} else {
adapter.log.info('Polling was not started!');
}
} catch (e) {
adapter.log.error(e);
adapter.log.info('Polling was not started!');
}
}
function onStop () {
try {
// Interval abbrechen
clearInterval();
// Alle Verbindungen abmelden...
Object.keys(connections)
.filter(connectionName => !connections[connectionName].paused)
.forEach(async connectionName => {
const connection = connections[connectionName];
try {
await connection.twinkly.logout();
} catch (e) {
adapter.log.error(`[onStop.${connection.twinkly.name}] ${e}`);
}
// Set connection status to false
if (await adapter.getStateAsync(connectionName + '.' + apiObjectsMap.connected.id)) {
await adapter.setStateAsync(connectionName + '.' + apiObjectsMap.connected.id, false, true);
}
});
// Set connection status to false
adapter.setState('info.connection', false, true);
adapter.log.info('cleaned everything up...');
} catch (e) {
adapter.log.error(`[onStop] ${e}`);
}
}
/**
*
* @param {ioBroker.Message} obj
*/
async function processMessage(obj) {
if (!obj || !obj.command) {
return;
}
let returnMsg;
/**
* @param {{checkPaused?: Boolean, checkConnected?: Boolean, ignoreConnected?: Boolean}} options
* @return {Promise<{enabled: Boolean, paused: Boolean, modeOn: String, lastModeOn: String, connected: Boolean, twinkly: Twinkly}>}
*/
async function getConnectionObj(options = {}) {
if (obj.message && typeof obj.message === 'object') {
try {
return await getConnection(obj.message.connection, options);
} catch (e) {
returnMsg = e.message;
}
} else {
returnMsg = 'Message has to be of type object!';
}
}
adapter.log.info(`[processMessage.${obj.command}] ${JSON.stringify(obj.message).substring(0, 100)}`);
try {
switch (obj.command.toLowerCase()) {
case 'uploadmovie': {
const connection = await getConnectionObj();
if (connection && typeof obj.message === 'object' && typeof obj.message.frames === 'object' && typeof obj.message.delay === 'number') {
returnMsg = await connection.twinkly.uploadMovie(obj.message.frames, obj.message.delay);
}
break;
}
case 'uploadtemplatemovie': {
const connection = await getConnectionObj();
if (connection && typeof obj.message === 'object' && typeof obj.message.template === 'number') {
returnMsg = await uploadTemplateMovie(obj.message.connection, obj.message.template);
}
break;
}
case 'uploadtwinklemovie': {
const connection = await getConnectionObj();
if (connection && typeof obj.message === 'object' && typeof obj.message.baseColor !== 'undefined' && typeof obj.message.secondColor !== 'undefined') {
returnMsg = await uploadTwinkleMovie(obj.message.connection, obj.message.baseColor, obj.message.secondColor);
}
break;
}
case 'sendrealtimeframe': {
const connection = await getConnectionObj();
if (connection && typeof obj.message === 'object' && typeof obj.message.frame === 'object') {
returnMsg = await connection.twinkly.sendRealtimeFrame(obj.message.frame);
}
break;
}
case 'generateframe': {
const connection = await getConnectionObj({checkPaused: false, ignoreConnected: true});
if (connection && typeof obj.message === 'object') {
if (obj.message.color) {
returnMsg = connection.twinkly.generateFrame(obj.message.color);
} else if (obj.message.colors) {
returnMsg = connection.twinkly.generateFrames(obj.message.colors);
}
}
break;
}
default: {
returnMsg = `Unknown command ${obj.command}!`;
break;
}
}
} catch (e) {
adapter.log.error(`[processMessage.${obj.command}] ${e}`);
}
if (returnMsg) {
adapter.log.info(`[processMessage.${obj.command}] ${JSON.stringify(returnMsg).substring(0, 100)}`);
if (obj.callback) {
adapter.sendTo(obj.from, obj.command, returnMsg, obj.callback);
}
}
}
/**
* Konfiguration auslesen und verarbeiten
* @return Promise<Boolean>
*/
async function syncConfig() {
let result = true;
// Details hinzufügen, wenn gewünscht
if (adapter.config.details)
statesConfig.push(apiObjectsMap.details.parent.id);
// MQTT hinzufügen, wenn gewünscht
if (adapter.config.mqtt)
statesConfig.push(apiObjectsMap.mqtt.parent.id);
// Network hinzufügen, wenn gewünscht
if (adapter.config.network)
statesConfig.push(apiObjectsMap.networkStatus.parent.id);
// Movies nur im Debugger anlegen
// statesConfig.push(apiObjectsMap.ledMovies.id);
// // statesConfig.push(apiObjectsMap.status.id);
try {
adapter.log.debug('[syncConfig] config devices: ' + JSON.stringify(adapter.config.devices));
adapter.log.debug('[syncConfig] config interval: ' + adapter.config.interval);
adapter.log.debug('[syncConfig] config details: ' + adapter.config.details);
adapter.log.debug('[syncConfig] config mqtt: ' + adapter.config.mqtt);
adapter.log.debug('[syncConfig] config network: ' + adapter.config.network);
if (adapter.config.devices.length === 0) {
adapter.log.info('no connections added...');
result = false;
}
// Verbindungen auslesen und erstellen
if (result)
for (const device of adapter.config.devices) {
const deviceName = stateTools.removeForbiddenChars(device.name.trim() !== '' ? device.name : device.host).replace(/[.\s]+/g, '_');
// Verbindung aktiviert?
if (!device.enabled) {
adapter.log.debug(`[syncConfig] ${deviceName} deaktiviert... ${JSON.stringify(device)}`);
continue;
}
// Host gefüllt
if (device.host === '') {
adapter.log.warn(`${deviceName}: Host nicht gefüllt!`);
continue;
}
// Verbindung anlegen
if (Object.keys(connections).includes(deviceName)) {
adapter.log.warn(`Objects with same id = ${deviceName} created for two connections ${JSON.stringify(device)}`);
} else {
connections[deviceName] = {
enabled : device.enabled,
paused : false,
modeOn : device.stateOn && (Object.keys(twinkly.lightModes.value).includes(device.stateOn) || twinkly.STATE_ON_LASTMODE === device.stateOn) ?
device.stateOn : twinkly.lightModes.value.movie,
lastModeOn : twinkly.lightModes.value.movie,
connected : false,
twinkly : new twinkly.Twinkly(adapter, deviceName, device.host, onDataChange)
};
await loadTwinklyDataFromObjects(deviceName);
}
}
// Prüfung ob aktive Verbindungen verfügbar sind
if (result && Object.keys(connections).length === 0) {
adapter.log.info('no enabled connections added...');
result = false;
}
if (result) {
// Create Instance Objects
await processObjectChanges('');
}
} catch (e) {
throw Error(e);
}
return result;
}
async function processObjectChanges(specificConnection) {
adapter.log.debug('[processObjectChanges] Get existing objects');
const _objects = await adapter.getAdapterObjectsAsync();
function removeConnectionObjects(connection) {
const connectionId = `${adapter.namespace}.${connection}`;
Object.keys(_objects).forEach(id => {
if (id === connectionId || id.startsWith(connectionId + '.')) {
delete _objects[id];
}
});
}
if (specificConnection === '') {
adapter.log.debug('[processObjectChanges] Remove all connections listed in config ==> Deletes all old connections');
Object.keys(connections).forEach(connection => {
removeConnectionObjects(connection);
});
} else {