Template to Select Scene in Action Block

Help Needed:
In action block, create template with if-then logic to select appropriate scene based on time of day.

Background:
Newbie running HA ion a raspberry pi. Yes, I’ve spent hours searching and trying solving my own problem.

Goal:
Automate lights to turn on one of two scene-based brightness based on time of day, sun angle, and occupancy.

Trigger:
Occupancy reported

Condition:
Sun below 10 degree

Action:
If time < 9 PM, then turn on scene.evening_interior_lights_on
If time > 9 PM, then turn on scene.evening_interior_lights_dim

Current Code:

alias: Evening Lights On (Occupancy and Sun Angle)
description: ''
trigger:
  - type: occupied
    platform: device
    device_id: 7d2e97ba53cdb2245fb66fe5fee3c43f
    entity_id: binary_sensor.living_room_occupancy
    domain: binary_sensor
  - type: occupied
    platform: device
    device_id: b9b03853cb63626bd2ab51747c47b861
    entity_id: binary_sensor.main_floor_occupancy
    domain: binary_sensor
condition:
  - condition: numeric_state
    entity_id: sun.sun
    attribute: elevation
    below: '10'
action:
    data_template: >-
        {% if (states.sensor.time.state <= 21:00) %}
          entity_id: scene.evening_interior_lights_on
        {% else %}
          entity_id: scene.evening_interior_lights_dim
        {% endif %}
    service: scene.turn_on
mode: single

Error Message:
Message malformed: extra keys not allowed @ data[‘action’][0][’-data_template’]

data_template was dropped in version 0.115. Just use data now. There were a few other issues with your template. Try this instead:

action:
  - choose:
      - conditions:
          condition: time
          before: '21:00:01'
        sequence:
          - service: scene.turn_on
            target:
              entity_id: scene.evening_interior_lights_on
    default:
      - service: scene.turn_on
        target:
          entity_id: scene.evening_interior_lights_dim

The reason for using a choose action instead of a template is that it is a lot easier to determine if the time is before 9pm using a time condition rather than a template. Your template would not have worked as the sensor.time state is a string. Which you can’t do less than comparisons with. You would have had to convert it to a timestamp first, which would require adding a date… it gets messy. Much easier this way.

With both methods you are currently only dimming between 9pm and midnight.

However it is possible to supply a time condition with a range, e.g after 6am and before 9pm.

Tom! You are the man. Code work perfectly and is so much easier to understand. Thank you!

1 Like