I have created an automation to automatically turn on/off my outside lights based on a number of different factors. It is currently working, but I feel like I’m brute forcing this a bit.
My automation (below) uses a service_template
to manage the logic for the light, and I just trigger it every minute with a time_pattern
.
Originally, I tried to create everything using the GUI-friendly triggers and actions, but I found that it was a ton of redundant code. I had to set up triggers for the sun set, the sun rise, people arriving, people leaving, time changing, etc. And then nearly identical conditions. Doing it with the service_template is significantly less redundant, but the use of time_pattern
feels really brute-forcey.
Is there a better way to do this? What improvements would you all suggest?
alias: Outside Lights Control (new)
description: >-
Turns outside lights on at sunset, off at sunrise. Turn lights off when
everyone is in bed. Turn lights on once someone is up. Keep lights on when
anyone is away.
trigger:
- platform: time_pattern
minutes: /1
- platform: homeassistant
event: start
condition: []
action:
- service_template: >
{% set person_home = ( states.person | selectattr('state', 'eq', 'home') |
join(', ', attribute="entity_id") ) | length %}
{% if (state_attr('sun.sun', 'elevation') < 3.5) %}
{# Sundown State #}
{% if not person_home %}
{# Someone is not home state #}
switch.turn_on
{% elif now().hour >= 22 or now().hour < 5 %}
{# Everyone is asleep state #}
switch.turn_off
{% else %}
switch.turn_on
{% endif %}
{% else %}
switch.turn_off
{% endif %}
entity_id: switch.front_outside_lights_switch
mode: single