Skip to content

Instantly share code, notes, and snippets.

@hkraal
Last active July 15, 2023 07:02
Show Gist options
  • Save hkraal/c9a93558a67c78942af1be731cc1f64e to your computer and use it in GitHub Desktop.
Save hkraal/c9a93558a67c78942af1be731cc1f64e to your computer and use it in GitHub Desktop.
A Home-assistant automation to dimm the lights gradually with vanilla HA.
{% set min_dim_level = 20 %}
{% set max_dim_level = 100 %}
# Calculate sun_dim_level based on sun elevation.
{% set sun_dim_level = 100 - (states.sun.sun.attributes.elevation|abs * 3) %}
{% if sun_dim_level < min_dim_level %}
{% set sun_dim_level = min_dim_level %}
{% endif %}
# Calculate time_dim_level based on time and reset to max.
{% set current_time = now() %}
{% set reset_time = today_at("06:00") %}
{% set start_time = today_at("19:00") %}
{% set end_time = today_at("22:00") %}
{% if current_time >= reset_time and current_time < start_time %}
{% set dim_level = 100 %}
{% elif current_time >= start_time %}
{% set total_duration = (as_timestamp(end_time) - as_timestamp(start_time)) / 60 %}
{% set elapsed_duration = (as_timestamp(current_time) - as_timestamp(start_time)) / 60 %}
{% set time_dim_level = max_dim_level - ((max_dim_level - min_dim_level) / total_duration * elapsed_duration) | round %}
{% if time_dim_level < min_dim_level %}
{% set time_dim_level = min_dim_level %}
{% endif %}
# Use the lower value of the two.
{% set dim_level = [time_dim_level, sun_dim_level] | min %}
{% endif %}
{{dim_level}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment