Automation for if something happens within x seconds of something else

Hi. How can I create an automation for if motion 1 is triggered, and then motion 2 is triggered within x seconds of that, then whatever actions occur.

I’m trying to do the standard when motion 1 is triggered “And If” motion 2 is triggered, however I can not figure out a way to have any kind of “within x seconds” criteria doing it this way.

Thank you!

Use a state trigger for motion 1.

Then in the actions use a “wait for trigger” with a timeout of x seconds and continue on timeout set to false. See: https://www.home-assistant.io/docs/scripts#wait-for-a-trigger

triggers:
  - trigger: state
    entity_id: binary_sensor.motion_1
    from: "off"
    to: "on"
actions:
  - wait_for_trigger:
      - trigger: state
        entity_id: binary_sensor.motion_2
        from: "off"
        to: "on"
    timeout:
      seconds: x # replace with a number
    continue_on_timeout: false

Put the action you want to do after the wait for trigger action.

This way the automation triggers on motion 1. If motion 2 occurs within x seconds then your wanted action is performed. If the wait times out then nothing happens and the automation stops, ready for the next motion 1 event.

1 Like

Thanks so much for the reply. I will try that. Curious, is there a difference between doing the sensors as “state” like you did above vs like this:

Yes.

2 Likes

Hi @tom_l ! WOW that is SUCH great info! I’ve always wondered that. Just implemented the change and will test.

One thing I noticed is that when I made the change it put hyphens like this. What do the hyphens mean? Thanks!

It’s how you define a list in YAML. Here’s a list with 4 items.

animals:
  - "cat"
  - "dog"
  - "bird"
  - "horse"

The from and to options can accept a list containing multiple items. In your example, it’s a list with 1 item.

1 Like

Why didn’t Tom’s first YAML example above have hyphens, and HA put hyphens in mine?

Also, are they just for human reference or do they have an effect in HA?

Thanks!

The Automation Editor follows its own set of rules for YAML formatting. Basically, it represents values in list format if the given option supports lists.

from supports a list value so the Automation Editor represented the single value off as a list containing one item.

The Automation Editor understands these two examples but will ultimately represent them in YAML list format.

off as a string

  from: 'off'

off as a single item in a python list

  from: ['off']
1 Like