I am trying to do a very basic automation to have 2 different settings for my lights in the main bathroom upon motion depending on time of day. With the below it only works pre 8 PM, but the part that should start at night time never fires.
To get to the second Time Condition, it has to pass the first Time Condition. However, it can never do that if the current time is after 20:00:00 (because it fails the first Time Condition).
alias: Motion lights - Main bathroom
description: ''
variables:
light: "light.main_bathroom_ceiling_light"
trigger:
- platform: state
entity_id: binary_sensor.main_bathroom_motion_sensor_motion
to: 'on'
- platform: state
entity_id: binary_sensor.main_bathroom_motion_sensor_motion
to: 'off'
for: '00:05:00'
condition:
- condition: template
value_template: >
{{ (trigger.to_state.state == 'on' and is_state(light, 'off')) or
(trigger.to_state.state == 'off' and is_state(light, 'on')) }}
action:
- choose:
- conditions: "{{ trigger.to_state.state == 'on' }}"
sequence:
- variables:
is_day: "{{ 7 <= now().hour < 20 }}"
- service: light.turn_on
target:
entity_id: "{{ light }}"
data:
transition: 3
kelvin: "{{ 3400 if is_day else 2600 }}"
brightness_pct: "{{ 100 if is_day else 25}}"
default:
- service: light.turn_off
data:
transition: 3
target:
entity_id: "{{ light }}"
mode: single
How it works
It is triggered when the motion sensor:
Detects motion. OR
Detects no motion for 5 minutes (i.e. light will be turned off 5 minutes after the room is unoccupied; feel free to change this duration to whatever you prefer).
The condition ensures the action is performed only if:
Motion is detected and the light is currently off. OR
No motion is detected (for at least 5 minutes) and the light is currently on.
The reason for the Template Condition is that there’s no need to turn on the light if it’s already on nor turn it off if it’s already off.
If triggered by the first trigger, the action turns on the light using the appropriate parameters depending on the current hour.
If triggered by the second trigger, the action turns off the light.