Light transition duration with templates

Hey!
I’m currently trying to set up an automation to start fading in a light when someone gets home before sunset. I’d like to use a transition and make sure the brightness is at 100% by sunset. So for example, if a person arrives at home exactly 2 hours before sunset, the transition time would be 7200 seconds, 1 hour before sunset and 3600 seconds etc.
I was able to create a template that returns the seconds until sunset, the template renders fine and returns a correct number but somehow I haven’t been able to use that value for the transition. Does anyone have an idea on how to make it work? Here’s my automation:

alias: Light on at sunset
id: light_on_sunset
trigger:
- event: sunset
  offset: -02:00:00
  platform: sun
- platform: state
  entity_id: group.all_devices
  to: 'home'
condition:
- condition: state
  entity_id: group.all_devices
  state: home
- condition: sun
  after: sunset
  after_offset: -02:00:00
action:
- alias: Light on
  service: light.turn_on
  data:
    entity_id: light.Lamp
    transition: >
        {% set secondsToSunset = as_timestamp(states.sun.sun.attributes.next_setting) - as_timestamp(now()) | int %}
        {% if  secondsToSunset < 7200 %}
            {{ secondsToSunset | int }}
        {% elif secondsToSunset < 0%}
          0
        {% else %}
          0
        {% endif %}
    brightness_pct: 100
    color_temp: 500

Use data_template: instead of data: in your action, because a template is being evaluated. I’m not sure if it’s your only problem, but it’s definitely a problem.

This automation is ridiculous. Sounds like something I would do. I love it! :laughing:

Thanks! I’m pretty sure that did the trick :smiley:

1 Like