Timer Triggered by State Condition

I’ve configured the following timer for my lights to turn ON at 10:00 and OFF at 19:15. While it works fine but it has a flaw. If someone manually turn off the switch between the specified time, at the next trigger 19:15, the switch will turn the lights back on instead of letting it stay off.

- id: '1585533112292'
  alias: Some Lights
  description: Some Lights
  trigger:
  - at: '10:00'
    platform: time
  - at: '19:15'
    platform: time
  action:
    service: switch.toggle
    entity_id: switch.lights

One way to solve this is to introduce the state condition so I wrote the following:

- id: '1585533112292'
  alias: Some Lights
  description: Some Lights
  trigger:
  - at: '10:00'
    platform: time
  - at: '19:15'
    platform: time
  condition:
  -  condition: state
     entity_id: switch.lights
     state: 'on'
  -  condition: state
     entity_id: switch.lights
     state: 'off'
  action:
    service: switch.toggle
    entity_id: switch.lights

I understand that I can just make 2 separate triggers. I was wondering if there’s a way to combine 2 triggers into one for simplicity. I can see there’s a race condition in my logic but not sure how to fix this issue.

There’s an easier way to do it:

- id: '1585533112292'
  alias: Some Lights
  description: Some Lights
  trigger:
  - at: '10:00'
    platform: time
  - at: '19:15'
    platform: time
  action:
    service_template: "switch.turn_{{ 'on' if trigger.now.hour == 10 else 'off' }}"
    entity_id: switch.lights
  • If the first trigger occurred then trigger.now.hour is 10 and the light will be turned on.
  • If the second trigger occurred then trigger.now.hour is 19 and the light will be turned off.

This by far the most clever and elegant solution I’ve seen. Thank you!

1 Like