-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathecho speaks device
3215 lines (2942 loc) · 142 KB
/
echo speaks device
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
/* groovylint-disable CompileStatic, MethodCount, MethodSize, UnnecessaryGetter */
/**
* Echo Speaks Device (Hubitat ONLY)
*
* Copyright 2018, 2019, 2020, 2021, 2022, 2023, 2024 Anthony Santilli
* Code Contributions by @nh.schottfam
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*/
//file:noinspection GroovySillyAssignment
//file:noinspection GroovyUnusedAssignment
//file:noinspection GroovyPointlessBoolean
import groovy.json.JsonOutput
import groovy.transform.Field
import java.text.SimpleDateFormat
//************************************************
//* STATIC VARIABLES *
//************************************************
@Field static final String devVersionFLD = '4.2.4.0'
@Field static final String devModifiedFLD = '2024-03-07'
@Field static final String sNULL = (String)null
@Field static final String sBLANK = ''
@Field static final String sSPACE = ' '
@Field static final String sLINEBR = '<br>'
@Field static final String sTRUE = 'true'
@Field static final String sFALSE = 'false'
@Field static final String sCLRRED = 'red'
@Field static final String sCLRGRY = 'gray'
@Field static final String sCLRORG = 'orange'
@Field static final String sAPPJSON = 'application/json'
//************************************************
//* IN-MEMORY ONLY VARIABLES *
//* (Cleared only on HUB REBOOT or CODE UPDATES) *
//************************************************
@Field volatile static Map<String,Map> historyMapFLD = [:]
@Field volatile static Map<String,Map> cookieDataFLD = [:]
// @Field volatile static String gitBranchFLD = null
static String devVersion() { return devVersionFLD }
static String devVersionDt() { return devModifiedFLD }
static Boolean isWS() { return false }
static Boolean isZone() { return false }
metadata {
definition (name: "Echo Speaks Device", namespace: "tonesto7", author: "Anthony Santilli", importUrl: "https://raw.githubusercontent.com/tonesto7/echo-speaks/master/drivers/echo-speaks-device.groovy") {
capability "AudioNotification"
capability "AudioVolume"
capability "MusicPlayer"
capability "Notification"
capability "Refresh"
capability "Sensor"
capability "SpeechSynthesis"
if(!isZone()) {
capability "SpeechRecognition"
}
attribute "alarmVolume", "number"
attribute "alexaPlaylists", "JSON_OBJECT"
attribute "alexaGuardStatus", "string"
attribute "alexaWakeWord", "string"
attribute "btDeviceConnected", "string"
attribute "btDevicesPaired", "JSON_OBJECT"
attribute "currentAlbum", "string"
attribute "currentStation", "string"
attribute "deviceFamily", "string"
attribute "deviceSerial", "string"
attribute "deviceIcon", "string"
attribute "deviceStatus", "string"
attribute "deviceStyle", "string"
attribute "deviceType", "string"
attribute "doNotDisturb", "string"
attribute "firmwareVer", "string"
attribute "followUpMode", "string"
// attribute "lastCmdSentDt", "string"
attribute "lastSpeakCmd", "string"
attribute "lastAnnouncement", "string"
attribute "lastSpokenToTime", "number"
attribute "lastVoiceActivity", "string"
attribute "lastUpdated", "string"
attribute "mediaSource", "string"
attribute "onlineStatus", "string"
attribute "permissions", "string"
attribute "supportedMusic", "string"
attribute "trackImage", "string"
attribute "trackImageHtml", "string"
attribute "volume", "number"
attribute "wakeWords", "enum"
attribute "wasLastSpokenToDevice", "string"
attribute "audioTrackData", "JSON_OBJECT" // To support SharpTools.io Album Art feature
command "replayText"
if(!isZone()) {
command "doNotDisturbOn"
command "doNotDisturbOff"
}
command "setAlarmVolume", [[name: "Alarm Volume*", type: "NUMBER", description: "Sets the devices Alarm notification volume"]]
command "playWeather", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "playSingASong", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "playFlashBrief", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "playFunFact", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "playGoodNews", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "playTraffic", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "playJoke", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "playSoundByName", [[name: "Sound Name", type: "STRING", description: "Sound object name"], [name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing"]]
command "playTellStory", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "sayGoodbye", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "sayGoodNight", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "sayBirthday", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "sayCompliment", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "sayGoodMorning", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "sayWelcomeHome", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "parallelPlayAnnouncement", [[name: "Message to Announce*", type: "STRING", description: "Message to announce"],[name: "Announcement Title", type: "STRING", description: "This displays a title above message on devices with display"]]
command "playAnnouncement", [[name: "Message to Announce*", type: "STRING", description: "Message to announce"],[name: "Announcement Title", type: "STRING", description: "This displays a title above message on devices with display"], [name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "playAnnouncementIgnore", [[name: "Message to Announce*", type: "STRING", description: "Message to announce"],[name: "Announcement Title", type: "STRING", description: "This displays a title above message on devices with display"], [name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "playAnnouncementAll", [[name: "Message to Announce*", type: "STRING", description: "Message to announce"],[name: "Announcement Title", type: "STRING", description: "This displays a title above message on devices with display"]]
command "playCalendarToday", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "playCalendarTomorrow", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "playCalendarNext", [[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing the message"],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
command "stopAllDevices"
command "noOp"
if(!isZone()) {
command "searchMusic", [[name: "Music Search Phrase*", type: "STRING", description: "Enter the artist, song, playlist, etc."], [name: "Music Provider*", type: "ENUM", constraints: ["AMAZON_MUSIC", "APPLE_MUSIC", "TUNEIN", "PANDORA", "SIRIUSXM", "SPOTIFY", "I_HEART_RADIO", "CLOUDPLAYER"], description: "Select One of these Music Providers to use."], [name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing"],[name: "Sleep Time", type: "NUMBER", description: "Sleep time in seconds"]]
command "searchAmazonMusic", [[name: "Music Search Phrase*", type: "STRING", description: "Enter the artist, song, playlist, etc."],[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing"],[name: "Sleep Time", type: "NUMBER", description: "Sleep time in seconds"]]
command "searchAppleMusic", [[name: "Music Search Phrase*", type: "STRING", description: "Enter the artist, song, playlist, etc."],[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing"],[name: "Sleep Time", type: "NUMBER", description: "Sleep time in seconds"]]
command "searchPandora", [[name: "Music Search Phrase*", type: "STRING", description: "Enter the artist, song, playlist, etc."],[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing"],[name: "Sleep Time", type: "NUMBER", description: "Sleep time in seconds"]]
command "searchIheart", [[name: "Music Search Phrase*", type: "STRING", description: "Enter the artist, song, playlist, etc."],[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing"],[name: "Sleep Time", type: "NUMBER", description: "Sleep time in seconds"]]
command "searchSiriusXm", [[name: "Music Search Phrase*", type: "STRING", description: "Enter the artist, song, playlist, etc."],[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing"],[name: "Sleep Time", type: "NUMBER", description: "Sleep time in seconds"]]
command "searchSpotify", [[name: "Music Search Phrase*", type: "STRING", description: "Enter the artist, song, playlist, etc."],[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing"],[name: "Sleep Time", type: "NUMBER", description: "Sleep time in seconds"]]
// command "searchTidal", [[name: "Music Search Phrase*", type: "STRING", description: "Enter the artist, song, playlist, etc."],[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing"],[name: "Sleep Time", type: "NUMBER", description: "Sleep time in seconds"]]
command "searchTuneIn", [[name: "Music Search Phrase*", type: "STRING", description: "Enter the artist, song, playlist, etc."],[name: "Set Volume", type: "NUMBER", description: "Sets the volume before playing"],[name: "Sleep Time", type: "NUMBER", description: "Sleep time in seconds"]]
}
command "sendAlexaAppNotification", [ [name: "Notification Message*", type: "STRING", description: ""]]
if(!isZone()) {
command "executeSequenceCommand", [[name: "Sequence Message Text*", type: "STRING", description: ""]]
command "executeRoutineId", [[name: "Routine ID*", type: "STRING", description: ""]]
command "createAlarm", [[name: "Alarm Label*", type: "STRING", description: "This is the title of the alarm"], [name: "Date*",type: "STRING", description: "Date (2021-01-05 | YYYY-MM-DD)"], [name: "Time*", type: "STRING", description: "Time (18:10 | HH:MM)"]]
command "createReminder", [[name: "Reminder Label*", type: "STRING", description: "This is the title of the reminder"], [name: "Date*", type: "STRING", description: "Date (2021-01-05 | YYYY-MM-DD)"], [name: "Time*", type: "STRING", description: "Time (18:10 | HH:MM)"]]
// command "createReminderNew", ["string", "string", "string", "string", "string"]
command "removeNotification", [[name: "Notification ID to Remove*", type: "STRING", description: ""]]
// command "removeAllNotificationsByType", ["string"]
command "setWakeWord", [[name: "New Wake Word*", type: "STRING", description: ""]]
command "renameDevice", [[name: "New Device Name*", type: "STRING", description: ""]]
}
command "storeCurrentVolume"
command "restoreLastVolume"
command "togglePlayback"
command "setVolumeAndSpeak", [[name: "Volume*", type: "NUMBER", description: "Sets the volume before playing the message"], [name: "Message to Speak*", type: "STRING", description: ""]]
command "setVolumeSpeakAndRestore", [[name: "Volume*", type: "NUMBER", description: "Sets the volume before playing the message"], [name: "Message to Speak*", type: "STRING", description: ""],[name: "Restore Volume", type: "NUMBER", description: "Restores the volume after playing the message"]]
// command "volumeUp"
// command "volumeDown"
command "speechTest"
// command "speak", [[name: "Message to Speak*", type: "STRING", description: ""], volume, voice]
command "speakIgnoreDnd", [[name: "Message to Speak (Ignores Do Not Disturb)*", type: "STRING", description: ""], [name: "Set Volume", type: "NUMBER", description: "Sets the volume before speak"], [name: "Voice", type: "STRING", description: "Voice to use"]]
command "sendTestAnnouncement"
command "sendTestAnnouncementAll"
if(!isZone()) {
command "getDeviceActivity"
command "getBluetoothDevices"
command "connectBluetooth", [[name: "Bluetooth Device Label", type: "STRING", description: ""]]
command "disconnectBluetooth"
command "removeBluetooth", [[name: "Bluetooth Device Label*", type: "STRING", description: ""]]
}
command "parallelSpeak", [[name: "Message to Speak*", type: "STRING", description: ""]]
command "parallelSpeakIgnoreDnd", [[name: "Message to Speak (Ignores Do Not Disturb)*", type: "STRING", description: ""]]
command "sendAnnouncementToDevices", ["string", "string", "object", "number", "number"]
command "voiceCmdAsText", [[name: "Voice Command as Text*", type: "STRING", description: ""]]
}
preferences {
section("Preferences") {
input "logInfo", "bool", title: "Show Info Logs?", required: false, defaultValue: true
input "logWarn", "bool", title: "Show Warning Logs?", required: false, defaultValue: true
input "logError", "bool", title: "Show Error Logs?", required: false, defaultValue: true
input "logDebug", "bool", title: "Show Debug Logs?", description: "Only leave on when required", required: false, defaultValue: false
input "logTrace", "bool", title: "Show Detailed Logs?", description: "Only Enabled when asked by the developer", required: false, defaultValue: false
input "ignoreTimeoutErrors", "bool", required: false, title: "Don't show errors in the logs for request timeouts?", description: sBLANK, defaultValue: true
input "ignoreHealth", "bool", required: false, title: "Ignore Devices Online/Offline State?", description: sBLANK, defaultValue: true
input "sendDevNotifAsAnnouncement", "bool", required: false, title: "Send Device Notifications as Announcements?", description: sBLANK, defaultValue: false
// maxVolume not used
// input "maxVolume", "number", required: false, title: "Set Max Volume for this device", description: "There will be a delay of 30-60 seconds in getting the current volume level"
}
}
}
def installed() {
logInfo("${device?.displayName} Executing Installed...")
updateMute('unmuted') // sendEvent(name: "mute", value: "unmuted")
if(!isZone()) {
sendEvent(name: "status", value: "stopped")
sendEvent(name: "deviceStatus", value: "stopped_echo_gen1")
sendEvent(name: "trackDescription", value: "NA")
sendEvent(name: "followUpMode", value: sFALSE)
sendEvent(name: "alexaWakeWord", value: "ALEXA")
sendEvent(name: "mediaSource", value: "NA")
sendEvent(name: "wasLastSpokenToDevice", value: sFALSE)
sendEvent(name: "alarmVolume", value: 0)
sendEvent(name: "doNotDisturb", value: sFALSE)
}
sendEvent(name: "onlineStatus", value: "online")
// state.doNotDisturb = false
initialize()
runIn(20, "postInstall")
}
def updated() {
logInfo("${device?.displayName} Executing Updated()")
initialize()
}
def initialize() {
logInfo("${device?.displayName} Executing initialize()")
unschedule()
state.refreshScheduled = false
stateCleanup()
if(minVersionFailed()) { logError("CODE UPDATE required to RESUME operation. No Device Events will updated."); return }
schedDataRefresh(true)
if(advLogsActive()) { runIn(1800, "logsOff") }
state.websocketActive = isZone() ? parent?.relayGetWWebSocketStatus() : parent?.getWWebSocketStatus()
sendEvent(name: "lastAnnouncement", value: "NA")
sendEvent(name: "lastSpeakCmd", value: "NA")
sendEvent(name: "lastVoiceActivity", value: "NA")
sendEvent(name: "phraseSpoken", value: "NA")
refresh() //refreshData(true)
}
Boolean advLogsActive() { return ((Boolean)settings.logDebug || (Boolean)settings.logTrace) }
public void logsOff() {
device.updateSetting("logDebug",[value:sFALSE,type:"bool"])
device.updateSetting("logTrace",[value:sFALSE,type:"bool"])
log.debug "Disabling debug logs"
}
def postInstall() {
if(device?.currentState('level') == 0) { setLevel(30) }
if(device?.currentState('alarmVolume') == 0) { setAlarmVolume(30) }
}
public triggerInitialize() { runIn(3, "initialize") }
String getEchoDeviceType() { return (String)state.deviceType ?: sNULL }
String getEchoSerial() { return (String)state.serialNumber ?: sNULL }
String getEchoOwner() { return (String)state.deviceOwnerCustomerId ?: sNULL }
String getEchoAccountId() { return (String)state.deviceAccountId ?: sNULL }
Map getEchoDevInfo(String cmd, Boolean ignoreDoNotDisturb=false) {
if(isCommandTypeAllowed(cmd, false, ignoreDoNotDisturb)) {
return [deviceTypeId: getEchoDeviceType(), deviceSerialNumber: getEchoSerial(), deviceOwnerCustomerId: getEchoOwner(), deviceAccountId: getEchoAccountId(), dni: device.deviceNetworkId ]
}
return null
}
String getHealthStatus(Boolean lower=false) {
String res = device?.getStatus()
if(lower) { return res?.toLowerCase() }
return res
}
String getShortDevName(){
return device?.displayName?.replace("Echo - ", sBLANK)
}
public void setAuthState(Boolean authenticated) {
state.authValid = authenticated
if(!authenticated && (Boolean)state.refreshScheduled) {
removeCookies()
}
}
public void updateCookies(Map cookies, Boolean doInit=true) {
String msg = "Cookies Update by Parent."
msg += doInit ? " Re-Initializing Device in 5 Seconds..." : ""
logDebug(msg)
state.cookie = cookies
cookieDataFLD = [:]
setAuthState(true)
if(doInit) runIn(5, "initialize")
}
public void removeCookies(Boolean isParent=false) {
if(state.cookie != null || (Boolean)state.authValid || (Boolean)state.refreshScheduled) {
logWarn("Cookie Authentication Cleared by ${isParent ? "Parent" : "Device"} | Scheduled Refreshes also cancelled!")
if((Boolean)state.refreshScheduled) { unschedule("refreshData"); state.refreshScheduled = false }
state.cookie = null
cookieDataFLD = [:]
state.authValid = false
}
}
Boolean isAuthOk(Boolean noLogs=false) {
if(!(Boolean)state.authValid) {
if((Boolean)state.refreshScheduled) { unschedule("refreshData"); state.refreshScheduled = false }
if(state.cookie != null) {
if(!noLogs) { logWarn("Echo Speaks Authentication is no longer valid... Please login again and commands will be allowed again!!!", true) }
state.remove("cookie")
cookieDataFLD = [:]
}
return false
} else { return true }
}
Boolean isCommandTypeAllowed(String type, Boolean noLogs=false, Boolean ignoreDoNotDisturb=false) {
if(isZone()) return true
if(!type) { if(!noLogs) { logWarn("Invalid Permissions Type Received: ${type}", true) }; return false }
if(!isAuthOk(noLogs)) { return false }
if(!getAmazonDomain()) { if(!noLogs) { logWarn("amazonDomain State Value Missing: ${getAmazonDomain()}", true) }; return false }
if(!state.cookie || !state.cookie.cookie || !state.cookie.csrf) { if(!noLogs) { logWarn("Amazon Cookie State Values Missing: ${state.cookie}", true) }; setAuthState(false); return false }
if(!(String)state.serialNumber) { if(!noLogs) { logWarn("SerialNumber State Value Missing: ${(String)state.serialNumber}", true) }; return false }
if(!(String)state.deviceType) { if(!noLogs) { logWarn("DeviceType State Value Missing: ${(String)state.deviceType}", true) }; return false }
if(!(String)state.deviceOwnerCustomerId) { if(!noLogs) { logWarn("OwnerCustomerId State Value Missing: ${(String)state.deviceOwnerCustomerId}", true) }; return false }
Boolean isOnline = settings.ignoreHealth!=false || device?.currentValue("onlineStatus") == "online"
if(!isOnline) {
if(!noLogs) { logWarn("Commands NOT Allowed! Device is currently (OFFLINE) | Type: (${type})", true) }
triggerDataRrshF("found offline" )
return false
}
if(!(Boolean)state.isSupportedDevice) { logWarn("You are using an Unsupported/Unknown Device all restrictions have been removed for testing! If commands function please report device info to developer", true); return true }
if(state.permissions == null) { if(!noLogs) { logWarn("Permissions State Object Missing: ${state.permissions}", true) }; return false }
if(!ignoreDoNotDisturb && !(type in ["volumeControl", "alarms", "reminders", "doNotDisturb", "wakeWord", "bluetoothControl", "mediaPlayer"])
&& device?.currentValue("doNotDisturb") == sTRUE ) { if(!noLogs) { logWarn("All Voice Output Blocked... Do Not Disturb is ON", true) }; return false }
if(permissionOk(type)) { return true }
else {
String warnMsg = sNULL
switch(type) {
case "TTS":
warnMsg = "OOPS... Text to Speech is NOT Supported by this Device!!!"
break
case "announce":
warnMsg = "OOPS... Announcements are NOT Supported by this Device!!!"
break
case "followUpMode":
warnMsg = "OOPS... Follow-Up Mode is NOT Supported by this Device!!!"
break
case "mediaPlayer":
warnMsg = "OOPS... Media Player Controls are NOT Supported by this Device!!!"
break
case "volumeControl":
warnMsg = "OOPS... Volume Control is NOT Supported by this Device!!!"
break
case "bluetoothControl":
warnMsg = "OOPS... Bluetooth Control is NOT Supported by this Device!!!"
break
case "alarms":
warnMsg = "OOPS... Alarm Notification are NOT Supported by this Device!!!"
break
case "reminders":
warnMsg = "OOPS... Reminders Notifications are NOT Supported by this Device!!!"
break
case "doNotDisturb":
warnMsg = "OOPS... Do Not Disturb Control is NOT Supported by this Device!!!"
break
case "wakeWord":
warnMsg = "OOPS... Alexa Wake Word Control is NOT Supported by this Device!!!"
break
case "amazonMusic":
warnMsg = "OOPS... Amazon Music is NOT Supported by this Device!!!"
break
case "appleMusic":
warnMsg = "OOPS... Apple Music is NOT Supported by this Device!!!"
break
case "tuneInRadio":
warnMsg = "OOPS... Tune-In Radio is NOT Supported by this Device!!!"
break
case "iHeartRadio":
warnMsg = "OOPS... iHeart Radio is NOT Supported by this Device!!!"
break
case "pandoraRadio":
warnMsg = "OOPS... Pandora Radio is NOT Supported by this Device!!!"
break
case "siriusXm":
warnMsg = "OOPS... Sirius XM Radio is NOT Supported by this Device!!!"
break
// case "tidal":
// warnMsg = "OOPS... Tidal Music is NOT Supported by this Device!!!"
// break
case "spotify":
warnMsg = "OOPS... Spotify is NOT Supported by this Device!!!"
break
case "cloudPlayer":
warnMsg = "OOPS... Cloudplayer is NOT Supported by this Device!!!"
break
case "flashBriefing":
warnMsg = "OOPS... Flash Briefs and Good News are NOT Supported by this Device!!!"
break
}
if(warnMsg && !noLogs) { logWarn(warnMsg, true) }
return false
}
}
Boolean permissionOk(String type) {
if(isZone()) return true
Map p = (Map)state.permissions
if(type && p?.containsKey(type) && (Boolean)p[type]) { return true }
return false
}
void updateDeviceStatus(Map devData) {
if(isZone()) return
Boolean isOnline = false
if(devData.size()) {
isOnline = (Boolean)devData.online
// log.debug "isOnline: ${isOnline}"
// log.debug "deviceFamily: ${devData?.deviceFamily} | deviceType: ${devData?.deviceType}" // UNCOMMENT to identify unidentified devices
// NOTE: These allow you to log all device data items
// devData?.each { k,v ->
// if(!(k in ["playerState", "capabilities", "deviceAccountId"])) {
// log.debug("$k: $v")
// }
// }
state.isSupportedDevice = (devData.unsupported != true)
state.remove('isEchoDevice') // state.isEchoDevice = (devData?.permissionMap?.isEchoDevice == true)
String devSerial = (String)devData.serialNumber
state.serialNumber = devSerial
String devType = devData.deviceType ?: sBLANK
state.deviceType = devType
state.deviceOwnerCustomerId = (String)devData.deviceOwnerCustomerId
state.deviceAccountId = (String)devData.deviceAccountId
String firmwareVer = devData.softwareVersion ?: "NA"
state.softwareVersion = firmwareVer
// state.mainAccountCommsId = devData.mainAccountCommsId ?: null
// log.debug "mainAccountCommsId: ${state.mainAccountCommsId}"
if(!state.cookie) {
state.cookie = devData.cookie
cookieDataFLD = [:]
}
state.authValid = ((Boolean)devData.authValid)
state.amazonDomain = (String)devData.amazonDomain
state.regionLocale = (String)devData.regionLocale
Map permissions = state.permissions ?: [:]
devData.permissionMap?.each {String k,v -> permissions[k] = v }
state.permissions = permissions
state.hasClusterMembers = devData.hasClusterMembers
state.isWhaDevice = ((Boolean)devData.permissionMap?.isMultiroomDevice)
// log.trace "hasClusterMembers: ${state.hasClusterMembers}"
// log.trace "permissions: ${state.permissions}"
Boolean chg=false
List permissionList = permissions?.findAll { it?.value == true }?.collect { it?.key }
if(isStateChange(device, "permissions", permissionList?.toString())) {
sendEvent(name: "permissions", value: permissionList, display: false, displayed: false)
chg=true
}
Map deviceStyle = (Map)devData.deviceStyle
state.deviceStyle = deviceStyle
String devFamily = devData.deviceFamily ?: sBLANK
String devName = (String)deviceStyle?.n
String devIcon = "<img style='width:64px;height:64px;' src='https://raw.githubusercontent.com/tonesto7/echo-speaks/master/resources/icons/${isZone() ? "es_groups.png" : "${(String)deviceStyle?.i ?: "echo_gen1"}.png"}'/>"
// logInfo("deviceStyle (${devFamily}): ${devType} | Desc: ${devName}")
state.remove('deviceImage') // state.deviceImage = (String)deviceStyle?.i
if(isStateChange(device, "deviceStyle", devName)) {
sendEvent(name: "deviceStyle", value: devName, descriptionText: "Device Style", display: true, displayed: true)
chg=true
}
if(isStateChange(device, "firmwareVer", firmwareVer)) {
sendEvent(name: "firmwareVer", value: firmwareVer, descriptionText: "Firmware Version", display: true, displayed: true)
chg=true
}
if(isStateChange(device, "deviceFamily", devFamily)) {
sendEvent(name: "deviceFamily", value: devFamily, descriptionText: "Echo Device Family", display: true, displayed: true)
chg=true
}
if(isStateChange(device, "deviceSerial", devSerial)) {
sendEvent(name: "deviceSerial", value: devSerial, descriptionText: "Echo Device Serial Number", display: true, displayed: true)
chg=true
}
if(isStateChange(device, "deviceType", devType)) {
sendEvent(name: "deviceType", value: devType, display: false, displayed: false)
chg=true
}
if(isStateChange(device, "deviceIcon", devIcon)) {
sendEvent(name: "deviceIcon", value: devIcon, display: false, displayed: false)
}
Map<String,String> musicProviders = (Map<String,String>)devData.musicProviders ?: [:]
String lItems = ""
musicProviders.each { String k, String v ->
if(v.size() > 0) lItems = lItems + (lItems.size() > 0 ? ", "+v : v)
}
//log.warn "musicProviders is $musicProviders lItems is $lItems"
if(isStateChange(device, "supportedMusic", lItems)) {
sendEvent(name: "supportedMusic", value: lItems, display: false, displayed: false)
chg=true
}
// if(devData.guardStatus) { updGuardStatus(devData.guardStatus) }
if(!isOnline) {
updateMute('unmuted') // sendEvent(name: "mute", value: "unmuted")
sendEvent(name: "status", value: "stopped")
sendEvent(name: "deviceStatus", value: "stopped_${state.deviceStyle?.i}")
sendEvent(name: "trackDescription", value: "NA")
} else { if(chg) { state.fullRefreshOk = true; triggerDataRrshF('updateDeviceStatus') }}
}
setOnlineStatus(isOnline)
sendEvent(name: "lastUpdated", value: formatDt(new Date()), display: false, displayed: false)
schedDataRefresh()
}
public void updSocketStatus(Boolean active) {
if(!active) { schedDataRefresh(true) }
state.websocketActive = active
}
@SuppressWarnings('GroovyFallthrough')
void websocketUpdEvt(List<String> triggers) {
logTrace("websocketEvt: $triggers")
// if((Boolean)state.isWhaDevice) { return }
if(triggers?.size()) {
triggers.each { String k->
switch(k) {
case "all":
state.fullRefreshOk = true
runIn(2, "refresh")
break
case "media":
runIn(2, "getPlaybackState")
break
case "queue":
runIn(4, "getPlaylists")
case "notification":
case "notif":
// runIn(2, "getNotifications")
break
case "bluetooth":
runIn(20, "getBluetoothDevices")
break
case "online":
setOnlineStatus(true)
break
case "offline":
setOnlineStatus(false)
break
case "activity":
runIn(5, "getDeviceActivity")
break
default:
logTrace("unknown websocket trigger $k")
}
}
}
}
void refresh() {
logTrace("refresh()")
if(isZone()) parent?.relayChildInitiatedRefresh() else parent?.childInitiatedRefresh()
runIn(6, "refreshData3")
}
void refreshData1() {
refreshData()
}
private void triggerDataRrshF(String src) {
logTrace("triggerDataRrshF $src")
runIn(6, "refresh")
}
@SuppressWarnings('unused')
void refreshData3() {
refreshData(true)
}
public schedDataRefresh(Boolean frc=false) {
if(frc || !(Boolean)state.refreshScheduled) {
runEvery30Minutes("refreshData")
state.refreshScheduled = true
}
}
void refreshData(Boolean full=false) {
String msg = "refreshData($full)..."
Boolean wsActive = (Boolean)state.websocketActive
Boolean isWHA = (Boolean)state.isWhaDevice
Boolean mfull = (Boolean)state.fullRefreshOk
// Boolean isEchoDev = (state.isEchoDevice == true)
if(device?.currentValue("onlineStatus") != "online") {
exitMsg("Device Data Refresh... Device is OFFLINE... (Offline Status Updated Every 10 Minutes) "+ msg)
return
}
if(!isAuthOk()) { exitMsg(msg + " No valid auth"); return}
logTrace(msg)
if(minVersionFailed()) { logError("CODE UPDATE required to RESUME operation. No Device Events will updated."); return }
// logTrace("permissions: ${state.permissions}")
if((Boolean)state.permissions?.mediaPlayer && (full || mfull || !wsActive)) {
getPlaybackState()
// if(!isWHA) { getPlaylists() }
}
if(!isWHA) {
if (full || mfull) {
// if(isEchoDev) { getWifiDetails() }
getDeviceSettings()
}
if((Boolean)state.permissions?.doNotDisturb) { getDoNotDisturb() }
if(!wsActive || full || mfull) {
getDeviceActivity()
}
if(!mfull && full) state.fullRefreshOk = true
if((Boolean)state.fullRefreshOk || full) runIn(3, "refreshStage2")
} else { state.fullRefreshOk = false }
}
@SuppressWarnings('unused')
private void refreshStage2() {
// log.trace("refreshStage2()...")
Boolean wsActive = (Boolean)state.websocketActive
Boolean full = (Boolean)state.fullRefreshOk
state.fullRefreshOk = false
if(state.permissions?.wakeWord && full) {
getWakeWord()
getAvailableWakeWords()
}
if( (Boolean)state.permissions?.alarms || (Boolean)state.permissions?.reminders) {
if((Boolean)state.permissions?.alarms) { getAlarmVolume() }
// getNotifications()
}
if(state.permissions?.bluetoothControl && (!wsActive || full)) {
getBluetoothDevices()
}
// updGuardStatus()
}
public void setOnlineStatus(Boolean isOnline) {
String onlStatus = (isOnline ? "online" : "offline")
if(isStateChange(device, "onlineStatus", onlStatus)) {
logDebug("OnlineStatus has changed to (${onlStatus})")
sendEvent(name: "onlineStatus", value: onlStatus, display: true, displayed: true)
}
}
//private void getPlaybackState(Boolean isGroupResponse=false) {
private void getPlaybackState() {
String msg = "getPlaybackState"
if(isZone()) { exitMsg(msg); return }
Boolean isGroupResponse = (Boolean)state.isWhaDevice || (Boolean)state.hasClusterMembers
Map params = [
uri: getAmazonUrl(),
path: "/api/np/player",
query: [ deviceSerialNumber: getEchoSerial(), deviceType: getEchoDeviceType(), screenWidth: 2560, _: now() ],
headers: getCookieMap(),
contentType: sAPPJSON,
timeout: 20
]
Map playerInfo = [:]
try {
logTrace(msg)
httpGet(params) { response->
Map sData = response?.data ?: [:]
playerInfo = (Map)sData?.playerInfo ?: [:]
}
} catch (ex) {
respExceptionHandler(ex, msg, false, true)
return
}
playbackStateHandler(playerInfo, isGroupResponse)
}
/*
* called from above, or by parent when passing down WHA device changes to individual devices
*/
void playbackStateHandler(Map playerInfo, Boolean isGroupResponse=false) {
//if(isZone()) return
// log.debug "playerInfo: ${playerInfo}"
Boolean isPlayStateChange = false
Boolean isMediaInfoChange = false
// logTrace("getPlaybackState: ${playerInfo}")
String playState = (String)playerInfo.state == 'PLAYING' ? "playing" : "stopped"
String deviceStatus = "${playState}_${state.deviceStyle?.i}".toString()
// log.debug "deviceStatus: ${deviceStatus}"
if(isStateChange(device, "status", playState) || isStateChange(device, "deviceStatus", deviceStatus)) {
logTrace("Status Changed to ${playState} Groupresp: ${isGroupResponse}")
isPlayStateChange = true
if (isGroupResponse) {
state.isGroupPlaying = ((String)playerInfo.state == 'PLAYING')
}
}
Boolean iamWHA = ((Boolean)state.isWhaDevice || (Boolean)state.hasClusterMembers)
Boolean iamWHAplaying = (device?.currentState('status') == 'playing') && iamWHA
if(isPlayStateChange) {
sendEvent(name: "status", value: playState, descriptionText: "Player Status", display: true, displayed: true)
sendEvent(name: "deviceStatus", value: deviceStatus, display: false, displayed: false)
}
// for WHA devices - Update cluster (unless we remain paused)
if (iamWHA && (iamWHAplaying || playerInfo.state == 'PLAYING')) {
parent?.sendPlaybackStateToClusterMembers((String)state.serialNumber, playerInfo)
}
//Track Title
String title = playerInfo.infoText?.title ?: "NA"
if(isStateChange(device, "trackDescription", title)) {
isMediaInfoChange = true
sendEvent(name: "trackDescription", value: title, descriptionText: "Track Description", display: true, displayed: true)
}
//Track Sub-Text2
String subText1 = playerInfo.infoText?.subText1 ?: "Idle"
if(isStateChange(device, "currentAlbum", subText1)) {
isMediaInfoChange = true
sendEvent(name: "currentAlbum", value: subText1, descriptionText: "Album", display: true, displayed: true)
}
//Track Sub-Text2
String subText2 = playerInfo.infoText?.subText2 ?: "Idle"
if(isStateChange(device, "currentStation", subText2)) {
isMediaInfoChange = true
sendEvent(name: "currentStation", value: subText2, descriptionText: "Station", display: true, displayed: true)
}
//Track Art Image
String trackImg = playerInfo.mainArt?.url ?: "NA"
if(isStateChange(device, "trackImage", trackImg)) {
isMediaInfoChange = true
sendEvent(name: "trackImage", value: trackImg, descriptionText: "Track Image", display: false, displayed: false)
sendEvent(name: "trackImageHtml", value: """<img src="${trackImg?.toString()}"/>""", display: false, displayed: false)
}
//Media Source Provider
String mediaSource = playerInfo.provider?.providerName ?: "NA"
if(isStateChange(device, "mediaSource", mediaSource)) {
isMediaInfoChange = true
sendEvent(name: "mediaSource", value: mediaSource, descriptionText: "Media Source", display: true, displayed: true)
}
//Update Audio Track Data
if (isMediaInfoChange){
Map trackData = [:]
if(playerInfo.infoText?.title) { trackData.title = playerInfo.infoText?.title }
if(playerInfo.infoText?.subText1) { trackData.artist = playerInfo.infoText?.subText1 }
//To avoid media source provider being used as album (ex: Apple Music), only inject `album` if subText2 and providerName are different
if(playerInfo.infoText?.subText2 && playerInfo?.provider?.providerName!=playerInfo?.infoText?.subText2) { trackData.album = playerInfo.infoText?.subText2 }
if(playerInfo.mainArt?.url) { trackData.albumArtUrl = playerInfo.mainArt?.url }
if(playerInfo.provider?.providerName) { trackData.mediaSource = playerInfo.provider?.providerName }
//log.debug(trackData)
sendEvent(name: "trackData", value: new JsonOutput().toJson(trackData), display: false, displayed: false)
// non-standard:
sendEvent(name: "audioTrackData", value: new JsonOutput().toJson(trackData), display: false, displayed: false)
}
if (state.isGroupPlaying && !isGroupResponse) {
logDebug("ignoring remaining getPlaybackState because group is playing here")
return
}
//NOTE: Group response data never has valid data for volume
if(!isGroupResponse && playerInfo.volume) {
String muteState = sNULL
if(playerInfo.volume?.muted != null) {
muteState = ((Boolean)playerInfo.volume?.muted) ? "muted" : "unmuted"
updateMute(muteState)
}
if(playerInfo?.volume?.volume != null && muteState != 'muted') {
Integer level = playerInfo.volume?.volume
if(level < 0) { level = 0 }
if(level > 100) { level = 100 }
updateLevel(level, null)
}
}
}
private getAlarmVolume() {
String msg = "getAlarmVolume"
if(isZone()) { exitMsg(msg); return }
Map params = [
uri: getAmazonUrl(),
path: "/api/device-notification-state/${(String)state.deviceType}/${device.currentValue("firmwareVer") as String}/${(String)state.serialNumber}",
headers: getCookieMap(true),
query: [_: new Date().getTime()],
contentType: sAPPJSON,
timeout: 20
]
try {
logTrace(msg)
httpGet(params) { response->
def sData = response?.data ?: null
// logTrace("getAlarmVolume: $sData")
if(sData && isStateChange(device, "alarmVolume", (sData?.volumeLevel ?: 0)?.toString())) {
logDebug("Alarm Volume Changed to ${(sData?.volumeLevel ?: 0)}")
sendEvent(name: "alarmVolume", value: (sData?.volumeLevel ?: 0), display: true, displayed: true)
}
}
} catch (ex) {
respExceptionHandler(ex, msg)
}
}
private getWakeWord() {
String msg = "getWakeWord"
if(isZone()) { exitMsg(msg); return }
Map params = [
uri: getAmazonUrl(),
path: "/api/wake-word",
query: [cached: true, _: new Date().getTime()],
headers: getCookieMap(true),
contentType: sAPPJSON,
timeout: 20
]
try {
logTrace(msg)
httpGet(params) { response->
def sData = response?.data ?: null
// log.debug "sData: $sData"
if(sData && sData?.wakeWords) {
def t0 = sData?.wakeWords?.find { it?.deviceSerialNumber == (String)state.serialNumber }
def wakeWord = t0 ?: null
// logTrace("getWakeWord: ${wakeWord?.wakeWord}")
if(isStateChange(device, "alexaWakeWord", wakeWord?.wakeWord?.toString())) {
logDebug("Wake Word Changed to ${(wakeWord?.wakeWord)}")
sendEvent(name: "alexaWakeWord", value: wakeWord?.wakeWord, display: false, displayed: false)
}
}
}
} catch (ex) {
respExceptionHandler(ex, msg)
}
}
private getDeviceSettings() {
String msg = "getDeviceSettings"
if(isZone()) { exitMsg(msg); return }
Map params = [
uri: getAmazonUrl(),
path: "/api/device-preferences",
query: [cached: true, _: new Date().getTime()],
headers: getCookieMap(true),
contentType: sAPPJSON,
timeout: 20
]
try {
logTrace(msg)
httpGet(params) { response->
Map sData = response?.data ?: null
// log.debug "sData: $sData"
def t0 = sData?.devicePreferences?.find { it?.deviceSerialNumber == (String)state.serialNumber }
def devData = t0 ?: null
state.devicePreferences = devData ?: [:]
// log.debug "devData: $devData"
Boolean fupMode = (Boolean)devData?.goldfishEnabled
if(isStateChange(device, "followUpMode", fupMode.toString())) {
logDebug("FollowUp Mode Changed to ${(fupMode)}")
sendEvent(name: "followUpMode", value: fupMode.toString(), display: false, displayed: false)
}
// logTrace("getDeviceSettingsHandler: ${sData}")
}
} catch (ex) {
respExceptionHandler(ex, msg)
}
}
private getAvailableWakeWords() {
String msg = "getAvailableWakeWords"
if(isZone()) { exitMsg(msg); return }
Map params = [
uri: getAmazonUrl(),
path: "/api/wake-words-locale",
query: [ cached: true, _: new Date().getTime(), deviceSerialNumber: getEchoSerial(), deviceType: getEchoDeviceType(), softwareVersion: device.currentValue('firmwareVer') ],
headers: getCookieMap(true),
contentType: sAPPJSON,
timeout: 20
]
try {
logTrace(msg)
httpGet(params) { response->
Map sData = response?.data ?: null
// log.debug "sData: $sData"
String wakeWords = (sData && sData?.wakeWords) ? sData?.wakeWords?.join(",") : "None Found" //(String)null
if(isStateChange(device, "wakeWords", wakeWords)) {
logDebug("getAvailableWakeWords: ${wakeWords}")
sendEvent(name: "wakeWords", value: wakeWords, display: false, displayed: false)
}
}
} catch (ex) {
respExceptionHandler(ex, msg)
}
}
void getBluetoothDevices() {
Map btData = !isZone() ? parent?.getBluetoothData((String)state.serialNumber) : [:]
btData = btData ?: [:]
String curConnName = btData.curConnName ?: 'None Connected' //(String)null
Map btObjs = (Map)btData?.btObjs ?: [:]
// logDebug("Current Bluetooth Device: ${curConnName} | Bluetooth Objects: ${btObjs}")
state.bluetoothObjs = btObjs
Map btMap = [:]
btMap.names = (btData.pairedNames && btData.pairedNames.size()) ? btData.pairedNames.collect { it as String } : []
String btPairedJson = new JsonOutput().toJson(btMap)
if(isStateChange(device, "btDevicesPaired", btPairedJson)) {
logDebug("Paired Bluetooth Devices: ${btPairedJson}")
sendEvent(name: "btDevicesPaired", value: btPairedJson, descriptionText: "Paired Bluetooth Devices", display: true, displayed: true)
}
if(isStateChange(device, "btDeviceConnected", curConnName)) {
// log.info "Bluetooth Device Connected: (${curConnName})"
sendEvent(name: "btDeviceConnected", value: curConnName, descriptionText: "Bluetooth Device Connected", display: true, displayed: true)
}
}
void updGuardStatus(String val=sNULL) {
//TODO: Update this because it's not working
Boolean guardSup = (Boolean)state.permissions?.guardSupported
String t0 = guardSup ? (val ?: (!isZone() ? parent?.getAlexaGuardStatus() : parent?.relayGetAlexaGuardStatus() ) ) : "Not Supported"
String gState = t0 ?: "Unknown"
if(guardSup) {
//TODO: Guard is location based ? ie we may be seeing multiple locations, each with different Guard status?
// get something from the parent to check this device or location's guard status
// we may really need a new virtual device at each location that is that location's guard status if guard is present at that location
}
if(isStateChange(device, "alexaGuardStatus", gState)) {
sendEvent(name: "alexaGuardStatus", value: gState, display: false, displayed: false)
logDebug("Alexa Guard Status: (${gState})")
}
}
private String getBtAddrByAddrOrName(String btNameOrAddr) {
Map btObj = state.bluetoothObjs
String curBtAddr = btObj?.find { it?.value?.friendlyName == btNameOrAddr || it?.value?.address == btNameOrAddr }?.key ?: sNULL
// logDebug("curBtAddr: ${curBtAddr}")
return curBtAddr
}
private String getBtFirst() {
Map btObj = state.bluetoothObjs
String curBtAddr = btObj?.keySet() ? (String)btObj.keySet()[0] : sNULL
// logDebug("curBtAddr: ${curBtAddr}")
return curBtAddr
}
private getDoNotDisturb() {
if(isZone()) return
Boolean dndEnabled = (Boolean)parent?.getDndEnabled((String)state.serialNumber)
// logTrace("getDoNotDisturb: $dndEnabled")
// state.doNotDisturb = dndEnabled
if(isStateChange(device, "doNotDisturb", dndEnabled?.toString())) {
logDebug("Do Not Disturb: (${(dndEnabled)})")
sendEvent(name: "doNotDisturb", value: dndEnabled?.toString(), descriptionText: "Do Not Disturb Enabled", display: true, displayed: true)
}
}
private getPlaylists() {
String msg = "getPlaylists"
if(isZone()) { exitMsg(msg); return }
Map params = [
uri: getAmazonUrl(),
path: "/api/cloudplayer/playlists",
query: [ deviceSerialNumber: getEchoSerial(), deviceType: getEchoDeviceType(), mediaOwnerCustomerId: getEchoOwner(), screenWidth: 2560 ],
headers: getCookieMap(true),
contentType: sAPPJSON,
timeout: 20
]
try {
logTrace(msg)
httpGet(params) { response->
def sData = response?.data ?: null
// logTrace("getPlaylistsHandler: ${sData}")
def playlist = sData ? sData?.playlists : [:]
String playlistJson = new JsonOutput().toJson(playlist)
if(isStateChange(device, "alexaPlaylists", playlistJson) && playlistJson.length() < 1024) {
logDebug("Alexa Playlists Changed to ${playlistJson}")
sendEvent(name: "alexaPlaylists", value: playlistJson, display: false, displayed: false)
}
}
} catch (ex) {
respExceptionHandler(ex, msg)