Wait Template use with variable

I’ve been trying to use a script, whereby I feed a media player’s name into the script through a variable, then send TTS to that speaker. I’ve had some issues with concurrent messages being played and so want to put a wait template in to make sure the speaker is not being used before playing.

In this example, variable source is being fed in, it contains the string “media_player.living_room_speaker”.

If I do this,

- service: tts.google_say
  data_template:
    entity_id: >
      {% if source is defined %}
      {{ source }}
      {% else %}
      group.google_home_speakers
      {% endif %}
    message: "Message here". 

If no source variable is supplied, the message is broadcast. If it is, then its only played on that speaker.

Normally with a wait template I could do the following:
- wait_template: "{{ states.group.google_home_speakers.state == 'off' }}"

However, if I want to check if that speaker supplied by the variable is playing, how do I transform the variable into the format of “states.{{variable}}.state”?

- wait_template: "{{ states."source".state == 'off' }}"

Tried a heap of different variants and can’t quite hit the right one?

if you just want the you are passing the entity_id then there are a number of ways to do this (assuming your variable is named source:

1

{% set domain, device = source.split('.') %}
{{ states[domain][device].state == 'off' }}

2

{{ states(source) == 'off' }}

3

{{ is_state(source,'off') }}

4

{% set entities = states | selectattr('entity_id','eq', source) | list %}
{{ entities[0].state == 'off' }}

I could come up with more, but they get even more obscure. I recommend method 2 and 3 if you are passing entity_ids as strings.

But if you need to check weather the entity_id inside the variable source is defined, then you need use method 4 with an alteration:

{% set entities = states | selectattr('entity_id','eq', source) | list %}
{% if entities | length > 0 %}
  ... etc...
1 Like

I’ll give 2/3 a go. I’m checking if it’s set via a ‘if else’ statement.

Thanks