I’d like to share a way of integrating particular periods of a day into automations. Likewise you can avoid relying on local time as condition for automations to trigger, because - depending on the season - days can be longer (summer) or shorter (winter) and therefore a static time might lead to frustrations.
The issue with the sun
component is that the dusk and dawn values are always directed towards future: Once you have gone beyond e.g. the current next_dusk
mark, it immediately switches to the next day’s mark. Therefore I used a trick in order to calculate the dusk and dawn zones. As soon as the result of next_dusk
minus next_setting
becomes negative, I know that I have entered the dusk-period. Once I pass the next_setting
mark, this value turns positive, so I know that I just left the dusk-period.
Here’s the sensor
component which updates automatically:
- platform: template
sensors:
period_of_day:
friendly_name: 'period of the day'
value_template: >-
{% if (as_timestamp(states.sun.sun.attributes.next_dusk)) - (as_timestamp(states.sun.sun.attributes.next_setting)) < 0 %}
dusk
{% elif (as_timestamp(states.sun.sun.attributes.next_rising)) - (as_timestamp(states.sun.sun.attributes.next_dawn)) < 0 %}
dawn
{% elif (states.sun.sun.attributes.elevation) < 0 %}
night
{% else %}
day
{% endif %}
icon_template: >-
{% if is_state('sun.sun', 'above_horizon') %}
mdi:weather-sunny
{% else %}
mdi:weather-night
{% endif %}
The GUI shows this sensor like this, whilst every day period is being displayed in another color:
You consume the information provided by the sensor through a value_template
as shown in this example:
- alias: 'turn on light in entry hall when main door opens'
trigger:
platform: state
entity_id: sensor.main_entrance_door
to: "open"
condition:
- condition: template
value_template: "{{ states.sensor.period_of_day.state != 'day' }}"
action:
- service: homeassistant.turn_on
entity_id: switch.aeotec_zw075_smart_switch_gen5_switch