/* 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 = '
'
@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 historyMapFLD = [:]
@Field volatile static 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 = ""
// 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 musicProviders = (Map)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 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: """""", 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)
}
}
private List getNotifications(String type="Reminder", all=false) {
String msg = "getNotifications"
if(isZone()) { exitMsg(msg); return null }
List