Skip to content

Examples: Automation

Didgeridrew edited this page Jun 15, 2023 · 45 revisions

Guides


Text to Speech (TTS)

Basic Script Example

(Be aware that using "type: announce" will cause Alexa to make a "ding" sound before speaking, while using "type: tts" will cause Alexa to speak right away. If you use the everywhere speaker group as your target, you must use "type: announce".)

doorbell:
  sequence:
  - service: media_player.volume_set
    entity_id: media_player.downstairs
    data:
      volume_level: '1.0'
  - service: notify.alexa_media
    data:
      data:
        type: tts
      message: 'Ding-dong. Someone is at the door.'
      target:
        - media_player.downstairs
        - media_player.upstairs

Basic notification automation

- id: washing_machine_finished
  alias: Washing machine
  trigger:
  - entity_id: sensor.washing_machine
    platform: state
    from: Washing
    to: Not washing
  action:
  - service: notify.alexa_media
    data:
      data:
        type: announce
      message: 'Yo Remco.. The washing machine is finished. Get off the couch.'
      target:
        - media_player.downstairs
        - media_player.upstairs

Example script using templated message:

remco_home:
  alias: Remco comes home
  sequence:
  - wait_template: '{{ is_state(''sensor.broadlink_s1c_sliding_door'', ''open'') }}'
    timeout: 00:08:00
  - delay: 00:00:12
  - service: notify.alexa_media
    data:
      target: media_player.downstairs
      data:
        type: announce
      message: 'Hello Remco. Welcome home. Cherry is {% if is_state("device_tracker.cherry",
        "home") -%} also at home. {%- else -%} not at home. {%- endif %} The temperature
        inside is {{ states("sensor.broadlink_sensor_temperature") }} degrees. And
        outside it is {{ states("sensor.weather_temperature") }} degrees.'

Activating Alexa Routines

Any Routines you create in the Alexa app can be triggered by Home Assistant.

Make sure to use media_content_type: routine and that the value for media_content_id: matches the name of your Routine in the Alexa App exactly (case, spacing, and punctuation).

scripts.yaml

remco_awake:
  alias: Remco woke up
  sequence:
  - service: media_player.play_media
    data:
      media_content_id: remcowakeup
      media_content_type: routine
    target:
      entity_id: media_player.upstairs
  - wait_template: '{{ is_state("sensor.broadlink_s1c_living_room_door", "open") }}'
  - service: media_player.play_media
    data:
      media_content_id: "I've Gone Downstairs"
      media_content_type: routine
    target:
      entity_id: media_player.downstairs
    

Activating Alexa Sequence Commands

Look for available sequences in Sequence commands This is case sensitive, so copy it exactly as it is in the list.

automation.yaml

- id: Remco_welcome_home
  trigger:
  - platform: state
    entity_id: device_tracker.remco
    to: home
  action:
  - wait_template: '{{ is_state("sensor.broadlink_s1c_sliding_door", "open") }}'
  - data:
      entity_id: media_player.downstairs
      media_content_id: Alexa.ImHome.Play
      media_content_type: sequence
    service: media_player.play_media
  condition: []

Live Sensor Reports

Combine the Last Alexa Sensor and Alexa Routines to have Alexa provide information about your HA sensors.

#configuration.yaml

light:
  - platform: template
    lights:
      alexa_virtual:
        friendly_name: "Alexa Dummy Light"
        turn_on:
        turn_off:
        set_level:
#automations.yaml

- alias: "Alexa Report"
  trigger:
  - platform: state
    entity_id: light.alexa_virtual
    to: 'on'
  condition:
  action:
  - service: alexa_media.update_last_called
  - delay: 2
  - variables:
      messages:
        1: "What you want to say {{ states('sensor.name_of_sensor') }} Degrees"
        2: "What you want to say {{ states('sensor.name_of_sensor') }} miles"
        3: "What you want to say {{ states('sensor.name_of_sensor') }} minutes"
        4: "What you want to say {{ states('sensor.name_of_sensor') }}"
        5: "What you want to say {{ states('sensor.name_of_sensor') }}"
        6: "What you want to say {{ states('sensor.name_of_sensor') }}"
        7: "What you want to say {{ states('sensor.name_of_sensor') }}"
        9: "What you want to say {{ states('sensor.name_of_sensor') }}"
        10: "What you want to say {{ states('sensor.name_of_sensor') }}"
  - service: notify.alexa_media_last_called
    data:
      data:
        type: tts
      message: >-
       {% set brightness = state_attr('light.alexa_virtual', 'brightness') %}
       {% set id = (brightness | int(0) / 255 * 100 ) | int %}
       {% if id in messages %}
         {{ messages.get(id) }}
       {% else %}
         No value has been set for brightness level {{ brightness }}
       {% endif %}
  - service: light.turn_off
    entity_id: light.alexa_virtual

You need to then expose the "light.alexa_virtual" to your Alexas. This is the same as exposing any HA device to your Alexa's and not directly related to this component. You can do this with emulated_hue, haaska, or Nabu Casa/Home Assistant Cloud.

Once the light is exposed and you can turn it on/off, etc with your voice start the next steps:

  1. Use the Alexa app to create a routine.
  2. Click + to create a new routine.
  3. Click the + next to "when this happens".
  4. Click on Voice and enter what you want to say. For example "Alexa, give me the surf report".
  5. Then click on "Add action".
  6. I recommend you add a step for "Alexa Says" and enter a short phrase "Let me check for you" is good example.
  7. Then add another action.
  8. Smart Home --> Control Device --> Select your Alexa Dummy Light and then select brightness.
  9. Select a value from 1 to 100, the number will correlate to the automation above.
  10. Click Save, give it a few minutes, and try it out.

Good uses of this would be to get temp info of a sensor, distance/time to a location using a waze/google sensor, tides, doors open/closed, etc.


Room Aware Alexa Routines

Use the Last Alexa Sensor to turn lights or switches on or off in the room you are currently in.

Alexa Routines

When you set up voice activated routines, including multiple trigger phrases can make use more reliable for other users in your household. Here are four variations of turn on the lights routines you may like to setup.

  • "turn on the lights"
  • "turn on the light"
  • "turn on lights"
  • "turn on light"

Don't forget to add the "off" Alexa Routine as well. You could setup more routines for on/off, open/close, raise/lower... you get the idea.

Home Assistant Scripts

In your Alexa app match your Alexa Routines to following scripts. (Using homeassistant.turn_on allows you to turn on light., switch., script., and group. entities.)

scripts.yaml

# "Alexa, turn on the lights"
alexa_turn_on_the_lights:
  sequence:
    - service: homeassistant.turn_on
      data_template:
        entity_id: >-
          {# Use the name of each Echo to determine which room the command likely came from. #}
          {%- set room = states("sensor.last_alexa")|replace('media_player.','') -%}

          {%- if room == "kitchen" -%}
            group.kitchen_lights
          {%- elif room == "family_room" -%}
            light.family_room
          {%- elif room == "master_bedroom" -%}
            light.bedroom
          {%- elif room == "play_room" -%}
            light.play_room
          {%- endif -%}

# "Alexa, turn off the lights"
alexa_turn_off_the_lights:
  sequence:
    - service: homeassistant.turn_off
      data_template:
        entity_id: >-
          {# Use the name of each Echo to determine which room the command likely came from. #}
          {%- set room = states("sensor.last_alexa")|replace('media_player.','') -%}

          {%- if room == "kitchen" -%}
            group.kitchen_lights
          {%- elif room == "family_room" -%}
            light.family_room
          {%- elif room == "master_bedroom" -%}
            light.bedroom
          {%- elif room == "play_room" -%}
            light.play_room
          {%- endif -%}

Bonus Tip: Do you have an echo in one room which overrides the Echo in another room? This limitation can be circumvented by changing the wake word to something different on one of the Echos (ie. change one to "Computer").


Room Aware Live Sensor Reports

Using the Last Alexa Sensor and Alexa Routines, scripts can be extended to get room-specific sensor values using the same trigger phrase throughout the house.

scripts.yaml

# "Alexa, room temperature"

alias: Alexa Room-Aware Temperature
sequence:
  - service: notify.alexa_media
    data:
      target: '{{ states("sensor.last_alexa") }}'
      data:
        type: tts
      message: '{{active_therm}}'
mode: single
variables:
  active_therm: |-
    {% set last = states("sensor.last_alexa") -%}  
    {% set echo_room = dict([
          ('media_player.living_room_dot', ['living room', states("sensor.living_room_temperature")] ),
          ('media_player.basement_dot', ['basement', states("sensor.basement_temperature")] ),
          ('media_player.kitchen_dot', ['kitchen', states("sensor.kitchen_temperature")] )
      ]) %}
      {%- if last in echo_room -%}
        {%- set room = echo_room[last][0] -%}
        {%- set temp = echo_room[last][1] -%}
          The temperature in the {{ room }} is {{temp}} degrees
      {%- else -%}
        The average temperature in the house is {{states("sensor.average_household_temp")}} degrees
      {%- endif %}

Room Aware Scripts Using Areas

The expansion of the Areas integration in Home Assistant 2021.9 allows templates with the same function as Room Aware Alexa Routines and Room Aware Live Sensor Reports but with reduced maintenance needs. When adding new devices the scripts do not need to be updated manually like previous methods. You will only have to add new entities to their respective groups and assign areas to them:

Area Aware Lights

# "Alexa, turn on the lights"
alexa_turn_on_the_lights:
  alias: Alexa Turn On Area Lights
  sequence:
  - service: light.turn_on
    data:
      area_id: '{{area_id(states("sensor.last_alexa"))}}'
  mode: single

# "Alexa, turn off the lights"
alexa_turn_off_the_lights:
  alias: Alexa Turn Off Area Lights
  sequence:
  - service: light.turn_off
    data:
      area_id: '{{area_id(states("sensor.last_alexa"))}}'
  mode: single

Be aware that some custom integrations add devices as light entities that you might not normally consider "lights". With Area-based and Room-based approaches these entities will be turned on and off as well, which may be undesirable.

Area Aware Live Sensors

scripts.yaml

# "Alexa, room temperature"

alias: Alexa Room-Aware Temperature
sequence:
  - service: notify.alexa_media
    data:
      target: '{{ states("sensor.last_alexa") }}'
      data:
        type: tts
      message: '{{active_therm}}'
mode: single
variables:
  active_therm: |-
    {%- set echo_area = area_name(states('sensor.last_alexa')) %}
    {%- for s in expand('group.indoor_thermometers')|map(attribute = 'entity_id') | list %}
      {% if area_name(s) == echo_area %}
      The temperature in the {{ area_name(s)|lower }} is {{states(s)}} degrees Farenheit
      {% endif %}
    {% endfor %}

Selecting bluetooth speakers for Alexa output

While the components source_list only lists input (bluetooth devices that can stream sound to the Alexa device), you can call the select_source service to connect to any previously paired Bluetooth Speaker. Switching it back to "Local Speaker" disconnects it again.

scripts.yaml

alexa_connect_kitchen_speaker:
  sequence:
    - service: media_player.select_source
      data:
        source: "Kitchen Speaker."
      target:
        entity_id: media_player.echo_living_room
alexa_disconnect_kitchen_speaker:
  sequence:
    - service: media_player.select_source
      data:
        source: "Local Speaker."
      target:
        entity_id: media_player.echo_living_room

Time remaining announcements for timers

- id: timer_announcement
  alias: Timer Announcement
  description: 'Announce the time remaining on a timer at 5 minute intervals, if the timer is for longer than 5 minutes.'
  trigger:
    - platform: template
      value_template: >
        {% if not is_state('sensor.kitchen_next_timer', "unavailable") -%}
        {%- set sorted_active = state_attr('sensor.kitchen_next_timer', 'sorted_active') | from_json -%}
        {%- set duration = (sorted_active[0][1].originalDurationInMillis / 60000)|int %}
        {% set remaining = ((as_datetime(states('sensor.kitchen_next_timer')) - states.sensor.time.last_changed|as_local).seconds // 60) -%}
        {{ duration > 5 and remaining != duration and remaining != 0 and remaining % 5 == 0 }}
        {% endif -%}
  action:
    - service: notify.alexa_media_kitchen
      data:
        message: >
          You have {{ time_remaining }} {{ "minutes" if time_remaining > 1 else "minute" }} left on your {{ timer_duration }} minute timer.
        data:
          type: announce
          method: all
  mode: single
  variables:
    timer_duration: >
      {% if not is_state('sensor.kitchen_next_timer', "unavailable") -%}
      {%- set sorted_active = state_attr('sensor.kitchen_next_timer', 'sorted_active') | from_json -%}
      {{ (sorted_active[0][1].originalDurationInMillis / 60000)|int }}
      {% endif %}
    time_remaining: >
      {% if not is_state('sensor.kitchen_next_timer', "unavailable")-%}
      {{ ((as_datetime(states('sensor.kitchen_next_timer')) - states.sensor.time.last_changed|as_local).seconds // 60) }}
      {% endif %}

(Replace sensor.kitchen_next_timer and notify.alexa_media_kitchen as required for your setup.)

Notes: This may have issues determining the duration of the timer if there are multiple overlapping times. If this is an issue, you may need to remove the duration from the announcement (the time remaining should still work).

This automation requires the Time & Date to be enabled.


Notification when Amazon Login Required

This automation will notify a phone when the alexa_media_player_relogin_required event is fired. This happens when Amazon requires the user to answer a CAPTCHA question. The login form can be access through the Persistent Notification drawer of Home Assistant.

- id: alexa_media_player_authentication_required
  alias: Alexa Media Player Authentication Required
  trigger:
    platform: event
    event_type: alexa_media_relogin_required
  condition: []
  action:
  - service: notify.mobile_app
    data:
      title: Alexa Media Player Integration
      message: 🔑 Authentication Required
      data:
        actions:
        - action: URI
          title: Resolve now!
          uri: /lovelace/home

Note: The notify.mobile_app includes an actionable notification in order to simply open your Lovelace dashboard and quickly access the Persistent Notification drawer. (Reported working on Android)


Controlling Fire TV Cube external Speakers

If you are trying to use this plugin to control a Fire TV (Cube) that is connectected to external speakers (i.e. through HDMI => TV => optical out => Receiver), you won't be able to control the volume. The same would be the case if you use the TVs internal speakers.

However, there is a workaround that is usable on the Cube, as it is able control IR devices and also comes with the little "remote blaster":

  1. Make sure you can control your TV (and Receiver) using the Cube (Settings -> Device Control). You will also run through this when connecting your Cube for the first time (or after a factory reset). After completing it, the devices (TV + Receiver, if any) should show up in your Alexa App.
  2. Setup (4) routines for "TV on/off" (Individual device(s)) and "Volume Up/Down" (Fire TV menu) in your Alexa App. Don't use volume steps of 1 or Alexa will ignore most of the commands if you smash the button too fast.
  3. Create scripts to call these routines:
alias: Fernseher an
sequence:
 - service: media_player.play_media
    data:
     media_content_id: Fernseher an # name from Alexa App
      media_content_type: routine
    target:
      entity_id: media_player.fire_tv_cube
mode: single
icon: mdi:television

alias: Fernseher aus
sequence:
  - service: media_player.play_media
    data:
      media_content_id: Fernseher aus
      media_content_type: routine
    target:
      entity_id: media_player.fire_tv_cube
mode: single
icon: mdi:television-off

alias: Fernseher lauter
sequence:
  - service: media_player.play_media
    data:
      media_content_id: Fernseher lauter
      media_content_type: routine
    target:
      entity_id: media_player.fire_tv_cube
mode: single
icon: mdi:volume-plus

alias: Fernseher leiser
sequence:
  - service: media_player.play_media
    data:
      media_content_id: Fernseher leiser
      media_content_type: routine
    target:
      entity_id: media_player.fire_tv_cube
mode: single
icon: mdi:volume-minus
  1. Create buttons in the UI to call the scripts

Now you can create a media player interface like this:

grafik