How to create a template script using variables in create scenes?

How to create a template script using variables in create scenes?

Documentation create scenes. Full version of working automation for volume control volume level
Video how adaptive volume works

We have a smart speaker with a voice assistant Alice, an analogue of Alexa. Our speakers do not know how to speak louder than the music is playing, and because of this it turns out that after the music it is not very good what the voice assistant says. I have implemented automation, you can see the full version here and everything works fine. But I decided to make a script with a template, where it is enough to specify the column ID and the name of the scene to save to history. But then I ran into a problem. The thing is that create scenes saves either all the attributes of the entity, or we specify which attribute of the entity we need to save.

If I use snapshot_entities, then I can use a variable and there are no questions here, but this option will then save all the attributes of the entity, which I don’t need. I don’t need to save all the attributes of the entity.

  - service: scene.create
    data:
      scene_id: '{{ message }}'
      snapshot_entities: '{{ device }}'

In this case, you can save a specific attribute of the entity, but I have to specify the media_player entity.yandex_station_XXXXXX, instead of ‘{{device }}’. If I specify ‘{{device }}’: there will be an error about the absence of entities_id. How to get around this so that I can use entities: specifying a specific attribute. I can’t specify other entities, because it doesn’t work.

So it can be used with variables

  - service: scene.create
    data:
      scene_id: '{{ message }}'
      entities:
        media_player.yandex_station_XXXXXX:
          state: '{{ device }}'
          volume_level: '{{ dev_vol }}'

This cannot be used with variables

  - service: scene.create
    data:
      scene_id: '{{ message }}'
      entities:
        '{{ device }}':
          state: '{{ device }}'
          volume_level: '{{ dev_vol }}'

Below is a fully working version, but I am not satisfied with the fact that snapshot_entities is used here, since this saves all the attributes of the entity, which cannot be used for such columns, because when the scene starts, all the values in the column will be returned to when it was saved and if, for example, music was playing before, and then I turned it off and the scene started, then the column will start playing music.

alias: 'Template: Yandex station. Adaptive volume. Alice speaks louder. History'
fields:
  device:
    name: Choose your column
    required: true
    selector:
      entity: null
  message:
    name: Specify the name of the scene
    example: Specify any text
    required: true
    selector:
      text: null
sequence:
  - condition: template
    value_template: |-
      {% set device = "{{ device }}" %}
      {% set volume = "volume_level" %}
      {% set dev_vol = state_attr(device,volume) %}
      {% set ya_vol = states("input_number.yandex_station_volume_level")|float%}
      {% set ya_room_vol = state_attr(device,volume)|float %}
      {% if ya_room_vol < ya_vol and ya_room_vol < 0.7 %} true
      {% else %} false
      {% endif %}
  - service: scene.create
    data:
      scene_id: '{{ message }}'
      snapshot_entities: '{{ device }}'
  - service: media_player.volume_set
    data:
      volume_level: '{{ states("input_number.yandex_station_volume_level") }}'
    target:
      entity_id: '{{ device }}'
mode: single
Текст на русском (Text in Russian)

Как создать шаблонный скрипт, используя переменные в create scenes?

Документация create scenes
Полная версия рабочей автоматизации для управления громкости уровня громкости
Видео как работает адаптивная громкость

Имеется у нас умная колонка с голосовым помощником Алиса, аналог Алексы. У нас колонки не умеют говорить громче, чем играет музыка и из-за этого получается, что после музыки не очень хорошо, что говорит голосовой помощник. Я реализовал автоматизацию, полный вариант можете посмотреть здесь и все прекрасно работает. Но я решил сделать скрипт с шаблоном, где достаточно указать ID колонки и имя сцены для сохранения в историю. Но тут я столкнулся с проблемой. Все дело в том, что create scenes сохраняет либо все атрибуты сущности, либо мы указываем какой атрибут сущности нам нужно сохранить.

В случае, если я буду использовать snapshot_entities, то я могу использовать переменную и тут никаких вопросов нет, но данный вариант тогда сохранит все атрибуты сущности, чего мне не нужно. Мне не надо сохранять все атрибуты сущности.

  - service: scene.create
    data:
      scene_id: '{{ message }}'
      snapshot_entities: '{{ device }}'

В таком варианте можно сохранить конкретный атрибут сущности, но я вынужден указывать сущность media_player.yandex_station_XXXXXX, вместо ‘{{ device }}’. Если я буду указывать ‘{{ device }}’: то будет ошибка про отсутствие entities_id. Как обойти это, чтобы я могу использовать entities: с указанием конкретного атрибута

Так можно использовать с переменными

  - service: scene.create
    data:
      scene_id: '{{ message }}'
      entities:
        media_player.yandex_station_XXXXXX:
          state: '{{ device }}'
          volume_level: '{{ dev_vol }}'

Так нельзя использовать с переменными

  - service: scene.create
    data:
      scene_id: '{{ message }}'
      entities:
        '{{ device }}':
          state: '{{ device }}'
          volume_level: '{{ dev_vol }}'

Ниже полностью рабочий вариант, но меня не устраивает то, что тут используется snapshot_entities, так как это сохраняет все атрибуты сущности, чего нельзя использовать для таких колонок, потому что при запуске сцены, все значения в колонке будут возвращены к тому, когда это было сохранено и если к примеру до этого играла музыка, а потом я ее выключил и запустилась сцена, то колонка начнет играть музыку.

alias: 'Шаблон: Яндекс станция. Адаптивная громкость. Алиса говорит громче. История'
fields:
  device:
    name: Выберите свою колонку
    required: true
    selector:
      entity: null
  message:
    name: Укажите название сцены
    example: Укажите любой текст
    required: true
    selector:
      text: null
sequence:
  - condition: template
    value_template: |-
      {% set device = "{{ device }}" %}
      {% set volume = "volume_level" %}
      {% set dev_vol = state_attr(device,volume) %}
      {% set ya_vol = states("input_number.yandex_station_volume_level")|float%}
      {% set ya_room_vol = state_attr(device,volume)|float %}
      {% if ya_room_vol < ya_vol and ya_room_vol < 0.7 %} true
      {% else %} false
      {% endif %}
  - service: scene.create
    data:
      scene_id: '{{ message }}'
      snapshot_entities: '{{ device }}'
  - service: media_player.volume_set
    data:
      volume_level: '{{ states("input_number.yandex_station_volume_level") }}'
    target:
      entity_id: '{{ device }}'
mode: single