forked from Apollon77/ioBroker.alexa2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
2241 lines (2042 loc) · 123 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
/* jshint -W097 */
/* jshint -W030 */
/* jshint -W083 */
/* jshint strict: false */
/* jslint node: true */
/* jslint esversion: 6 */
'use strict';
const Alexa = require('alexa-remote2');
const path = require('path');
const os = require('os');
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const shObjects = require(path.join(__dirname, 'lib', 'smarthomedevices.js'));
const bespokenVdSDK = require("virtual-device-sdk");
let bespokenDevice;
const forbiddenCharacters = /[\]\[*,;'"`<>\\\s?]/g;
let alexa;
const playerControls = {
controlPlay: { command: 'play', val: false, common: { type: 'boolean', read: false, write: true, role: 'button.play'}},
controlPause:{ command: 'pause', val: false, common: { type: 'boolean', read: false, write: true, role: 'button.pause'}}
};
const musicControls = {
controlNext: { command: 'next', val: false, common: { type: 'boolean', read: false, write: true, role: 'button.next'}},
controlPrevious: { command: 'previous', val: false, common: { type: 'boolean', read: false, write: true, role: 'button.prev'}},
controlForward: { command: 'forward', val: false, common: { type: 'boolean', read: false, write: true, role: 'button.forward'}},
controlRewind: { command: 'rewind', val: false, common: { type: 'boolean', read: false, write: true, role: 'button.reverse'}},
controlShuffle: { command: 'shuffle', val: false, common: { type: 'boolean', read: false, write: true, role: 'media.mode.shuffle'}},
controlRepeat: { command: 'repeat', val: false, common: { type: 'boolean', read: false, write: true, role: 'media.mode.repeat'}},
};
const commands = {
'weather': { val: false, common: { type: 'boolean', read: false, write: true, role: 'button'}},
'traffic': { val: false, common: { type: 'boolean', read: false, write: true, role: 'button'}},
'flashbriefing': { val: false, common: { type: 'boolean', read: false, write: true, role: 'button'}},
'goodmorning': { val: false, common: { type: 'boolean', read: false, write: true, role: 'button'}},
'singasong': { val: false, common: { type: 'boolean', read: false, write: true, role: 'button'}},
'tellstory': { val: false, common: { type: 'boolean', read: false, write: true, role: 'button'}},
'deviceStop': { val: false, common: { type: 'boolean', read: false, write: true, role: 'button'}},
'calendarToday': { val: false, common: { type: 'boolean', read: false, write: true, role: 'button'}},
'calendarTomorrow': { val: false, common: { type: 'boolean', read: false, write: true, role: 'button'}},
'calendarNext': { val: false, common: { type: 'boolean', read: false, write: true, role: 'button'}},
'notification': { val: '', common: { type: 'string', read: false, write: true, role: 'text'}}
};
const knownDeviceType = {
'A10A33FOX2NUBK': {name: 'Echo Spot', commandSupport: true, icon: 'icons/spot.png'},
'A12GXV8XMS007S': {name: 'FireTV', commandSupport: false, icon: 'icons/firetv.png'}, //? CHANGE_NAME,MICROPHONE,SUPPORTS_SOFTWARE_VERSION,ARTHUR_TARGET,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,ACTIVE_AFTER_FRO,FLASH_BRIEFING,VOLUME_SETTING
'A15ERDAKK5HQQG': {name: 'Sonos', commandSupport: false, icon: 'icons/sonos.png'}, //? AUDIO_PLAYER,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,AMAZON_MUSIC,TUNE_IN,PANDORA,REMINDERS,I_HEART_RADIO,CHANGE_NAME,VOLUME_SETTING,PEONY
'A17LGWINFBUTZZ': {name: 'Anker Roav Viva Alexa', commandSupport: false}, // PERSISTENT_CONNECTION,PEONY,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,VOLUME_SETTING,MICROPHONE,AUDIO_PLAYER,AMAZON_MUSIC,TUNE_IN,I_HEART_RADIO,KINDLE_BOOKS,GOLDFISH,TIMERS_AND_ALARMS,DREAM_TRAINING,DEREGISTER_DEVICE,REMINDERS,SLEEP,AUDIBLE,CHANGE_NAME
'A18O6U1UQFJ0XK': {name: 'Echo Plus 2.Gen', commandSupport: true, icon: 'icons/echo_plus2.png'}, // PERSISTENT_CONNECTION,ACTIVE_AFTER_FRO,PAIR_BT_SINK,GADGETS,ASCENDING_ALARM_VOLUME,SET_LOCALE,MICROPHONE,VOLUME_SETTING,AUDIBLE,PAIR_BT_SOURCE,AUDIO_PLAYER,DREAM_TRAINING,FAR_FIELD_WAKE_WORD,UPDATE_WIFI,TUPLE,CUSTOM_ALARM_TONE,REQUIRES_OOBE_FOR_SETUP,EARCONS,KINDLE_BOOKS,SUPPORTS_SOFTWARE_VERSION,ALLOW_LOG_UPLOAD,POPTART,GOLDFISH,DEREGISTER_DEVICE,SLEEP,TAHOE_BYOD,VOICE_TRAINING,SOUND_SETTINGS,CHANGE_NAME,FLASH_BRIEFING,AUX_SETTINGS,REMINDERS,LEMUR_ALPHA,PAIR_REMOTE,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,TUPLE_CATEGORY_A,TIMERS_AND_ALARMS
'A1DL2DVDQVK3Q': {name: 'Apps', commandSupport: false}, // (PEONY,VOLUME_SETTING)
'A1H0CMF1XM0ZP4': {name: 'Echo Dot/Bose', commandSupport: false}, // ??? // CHANGE_NAME,AUDIO_PLAYER,AMAZON_MUSIC,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,VOLUME_SETTING,LAMBDA // Bose: LAMBDA_DOWNCHANNEL,AUDIO_PLAYER,CHANGE_NAME,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,AMAZON_MUSIC,PANDORA,PEONY,I_HEART_RADIO,TUNE_IN,REMINDERS,VOLUME_SETTING
'A1J16TEDOYCZTN': {name: 'Fire tab', commandSupport: true, icon: 'icons/firetab.png'}, // (PEONY,MICROPHONE,SUPPORTS_SOFTWARE_VERSION,VOLUME_SETTING,ASX_TIME_ZONE,REMINDERS)
'A1NL4BVLQ4L3N3': {name: 'Echo Show', commandSupport: true, icon: 'icons/echo_show.png'}, // PAIR_BT_SINK,CUSTOM_ALARM_TONE,TIMERS_AND_ALARMS,TUNE_IN,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,SOUND_SETTINGS,SET_LOCALE,SLEEP,EARCONS,SHARKNADO,SUPPORTS_SOFTWARE_VERSION,TUPLE_CATEGORY_B,MICROPHONE,SALMON,ALLOW_LOG_UPLOAD,CHANGE_NAME,FAR_FIELD_WAKE_WORD,VOLUME_SETTING,AUDIO_PLAYER,I_HEART_RADIO,REMINDERS,ASCENDING_ALARM_VOLUME,PERSISTENT_CONNECTION,AUDIBLE,GADGETS,AMAZON_MUSIC,VOICE_TRAINING,FLASH_BRIEFING,GOLDFISH,FACTORY_RESET_DEVICE,TUPLE,PANDORA,DREAM_TRAINING,LEMUR_ALPHA,POPTART,KINDLE_BOOKS
'A1RTAM01W29CUP': {name: 'Windows App', commandSupport: false}, // FLASH_BRIEFING,AUDIO_PLAYER,VOLUME_SETTING,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,SET_LOCALE,SOUND_SETTINGS,PERSISTENT_CONNECTION,KINDLE_BOOKS,CHANGE_NAME,TUNE_IN,TIMERS_AND_ALARMS,AUDIBLE,AMAZON_MUSIC,MICROPHONE,I_HEART_RADIO,EARCONS,REMINDERS,SLEEP,DREAM_TRAINING,DEREGISTER_DEVICE
'A1X7HJX9QL16M5': {name: 'Bespoken.io', commandSupport: false},
'A21Z3CGI8UIP0F': {name: 'Apps', commandSupport: false}, // AUDIO_PLAYER,AMAZON_MUSIC,PANDORA,CHANGE_NAME,REMINDERS,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,I_HEART_RADIO,VOLUME_SETTING,TUNE_IN,LAMBDA_DOWNCHANNEL,PEONY
'A2825NDLA7WDZV': {name: 'Apps', commandSupport: false}, // PEONY,VOLUME_SETTING
'A2E0SNTXJVT7WK': {name: 'Fire TV V1', commandSupport: false, icon: 'icons/firetv.png'},
'A2GFL5ZMWNE0PX': {name: 'Fire TV', commandSupport: true, icon: 'icons/firetv.png'}, // SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,VOLUME_SETTING,SUPPORTS_SOFTWARE_VERSION,CHANGE_NAME,ACTIVE_AFTER_FRO,ARTHUR_TARGET,FLASH_BRIEFING
'A2IVLV5VM2W81': {name: 'Apps', commandSupport: false}, // VOLUME_SETTING,MICROPHONE
'A2L8KG0CT86ADW': {name: 'RaspPi', commandSupport: false}, // KINDLE_BOOKS,DREAM_TRAINING,PEONY,VOLUME_SETTING,CHANGE_NAME,PAIR_BT_SINK,SLEEP,I_HEART_RADIO,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,PERSISTENT_CONNECTION,TUNE_IN,TIMERS_AND_ALARMS,MICROPHONE,AUDIBLE,DEREGISTER_DEVICE,GOLDFISH,AUDIO_PLAYER,REMINDERS,AMAZON_MUSIC
'A2LWARUGJLBYEW': {name: 'Fire TV Stick V2', commandSupport: false, icon: 'icons/firetv.png'}, // ACTIVE_AFTER_FRO,FLASH_BRIEFING,ARTHUR_TARGET,CHANGE_NAME,VOLUME_SETTING,SUPPORTS_SOFTWARE_VERSION,MICROPHONE,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY
'A2M35JJZWCQOMZ': {name: 'Echo Plus', commandSupport: true, icon: 'icons/echo.png'}, // PAIR_BT_SINK,SOUND_SETTINGS,FAR_FIELD_WAKE_WORD,CUSTOM_ALARM_TONE,MICROPHONE,VOLUME_SETTING,ACTIVE_AFTER_FRO,POPTART,REMINDERS,AMAZON_MUSIC,TUNE_IN,CHANGE_NAME,I_HEART_RADIO,DEREGISTER_FACTORY_RESET,SUPPORTS_SOFTWARE_VERSION,EARCONS,PAIR_REMOTE,PERSISTENT_CONNECTION,LEMUR_ALPHA,SALMON,DREAM_TRAINING,UPDATE_WIFI,VOICE_TRAINING,TIMERS_AND_ALARMS,ASCENDING_ALARM_VOLUME,AUDIBLE,SLEEP,AUDIO_PLAYER,PAIR_BT_SOURCE,FLASH_BRIEFING,SET_LOCALE,REQUIRES_OOBE_FOR_SETUP,DEREGISTER_DEVICE,PANDORA,GOLDFISH,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,KINDLE_BOOKS
'A2M4YX06LWP8WI': {name: 'Fire Tab', commandSupport: false, icon: 'icons/firetab.png'}, // SUPPORTS_SOFTWARE_VERSION,VOLUME_SETTING,ASX_TIME_ZONE,MICROPHONE,PEONY
'A2OSP3UA4VC85F': {name: 'Sonos', commandSupport: true, icon: 'icons/sonos.png'}, // DEREGISTER_DEVICE,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,CHANGE_NAME,KINDLE_BOOKS,AUDIO_PLAYER,TIMERS_AND_ALARMS,VOLUME_SETTING,PEONY,AMAZON_MUSIC,REMINDERS,SLEEP,I_HEART_RADIO,AUDIBLE,GOLDFISH,TUNE_IN,DREAM_TRAINING,PERSISTENT_CONNECTION
'A2T0P32DY3F7VB': {name: 'echosim.io', commandSupport: false},
'A2TF17PFR55MTB': {name: 'Apps', commandSupport: false}, // VOLUME_SETTING,MICROPHONE
'A32DOYMUN6DTXA': {name: 'Echo Dot 3.Gen', commandSupport: true, icon: '/icons/echo_dot3.png'}, // PAIR_BT_SINK,CUSTOM_ALARM_TONE,PAIR_REMOTE,TIMERS_AND_ALARMS,SUPPORTS_CONNECTED_HOME,TUNE_IN,SOUND_SETTINGS,DEREGISTER_DEVICE,SET_LOCALE,SLEEP,EARCONS,UPDATE_WIFI,PAIR_BT_SOURCE,SUPPORTS_SOFTWARE_VERSION,REQUIRES_OOBE_FOR_SETUP,MICROPHONE,SALMON,TAHOE_BYOD,CHANGE_NAME,FAR_FIELD_WAKE_WORD,VOLUME_SETTING,AUDIO_PLAYER,I_HEART_RADIO,REMINDERS,PERSISTENT_CONNECTION,AUDIBLE,GADGETS,SUPPORTS_CONNECTED_HOME_ALL,AMAZON_MUSIC,VOICE_TRAINING,FLASH_BRIEFING,DEREGISTER_FACTORY_RESET,GOLDFISH,PANDORA,ACTIVE_AFTER_FRO,DREAM_TRAINING,LEMUR_ALPHA,POPTART,KINDLE_BOOKS
'A37SHHQ3NUL7B5': {name: 'Bose Homespeaker', commandSupport: false}, // MICROPHONE,AMAZON_MUSIC,AUDIO_PLAYER,SLEEP,PERSISTENT_CONNECTION,I_HEART_RADIO,AUDIBLE,TIMERS_AND_ALARMS,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,DREAM_TRAINING,TUNE_IN,VOLUME_SETTING,GOLDFISH,KINDLE_BOOKS,DEREGISTER_DEVICE,CHANGE_NAME
'A38BPK7OW001EX': {name: 'Raspberry Alexa', commandSupport: false, icon: 'icons/raspi.png'}, // TIMERS_AND_ALARMS,AMAZON_MUSIC,VOLUME_SETTING,AUDIBLE,I_HEART_RADIO,TUNE_IN,KINDLE_BOOKS,DEREGISTER_DEVICE,AUDIO_PLAYER,SLEEP,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,PERSISTENT_CONNECTION,DREAM_TRAINING,MICROPHONE,GOLDFISH,CHANGE_NAME,PEONY
'A38EHHIB10L47V': {name: 'Echo Dot', commandSupport: true, icon: '/icons/echo_dot.png'}, // ASCENDING_ALARM_VOLUME,MICROPHONE,REMINDERS,ASX_TIME_ZONE,VOLUME_SETTING,PEONY,SUPPORTS_SOFTWARE_VERSION)
'A3C9PE6TNYLTCH': {name: 'Multiroom', commandSupport: true, icon: '/icons/multiroom.png'}, // AUDIO_PLAYER,AMAZON_MUSIC,KINDLE_BOOKS,TUNE_IN,AUDIBLE,PANDORA,I_HEART_RADIO,SALMON,VOLUME_SETTING
'A3H674413M2EKB': {name: 'echosim.io', commandSupport: false},
'A3HF4YRA2L7XGC': {name: 'Fire TV Cube', commandSupport: true}, // FLASH_BRIEFING,TUNE_IN,PANDORA,FAR_FIELD_WAKE_WORD,DREAM_TRAINING,AMAZON_MUSIC,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,AUDIBLE,SUPPORTS_SOFTWARE_VERSION,PAIR_BT_SINK,CHANGE_NAME,AUDIO_PLAYER,VOICE_TRAINING,SET_LOCALE,EARCONS,SOUND_SETTINGS,SALMON,ACTIVE_AFTER_FRO,SLEEP,I_HEART_RADIO,TIMERS_AND_ALARMS,CUSTOM_ALARM_TONE,PERSISTENT_CONNECTION,ARTHUR_TARGET,KINDLE_BOOKS,REMINDERS
'A3NPD82ABCPIDP': {name: 'Sonos Beam', commandSupport: true, icon: 'icons/sonos.png'}, // AMAZON_MUSIC,CHANGE_NAME,AUDIO_PLAYER,KINDLE_BOOKS,SLEEP,DREAM_TRAINING,AUDIBLE,DEREGISTER_DEVICE,I_HEART_RADIO,GOLDFISH,PERSISTENT_CONNECTION,MICROPHONE,TIMERS_AND_ALARMS,PEONY,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,REMINDERS,VOLUME_SETTING,TUNE_IN
'A3R9S4ZZECZ6YL': {name: 'Fire Tab HD 10', commandSupport: true, icon: 'icons/firetab.png'}, // ASX_TIME_ZONE,PEONY,VOLUME_SETTING,SUPPORTS_SOFTWARE_VERSION
'A3S5BH2HU6VAYF': {name: 'Echo Dot 2.Gen', commandSupport: true, icon: '/icons/echo_dot.png'}, // PAIR_BT_SINK,CUSTOM_ALARM_TONE,PAIR_REMOTE,TIMERS_AND_ALARMS,SUPPORTS_CONNECTED_HOME,TUNE_IN,SOUND_SETTINGS,DEREGISTER_DEVICE,SET_LOCALE,SLEEP,EARCONS,UPDATE_WIFI,PAIR_BT_SOURCE,SUPPORTS_SOFTWARE_VERSION,REQUIRES_OOBE_FOR_SETUP,MICROPHONE,SALMON,TAHOE_BYOD,CHANGE_NAME,FAR_FIELD_WAKE_WORD,VOLUME_SETTING,AUDIO_PLAYER,I_HEART_RADIO,REMINDERS,PERSISTENT_CONNECTION,AUDIBLE,GADGETS,SUPPORTS_CONNECTED_HOME_ALL,AMAZON_MUSIC,VOICE_TRAINING,FLASH_BRIEFING,DEREGISTER_FACTORY_RESET,GOLDFISH,PANDORA,ACTIVE_AFTER_FRO,DREAM_TRAINING,LEMUR_ALPHA,POPTART,KINDLE_BOOKS
'A3SSG6GR8UU7SN': {name: 'Echo Sub', commandSupport: true, icon: '/icons/echo_sub.png'}, // PERSISTENT_CONNECTION,ACTIVE_AFTER_FRO,SET_LOCALE,MICROPHONE,VOLUME_SETTING,AUDIBLE,AUDIO_PLAYER,UPDATE_WIFI,TUPLE,CUSTOM_ALARM_TONE,REQUIRES_OOBE_FOR_SETUP,EARCONS,KINDLE_BOOKS,TUPLE_CATEGORY_C,SUPPORTS_SOFTWARE_VERSION,ALLOW_LOG_UPLOAD,DEREGISTER_DEVICE,SLEEP,SOUND_SETTINGS,CHANGE_NAME,FLASH_BRIEFING,REMINDERS,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,TIMERS_AND_ALARMS
'A7WXQPH584YP': {name: 'Echo 2.Gen', commandSupport: true, icon: '/icons/echo2.png'}, // PAIR_BT_SINK,CUSTOM_ALARM_TONE,PAIR_REMOTE,TIMERS_AND_ALARMS,TUNE_IN,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,SOUND_SETTINGS,DEREGISTER_DEVICE,SET_LOCALE,SLEEP,EARCONS,UPDATE_WIFI,PAIR_BT_SOURCE,SUPPORTS_SOFTWARE_VERSION,REQUIRES_OOBE_FOR_SETUP,MICROPHONE,SALMON,TAHOE_BYOD,CHANGE_NAME,FAR_FIELD_WAKE_WORD,VOLUME_SETTING,AUDIO_PLAYER,I_HEART_RADIO,REMINDERS,ASCENDING_ALARM_VOLUME,PERSISTENT_CONNECTION,AUDIBLE,GADGETS,TUPLE_CATEGORY_A,AMAZON_MUSIC,VOICE_TRAINING,FLASH_BRIEFING,DEREGISTER_FACTORY_RESET,GOLDFISH,TUPLE,PANDORA,ACTIVE_AFTER_FRO,DREAM_TRAINING,LEMUR_ALPHA,POPTART,KINDLE_BOOKS
'AB72C64C86AW2': {name: 'Echo', commandSupport: true, icon: '/icons/echo.png'}, // PAIR_BT_SINK,CUSTOM_ALARM_TONE,PAIR_REMOTE,TIMERS_AND_ALARMS,SUPPORTS_CONNECTED_HOME,TUNE_IN,SOUND_SETTINGS,DEREGISTER_DEVICE,SET_LOCALE,SLEEP,EARCONS,UPDATE_WIFI,PAIR_BT_SOURCE,SUPPORTS_SOFTWARE_VERSION,REQUIRES_OOBE_FOR_SETUP,TUPLE_CATEGORY_B,MICROPHONE,SALMON,TAHOE_BYOD,CHANGE_NAME,FAR_FIELD_WAKE_WORD,VOLUME_SETTING,AUDIO_PLAYER,I_HEART_RADIO,REMINDERS,ASCENDING_ALARM_VOLUME,PERSISTENT_CONNECTION,AUDIBLE,GADGETS,SUPPORTS_CONNECTED_HOME_ALL,AMAZON_MUSIC,VOICE_TRAINING,FLASH_BRIEFING,DEREGISTER_FACTORY_RESET,GOLDFISH,TUPLE,PANDORA,ACTIVE_AFTER_FRO,DREAM_TRAINING,LEMUR_ALPHA,POPTART,KINDLE_BOOKS
'ADVBD696BHNV5': {name: 'Fire TV Stick V1', commandSupport: false, icon: 'icons/firetv.png'}, // ARTHUR_TARGET,SUPPORTS_SOFTWARE_VERSION,FLASH_BRIEFING,MICROPHONE,PERSISTENT_CONNECTION,CHANGE_NAME,ACTIVE_AFTER_FRO,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,VOLUME_SETTING
'AILBSA2LNTOYL': {name: 'reverb App', commandSupport: false, icon: 'icons/reverb.png'},
'AVE5HX13UR5NO': {name: 'Logitech Zero Touch', commandSupport: false}, // SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,TUNE_IN,MICROPHONE,AUDIO_PLAYER,TIMERS_AND_ALARMS,PEONY,GOLDFISH,DEREGISTER_DEVICE,AUDIBLE,AMAZON_MUSIC,PERSISTENT_CONNECTION,KINDLE_BOOKS,CHANGE_NAME,I_HEART_RADIO,SLEEP,DREAM_TRAINING,VOLUME_SETTING
'AWZZ5CVHX2CD': {name: 'Echo Show 2.Gen', commandSupport: true, icon: '/icons/echo_show2.png'}, // TUNE_IN,AUDIBLE,SUPPORTS_CONNECTED_HOME_CLOUD_ONLY,LEMUR_ALPHA,GADGETS,FLASH_BRIEFING,SHARKNADO,PAIR_BT_SINK,PERSISTENT_CONNECTION,CHANGE_NAME,CUSTOM_ALARM_TONE,TUPLE_CATEGORY_B,EARCONS,I_HEART_RADIO,REMINDERS,SET_LOCALE,DREAM_TRAINING,POPTART,AMAZON_MUSIC,KINDLE_BOOKS,SALMON,FACTORY_RESET_DEVICE,SLEEP,GOLDFISH,ASCENDING_ALARM_VOLUME,SOUND_SETTINGS,ALLOW_LOG_UPLOAD,FAR_FIELD_WAKE_WORD,AUDIO_PLAYER,VOLUME_SETTING,VOICE_TRAINING,TUPLE,TIMERS_AND_ALARMS,SUPPORTS_SOFTWARE_VERSION,PANDORA,MICROPHONE
};
const unknownDeviceWarnings = {};
let updateStateTimer;
let updateHistoryTimer;
const updatePlayerTimer = {};
const updateNotificationTimer = {};
let musicProviders;
let automationRoutines;
let routineTriggerUtterances;
const playerDevices = {};
const lastPlayerState = {};
const notificationTimer = {};
let wsMqttConnected = false;
let shApplianceEntityMap = {};
let shGroupDetails = {};
let shDeviceParamValues = {};
let shQueryBlocker = {};
const stateChangeTrigger = {};
const objectQueue = [];
const existingStates = {};
const adapterObjects = {};
function setOrUpdateObject(id, obj, value, stateChangeCallback, createNow) {
let callback = null;
if (typeof value === 'function') {
createNow = stateChangeCallback;
stateChangeCallback = value;
value = undefined;
}
if (typeof createNow === 'function') {
callback = createNow;
createNow = true;
}
if (! obj.type) {
obj.type = 'state';
}
if (! obj.common) {
obj.common = {};
}
if (! obj.native) {
obj.native = {};
}
if (obj.common && obj.common.type === undefined) {
if (value !== null && value !== undefined) {
obj.common.type = typeof value;
}
else if (obj.common.def !== undefined) {
obj.common.type = typeof obj.common.def;
}
else if (obj.type === 'state') {
obj.common.type = 'mixed';
}
}
if (obj.common && obj.common.read === undefined) {
obj.common.read = true; //!(obj.common.type === 'boolean' && !!stateChangeCallback);
}
if (obj.common && obj.common.write === undefined) {
obj.common.write = !!stateChangeCallback;
}
/* if (obj.common && obj.common.def === undefined && value !== null && value !== undefined) {
obj.common.def = value;
}*/
if (obj.common && obj.common.name === undefined) {
obj.common.name = id.split('.').pop();
}
if (!adapterObjects[id] && existingStates[id]) {
adapterObjects[id] = existingStates[id];
if (adapterObjects[id].from) delete adapterObjects[id].from;
if (adapterObjects[id].ts) delete adapterObjects[id].ts;
if (adapterObjects[id].acl) delete adapterObjects[id].acl;
if (adapterObjects[id]._id) delete adapterObjects[id]._id;
if (obj.common.def === undefined && adapterObjects[id].common.def !== undefined) delete adapterObjects[id].common.def;
if (obj.common.unit === undefined && adapterObjects[id].common.unit !== undefined) delete adapterObjects[id].common.unit;
if (obj.common.min === undefined && adapterObjects[id].common.min !== undefined) delete adapterObjects[id].common.min;
if (obj.common.max === undefined && adapterObjects[id].common.max !== undefined) delete adapterObjects[id].common.max;
value = undefined; // when exists and it is first time do not overwrite value!
}
if (existingStates[id]) delete(existingStates[id]);
if (adapterObjects[id] && isEquivalent(obj, adapterObjects[id])) {
//adapter.log.debug('Object unchanged for ' + id + ': ' + JSON.stringify(adapterObjects[id]) + ' - update only: ' + JSON.stringify(value));
if (value !== undefined) adapter.setState(id, value, true);
if (stateChangeCallback) stateChangeTrigger[id] = stateChangeCallback;
return;
}
//adapter.log.debug('Add Object for ' + id + ': ' + JSON.stringify(adapterObjects[id]) + '/' + JSON.stringify(obj));
objectQueue.push({
id: id,
value: value,
obj: obj,
stateChangeCallback: stateChangeCallback
});
adapterObjects[id] = JSON.parse(JSON.stringify(obj));
//adapter.log.debug('Create object for ' + id + ': ' + JSON.stringify(obj) + ' with value: ' + JSON.stringify(value));
if (createNow) {
processObjectQueue(callback);
}
}
function deleteObject(id) {
const obj = adapterObjects[id];
if (obj && obj.type) {
if (obj.type !== 'state') {
Object.keys(adapterObjects).forEach((objId) => {
if (objId.startsWith(id + '.')) {
adapter.delObject(objId, (err) => {
err = err ? ' (' + err + ')' : '';
adapter.log.info(adapterObjects[objId].type + ' ' + objId + ' deleted' + err);
if (!err) {
delete adapterObjects[objId];
}
});
}
});
}
adapter.delObject(id, (err) => {
adapter.log.info(adapterObjects[id].type + ' ' + id + ' deleted (' + err + ')');
if (!err) {
delete adapterObjects[id];
}
});
}
}
function isEquivalent(a, b) {
//adapter.log.debug('Compare ' + JSON.stringify(a) + ' with ' + JSON.stringify(b));
// Create arrays of property names
if (a === null || a === undefined || b === null || b === undefined) {
return (a === b);
}
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
// If number of properties is different,
// objects are not equivalent
if (aProps.length !== bProps.length) {
//console.log('num props different: ' + JSON.stringify(aProps) + ' / ' + JSON.stringify(bProps));
return false;
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
if (typeof a[propName] !== typeof b[propName]) {
//console.log('type props ' + propName + ' different');
return false;
}
if (typeof a[propName] === 'object') {
if (!isEquivalent(a[propName], b[propName])) {
return false;
}
}
else {
// If values of same property are not equal,
// objects are not equivalent
if (a[propName] !== b[propName]) {
//console.log('props ' + propName + ' different');
return false;
}
}
}
// If we made it this far, objects
// are considered equivalent
return true;
}
function processObjectQueue(callback) {
if (!objectQueue.length) {
callback && callback();
return;
}
function handleObject(queueEntry, callback) {
if (!queueEntry.obj) {
handleValue(queueEntry, () => {
return callback && callback();
});
}
adapter.getObject(queueEntry.id, (err, obj) => {
if (!err && obj) {
adapter.extendObject(queueEntry.id, queueEntry.obj, () => {
handleValue(queueEntry, () => {
return callback && callback();
});
});
}
else {
adapter.setObject(queueEntry.id, queueEntry.obj, () => {
handleValue(queueEntry, () => {
return callback && callback();
});
});
}
});
}
function handleValue(queueEntry, callback) {
if (queueEntry.value === null || queueEntry.value === undefined) {
stateChangeTrigger[queueEntry.id] = queueEntry.stateChangeCallback;
return callback && callback();
}
adapter.setState(queueEntry.id, queueEntry.value, true, () => {
stateChangeTrigger[queueEntry.id] = queueEntry.stateChangeCallback;
return callback && callback();
});
}
const queueEntry = objectQueue.shift();
handleObject(queueEntry, () => {
return processObjectQueue(callback);
});
}
const adapter = utils.Adapter('alexa2');
adapter.on('unload', (callback) => {
if (alexa) {
alexa.stop();
}
callback && callback();
});
adapter.on('stateChange', (id, state) => {
adapter.log.debug('State changed ' + id + ': ' + JSON.stringify(state));
if (!state || state.ack) return;
id = id.substr(adapter.namespace.length + 1);
if (state && state.from && state.from.startsWith('system.adapter.cloud') && id.endsWith('.Commands.speak')) {
state.val = state.val.replace(/<[^>]+>/g, '').replace('/ /g', ' ');
}
if (typeof stateChangeTrigger[id] === 'function') {
if (adapterObjects[id] && adapterObjects[id].common && adapterObjects[id].common.type && adapterObjects[id].common.type !== 'mixed') {
if (adapterObjects[id].common.type === 'boolean' && adapterObjects[id].common.role && adapterObjects[id].common.role.startsWith('button')) state.val = !!state.val;
if (typeof state.val !== adapterObjects[id].common.type) {
adapter.log.error('Datatype for ' + id + ' differs from expected, ignore state change! Please write correct datatype (' + adapterObjects[id].common.type + ')');
return;
}
}
stateChangeTrigger[id](state.val);
}
if (!wsMqttConnected) scheduleStatesUpdate(3000);
});
adapter.on('objectChange', (id, object) => {
adapter.log.debug('Object changed ' + id + ': ' + JSON.stringify(object));
let ar = id.split('.');
if (ar[2] === 'Echo-Devices' && ar.length === 4) {
if (object === null) {
//deleted, do nothing
return;
}
let device = alexa.serialNumbers[ar[3]];
if (object && object.common && object.common.name) {
if (typeof device.rename === 'function') device.rename(object.common.name);
}
return;
}
});
adapter.on('ready', () => {
adapter.getForeignObject('system.config', (err, obj) => {
if (obj && obj.native && obj.native.secret) {
//noinspection JSUnresolvedVariable
adapter.config.email = decrypt(obj.native.secret, adapter.config.email);
adapter.config.password = decrypt(obj.native.secret, adapter.config.password);
} else {
//noinspection JSUnresolvedVariable
adapter.config.email = decrypt('Zgfr56gFe87jJOM', adapter.config.email);
adapter.config.password = decrypt('Zgfr56gFe87jJOM', adapter.config.password);
}
loadExistingAccessories(main);
});
});
process.on('SIGINT', () => {
if (alexa) {
alexa.stop();
}
});
process.on('SIGTERM', () => {
if (alexa) {
alexa.stop();
}
});
process.on('uncaughtException', err => {
if (adapter && adapter.log) {
adapter.log.warn('Exception: ' + err);
}
if (alexa) {
alexa.stop();
}
});
function decrypt(key, value) {
let result = '';
for (let i = 0; i < value.length; ++i) {
result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i));
}
return result;
}
function setRequestResult(err, res) {
if (!err) return;
adapter.setState('requestResult', err.message ? err.message : err, true);
}
/**
* Konvertiert eine Sekundenzahl in einen String im Format (HH:)MM:SS
*
* @param {number} sec seconds
* @return string
*/
function sec2HMS(sec) {
if (sec === 0) {
return '0';
}
const sec_num = parseInt(sec, 10);
let hours = Math.floor(sec_num / 3600);
let minutes = Math.floor((sec_num - (hours * 3600)) / 60);
let seconds = sec_num - (hours * 3600) - (minutes * 60);
if (minutes < 10) {minutes = '0' + minutes;}
if (seconds < 10) {seconds = '0' + seconds;}
if (hours === 0) {
return minutes + ':' + seconds;
}
if (hours < 10) {hours = '0' + hours;}
return hours + ':' + minutes + ':' + seconds;
}
function scheduleNotificationUpdate(deviceId, delay) {
if (updateNotificationTimer[deviceId]) {
clearTimeout(updateNotificationTimer[deviceId]);
}
updateNotificationTimer[deviceId] = setTimeout(() => {
updateNotificationTimer[deviceId] = null;
updateNotificationStates(deviceId);
}, delay);
}
function schedulePlayerUpdate(deviceId, delay) {
if (updatePlayerTimer[deviceId]) {
clearTimeout(updatePlayerTimer[deviceId]);
}
updatePlayerTimer[deviceId] = setTimeout(() => {
updatePlayerTimer[deviceId] = null;
updatePlayerStatus(deviceId);
}, delay);
}
function scheduleStatesUpdate(delay) {
if (updateStateTimer) {
clearTimeout(updateStateTimer);
}
if (delay === undefined) {
delay = adapter.config.updateStateInterval * 1000;
if (wsMqttConnected) delay = 60 * 60 * 1000; // 1h
}
updateStateTimer = setTimeout(() => {
updateStateTimer = null;
updateStates();
}, delay);
}
function updateStates(callback) {
let i = 0;
if (updateStateTimer) {
clearTimeout(updateStateTimer);
updateStateTimer = null;
}
updateDeviceStatus(() => {
updateBluetoothStatus(() => {
updatePlayerStatus();
});
});
}
/**
* Inkrementiert 'mediaProgress' alle 2 Sekunden um 2. So wird ein permanentes https-get überflüssig
* ruft sich nach 2 Sekunden erneut selbst auf, wenn 'currentState' noch auf 'PLAYING' steht.
* ist 'mediaProgress' größer als 'mediaLength', so ist der Song zu Ende und 'updateDevice' wird aufgerufen.
*
* @param {string} serialNumber serial number
*/
function updateMediaProgress(serialNumber) {
if (!lastPlayerState[serialNumber] || !lastPlayerState[serialNumber].resPlayer) return;
if (lastPlayerState[serialNumber].timeout) {
clearTimeout(lastPlayerState[serialNumber].timeout);
lastPlayerState[serialNumber].timeout = null;
}
let resPlayer = lastPlayerState[serialNumber].resPlayer;
let devId = lastPlayerState[serialNumber].devId;
let lastTimestamp = lastPlayerState[serialNumber].ts;
let currentState = resPlayer.playerInfo.state;
let mediaProgress = parseInt(resPlayer.playerInfo.progress.mediaProgress, 10);
let mediaLength = parseInt(resPlayer.playerInfo.progress.mediaLength, 10);
if (currentState === 'PLAYING') {
let timeframe = ~~((Date.now() - lastTimestamp) / 1000); // calculae time since last data
let mediaProgressNew = mediaProgress + timeframe; // add this to the progress
// Am Ende des Titels soll neu geladen werden. Ist es Radio (länge = 0) dann alle 200 sekunden
if (mediaProgressNew > mediaLength && (mediaLength > 0 || mediaProgressNew % 200 < 2)) {
schedulePlayerUpdate(serialNumber, 2000);
return;
}
// Nun mediaProgress und mediaProgressPercent neu berechnen
let mediaProgressPercent = 0;
if (mediaLength > 0) {
mediaProgressPercent = Math.round((((mediaProgressNew) * 100) / mediaLength));
}
adapter.setState(devId + '.Player.mediaProgressPercent', mediaProgressPercent, true);
adapter.setState(devId + '.Player.mediaProgress', mediaProgressNew, true);
adapter.setState(devId + '.Player.mediaProgressStr', sec2HMS(mediaProgressNew), true);
lastPlayerState[serialNumber].timeout = setTimeout( () => {
lastPlayerState[serialNumber].timeout = null;
updateMediaProgress(serialNumber);
}, 2000);
}
else {
schedulePlayerUpdate(serialNumber, (2 * 60 * 60 + 5) * 1000);
}
}
function queryAllSmartHomeDevices(initial, callback) {
let reqArr = [];
let blocked = [];
for (let applianceId in shApplianceEntityMap) {
if (!shApplianceEntityMap.hasOwnProperty(applianceId)) continue;
if (shApplianceEntityMap[applianceId].readable) {
if (shQueryBlocker[applianceId]) {
blocked.push(applianceId);
continue;
}
reqArr.push(applianceId);
if (!initial) {
let delay = 600000;
if (!applianceId.startsWith('SKILL_')) delay = 60000;
shQueryBlocker[applianceId] = setTimeout(() => {
shQueryBlocker[applianceId] = null;
}, delay);
}
}
}
if (blocked.length) {
adapter.log.warn('Smarthome device queries blocked for ' + blocked.join(','));
}
if (!reqArr.length) {
return callback && callback();
}
alexa.querySmarthomeDevices(reqArr, (err, res) => {
if (!err) {
updateSmarthomeDeviceStates(res);
}
callback && callback();
});
}
function buildSmartHomeControlParameters(entityId, objs, changedParamName, changedParamvalue) {
function getValueToSend(obj, value) {
if (value && obj.native.valueTrue) {
value = obj.native.valueTrue;
}
else if (!value && obj.native.valueFalse) {
value = obj.native.valueFalse;
}
else if (obj.native.valueMap) {
value = obj.native.valueMap[value];
}
else {
if (value === undefined && obj.native.defaultValue !== undefined) {
value = obj.native.defaultValue;
}
if (typeof value === 'number' && obj.native.factor) {
value *= obj.native.factor;
}
value = String(value);
}
return value;
}
let parameters = {};
if (!Array.isArray(objs)) objs = [objs];
for (let obj of objs) {
let paramName = obj.common.name;
if (obj.common.name === changedParamName) {
if (obj.native.action) {
parameters.action = obj.native.action;
if (obj.native.paramName) paramName = obj.native.paramName;
parameters[paramName] = getValueToSend(obj, changedParamvalue);
}
else {
if (changedParamvalue && obj.native.actionTrue) {
parameters.action = obj.native.actionTrue;
}
else if (!changedParamvalue && obj.native.actionFalse) {
parameters.action = obj.native.actionFalse;
}
}
}
else if (!obj.native.donotsend) {
if (obj.native.paramName) paramName = obj.native.paramName;
parameters[paramName] = getValueToSend(obj, shDeviceParamValues['Smart-Home-Devices.' + entityId + '.' + obj.common.name]);
}
}
return parameters;
}
function padding(num) {
num = num.toString(16);
if (num.length < 2) num = '0' + num;
return num;
}
// expected hue range: [0, 360]
// expected saturation range: [0, 1]
// expected lightness range: [0, 1]
// Based on http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c
function hsvToRgb(h, s, v) {
let r;
let g;
let b;
h = h / 360;
let i = Math.floor(h * 6);
let f = h * 6 - i;
let p = v * (1 - s);
let q = v * (1 - f * s);
let t = v * (1 - (1 - f) * s);
switch(i % 6){
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
return '#' + padding(Math.round(r * 255)) + padding(Math.round(g * 255)) + padding(Math.round(b * 255));
}
function updateSmarthomeDeviceStates(res) {
function handleObject(deviceEntityId, cap, stateName) {
if (!adapterObjects['Smart-Home-Devices.' + deviceEntityId + '.' + stateName]) {
adapter.log.debug('ignoring value "' + cap.namespace + '.' + cap.value + '" for Smart-Home-Devices.' + deviceEntityId + '.' + stateName);
return null;
}
let native = adapterObjects['Smart-Home-Devices.' + deviceEntityId + '.' + stateName].native;
let value = cap.value;
if (typeof value === 'object') {
value = value[native.valueSubKey || 'value'];
}
if (value === undefined) {
adapter.log.debug('Value not provided in answer for Smart-Home-Devices.' + deviceEntityId + '.' + stateName);
return null;
}
if (native.valueTrue && native.valueTrue === value) {
value = true;
}
else if (native.valueFalse && native.valueFalse === value) {
value = false;
}
else if (native.valueMap) {
adapter.log.debug('Get Index for value "' + cap.namespace + '.' + cap.value + '" for Smart-Home-Devices.' + deviceEntityId + '.' + stateName + ', value=' + value + ' of ' + JSON.stringify(native.valueMap));
value = native.valueMap.indexOf(value);
if (value === -1) return null;
}
value = {
val: value,
ack: true
};
if (cap.timeOfSample) value.ts = new Date(cap.timeOfSample).getTime();
adapter.setState('Smart-Home-Devices.' + deviceEntityId + '.' + stateName, value);
shDeviceParamValues['Smart-Home-Devices.' + deviceEntityId + '.' + stateName] = value.val;
return value.val;
}
if (res && res.errors && res.errors.length === 1 && res.errors[0] && res.errors[0].code) {
if (!res.deviceStates || res.deviceStates.length === 0) {
adapter.setState('requestResult', res.errors[0].code, true);
}
}
if (res.deviceStates) {
for (let states of res.deviceStates) {
if (!states.entity || !states.entity.entityId || !shApplianceEntityMap[states.entity.entityId]) continue;
const deviceEntityId = shApplianceEntityMap[states.entity.entityId].entityId;
if (deviceEntityId && states.capabilityStates) {
let colorDataIncluded = false;
const capValues = {};
for (let cap of states.capabilityStates) {
try {
cap = JSON.parse(cap);
}
catch (e) {
adapter.log.warn(e);
continue;
}
if (!shObjects.capabilityObjects[cap.namespace]) {
adapter.log.debug('unsupported namespace "' + cap.namespace + '" for Smart-Home-Devices.' + deviceEntityId + '.' + cap.name);
continue;
}
if (!shObjects.capabilityObjects[cap.namespace][cap.name]) {
adapter.log.debug('unsupported name "' + cap.namespace + '.' + cap.name + '" for Smart-Home-Devices.' + deviceEntityId + '.' + cap.name);
continue;
}
for (let obj of shObjects.capabilityObjects[cap.namespace][cap.name]) {
if (typeof obj === 'string') { // Redirect!!
capValues[obj] = handleObject(deviceEntityId, cap, obj);
adapter.log.debug(cap.namespace + '.' + cap.value + ': setValueFor=' + obj + ' to ' + capValues[obj]);
}
else {
capValues[obj.common.name] = handleObject(deviceEntityId, cap, obj.common.name);
}
}
if (cap.namespace === 'Alexa.ColorController') {
if (capValues['color-hue'] !== null && capValues['color-saturation'] !== null && capValues['color-brightness'] !== null) {
const colorRgb = hsvToRgb(capValues['color-hue'], capValues['color-saturation'], capValues['color-brightness']);
adapter.setState('Smart-Home-Devices.' + deviceEntityId + '.colorRgb', colorRgb, true);
shDeviceParamValues['Smart-Home-Devices.' + deviceEntityId + '.colorRgb'] = colorRgb;
capValues.colorRgb = colorRgb;
colorDataIncluded = true;
}
}
}
if (colorDataIncluded && capValues.colorRgb && !capValues.colorName) {
const colorRgbSearch = hsvToRgb(capValues['color-hue'], capValues['color-saturation'], 1.0);
const nearestColor = shObjects.nearestColor(colorRgbSearch);
let native = adapterObjects['Smart-Home-Devices.' + deviceEntityId + '.colorName'].native;
let value = native.valueMap.indexOf(nearestColor.name);
adapter.log.debug('find nearest color for ' + colorRgbSearch + ' (' + capValues.colorRgb + '): index=' + value + ' / ' + JSON.stringify(nearestColor));
if (value !== -1) {
adapter.setState('Smart-Home-Devices.' + deviceEntityId + '.colorName', value, true);
shDeviceParamValues['Smart-Home-Devices.' + deviceEntityId + '.colorName'] = value;
capValues.colorName = value;
}
}
}
}
}
if (res.errors) {
for (let states of res.errors) {
if (!states.entity || !states.entity.entityId || !shApplianceEntityMap[states.entity.entityId]) continue;
const deviceEntityId = shApplianceEntityMap[states.entity.entityId].entityId;
if (states.code === 'ENDPOINT_UNREACHABLE' && adapterObjects['Smart-Home-Devices.' + deviceEntityId + '.connectivity']) {
adapter.setState('Smart-Home-Devices.' + deviceEntityId + '.connectivity', false, true);
adapter.log.debug('Set Connectivity for ' + deviceEntityId + ' to false because ' + states.code);
}
}
}
}
function createSmarthomeStates(callback) {
shApplianceEntityMap = {};
shGroupDetails = {};
alexa.getSmarthomeBehaviourActionDefinitions((err, resProperties) => {
if (!err && resProperties) shObjects.patchProperties(resProperties);
alexa.getSmarthomeDevices((err, res) => {
if (err || !res) return callback(err);
setOrUpdateObject('Smart-Home-Devices', {type: 'device', common: {name: 'Smart Home Devices'}});
setOrUpdateObject('Smart-Home-Devices.deleteAll', {common: { type: 'boolean', read: false, write: true, role: 'button'}}, false, (val) => {
alexa.deleteAllSmarthomeDevices((err, res) => {
adapter.deleteDevice('Smart-Home-Devices', () => {
setTimeout(createSmarthomeStates, 1000);
});
});
});
setOrUpdateObject('Smart-Home-Devices.discoverDevices', {common: {name: 'Let Alexa search for devices', type: 'boolean', read: false, write: true, role: 'button'}}, false, (val) => {
alexa.discoverSmarthomeDevice((err, res) => {
return createSmarthomeStates();
});
});
alexa.getSmarthomeEntities((err, res2) => {
let behaviours = {};
if (res2) {
res2.forEach((behaviour) => {
behaviours[behaviour.id] = behaviour;
});
}
let readableCounter = 0;
let all = {};
if (
res &&
res.locationDetails &&
res.locationDetails.Default_Location &&
res.locationDetails.Default_Location.amazonBridgeDetails &&
res.locationDetails.Default_Location.amazonBridgeDetails.amazonBridgeDetails
) {
all = res.locationDetails.Default_Location.amazonBridgeDetails.amazonBridgeDetails;
}
for (let i of Object.keys(all)) {
for (let n of Object.keys(all[i].applianceDetails.applianceDetails)) {
let shDevice = all[i].applianceDetails.applianceDetails[n];
let friendlyName = shDevice.friendlyName;
shApplianceEntityMap[shDevice.applianceId] = {
entityId: shDevice.entityId,
readable: false
};
if (shDevice.aliases && shDevice.aliases[0] && shDevice.aliases[0].friendlyName) friendlyName = shDevice.aliases[0].friendlyName;
setOrUpdateObject('Smart-Home-Devices.' + shDevice.entityId, {
type: 'channel',
common: {
name: friendlyName,
role: 'channel'
},
native: {
friendlyDescription: shDevice.friendlyDescription,
friendlyName: friendlyName,
modelName: shDevice.modelName,
additionalApplianceIds: shDevice.additionalApplianceDetails.additionalApplianceDetails.ids || null,
object: n,
manufacturerName: shDevice.manufacturerName,
}
});
setOrUpdateObject('Smart-Home-Devices.' + shDevice.entityId + '.#enabled', {common: {role: 'indicator', write: false}}, shDevice.isEnabled);
setOrUpdateObject('Smart-Home-Devices.' + shDevice.entityId + '.#delete', {common: { type: 'boolean', read: false, write: true, role: 'button'}}, false, function (entityId, val) {
alexa.deleteSmarthomeDevice(n);
adapter.deleteChannel('Smart-Home-Devices', entityId);
}.bind(alexa, shDevice.entityId));
const excludeReadable = shDevice.manufacturerName.startsWith('ioBroker');
const deviceActions = {};
if (behaviours[shDevice.entityId] && behaviours[shDevice.entityId].supportedOperations) {
behaviours[shDevice.entityId].supportedOperations.forEach((a) => {
deviceActions[a] = true;
});
}
if (shDevice.actions && shDevice.actions.length) {
shDevice.actions.forEach((a) => {
deviceActions[a] = true;
});
}
let readableProperties = 0;
if (shDevice.capabilities.length) {
for (let cap of shDevice.capabilities) {
if (cap.interfaceName) {
if ((!cap.properties || !cap.properties.supported) && cap.interfaceName === 'Alexa.SceneController') {
cap.properties = {
'supported': [{
'name': 'active'
}]
};
}
if (!cap.properties || !cap.properties.supported) {
adapter.log.debug('Smarthome-Device Capability ' + cap.interfaceName + ' without properties.');
adapter.log.debug(JSON.stringify(shDevice) + ' / ' + JSON.stringify(behaviours[shDevice.entityId]));
continue;
}
if (!shObjects.capabilityObjects[cap.interfaceName]) {
adapter.log.debug('Smarthome-Device Capability ' + cap.interfaceName + ' unknown. Report to developer this and next log line from logfile on disk!');
adapter.log.debug(JSON.stringify(shDevice) + ' / ' + JSON.stringify(behaviours[shDevice.entityId]));
continue;
}
for (let capProp of cap.properties.supported) {
if (!shObjects.capabilityObjects[cap.interfaceName][capProp.name]) {
adapter.log.debug('Smarthome-Device Capability ' + cap.interfaceName + ' for ' + capProp.name + ' unknown. Report to developer this and next log line from logfile on disk!');
adapter.log.debug(JSON.stringify(shDevice) + ' / ' + JSON.stringify(behaviours[shDevice.entityId]));
continue;
}
for (let obj of shObjects.capabilityObjects[cap.interfaceName][capProp.name]) {
if (typeof obj === 'string') continue;
obj = JSON.parse(JSON.stringify(obj));
if (obj.experimental) {
adapter.log.debug('Smarthome-Device Capability ' + cap.interfaceName + ' for ' + capProp.name + '.' + obj.common.name + ' experimentally supported. Please check and report to developer this and next log line from logfile on disk if it works!!');
adapter.log.debug(JSON.stringify(shDevice) + ' / ' + JSON.stringify(behaviours[shDevice.entityId] + ' / ' + JSON.stringify(obj)));
}
if (obj.experimental) delete obj.experimental;
if (obj.common && obj.common.read) {
if (excludeReadable) obj.common.read = false;
else readableProperties++;
}
if (obj.native.supportedActions && obj.native.supportedActions.length) {
obj.native.supportedActions.forEach((n) => {
if (deviceActions[n] !== undefined) delete deviceActions[n];
});
}
setOrUpdateObject('Smart-Home-Devices.' + shDevice.entityId + '.' + obj.common.name, obj, false, function (entityId, paramName, applianceId, value) {
if (!obj.common.write) return;
const parameters = buildSmartHomeControlParameters(entityId, shObjects.capabilityObjects[cap.interfaceName][capProp.name], paramName, value);
if (!parameters.action || !behaviours[entityId] || ! behaviours[entityId].supportedOperations || !behaviours[entityId].supportedOperations.includes(parameters.action)) {
if (!parameters.action.startsWith('turn') && !parameters.action.startsWith('scene')) {
adapter.log.debug('Invalid action ' + parameters.action + ' provided for Capability ' + cap.interfaceName + ' for ' + obj.common.name + '. Report to developer this and next log line from logfile on disk!');
adapter.log.debug(JSON.stringify(shDevice) + ' / ' + JSON.stringify(behaviours[entityId]));
}
else {
adapter.log.debug('Action ' + parameters.action + ' provided for Capability ' + cap.interfaceName + ' for ' + obj.common.name + ' is not supported, ignore');
}
return;
}
alexa.executeSmarthomeDeviceAction(entityId, parameters, (err, res) => {
if (!err && res && res.controlResponses && res.controlResponses[0] && res.controlResponses[0].code && res.controlResponses[0].code === 'SUCCESS' && !excludeReadable) {
if (shQueryBlocker[applianceId]) {
clearTimeout(shQueryBlocker[applianceId]);
shQueryBlocker[applianceId] = null;
}
setTimeout(() => alexa.querySmarthomeDevices(applianceId, (err, res) => {
if (!err) {
updateSmarthomeDeviceStates(res);
}
}), 2000);
}
else {
updateSmarthomeDeviceStates(res);
}
});
}.bind(alexa, shDevice.entityId, obj.common.name, shDevice.applianceId));
if (shDevice.tags && shDevice.tags.tagNameToValueSetMap && shDevice.tags.tagNameToValueSetMap.groupIdentity) {
for (let group of shDevice.tags.tagNameToValueSetMap.groupIdentity) {
shGroupDetails[group] = shGroupDetails[group] || {
applianceIds: {},
entityIds: {},
parameters: {}
};
shGroupDetails[group].applianceIds[shDevice.applianceId] = true;
shGroupDetails[group].entityIds[shDevice.entityId] = true;
shGroupDetails[group].parameters[obj.common.name] = obj;
}
}
}
}
}
}
}
const deviceActionsArr = Object.keys(deviceActions);
if (deviceActionsArr.length) {
let readable = false;
if (!excludeReadable) {
for (let action of deviceActionsArr) {
if (action.startsWith('get') || action.startsWith('retrieve')) {
readable = true;
readableProperties++;
}
}
}
let ignoreSecondTurnOnOff = false;
for (let action of deviceActionsArr) {
if (ignoreSecondTurnOnOff && (action === 'turnOn' || action === 'turnOff')) continue;
if ((action === 'turnOn' && deviceActionsArr.includes('turnOff')) || (action === 'turnOff' && deviceActionsArr.includes('turnOn'))) {
action = 'turnOnOff';
ignoreSecondTurnOnOff = true;
}
if (!shObjects.actionObjects[action]) {
adapter.log.debug('Smarthome-Device Action ' + action + ' unknown. Report to developer this and next log line from logfile on disk!');
adapter.log.debug(JSON.stringify(shDevice) + ' / ' + JSON.stringify(behaviours[shDevice.entityId]));
continue;
}