Sun in Home Assistant
- Home Assistant, quickfix
- 4
- 1
- finished
Sun is a useful Home Assistant integration. which allows tracking position of sun in configured location and triggering automations based on it times of sunset and sunrise. However, writing automations which work with times is tricky because, let’s be honest, the concept of time is not trival and “after sunset” means something else Home Assistant than what our intuition tells us.
My kids often wake up at night so to keep them safe I wanted to automatically turn on the corridor night light when it’s getting dark and turn it off after few hours. Night light is connected to the Zigbee power plug.
I wanted to keep both turning on and off of the plug in a single automation. To do that, I used time trigger which checks turn on conditions every 15 minutes. My first automation said: “every 15 minutes check if it’s after sunset (offset -30 minutes) and before 00:59 and then turn on the power plug, otherwise turn it of. To my surprise, it never worked.
Home Assistant understands “after sunset” and “before 00:59” differently than we do. To people “after sunset” means “after sunset and before sunrise”, but Home Assistant must be more precise. Think about it: 3 AM occurs before the sunset on that day. My conditions actually meant:
- after sunset → after sunset and before 00:00
- before 00:59 → after 00:00 and before 00:59
Time cannot be both before and after midnight at the same time, so this condition was never triggered and light remained off for the whole night.
Knowing that, fix was easy: I had to use or condition instead of and. Now
automation reads: “every 15 minutes check if it’s after sunset (offset -30
minutes) or before 00:59 and then turn on the power, otherwise turn it of”,
which means (after sunset and before 00:00) or (after 00:00 and before
00:59)
.
Here’s the full yaml:
alias: Turn on the lights at night
trigger:
- platform: time_pattern
minutes: "15"
mode: single
action:
- if:
- condition: or
conditions:
- condition: sun
after: sunset
after_offset: "-00:30:00"
- condition: time
before: "00:59:00"
then:
- service: switch.turn_on
target:
entity_id:
- switch.plug_lights
else:
- service: switch.turn_off
target:
entity_id:
- switch.plug_lights