Trust me on this…If you want to learn and do Automations in YAML, don’t use device stuff. It’s meant for UI and does not lend itself well to manual editing. Templates are not available, the device and entity names are impossible to relate to.
What is your end goal here? You want an automation that:
if the light is turned on between 6am and 9pm: turn it off 2 hours later
if the light is turned on at any other time: turn it off when the next quarter hour occurs
Is that correct? A couple examples for clarity of the resulting logic:
light turns on at 5:58am: turn it off 2 minutes later at 6am
light turns on at 8:55pm: turn it off two hours later at 11:55pm
light turns on at 9:02: turn it off 13 minutes later at 9:15 pm
Besides avoiding device triggers and actions, it’s also good practice to avoid long-running automations. Long delays or repeats with delays will make your automations fragile to restarts or reloads. Generally you want your automations to execute quickly and if there’s something you want to do a while later, add another trigger for it.
I normally use the ‘choose’ action for automations like this that have multiple triggers. I’ll set a trigger id for each trigger and I’ll leave the main conditions section empty. In the ‘choose’ action I’ll use the ‘triggered by’ condition for each option of the choose action, so you can choose which logic to execute based on what trigger fired the automation.
But this one turned out to be a bit more simple and I was able to put the conditions into the main condition block and just turn off the plug if the conditions passed. Or in this case, since I used ‘not’, the automation is only executed when both conditions are not met
alias: Switch automation
trigger:
- platform: state
entity_id: switch.kasa_plug
to: "on"
id: turned_on
- platform: state
entity_id: switch.kasa_plug
to: "on"
for:
hours: 2
- platform: time
at: "21:00:00"
condition:
- condition: not
conditions:
- condition: trigger
id:
- turned_on
- condition: time
after: "06:00:00"
before: "21:00:00"
action:
- service: switch.turn_off
target:
entity_id: switch.kasa_plug
mode: restart
I set the mode to restart just in case someone rapidly turns on/off the plug after 9pm or before 6am, this should allow the automation to keep restarting and perform the appropriate action based on the ‘final’ state.