Running alexa_remote_control.sh inside Hass.io

NOTE This script is no longer required. All options now supported in @ keatontaylor custom component

I have been fighting to run the https://loetzimmer.de/patches/alexa_remote_control.sh in Hass.io

After some time I think I have a workable solution :slight_smile:

I have created a new post as the original post is enormous and the information is now difficult to extract

This solution is for Hass.io and It will be a long post so ā€œbare with meā€

Before I begin . I would recommend anybody using Haas.io to use the excellent custom media player

This will give you TTS and has been extremely reliable in my Hass.io setup. However, it does not have all the features of the alexa_remote_control.sh script.

This post assumes you have SSH access to your Hass.io setup and you have edited the script with the correct website and login details. I am from the UK so unsure if this information is accurate anywhere else.

The first issue in running the alexa_remote_control.sh in Hass.io ( and just about every other environment) is
the following error

cookie does not exist. logging in ...
ERROR: Amazon Login was unsuccessful. Possibly you get a captcha login screen.
 Try logging in to https://alexa.amazon.com with your browser. In your browser
 make sure to have all Amazon related cookies deleted and Javascript disabled!

This is caused by the script logging into Amazon site and being asked for a captua authentification. If you are very lucky it may work, but the majority of the time it will fail with the above error.

Run the following command ls /tmp -la and you will find an .alexa.login file. For the script to run successfully, it needs to create a .alexa.cookie file. I have tried lots of methods to create this file, all involving copying cookie files from working systems. None have worked all have said cookie expired The only solution that has worked for me is setting up two-factor authentication on the amazon site and using the Authenticator App on my mobile phone. see

https://www.amazon.co.uk/gp/help/customer/display.html?nodeId=202073820

Once your Authenticator app is generating 6 digits codes for the Amazon site. You can append the 6 digits to the end of your password in the alexa_remote_control.sh script. run alexa_remote_control.sh -a to force a login

The extra authentification in the script will bypass the captua authentification and will work correctly. Confirm you have the .alexa.cookie in the \tmp folder by running ls /tmp -la

Remove the 6 digits code from the alexa_remote_control.sh once you have the .alexa.cookie file. This cookie will eventually expire and the keeping the password + the code will ensure the script will never log in again!

Once you have a script which works, you have a second major issue. Hass.io does not support command line sensors, switches or shell commands. So you cannot integrate the script into HA!

https://www.home-assistant.io/hassio/run_local/

Fortunately, I found python scripts do run correctly from the shell and command line sensors. I cannot claim any originality in this insite, just plenty of googling this forum.

You will need to ensure all the files required for alexa_remote_control.sh, reside in the same folder. So I created /config/alexa folder using mkdir /config/alexa command. Copy the alexa_remote_control.sh and the .alexa.cookie from the /tmp folder cp /tmp/.alexa.cookie /config/alexa/.alexa.cookie

You will then need to edit the alexa_remote_control.sh file and change the following line to ensure everything runs in the same dir

TMP=ā€œ/config/alexaā€

confirm the script is still working, you may have to recreate the .alexa.cookie file. Then create the following file in the /config/alexa folder

import subprocess
import sys
params = sys.argv[1]
cmd = "/config/alexa/alexa_remote_control.sh " + params
x = subprocess.check_output(cmd, shell=True)
print(x.decode("utf-8"))

Save this as alexa_wrapper.py. This creates a wrapper file to allow the shell scripts to work in Hass.io. Run chmod +x /config/alexa/alexa_wrapper.py to make is executable.

Now you can create the following in HA

command line sensor

- platform: command_line
    name: Last Alexa
    command: 'python3 /config/alexa/alexa_wrapper.py {{ "-lastalexa" }}'

Shell command

alexa: 'python3 /config/alexa/alexa_wrapper.py "{{ params }}"'

The last Alexa sensor will update with the last Alexa to receive a command

The shell command will take any parameters the alexa_remote.control will accept. Ensure you wrap commands with the correct quotes. Run this from the developerā€™s tools services to test

{ā€œparamsā€:ā€œ-d ā€˜name of echoā€™ -e speak:ā€˜testing testingā€™ā€}

I do not know how long the cookie will last before it expires, but the last alexa sensor should keep the connection alive. I have been running for about 4 days now without issue

hope this helps. thanks for reading to the end :slight_smile:

3 Likes

The latest cookie expired after two days. Have created the following sensors so I can log more accurately

- platform: folder
    folder: /config/alexa
    filter: .alexa.login

- platform: template
    sensors:   
      alexa_alarm:
        entity_id:
          - sensor.alexa
        friendly_name: "Alexa Alarm"
        value_template: >-
          {% set numfiles = states.sensor.alexa.attributes.number_of_files|float %}
          {% if numfiles  == 0 %}
            off
          {% else %}
            on
          {% endif %}

I was hoping the cookies would last longer than this !

you know i also use the script.
i had it working for months without any trouble and without expirement.
then i started to use a last alexa sensor.
so i tried to retrieve the value every 30 secs.
that worked very well, but my cookie expired in a day.
i did a rewrite but still it expired pretty quick.

now i only check for last alexa when there has been a known alexa event (custom alexa skill, emulated hue items) and i set the value myselve after i used TTS.

and love and behold, the cookie doesnt expire anymore.
so my assuption is that using the script to much in a day lets the cookie expire somehow.

just to let you know and think about trying other ways.

for instance:
make an automation that calls the script with lastalexa
update a sensor from there
call that automation only when you use TTS or entities that are used by alexa.
also update when using media_player

and yeah, you wont find out that someone asked for the weather, started music or anything else thats not HA related.
but then again, thats info you dont want to use anyway.

1 Like

I thought just the opposite, by keeping the connection alive every 60 seconds it would keep the session alive.
I will play with the timeout values to prove the point, but your post makes lots of sense as Iā€™m sure the cookies lasted longer than this before I started playing with the lastalexa option.

Fortunately, the latest version of HA now supports the manual update of sensors with a service so I will start extending the timeout of the sensor and proves how this correlates to the life of the cookie.

I will update with my findings

Thanks again :slight_smile:

your welcome and i am curious what you find out.
(by the way i had simular thoughts, but on the other hand i also think its not a wise move to keep sending calls to the alexa servers, i dont think amazon would like that)

hopefully, I wonā€™t bring down the Amazon servers single-handedly :slight_smile:

I am looking to increase the timeout not reduce them, with the new HA service I can push the timeouts to once a day or whatever the largest value in seconds scan_interval will hold.

Iā€™m just curious if its the number of requests that force the connection closed. Maybe the script recovers and the login re-request works. Thatā€™s why Iā€™ve put a sensor on the creation of the .alexa.login file. It could be Hass.io getting in the way again.

Interestingly the Alexa media custom component also asked to be reauthenticated today, thatā€™s the first time in weeks. so maybe a change in UK Servers!

Iā€™ll let you know

1 Like

Before I waste the next few days trying to understand this, do you know if it works if Amazonā€™s 2-step verification is being used?

I had tried the ā€œecho devices (alexa) as media playerā€, but this does not work if 2-step verification is being used.

what is the 2-step verification?
can you login to the alexa.amazonā€¦ server on your PC and have it so that you dont need to login every time?

https://www.amazon.co.uk/gp/help/customer/display.html?nodeId=202025410

Once a PC or TV etc is recognised it doesnā€™t need the second verification. logging in from HA via Amazon Developer works OK. But couldnā€™t get the ā€œecho devices (alexa) as media playerā€ to work.

this script uses the app
and in that doc it says:

To simplify sign-in on computers and devices that you routinely use, you can tell us not to ask for a security code so that you wonā€™t need to enter a code each time you sign in. Afterward, that computer or device will only ask for your password when you sign in.

i think that you could also use that for the mediaplayer part.

Sorry, I misunderstood. I have now re-read the ā€œecho devices (alexa) as media playerā€ post and got it working with 2FA. Maybe my previous attempt was too early.

1 Like

Cooke timeout after 27 hours using sensor with 1 min timeout . My fag packet math say this is about 1620 updates on the amazon server. I have change the time out to 1 per hour so this should last 67 days !

I will update

1 Like

or just forever :wink:
if they just expire the cookie if there are a specific amount of calls within a certain timeframe.

Hi guys. BTW, very good summary @lonebaggie. Thanks!
I keep getting an error when I run the service from HA but it works OK from the command line (using the Hassio addon ā€œTerminalā€ ).
Iā€™m running Hassio on a RPi 3B+. (HassOS 1.12, Supervisor v 138, HA 0.81.2) and this is the error message I get:

2018-11-02 22:26:53 ERROR (SyncWorker_8) [custom_components.sensor.command_line] Command failed: python3 /config/alexa/alexa_wrapper.py {{ "-lastalexa" }}
2018-11-02 22:27:20 DEBUG (MainThread) [homeassistant.components.shell_command] Stderr of command: `python3 /config/alexa/alexa_wrapper.py "{{ params }}"`, return code: 1:
b'Traceback (most recent call last):\n  File "/config/alexa/alexa_wrapper.py", line 5, in \n    x = subprocess.check_output(cmd, shell=True)\n  File "/usr/local/lib/python3.6/subprocess.py", line 336, in check_output\n    **kwargs).stdout\n  File "/usr/local/lib/python3.6/subprocess.py", line 418, in run\n    output=stdout, stderr=stderr)\nsubprocess.CalledProcessError: Command \'/config/alexa/alexa_remote_control.sh -d \'name of echo\' -e speak:\'testing testing\'\' returned non-zero exit status 1.\n'
2018-11-02 22:27:20 ERROR (MainThread) [homeassistant.components.shell_command] Error running command: `python3 /config/alexa/alexa_wrapper.py "{{ params }}"`, return code: 1
NoneType: None

Any idea what it could be?
Thanks in advance!!

try the following from Hass.io terminal

cd /config/alexa
ls -la

This should display four files

drwxr-xr-x    2 root     root          4096 Oct 30 08:27 .
drwxr-xr-x   14 root     root          4096 Nov  3 07:20 ..
-rw-r--r--    1 root     root          1734 Oct 30 08:27 .alexa.cookie
-rw-r--r--    1 root     root          7439 Oct 30 08:27 .alexa.devicelist.json
-rwxr-xr-x    1 root     root         32811 Oct 30 08:28 alexa_remote_control.sh
-rwxr-xr-x    1 root     root           182 Oct 29 18:29 alexa_wrapper.py

If you have .alexa.login the cookie has expired. If you are missing the .cookie or the json file. You have not amended the TMP path in alexa_remote_control.sh file. Check your files rights have you run chmod +x

Confirm the script runs OK from this dir

./alexa_remote_control,sh -a

If all the above is OK. Things get tricky as you cannot? run python direct in the terminal. If you have created the shell command. Confirm it runs from HA

Edit just noticed in the output you have ā€œname of echoā€ this should be the actual name extracted from alexa_remote_control.sh -a

Big thanks again @lonebaggie.

The simplest parts (missed the TMP update) was the problem.
I have all 4 files and appropriate file permissions ā€¦ so it now runs from the command line and the shell command runs from HA. Great!! I can now automate one of those cheaper ā€œAlexa lamp bulbsā€ I couldnā€™t reach from HA.

I keep getting this recurrent error message though ā€¦

2018-11-03 10:19:31 ERROR (SyncWorker_13) [custom_components.sensor.command_line] Command failed: python3 /config/alexa/alexa_wrapper.py {{ "-lastalexa" }}

2018-11-03 10:20:26 DEBUG (MainThread) [homeassistant.components.shell_command] Stdout of command: `python3 /config/alexa/alexa_wrapper.py "{{ params }}"`, return code: 0:

b'sending cmd:automation:guest lamp on to dev:<REDACTED> type:<REDACTED> serial:<REDACTED> customerid:<REDACTED>\nRunning routine: guest lamp on\n\n'

2018-11-03 10:20:32 ERROR (SyncWorker_13) [custom_components.sensor.command_line] Command failed: python3 /config/alexa/alexa_wrapper.py {{ "-lastalexa" }}

2018-11-03 10:21:33 ERROR (SyncWorker_3) [custom_components.sensor.command_line] Command failed: python3 /config/alexa/alexa_wrapper.py {{ "-lastalexa" }}

2018-11-03 10:22:34 ERROR (SyncWorker_19) [custom_components.sensor.command_line] Command failed: python3 /config/alexa/alexa_wrapper.py {{ "-lastalexa" }}

I guess it canā€™t be the cookies since the script runs form CLI and HAā€¦

I would change the timeout on the last alexa to at least once an hour and use the new service to manually update

return code 0 is a success. Must be the logging level on your Hass.io mine returns

2018-11-03 09:24:20 INFO (SyncWorker_16) [homeassistant.components.sensor.command_line] Running command: python3 /config/alexa/alexa_wra
per.py -lastalexa
2018-11-03 09:24:21 INFO (SyncWorker_7) [homeassistant.components.device_tracker.asuswrt] Checking Devices

My yaml code is

- platform: command_line
    name: Last Alexa
    command: 'python3 /config/alexa/alexa_wrapper.py {{ "-lastalexa" }}'

I added the code you shared, and I ready to manually update ā€¦ but I canā€™t find where I should change the time interval between the calls.

just noticed your log says [custom_components.sensor.command_line] ?

scan_interval: 3600 (1 hour)

Cool. Confirmed ā€¦ changed the interval and itā€™s no longer polling every minute.
Thanks again @lonebaggie. Great help!