alandtse / alexa_media_player

This is a custom component to allow control of Amazon Alexa devices in Home Assistant using the unofficial Alexa API.
Apache License 2.0
1.44k stars 277 forks source link

last_called state attributes showing as null; api/activities returned 404:Not Found:text/html #2089

Closed oneseventhree closed 10 months ago

oneseventhree commented 10 months ago

IMPORTANT: Please search the issues, including closed issues, and the FAQ before opening a new issue. The template is mandatory; failure to use it will result in issue closure.

Describe the bug

As the subject says:

image

To Reproduce

  1. Say "alexa"
  2. last_called used to change
  3. Now stays blank

Expected behavior

Screenshots Happens on all devices:

image

System details

Logs Please provide logs.

home-assistant_2023-10-25T09-39-31.640Z.log

Additional context

Pirol62 commented 10 months ago

related to this thread: https://github.com/custom-components/alexa_media_player/issues/2090

danielbrunt57 commented 10 months ago

image

I'm fearing the worst may have happened..

alandtse commented 10 months ago

Cause is due to activities API being down. We'll need a new API endpoint as found by https://github.com/custom-components/alexa_media_player/issues/2090#issuecomment-1779220821

https://www.amazon.com/alexa-privacy/apd/rvh may be a workaround url but will require webscraping. Preference is still an actual API as webscraping is incredibly brittle.

Fredo70 commented 10 months ago

https://www.amazon.com/alexa-privacy/apd/rvh may be a workaround url but will require webscraping. Preference is still an actual API as webscraping is incredibly brittle.

Are you sure it would work? But the URL depends on where the user is. For example, the .com shows me no activity at all. The .de does.

alandtse commented 10 months ago

The current code chooses the domain. Again, these are notes for whoever wants to fix it. They will need to figure out the proper way to handle.

Daverover66 commented 10 months ago

Cause is due to activities API being down. We'll need a new API endpoint as found by #2090 (comment)

https://www.amazon.com/alexa-privacy/apd/rvh may be a workaround url but will require webscraping. Preference is still an actual API as webscraping is incredibly brittle.

This won't work for me as the activity history for my account seems to shows nothing.

Tloram commented 10 months ago

Cause is due to activities API being down. We'll need a new API endpoint as found by #2090 (comment)

https://www.amazon.com/alexa-privacy/apd/rvh may be a workaround url but will require webscraping. Preference is still an actual API as webscraping is incredibly brittle.

If you check the network xhr requests made from that URL, there is a direct api request URL (different from the above) that returns JSON with most recent used alexa device as the first entry in an array of objects.

It seems to be:

https://[amazon domain for your region]/alexa-privacy/apd/rvh/customer-history-records-v2?startTime=1698274800000&endTime=1698308483234&disableGlobalNav=false

Of course, it will only work if passed the correct headers, cookies, tokens etc. so it might be hard to access it from outside of a logged in Amazon account.

One other thing to note, I tested the latency between issuing a command to an alexa device and this api returning the latest data, there is currently about a 10 second delay/cache mechanism... so this probably makes it almost worthless/pointless to be used for automations that require an immediate response.

alandtse commented 10 months ago

You can try replacing the url in alexapy and perhaps the component will have the right auth.

The delay was always there since it has to round trip up to Amazon and then back. It's possible this api is slower. I forgot if we rely on the http2 push stream for the data before the url returns but it seems like something I would've done before.

danielbrunt57 commented 10 months ago

The delay was always there since it has to round trip up to Amazon and then back. It's possible this api is slower. I forgot if we rely on the http2 push stream for the data before the url returns but it seems like something I would've done before.

Alan, Is HTTP2 rather new? About a week or two ago, I had instant updating of my media players' last_called(_xxx) attributes for about a day or so. I tested it over and over and it was virtually instantaneous (< 1s). It surprised me greatly and I thought it might have been related to HTTP2...

Fredo70 commented 10 months ago

I used to have openHAB. But I no longer have openHAB. So I can't test it. The URL "/api/activities" is also called up in the original binding. However, there is a fork and there a request is made for "https://" + getAmazonSite() + "/alexa-privacy/apd/rvh/customer-history-records". Maybe this can help? The language is Java. https://github.com/smarthomej/addons/blob/bc8a20aa95e764c3008e1351ec075b6d8bc9764f/bundles/org.smarthomej.binding.amazonechocontrol/src/main/java/org/smarthomej/binding/amazonechocontrol/internal/connection/Connection.java#L938

Pull request: https://github.com/smarthomej/addons/pull/235

sdholden28 commented 10 months ago

Seems to be an intentional change on Amazon's part. This went out to ifttt users today.

We’re writing to let you know that on October 31st, 2023 the Amazon Alexa service will no longer be available on IFTTT.

Amazon has made the decision to no longer support their integration on IFTTT. Like you, many of us here on the IFTTT team use the Alexa IFTTT integration daily for things ranging from controlling lights and music in our homes to integrating with task management apps to boost productivity. We were disappointed to hear about this change, we understand it is always difficult to see an existing service removed from IFTTT.

We encourage you to update your Alexa Applets to use alternative triggers prior to October 31st. You can find more information on how to update your Applets, as well as suggested alternative triggers [here].

Starting November 1st, Applets that use the Say a specific phrase trigger will be migrated to instead use the IFTTT Button Widget. Applets that use any Amazon Alexa trigger other than Say a specific phrase or any Amazon Alexa query will be archived on October 31st if they are not updated to use a different trigger and/or query prior to that date.

IFTTT Community team

Cpd5899 commented 10 months ago

Seems to be an intentional change on Amazon's part. This went out to ifttt users today.

We’re writing to let you know that on October 31st, 2023 the Amazon Alexa service will no longer be available on IFTTT.

Amazon has made the decision to no longer support their integration on IFTTT. Like you, many of us here on the IFTTT team use the Alexa IFTTT integration daily for things ranging from controlling lights and music in our homes to integrating with task management apps to boost productivity. We were disappointed to hear about this change, we understand it is always difficult to see an existing service removed from IFTTT.

We encourage you to update your Alexa Applets to use alternative triggers prior to October 31st. You can find more information on how to update your Applets, as well as suggested alternative triggers [here].

Starting November 1st, Applets that use the Say a specific phrase trigger will be migrated to instead use the IFTTT Button Widget. Applets that use any Amazon Alexa trigger other than Say a specific phrase or any Amazon Alexa query will be archived on October 31st if they are not updated to use a different trigger and/or query prior to that date.

IFTTT Community team

Thats great.... (sarcasm) It would be really great, if someone from HA would tell us something. I posted in the forum, but apparently I am the only one who uses it, since there is no response. LOL

vinimeca commented 10 months ago

I use the "last alexa" for a lot of automations and it is very important in HA. All of this is useless now. Please someone help.

master-kenobi commented 10 months ago

I use the "last alexa" for a lot of automations and it is very important in HA. All of this is useless now. Please someone help.

me too

danielbrunt57 commented 10 months ago

Thats great.... (sarcasm) It would be really great, if someone from HA would tell us something. I posted in the forum, but apparently I am the only one who uses it, since there is no response.

You are not the only one using it as there are 1,200 "*" but it has nothing to do with anyone at Home Assistant per se since Alexa Media Player is a custom component by Alan Tse and contributed to by 35 other contributors over the years. Not to mention it's using an unofficial API to accomplish its miraculous feats! I applaude them for what they've been able to achieve and if it's to be be no more then so be it. You can blame Amazon but not HA. But, I've not given up hope yet!

I've edited my scripts/automations and fortunately, only good_night/good_morning were my biggest calls, which 99.99% of the time I make from bedroom so I have hard coded them to bedroom_echo_right (on my night stand). Car arrival script asking to close garage door was already hard coded to garage echo. The only other script/scene was "light" which I developed to turn on the lights in the area I'm in but will have to use Alexa, turn on the light and ensure Alexa's areas are properly set up. I'm sure for other users/implementations, it won't be so easy!

acid115 commented 10 months ago

But maybe there is hope. If you call https://alexa.amazon.de/api/activities Then you see the following: generic.png

So, maybe the Service is just temporarly unavailable and works again in a few days

Fredo70 commented 10 months ago

As I wrote in https://github.com/custom-components/alexa_media_player/issues/2089#issuecomment-1780792390 above, it should be possible with this solution. But I don't know how reactive the contributors are. I would like to try it myself, but I really need support from a contributor. Because... I've never contributed to HA before, I haven't set up a development environment for HA, I only have a basic knowledge of Python, I have no idea about the Alexa API and authentication. I really need an exchange so that I don't do anything wrong and more than once. Besides, my free time is very tight, so it could take longer.

danielbrunt57 commented 10 months ago

But maybe there is hope. If you call https://alexa.amazon.de/api/activities Then you see the following: ![generic.png]

So, maybe the Service is just temporarly unavailable and works again in a few days

O maybe not! There have been lots of layoffs recently in Amazon's Alexa dev workforce...

Pirol62 commented 10 months ago

I may have a quite good work around for the meantime. Here it solves 80% of the issues and works for all guys, who have motion sensors in at least most of all rooms. Its not 100% accurate even when two or more persons moving around in the house but it can increase the situation

I had an automation whitch wrotes the location of the latest movement into a variable:

- service: variable.update_sensor
  data:
    value: "{{now().strftime('%H:%M:%S - %d-%m-%Y')}}"
    attributes:
      location: "{{trigger.to_state.attributes.friendly_name}}"
  target:
    entity_id: sensor.last_general_motion_detected

I created an additional sensor around the location attribute in order to display that in a button_card

Now I already wrote a custom template which translates a given movement into an alexa media_player

{% macro last_movement_alexa_target(palexa) %}
{% if states('sensor.last_called_alexa') == 'media' %}
    {% set map = {
    "Wohnzimmer": "media_player.unten",
    "Gästezimmer": "media_player.gastezimmer",
    "Office": "media_player.office",
    "Office 2": "media_player.office",
    "Küche": "media_player.kuche",
    "Fitnessraum": "media_player.fitnessraum",
    "Schlafzimmer": "media_player.dachgeschoss",
    "Treppe oben": "media_player.dachgeschoss"}
    %}
    {{ map[palexa] if palexa in map else 'media_player.wohnzimmer' }} 
{% else %}
    {{states('sensor.last_called_alexa')}}
{% endif %}
{% endmacro %}````

and now I can build my own alexa last_called
command_announce_something:
  variables:
     vtarget: "init"
  sequence:
    - service: alexa_media.update_last_called
    - delay: 00:00:01
    - variables:
        vtarget: >
          {% from 'global_functions.jinja' import last_movement_alexa_target %}
          {{ last_movement_alexa_target() }}
    - service: notify.alexa_media
      data:
        target: "{{vtarget}}"
        data:
          type: tts
        message: "bla bla"

with a little more time it can shurely be defined a little more sophisticated, but on the other hand we hope that its only for a short time

Edit 28.10: improved the macro a little Edit: 30.10 make it so, that I either can modify update_last_called in an own script or wait until it works again

lloydbayley commented 10 months ago

That's a great idea. Very clever. Would work for me as it's just me here most of the time. Even if this problem can be fixed, the code is still good for other ideas!

master-kenobi commented 10 months ago

I may have a quite good work around for the meantime. Here it solves 80% of the issues and works for all guys, who have motion sensors in at least most of all rooms. Its not 100% accurate even when two or more persons moving around in the house but it can increase the situation

I had an automation whitch wrotes the location of the latest movement into a variable:

- service: variable.update_sensor
  data:
  value: "{{now().strftime('%H:%M:%S - %d-%m-%Y')}}"
  attributes:
    location: "{{trigger.to_state.attributes.friendly_name}}"
  target:
  entity_id: sensor.last_general_motion_detected

I created an additional sensor around the location attribute in order to display that in a button_card

Now I already wrote a custom template which translates a given movement into an alexa media_player

{% macro last_movement_alexa_target(palexa) %}
{% set map = {
   "Wohnzimmer": "media_player.wohnzimmer",
   "Gästezimmer": "media_player.gastezimmer",
   "Office": "media_player.office",
   "Küche": "media_player.kuche",
   "Fitnessraum": "media_player.fitnessraum",
   "Schlafzimmer": "media_player.schlafzimmer"}
   %}
   {{ map[palexa] if palexa in map else 'media_player.wohnzimmer' }} 
{% endmacro %}

and now I can build my own alexa last_called

command_announce_something:
  sequence:
    - service: notify.alexa_media
    data:
      target: >
        {%set loc = states('sensor.current_motion_location') %}
        {% from 'global_functions.jinja' import last_movement_alexa_target %}
        {{ last_movement_alexa_target(loc) }}
      data:
        type: tts
      message: "bla bla"

with a little more time it can shurely be defined a little more sophisticated, but on the other hand we hope that its only for a short time

Good idea but not a viable solution for home with multiple occupants where they roam freely from room to room. maybe can put a light sensor on the Echo LED ring as workaround?

Tloram commented 10 months ago

The existing solution is so fragile, relying as it did on an unofficial Amazon api, I have often wondered for how long will it last without issue. TBH it is kind of annoying that Amazon do not offer some official way to query the last used device.

One possibility I have considered in the past, although it would be a lot of work, is to place some other wireless microphone near to the alexa in each room, which is connected to some internal voice recognition software running 24/7 on some type of linux box, and is only listening for the Alexa "wake word". This could then be used to record the room accurately and instantly, with no reliance on Amazon. It would also decouple the room aware functionality entirely from any specific vendor (Amazon, Google, whatever).

Alas it is a lot of work and I am too lazy to research the hardware side and software side for a solution.

garysargentpersonal commented 10 months ago

I have a better workaround but not yet thought it through or how to make something generic anyone could use.... But each time Alexa goes off to the cloud to process a voice request, it looks up specific DNS entries, and makes connections to specific servers. If this can be captured, we can work out which Alexa it was from the source IP address. This would all be local and much quicker than using any Amazon API.

Tloram commented 10 months ago

I have a better workaround but not yet thought it through or how to make something generic anyone could use.... But each time Alexa goes off to the cloud to process a voice request, it looks up specific DNS entries, and makes connections to specific servers. If this can be captured, we can work out which Alexa it was from the source IP address. This would all be local and much quicker than using any Amazon API.

I looked into this a long long time ago, it isn't possible because Amazon employ a "round-robin" approach to sending the network request. The device you interact with is not likely to be the same device that sends the request to Amazon.

garysargentpersonal commented 10 months ago

I looked into this a long long time ago, it isn't possible because Amazon employ a "round-robin" approach to sending the network request. The device you interact with is not likely to be the same device that sends the request to Amazon.

So you speak to one Alexa, but a different one sends the actual network request? That doesn't make much sense. Though I suppose if you're between Alexa's they may both send things to the cloud if they both hear you.

Tloram commented 10 months ago

I looked into this a long long time ago, it isn't possible because Amazon employ a "round-robin" approach to sending the network request. The device you interact with is not likely to be the same device that sends the request to Amazon.

So you speak to one Alexa, but a different one sends the actual network request? That doesn't make much sense. Though I suppose if you're between Alexa's they may both send things to the cloud if they both hear you.

Exactly that. It's possible things have changed since I last checked, that was about 6 years ago.

garysargentpersonal commented 10 months ago

That would suggest they are broadcasting something locally, which might be useful.

Tloram commented 10 months ago

That would suggest they are broadcasting something locally, which might be useful.

Possibly. Here is a discussion on this topic from 2017 in case you find it of any use: https://github.com/bwssytems/ha-bridge/issues/386

Tloram commented 10 months ago

You can try replacing the url in alexapy and perhaps the component will have the right auth.

The delay was always there since it has to round trip up to Amazon and then back. It's possible this api is slower. I forgot if we rely on the http2 push stream for the data before the url returns but it seems like something I would've done before.

@alandtse I tried this but the current auth is not sufficient.

I have narrowed down the request to a bare minimum set of headers and tokens that this api endpoint requires before rejecting us, but TBH I am not sure how to actually get real valid values for all of these (.co.uk used in the example below, REQUIRED_VALUE placeholder needs to be substituted for real & current valid values):

curl 'https://www.amazon.co.uk/alexa-privacy/apd/rvh/customer-history-records-v2?startTime=REQUIRED_VALUE&endTime=REQUIRED_VALUE' \
  -H 'anti-csrftoken-a2z: REQUIRED_VALUE' \
  -H 'content-type: application/json;charset=UTF-8' \
  -H 'cookie: REQUIRED_VALUE' \
  -H 'referer: https://www.amazon.co.uk/alexa-privacy/apd/rvh' \
  -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' \
  --data-raw '{"previousRequestToken":"REQUIRED_VALUE"}'

If you copy and run the request from your browser using curl you will get a JSON response of this format (customerHistoryRecords[0] being the most recent, with device.deviceName being the useful value for us) :

{
    "customerHistoryRecords": [
        {
            "recordKey": "...",
            "recordType": "VOICE_HISTORY",
            "timestamp": 1698406415222,
            "customerId": "...",
            "device": {
                "deviceName": "Office Alexa Show",
                "deviceEntityId": null
            },
            "isBinaryFeedbackProvided": false,
            "isFeedbackPositive": false,
            "utteranceType": "GENERAL",
            "domain": "Global",
            "intent": "UnMuteIntent",
            "skillName": "",
            "voiceHistoryRecordItems": [
                {
                    "recordItemKey": "...",
                    "recordItemType": "CUSTOMER_TRANSCRIPT",
                    "utteranceId": "..",
                    "timestamp": 1698406414732,
                    "transcriptText": "unmute",
                    "agentVisualName": "",
                    "personsInfo": []
                }
            ],
            "personsInfo": [],
            "cardResponse": null
        },
        { ... },
        { ... },
        { ... }
    ],
    "encodedRequestToken": "",
    "noDataFoundWithinTimeLimit": false,
    "lastRecordTimestamp": null,
    "voiceProfileAssociatedWithPerson": false
}
Fredo70 commented 10 months ago

@Tloram Can you have a look here? If it works with openHAB (Java) it should also be possible with python.

https://github.com/smarthomej/addons/blob/bc8a20aa95e764c3008e1351ec075b6d8bc9764f/bundles/org.smarthomej.binding.amazonechocontrol/src/main/java/org/smarthomej/binding/amazonechocontrol/internal/connection/Connection.java#L938

Fredo70 commented 10 months ago

@Tloram Sorry for the stupid question. But where is the pypi module alexapy stored in HAOS?

acid115 commented 10 months ago

Within the homeassistant container alexapy is located here: /usr/local/lib/python3.11/site-packages/alexapy/

carlos33193 commented 10 months ago

I'm using a bit of a silly workaround but all my HA automations that were relying on "last_called" are now working again seamlessly as before.

I added to my alexa routines (which used to call my scripts and my scripts determined which alexa it came from using the last called attribute), I am now adding for it to set the volume to 10 (1.0).. then I created my own "last_called" sensor that checks for volume to be at 1.0 and uses that to track which alexa was called.

The Alexa routine looks like this: Set Volume to 10 (100% or 1.0 in HA) > Call HA Script (check for which device is at volume 100% (1.0), execute script > Wait 5 seconds (minimum in alexa routines) > Set Volume to 3.

The Binary Sensor in configuration.yaml is like this. template:

P.S - The volume attribute seems to update almost immediately, so you could just add a 1 second delay in your HA script before your actions are called and it should work faster than before since the last_called attribute actually had about a 3 second or so delay.

Kethlak commented 10 months ago

@carlos33193 Thanks for the inspiration. I made a trigger-based sensor for this, so it updates whenever the volume of one is changed to be 1.0, and keeps that value until it's replaced by another device. That way I can easily reset the volume (I have a separate script that sets different ones to different hard-coded values) of all devices before playing tts without having to set variables to avoid it screaming at me.

- trigger:
    - platform: template
      value_template: |-
        {{ expand(integration_entities('alexa_media') | select('search', 'media_player')) | selectattr('attributes.volume_level', 'defined') 
        | selectattr('attributes.volume_level', 'eq', 1)
        | map(attribute='entity_id') | first is defined }}
  sensor:
    - name: Last Alexa Volume Based
      unique_id: last_alexa_volume_based
      state: |-
        {{ expand(integration_entities('alexa_media') | select('search', 'media_player')) | selectattr('attributes.volume_level', 'defined') 
        | selectattr('attributes.volume_level', 'eq', 1)
        | map(attribute='entity_id') | first }}
grillp commented 10 months ago

Someone has opened an issue on this in AlexaPy: https://gitlab.com/keatontaylor/alexapy/-/issues/27

sarigaus commented 10 months ago

Thanks everyone for your comments and solutions. Based on your comments I have found a viable alternative that seems to be working now. I use Alexa devices mainly to trigger HA routines by setting on a Boolean to trigger HA to do its thing. Here is what I ended up doing and I hope it helps:

First I changed my sensor in configuration.yaml to:

Then I amended all my Alexa routines that set on a HA Boolean to change volume to 0 and then toggle boolean All my routines in HA that interface with an Alexa device, like notifications etc call a script called Last Alexa before doing anything. This scripts purpose in life is to take the value from the sensor.last_alexa and stores it in a helper called input_text.last_alexa. The reason for this is the sensor.last_alexa will be cleared as soon as my routine calls a notification script that sets the volume to a value depending on time of day etc. As soon as the volume is changed from 0 it is cleared which is what I wanted. Then my routines and scripts just use the value from the input_text.last_alexa to announce ask questions etc. This updates instantaneous in HA when the volume level is changed to 0 and the sensor is updated with no delay.

Like most on this forum I have been racking my brain for days since this functionality stopped working as my integration with Amazon is pretty big so I can use my echos dotted around the home. I Hope to one day move away from this with wake words becoming a thing in HA without the need for cloud based solutions.

smarterhome-my commented 10 months ago

I'm using a bit of a silly workaround but all my HA automations that were relying on "last_called" are now working again seamlessly as before.

I added to my alexa routines (which used to call my scripts and my scripts determined which alexa it came from using the last called attribute), I am now adding for it to set the volume to 10 (1.0).. then I created my own "last_called" sensor that checks for volume to be at 1.0 and uses that to track which alexa was called.

The Alexa routine looks like this: Set Volume to 10 (100% or 1.0 in HA) > Call HA Script (check for which device is at volume 100% (1.0), execute script > Wait 5 seconds (minimum in alexa routines) > Set Volume to 3.

The Binary Sensor in configuration.yaml is like this. template:

  • binary_sensor:

    • name: LAST ALEXA CALLED - OFFICE state: "{{ is_state_attr('media_player.office_echo_studio', 'volume_level', 1) }}"

P.S - The volume attribute seems to update almost immediately, so you could just add a 1 second delay in your HA script before your actions are called and it should work faster than before since the last_called attribute actually had about a 3 second or so delay.

thanks for this idea but my volume_level attraibute of the media_player entity doesn't change. I have tried adding a new action to set the volume to 10 in the relevant Alexa routine and manually command the echo to change the volume to 10. The volume_level attribute in my HA remains the same.

sarigaus commented 10 months ago

@smarterhome-my, that is interesting that your integration does not at least update the volume level sensor attributes in HA. For me it changes as soon as I press the volume up/down on the echo device or through routines etc. Not sure why your setup would be any different.

zaphod2010 commented 10 months ago

I'm using a bit of a silly workaround but all my HA automations that were relying on "last_called" are now working again seamlessly as before. I added to my alexa routines (which used to call my scripts and my scripts determined which alexa it came from using the last called attribute), I am now adding for it to set the volume to 10 (1.0).. then I created my own "last_called" sensor that checks for volume to be at 1.0 and uses that to track which alexa was called. The Alexa routine looks like this: Set Volume to 10 (100% or 1.0 in HA) > Call HA Script (check for which device is at volume 100% (1.0), execute script > Wait 5 seconds (minimum in alexa routines) > Set Volume to 3. The Binary Sensor in configuration.yaml is like this. template:

  • binary_sensor:

    • name: LAST ALEXA CALLED - OFFICE state: "{{ is_state_attr('media_player.office_echo_studio', 'volume_level', 1) }}"

P.S - The volume attribute seems to update almost immediately, so you could just add a 1 second delay in your HA script before your actions are called and it should work faster than before since the last_called attribute actually had about a 3 second or so delay.

thanks for this idea but my volume_level attraibute of the media_player entity doesn't change. I have tried adding a new action to set the volume to 10 in the relevant Alexa routine and manually command the echo to change the volume to 10. The volume_level attribute in my HA remains the same.

same for me. tried several devices without any luck. neither changing the volume via voice, device buttons nor alexa app works :-(

Morpheus2018 commented 10 months ago

I may have a quite good work around for the meantime. Here it solves 80% of the issues and works for all guys, who have motion sensors in at least most of all rooms. Its not 100% accurate even when two or more persons moving around in the house but it can increase the situation

Thanks for the idea, I will use it for my Fire HD TAB + Fully Browser - Screen Unlock sensor. Unfortunately it works with a very long delay.

    sensor:
      - platform: template
        sensors:
          my_last_alexa_state:
            friendly_name: "My Last Alexa State"
            value_template: >-
              {% if is_state('switch.home_fire_tab_fully_bildschirm', 'on') %}
                media_player.home_fire_tab
              {% else %}
                media_player.alexa_echo_dot
              {% endif %}

script

service: notify.alexa_media
data:
  data:
    method: all
  message: >
    {{ states('sensor.terrassen_temperatur') }}°C
  title: Title
  target: "{{ states('sensor.my_last_alexa_state') }}"
juan11perez commented 10 months ago

@sarigaus Would you please post your code that does this part:

All my routines in HA that interface with an Alexa device, like notifications etc call a script called Last Alexa before doing anything. This scripts purpose in life is to take the value from the sensor.last_alexa and stores it in a helper called input_text.last_alexa. The reason for this is the sensor.last_alexa will be cleared as soon as my routine calls a notification script that sets the volume to a value depending on time of day etc. As soon as the volume is changed from 0 it is cleared which is what I wanted. Then my routines and scripts just use the value from the input_text.last_alexa to announce ask questions etc.
This updates instantaneous in HA when the volume level is changed to 0 and the sensor is updated with no delay.

apologies but i dont quite follow. Thank you

Morpheus2018 commented 10 months ago

The Alexa routine looks like this: Set Volume to 10 (100% or 1.0 in HA) > Call HA Script (check for which device is at volume 100% (1.0), execute script > Wait 5 seconds (minimum in alexa routines) > Set Volume to 3.

Can you please explain exactly how you set up the routine with volume 1 then 0.3.

msolomos commented 10 months ago

for me, living at a big house with 5 alexa's, is a big problem indeed. Especially when I have built many automation based on sensor.last_alexa, such as "Is the water hot?"

When I saw that sensor.last_alexa is not been updated I thought I should try to update it manually. As soon as I replaced unknown with the name of a media player it worked! Then I thought why not use media_player.everywhere for a while until the problem is solved (hopefully).

I was n't lucky this time, When use media_player.everywhere my scripts are not working No error in logs this time, but not a reply from alexa either

juan11perez commented 10 months ago

@sarigaus go it @Morpheus2018 open the routine, add a new action, set volume to 0.1, add another action set a 5sec wait, add another action set volume to 0.3 It does work well

Morpheus2018 commented 10 months ago

My current solution, a bit complicated but works okay.

sensor

    template:
      - sensor:
          - name: Last Alexa
            state: >
              {{ expand('group.all_alexa_echos') | selectattr('attributes.volume_level','eq', 0.2) | map(attribute='entity_id') | first }}
            availability: >
              {{ expand('group.all_alexa_echos') | selectattr('attributes.is_volume_muted','eq', True) | first is defined }}

script

alias: Test Last Alexa State
sequence:
  - service: notify.alexa_media
    data:
      data:
        method: all
      message: |
        *
      title: empty message to activate
      target: "{{states.sensor.last_alexa.state}}"
    enabled: true
  - delay:
      hours: 0
      minutes: 0
      seconds: 1
      milliseconds: 0
  - service: notify.alexa_media
    data:
      data:
        method: all
      message: |
        The temperature is {{ states('sensor.terrassen_temperatur') }}°C
      title: your script
      target: "{{states.sensor.last_alexa.state}}"
    enabled: true
  - delay:
      hours: 0
      minutes: 0
      seconds: 30
      milliseconds: 0
  - service: media_player.play_media
    data:
      media_content_id: volume 0
      media_content_type: custom
    target:
      entity_id:
        - media_player.alexa_echo_dot
        - media_player.home_fire_tab
    enabled: true
mode: single
icon: mdi:thermometer
sarigaus commented 10 months ago

Yep that will work Morpheus. Many ways to achieve same result.

carlos33193 commented 10 months ago

thanks for this idea but my volume_level attraibute of the media_player entity doesn't change. I have tried adding a new action to set the volume to 10 in the relevant Alexa routine and manually command the echo to change the volume to 10. The volume_level attribute in my HA remains the same.

Make sure your integration is updated in HACS, and then try reloading the integration. I had an issue with it not working for a bit, reloading the integration fixed it.

carlos33193 commented 10 months ago

same for me. tried several devices without any luck. neither changing the volume via voice, device buttons nor alexa app works :-(

Try reloading the integration and recheck.

Morpheus2018 commented 10 months ago

Yep that will work Morpheus. Many ways to achieve same result.

It's just a stopgap solution, I hope for a better solution.

Toolmaster30 commented 10 months ago

IOBroker auf einem Py oder unter Proxmox installieren, danach Alexa2 und Mqtt Client installieren. Die letzte Alexa einfach per MQTT senden lassen und unter Homeassistant per Mqtt Sensor abfragen. Funktioniert fast in Echtzeit. Das Alexa2 Modul muss von Github installiert werde.