Template in automation to create scene not working

Hi all,

I’m using my motion sensor to turn on some ambient_lights in the flat when movement is detected. When the motion sensor detects no movement, I would like to switch off the lights that have been turned on by the previous automation.

Therefore I would like to create a scene within the automation that turns the lights on which only contains the switched off lights.

I could just create a scene for all lights in the group, but this would mean that if lights got switched off in between the on-automation and the off-automation, they would get switched on again.

So my automation looks like this:

service: scene.create
data:
  scene_id: nachtlicht_lights_last_status
  snapshot_entities: |
    {% for state in expand('group.ambient_light') -%}
    {% if is_state(state.entity_id, 'off') -%}
    - {{ state.entity_id }}
    {% endif -%}
    {% endfor -%}

This returns the following:

Stopped because an error was encountered at 18 April 2021, 18:55:34 (runtime: 0.02 seconds)
Entity ID - light.schreibtischlampe - light.stehlampe - light.tz3000_dbou1ap4_ts0505a_level_light_color_on_off is an invalid entity ID for dictionary value @ data['snapshot_entities']

Looking at the step details in the debugger, I can see the following that got created from the template:

  service: create
  service_data:
    scene_id: nachtlicht_lights_last_status
    snapshot_entities: |-
      - light.schreibtischlampe
      - light.stehlampe
      - light.tz3000_dbou1ap4_ts0505a_level_light_color_on_off

Any hint is highly appreciated,

Many thanks in advance!!

Hi,

Posting the solution as it might help someone in the future.

service: scene.create
data:
  scene_id: old_scene
  snapshot_entities: >
    {{ expand(['group.ambient_light']) | selectattr("state",'eq', 'off') |
    map(attribute="entity_id") | join(', ') }}

Which results in:

service: create
  service_data:
    scene_id: nachtlicht_lights_last_status
    snapshot_entities: 'light.stehlampe, light.tz3000_dbou1ap4_ts0505a_level_light_color_on_off'

It seemed a bit weird to me as the other notation worked when I did it manually.