Alexa Media Player timers as a trigger

I’ve noticed that I seem to get entries in the log saying “Script script.alexa_timer_check already running.” when a timer is set. Any idea why? I didn’t think this was possible, since the automation calls turn_off immediately before calling the script? Weirdly this doesn’t actually seem to stop it working though.

it shouldn’t stop working because you turn it off before turning it on again. Do the entries in the log say INFO, ERROR, or WARNING?

They are WARNINGs.

I have noticed that after updating the alexa media player custom component I am also getting some errors because the sensor returns “unknown” now instead of “None”, so I have updated the automation and scripts accordingly.

I set the timer by voice command. Is it possible to read the countown from the Alexa timer and display it in the lovelace?

by the way: I use Sonos with Alexa and have Haaska installed

Thanks

I have sensor.kitchen_echo_next_timer in an entities card in Lovelace and it shows a countdown. It only shows whole minutes remaining, then seconds when there is less than one minute left.

Thanks!
How do you get this sensor? My sonos speacker has just the entity “media_player.kitchen”. There are no sensor (-domains).

Have you installed the Alexa Media Player custom integration from HACS and configured it? https://github.com/custom-components/alexa_media_player/wiki/Configuration
That’s the one I used for all of the stuff earlier in this thread. I don’t know if it works with Sonos speakers - I’ve only used it with Echoes.

1 Like

What is the state change for your automation’s trigger? I keep getting errors that the trigger is undefined. I have copied your script and automation exactly and changed my entity_id to the device I am using.

The scripts have slightly evolved over time since I posted them here. Here’s what I’ve currently got running and it’s probably 95% reliable (sometimes the integration fails to update next_timer when it is set but that seems to have improved with recent updates). No doubt some bits are probably unnecessary but now it works I’m leaving it alone!

The automation:

- alias: Kitchen Timer Announcement
  trigger:
    platform: state
    entity_id: sensor.kitchen_echo_next_timer
  condition:
    condition: template
    value_template: '{{ trigger.to_state.state not in [''None'', ''unknown'', ''unavailable'']
      and trigger.from_state.state != trigger.to_state.state }}'
  action:
  - service: script.turn_off
    data:
      entity_id: script.alexa_timer_check
  - delay:
      seconds: 1
  - service: script.alexa_timer_check
    data_template:
      duration: '{{ (as_timestamp(trigger.to_state.state) - now().timestamp() + 5)
        | timestamp_custom(''%H:%M:%S'', false) }}'

And these are the scripts:

alexa_timer_check:
  sequence:
  - delay: '{{ duration }}'
  - service: script.alexa_timer_announce

alexa_timer_announce:
  sequence:
  - condition: template
    value_template: '{{ states(''sensor.kitchen_echo_next_timer'') not in [''None'',
      ''unknown'', ''unavailable''] and as_timestamp(states(''sensor.kitchen_echo_next_timer''))
      < as_timestamp(now()) }}'
  - service: notify.alexa_media
    data_template:
      target:
      - media_player.living_room_echo
      - media_player.bedroom_echo
      data:
        type: announce
      message: The kitchen timer is going off
  - service: script.turn_off
    data:
      entity_id: script.alexa_timer_loop
  - delay:
      seconds: 1
  - service: script.alexa_timer_loop

alexa_timer_loop:
  sequence:
  - delay: 00:00:9
  - service: script.alexa_timer_announce

hmm, still getting errors. Now with what you just posted, I receive an error about the delay duration of Alexa Timer Check:

alexa_timer_check: Error rendering alexa_timer_check delay template: offset should be format 'HH:MM' or 'HH:MM:SS'`

Then when I try to run the entire automation, I receive this error:

Kitchen Timer Announcement: Error executing script. Unexpected error for call_service at pos 2: Error rendering data template: UndefinedError: 'trigger' is undefined
Kitchen Timer Announcement: Error executing script. Unexpected error for call_service at pos 3: Error rendering data template: UndefinedError: 'trigger' is undefined
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 221, in async_render
    return compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
  File "/usr/local/lib/python3.7/site-packages/jinja2/sandbox.py", line 407, in getattr
    value = getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'trigger' is undefined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 104, in async_prepare_call_from_config
    template.render_complex(config[CONF_SERVICE_DATA_TEMPLATE], variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 70, in render_complex
    return {key: render_complex(item, variables) for key, item in value.items()}
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 70, in <dictcomp>
    return {key: render_complex(item, variables) for key, item in value.items()}
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 72, in render_complex
    return value.async_render(variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 223, in async_render
    raise TemplateError(err)
homeassistant.exceptions.TemplateError: UndefinedError: 'trigger' is undefined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 154, in _async_step
    self, f"_async_{cv.determine_script_action(self._action)}_step"
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 624, in _async_call_service_step
    *self._prep_call_service_step(), blocking=True, context=self._context
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 253, in _prep_call_service_step
    return async_prepare_call_from_config(self._hass, self._action, self._variables)
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 107, in async_prepare_call_from_config
    raise HomeAssistantError(f"Error rendering data template: {ex}") from ex
homeassistant.exceptions.HomeAssistantError: Error rendering data template: UndefinedError: 'trigger' is undefined

Am I doing something incorrectly?

UPDATE: It is working now… I didn’t change anything and it started working… Thanks!

I don’t want hijack this topic.
I like to use the timer function. But i have some problems to integrate my sonos speaker. Everything is not available (nicht Verfügbar). And all my Sonos shows up as two devices (“Yves 2’nd Sonos One” and “Büro” ). I Reinstall the Tool several times and i have no idea what i did wrong. The only Fail i did during the first installation was to choos amazon.com instead of amazone.de

alexa_media_player|433x429

Any idea to help me?
Thanks a lot!

I have one more slit issue with this. All of a sudden, when I set a timer, and that time goes off, the notification seems to loop and the only way I can get it to stop is to restart HA. It was working prior to today just fine where the timer would go off once and then the automation would notify the alexa group I entered, and they it would stop. But like I said, now it just keeps going and the only way to stop it is to reboot HA.

Sorry not to answer the queries above, I’ve not been on here for a while. However, I have just been updating the scripts since they broke after I upgraded to 0.114. The good news is they are much simpler now that they can use the new repeat functionality and mode options for multiple calls, with just one automation and one script instead of three.

Automation:

- alias: Kitchen Timer Announcement
  mode: parallel
  trigger:
    platform: state
    entity_id: sensor.kitchen_echo_next_timer
  condition:
    condition: template
    value_template: '{{ trigger.to_state.state not in [''None'', ''unknown'', ''unavailable'']
      and trigger.from_state.state != trigger.to_state.state }}'
  action:
  - service: script.alexa_timer_announce
    data_template:
      duration: '{{ (as_timestamp(trigger.to_state.state) - now().timestamp() + 5)
        | timestamp_custom(''%H:%M:%S'', false) }}'

And the script:

alexa_timer_announce:
  alias: "Kitchen Timer Announcement Loop"
  mode: restart
  sequence:    
    - delay: '{{ duration }}'
    - repeat:
        while:
          - condition: template
            value_template: '{{ states(''sensor.kitchen_echo_next_timer'') not in [''None'',
              ''unknown'', ''unavailable''] and as_timestamp(states(''sensor.kitchen_echo_next_timer''))
              < as_timestamp(now()) }}'
        sequence:
          - service: notify.alexa_media
            data_template:
              target:
              - media_player.living_room_echo
              - media_player.bedroom_echo
              data:
                type: announce
              message: The kitchen timer is going off
          - delay:
              seconds: 10

I have tested this and it appears to work with single and multiple timers, including when additional timers are set to go off earlier or later than the already running one.

Note: The combination of “mode: parallel” on the automation and “mode: restart” on the script is the critical bit to making the multiple timers work correctly.

2 Likes

Has anyone been able to replicate this with Node-Red? I would like to do it this way so i can easily dupllcate for different actions and events. However I am stuck at first hurdle of getting node-red to start action when alexa timer (or alarm) is reached?
I think i want the check to start when timer/alarm set. This outputs the payload with DateTime stamp I can use. However unsure which node i would use to say when time = value then do next action.
Appreciate any guidance as fairly new to Node-Red

Possibly not the best way but here is way I have achieved it. Its all running off the Time sensor and if there is a timer set one a specific device it will output in same minute on others that it is due. (i could not get the seconds to line up for exact notification on time complete)

[{"id":"d797401a.4ce6b8","type":"api-current-state","z":"3eb8c7f5.da2088","name":"timer","server":"9905c3e1.09ce1","version":1,"outputs":1,"halt_if":"","halt_if_type":"str","halt_if_compare":"is","override_topic":false,"entity_id":"sensor.living_room_next_timer","state_type":"str","state_location":"payload","override_payload":"msg","entity_location":"data","override_data":"msg","blockInputOverrides":false,"x":410,"y":720,"wires":[["850e7f9e.fc8448"]]},{"id":"850e7f9e.fc8448","type":"moment","z":"3eb8c7f5.da2088","name":"format","topic":"","input":"","inputType":"msg","inTz":"Europe/London","adjAmount":0,"adjType":"days","adjDir":"add","format":"YYYY-MM-DD, HH:mm","locale":"C","output":"","outputType":"msg","outTz":"Europe/London","x":510,"y":720,"wires":[["12617f44.29c299"]]},{"id":"1235b6c2.9b7eb9","type":"api-current-state","z":"3eb8c7f5.da2088","name":"echo timer set?","server":"9905c3e1.09ce1","version":1,"outputs":2,"halt_if":"unavailable","halt_if_type":"str","halt_if_compare":"is_not","override_topic":false,"entity_id":"sensor.living_room_next_timer","state_type":"str","state_location":"","override_payload":"global","entity_location":"data","override_data":"msg","blockInputOverrides":false,"x":263,"y":760,"wires":[["d797401a.4ce6b8","d58c8e70.cab97"],[]]},{"id":"12617f44.29c299","type":"join","z":"3eb8c7f5.da2088","name":"","mode":"custom","build":"array","property":"payload","propertyType":"msg","key":"topic","joiner":"\\n","joinerType":"str","accumulate":false,"timeout":"","count":"2","reduceRight":false,"reduceExp":"","reduceInit":"","reduceInitType":"","reduceFixup":"","x":650,"y":740,"wires":[["f0d77987.dad4c"]]},{"id":"975148ce.66537","type":"server-state-changed","z":"3eb8c7f5.da2088","name":"Now","server":"9905c3e1.09ce1","version":1,"exposeToHomeAssistant":false,"haConfig":[{"property":"name","value":""},{"property":"icon","value":""}],"entityidfilter":"sensor.date_time","entityidfiltertype":"exact","outputinitially":false,"state_type":"str","haltifstate":"","halt_if_type":"str","halt_if_compare":"is","outputs":1,"output_only_on_state_change":true,"x":70,"y":840,"wires":[["1235b6c2.9b7eb9"]]},{"id":"d58c8e70.cab97","type":"moment","z":"3eb8c7f5.da2088","name":"format","topic":"","input":"","inputType":"msg","inTz":"Europe/London","adjAmount":0,"adjType":"days","adjDir":"add","format":"YYYY-MM-DD, HH:mm","locale":"C","output":"","outputType":"msg","outTz":"Europe/London","x":454,"y":780,"wires":[["12617f44.29c299"]]},{"id":"f0d77987.dad4c","type":"function","z":"3eb8c7f5.da2088","name":"Compare","func":"newmsg = {};\nif (msg.payload[0] == msg.payload[1]) {\n    newmsg.payload = \"True\";\n} else {\n    newmsg.payload = \"False\";\n}\n\nreturn newmsg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":760,"y":740,"wires":[["b6403c94.cc11f8"]]},{"id":"b6403c94.cc11f8","type":"switch","z":"3eb8c7f5.da2088","name":"","property":"payload","propertyType":"msg","rules":[{"t":"eq","v":"True","vt":"str"}],"checkall":"true","repair":false,"outputs":1,"x":870,"y":740,"wires":[["de978f6d.00c8a","aef46216.014828"]]},{"id":"de978f6d.00c8a","type":"api-call-service","z":"3eb8c7f5.da2088","name":"Bedroom Announce","server":"9905c3e1.09ce1","version":1,"debugenabled":false,"service_domain":"notify","service":"alexa_media_bedroom","entityId":"","data":"{\"data\":{\"type\":\"tts\"},\"target\":\"media_player.bedroom\",\"message\":\"Kitchen Timer is due. The Kitchen Timer is due\"}","dataType":"json","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":900,"y":680,"wires":[[]]},{"id":"aef46216.014828","type":"api-call-service","z":"3eb8c7f5.da2088","name":"Olivia Announce","server":"9905c3e1.09ce1","version":1,"debugenabled":false,"service_domain":"notify","service":"alexa_media_olivia","entityId":"","data":"{\"data\":{\"type\":\"tts\"},\"target\":\"media_player.olivia\",\"message\":\"Kitchen Timer is due. The Kitchen Timer is due\"}","dataType":"json","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":890,"y":800,"wires":[[]]},{"id":"9905c3e1.09ce1","type":"server","z":"","name":"Home Assistant"}]

hi all
i want to send the minute left on the next timer by notify, any one can help me how to do that?

For the life of me I cannot get this to work. Used your old setup for a long time now but this just wont work. The Alexa Timer triggers the automation and the script is triggered too but I thing both right at the moment that I set a new timer not when it goes off. But the other alexas just wont say anything.

I think it must have something to do with quotation marks. Esp since I have the scripts and automations on UI mode but cant see what.

Just sat down to write something like this and found I didn’t need to do anything beyond changing the names of the Echos. Thank you for this, works perfectly.

So I couldn’t get this to work, probably because I edit automations and scripts in the UI rather than use yaml and the UI always screwed it up.
So I used some of the code from this post and found a solution that is simpler for me and is UI based. In case anyone wants to also use the UI here is how I set it up:

  1. Create a new script in the UI.
  • Give it a name
  • choose Mode “restart”
  • In sequence choose “repeat”
  • as typ choose “while”
  • as while condition choose “template”
  • enter this as template value and replace YOUR_DEVICE:
{{ states('sensor.YOUR_DEVICE_next_timer') not in ['None', 'unknown', 'unavailable'] and as_timestamp(states('sensor.YOUR_DEVICE_next_timer')) < as_timestamp(now()) }}
  • as action add “call service”
  • as service choose “notify.alexa_media”
  • as service data enter this replacing your alexa devices to announce the end of the timer:
target:
  - media_player.DEVICE1
  - media_player.DEVICE2
data:
  type: announce
message: The Timer in the kitchen is up!
  • add another action and choose type “delay”
  • enter the value you want the announcement to repeat. I chose 10 seconds
  • save the script and remeber the name for the automation
  1. Go to Blueprints and import the Automation blueprint “Do something when Alexa timer expired” by entering this address:
    Do something when Alexa Timer has expired

  2. Once blueprint is imported create a new automation from it:

  • As Alexa Device chose your “sensor.YOUR_DEVICE_next_timer”
  • as action do “Call Service” and in service chose your script from step one.

That’s it. The announcement will now be repeated until the timer is cancled.
And in case people don’t know this yet: You can start and cancel Alexa Timers from other Alexas. So say you have this set up to announce a timer from the kitchen. You are in the living room and want to set up or cancle a timer that’s announced everywhere you can just say: “Alexa, start a 1 minute timer on Kitchen” or “Alexa stop the timer in the kitchen”

Hope this helps some people

1 Like