Release Candidate and Support: Amazon Echo Control Binding

I love this add-on and enjoying the Echo TTS.

I have a question though, is it possible to have a string item as a echo command instead of voice?

For example, send a command to ‘echo_command’ item to be ‘ask plex to play a movie’ instead of actually saying it to alexa.

I think this would open more options to customize my home automation :slight_smile:

Thanks!

Hi there,

this binding works like a charm with my echo’s. But I have also some Sonos One speakers, where Alex is also integrated.

Should it be possible to use this binding also with the Sonos One’s? They are recognized under “Amazon Echo Control - Amazon Account - Index” but I can’t get them working?

Does anyone have experience with it?

Best regards
Bert

Hi Thomas, or someone,

I tried to find out but failed… whats the difference between

Timer?.cancel() and Timer.cancel()

I see some people have the extra ‘?’ and some do not have it in their timer code. Is it regex?

I expect its a stupid question :slight_smile:

The .?cancel is a macro that tests to see if the timer exists before terminating. That is to say, it is a shortcut way of executing:

if(TheTimer !== null) TheTimer.cancel

In the timer examples I provided earlier the “.? cancel” method could be written as “.cancel” because {in my examples} the declared timer would not be null. But I use the .?cancel method for code consistency and as a personal reminder to provide a graceful ending on all timers.

  • Thomas
1 Like

I’ve been narrowing down speed issues with my REST item calls taking forever (6000+ms) and it seems that for each of my four Echos, the following channels seem to add significant delays when the linked items are called. If I comment out the items attached to these channels my interface is nice and snappy but with them things take forever. Has anyone else ran into this?

AmazonPlayListId (adds about 300-400ms each)
PlayAlarmSound (adds about 400-600ms each)
PlayMusicProvider (adds about 800-1000ms each)

So I turned on debug logging on the binding, it seems that the delay I am experiencing is because every time something calls /rest/items with the above channels linked, the binding does a round trip to Amazon’s servers for each one. Has anyone else run into this and is there a way to use those channels without needing the call to Amazon for an item status call?

Couple tips to share:

[1] I’m not sure if this has been discussed before, but I discovered that if a echo dot is offline (unplugged or dropped wifi), and a rule sets the volume, the entire .rule file will crash. Ugh!

I haven’t investigated further, but I suspect this issue would also affect any Echo Control command that is R/W (read/write). Fortunately it does not affect TTS because it is W only.

I use the volume command a lot and I want to prevent anything that could break/crash a rule file. My solution is to wrap the volume command with a test of the volume state. Like this:

//Near the top of your rule file:
val EchoVolumeKitchen = 60        // Volume Level, should be in steps of 10.

//Somewhere in your rule file:
if(Echo_Kitchen_Volume.state!=UNDEF && Echo_Kitchen_Volume.state!=NULL) {
      Echo_Kitchen_Volume.sendCommand(EchoVolumeKitchen)
}

A special rule to trap the device’s offline state needs to be created too, like this:

rule "Kitchen Echo Dot Online Status"
when
   Thing "amazonechocontrol:echo:accountTom:echoKitchen" changed
then
    var StatusEchoKitchen = ThingAction.getThingStatusInfo("amazonechocontrol:echo:accountTom:echoKitchen").getStatus()
    logInfo("AlexaTTS.rules" , 'Attention: Kitchen Echo Dot Status = ' + StatusEchoKitchen)

    if(StatusEchoKitchen.toString() == 'OFFLINE') {
        Echo_Kitchen_Volume.postUpdate(NULL)
    }
end

[2] A useful volume control trick for saving and restoring the echo device’s default local volume is to use OpenHab’s storeStates() and restoreStates() functions. These are very clever functions that do all the work with little effort on our part. For full details see:
See https://docs.openhab.org/addons/actions.html#event-bus-actions

For example, before I change the volume (for a TTS announcement or PlayAlarmSound), I store the echo item’s current volume like this (two echo dots are shown in this example):

var VolumeStates = storeStates(Echo_Kitchen_Volume,Echo_Theater_Volume)

Then using a timer that executes after the TTS and/or alarm sound is finished, I do this:

restoreStates(VolumeStates)

When the volume states are restored, not only are their individual values refreshed with the saved values, the function also sends them (using the .items volume command) to all the affected echo devices for you. BTW, if an echo device is offline, and use the offline rule shown in Tip #1, these functions will gracefully ignore the offline device. Very cool!

  • Thomas
3 Likes

Just an update: It’s been 10 days since changing the pollingIntervalInSeconds from 60 to 15 and the amazonechocontrol:account OFFLINE issue has not returned. I hope I haven’t jinxed my good fortune by saying this!

  • Thomas

Yesterday’s brag of my good fortune with the “Offline” Amazon account bug appears to have angered the Bezos demons; Early this morning the problem returned.

I have a rule action that sends me an email whenever my Amazon account goes offline. When I woke up this morning I had an endless stream of emails waiting for me. It’s the same issue as reported by others, the Amazon account goes offline for a few seconds then goes back online. Rinse and repeat, every few seconds.

I visited the amazonechocontrol web page and it showed that my account and all echo devices were online. Many rapid page refreshes did not reveal any instances of being offline.

I modified my email alerts so that the Amazon account would need to be offline for at least 30 seconds before I got a notification. That provided an interesting observation. Along with the rapid online/offline dance, every five minutes the account would go offline for at least 30 secs.

I restarted Openhab (via PuTTY, systemctl restart openhab2.service), waited for the system to initialize, and then revisited the amazonechocontrol web page. It required an Amazon account login (without CAPTCHA). Now everything is working fine again.

I hope that someone finds a solution to this.

  • Thomas
1 Like

Could you share your script for alerting when the account goes offline?

@Andrew_Pawelski:
Here’s the rule action, which will email the recipient when the Amazon Account is offline for more than 30 seconds.

// Near the top of your .rule file:
var Timer OfflineTimer = null
var DateTime ConnectionLostTime = null
val String emailRecipients = "recipient@provider.com" // Recipient email list. Separate multiple accounts with semicolon.

// Somewhere in your .rule file.
rule "Amazon Echo Account Online Status"
when 
    Thing "amazonechocontrol:account:YOURACCOUNTNAME" changed
then
    var EchoThing = getThingStatusInfo("amazonechocontrol:account:YOURACCOUNTNAME").getStatus()
    logInfo("DeviceStatus.rules" , 'Amazon Account Status is ' + EchoThing)
    ConnectionLostTime = now
    
    if(EchoThing.toString() != 'ONLINE') {
        logInfo("DeviceStatus.rules" , 'Amazon Echo Account is now ' + EchoThing + '. Starting Offline Timer')
        if (OfflineTimer === null) {
            OfflineTimer = createTimer(now.plusSeconds(30)) [|
                OfflineTimer?.cancel()
                OfflineTimer = null
                var AccountStatus = getThingStatusInfo("amazonechocontrol:account:YOURACCOUNTNAME").getStatus()
                if(AccountStatus.toString() == 'OFFLINE') {
                    logInfo("DeviceStatus.rules" , 'Amazon Echo Account offline too long. Sending email to ' + emailRecipients)
                    sendMail(emailRecipients, "Openhab Warning: Amazon Account is Offline!", "Openhab\'s Amazon Account Connection lost on " 
                    + ConnectionLostTime.toString('MM/dd/yy HH:mm a') + ".\r\n")
                }
            ]
        }    
    }
    else if(EchoThing.toString() == 'ONLINE') {
        logInfo("DeviceStatus.rules" , 'Amazon Echo Account is now ' + EchoThing + ', Canceled Offline Timer')
        OfflineTimer?.cancel()
        OfflineTimer = null
    }
end

Using OH2’s email rule requires that you setup the mail service per the published docs. The services/mail.cfg file will need your email provider’s details.

You can change the 30 second timer value to anything you wish, but shorter times may fill your email account with Account Offline messages!

  • Thomas
4 Likes

Hi to all.
Is it possible to use a timer to get the end of a TTS message?
I get the info in the logs:
EchoTTS changed from to “Text”
EchoTTS changed from “Text” to
Between this two logs is the time alexa needs to say the TTS.
Then i don’t need the sleep function and it will run much nicer.
But i don’t understand the item state of changed from “Text” to ???
Is it undef oder null?
Greetings,
Markus

@Master79: Unfortunately the EchoTTS changed from “Text” to state change occurs before the TTS voice has ended. So it’s not a good candidate to flag the end of TTS.

  • Thomas

Hi,
now I have more and more problems with the binding. Weeks ago the account was just disconnected from time to time. Reentering the Amazon side like described in the offline error fixed the problem for maybe two days. Then the account was offline again and the typical offline error was thrown all the time. I just ignored it after some time. The Echo was still ready for commands inside my network, while it was shown as offline.
But now from time to time when it goes offline, Alexa is not saying anything if I am sending commands to the Echo. After reentering the website it works again for two days until its offline again.
So right now, the binding is not a very reliable thing, because it just drives me nuts fixing the connecttion every two days.
Typical error:

2018-07-10 19:39:35.237 [INFO ] [mazonechocontrol.internal.Connection] - Login failed: Login fails. Check your credentials and try to login with your webbrowser to http(s)://<youropenhab:yourport>/amazonechocontrol/8XXXXXXXX

Wichtige Mitteilung! Zum besseren Schutz Ihres Kontos geben Sie bitte nochmals Ihr Passwort ein, und geben Sie dann die Zeichen ein, die in der Abbildung unten gezeigt werden.

I have been working on this. I created a virtual string type item called ‘Announcement’. When it receives a new message it triggers a rule that plays an attention tone using a short burst of one of the alarm melodies followed by Alexa speaking the message.

So, now I need to just one line code placed wherever I want an TTS announcement with a precdeing attention tone

eg

Announcement.postUpdate('Snow mode is set')

To create the attention tone I did it two ways. One with timers and the other using sleep function and played around with the timing to get the attention tone followed by the announcement.

Here is the more complicated rule using timers. Sleep is much simpler. I am not sure which is best to use.

var Timer PlayAlarmTimer = null
var Timer StopAlarmTimer = null
var Timer SpeakTextTimer = null

rule 'Echo announcement with attention tone'
when 
  Item Announcement changed
  then
  //start attention tone
  if (PlayAlarmTimer === null) {
    PlayAlarmTimer = createTimer(now.plusSeconds(0)) [|
    Echo_AlarmSound.sendCommand('ECHO:system_alerts_melodic_07')
    PlayAlarmTimer?.cancel()
    PlayAlarmTimer = null
    ]
  }

  //end attention tone
  if (StopAlarmTimer === null) {
    StopAlarmTimer = createTimer(now.plusMillis(8500)) [|
    Echo_AlarmSound.sendCommand('')
    StopAlarmTimer?.cancel()
    StopAlarmTimer = null
    ]
  }

  //play announcement
  if (SpeakTextTimer === null) {
    SpeakTextTimer = createTimer(now.plusMillis(9000)) [|
    Echo_Volume.sendCommand(35)
    Thread::sleep(2000)
    Echo_Speak.sendCommand(Announcement.state.toString)
    SpeakTextTimer?.cancel()
    SpeakTextTimer = null
    ]
  }
end

I need to improve the code a bit but it works.

edited to add…

I refined it a bit and edited above code. Now just the following code is placed wherever I want a TTS announcement preceded by an attention tone.

Announcement.postUpdate('<TTS text goes here>')

To enable this I changed the rule trigger to be without conditions:

when 
  Item Announcement changed

I also decided to go with the sleep function version as its a lot less code and it seems to give a more consistent attention tone timing. I will post it if someone asks for it.

2 Likes

Its been a few weeks and I have moved away from my RPi platform onto a virtual machine for OH2 and I am finding things much snappier.

I still have a few issues with the binding that I would like to raise again.

Volume changing very frequently
I reported this a while back just as Michi informed us of a two week break as he was busy on other things. The last idea ws any rules that were causing the change in volume. I have checked multiple times and I have no rules that affect the volume. Someone also pointed out that the volume change although reported always as from BR3_Echo_Volume actually in my DEBUG logs showed it was two different echo devices reporting (BR3 and BR2 devices) and for some reason they were both logging as BR3.
I have since reset both BR2 and BR3 echo devices and registered them again and the same thing occurs. comment out either of these devices stops the constant volume change events. It would appear that BR2 also complains that they set one volume and later when they try it the volume has changed so the volume may well be changing on the device. At this stage I am considering this may be an account issue but I need an easy way to explain the issue to Amazon support and demonstrate to them the problem, anyone any ideas of a simple test that eliminates Openhab and this binding from the equation?

wha device
I canot seem to define the wha thing correctly in the .things file to have it show as defined. See the screenshot.

vox device
Does the binding support the vox device as I cannot seem to get it to show as defined? This is the new device type that the alexa app uses.

.thing file

{
    Thing echo	LR_Echo		"Alexa" @ "Living Room" 	[serialNumber="G090P308741307M7"]
    Thing echo	HO_Echo		"Alexa" @ "Office" 			[serialNumber="G090LF0964851QJA"]
    Thing echo	BR1_Echo	"Alexa" @ "Bedroom" 		[serialNumber="G090LF0971160DL3"] 
    Thing echo	BR2_Echo	"Alexa" @ "Hollys Roomn" 	[serialNumber="G090L90971620LK5"]
    Thing echo	BR3_Echo	"Alexa" @ "O Ryans Room" 	[serialNumber="G090L90963910VUM"]

	Thing vox	Paul_Echo	"Alexa" @ "IOS Device"		[serialNumber="406F6AD7BC7248BEA4D405DF284088D7"]
	
    Thing wha	ALL_Echo	"Everywhere" @ "Music Groups" [serialNumber="bff62eee1e5f4d838a11447b03cd0131"]

    Thing flashbriefingprofile flashbriefing1 "Flash Briefing Technical" @ "Flash Briefings" 
    Thing flashbriefingprofile flashbriefing2 "Flash Briefing Life Style" @ "Flash Briefings" 
}

Thanks

Paul

I have noticed the volume as shown in the logs jumping around. Eg I send command to set it to 35 and a few seconds later it jumps from 35 to 37 or sometimes even UNDEF. I only notice this when I use values like 35 and wonder if this would go away if I only used only ten’s values?? eg 10,20,30,40 and not values in between. Voice command to Alexa is in integer steps, 1 to 10 so that might make sense.

Hi,
Thanks for the great work on this binding.
For me it’s working well with 3 Echo Dots.

But after a certain time i get the following messages in openhab.log. (every few seconds):

2018-07-12 04:57:57.837 [INFO ] [mazonechocontrol.internal.Connection] - Login failed: Login fails. Check your credentials and try to login
with your webbrowser to http(s)://youropenhab:yourport/amazonechocontrol/XXXXce
2018-07-12 04:58:00.936 [INFO ] [mazonechocontrol.internal.Connection] - Login failed: Login fails. Check your credentials and try to login
with your webbrowser to http(s)://youropenhab:yourport/amazonechocontrol/XXXXce
Wichtige Mitteilung! Zum besseren Schutz Ihres Kontos geben Sie bitte nochmals Ihr Passwort ein, und geben Sie dann die Zeichen ein, die in
der Abbildung unten gezeigt werden.

Than I have to stop and start the binding thru karaff shell. After that I have to reenter password twice and one captcha. (I’ve done this on a client PC, with the URL of openhab.log entry)
Afterwards the binding is running well a few days, until the same issue occurs.

Has anyone an idea, whats going wrong there?
Thanks a lot

@m4rk Have tested it. No change. Same problem.
Greetings,
Markus

1 Like

@helmar74
Same problem here. Every 5 days i think.
Greetings,
Markus

1 Like

Yes I think also 5 days for me…