Automation Trigger if the state have same value for 5 seconds, then loop

Hi!

I want to make an automation for a PIR sensor, but a little more advanced.
As far as I know, there are only two types of PIR sensors:

  • One which does not matter if sees motion for longer time than the cooldown time, it will go to clear (after the cooldown time), then it will trigger again for motion (I had some RF PIR sensors like this).
  • The second type of PIR sensors, which I think it is the most common: if there is motion, it will have “detected” state, if no motion for 5 seconds, it will go to “clear” state (this means that if I will move one hour in front of the device, he will not change state, it will keep “detected”)

So, based of this second type of PIR sensors, which I also have, I want to make an automation which will trigger everytime the PIR sensor will have the same “detected” state for more than 5 seconds. So, if I move for 22 seconds, the automation should trigger 4 times.

I already made an automation for this, it is working, but I want to know if there is a better approach. This is what I have:

triggers:
  - trigger: state
    entity_id:
      - binary_sensor.computer_2_presence_pir_sensor
    to: "on"
    for:
      hours: 0
      minutes: 0
      seconds: 5
conditions: []
actions:
  - action: persistent_notification.create
    metadata: {}
    data:
      message: Motion
  - action: python_script.set_state
    metadata: {}
    data:
      entity_id: binary_sensor.computer_2_presence_pir_sensor
      state: "off"
  - action: homeassistant.update_entity
    metadata: {}
    data:
      entity_id:
        - binary_sensor.computer_2_presence_pir_sensor
mode: single

I could use the python_script.set_state for off and on, but I wanted to use update_entity for on, don’t ask me why (brain fixations)
The automation will trigger again in 5 seconds, if “the state is the same” by “restarting” the state with the help of the last two actions from automation, but is this the right approach? There is no other better solution? Maybe something wihtout using “python_script.set_state” ?

Thanks

If you want an automation to keep running until the motion clears, you should use a repeat-until loop.

triggers:
  - trigger: state
    entity_id:
      - binary_sensor.computer_2_presence_pir_sensor
    to: "on"
    for:
      hours: 0
      minutes: 0
      seconds: 5
conditions: []
actions:
  - repeat:
      sequence:
        - action: persistent_notification.create
          metadata: {}
          data:
            message: Motion
        - delay: 5
      until:
        - condition: state
          entity_id: binary_sensor.computer_2_presence_pir_sensor
          state: "off"
1 Like

Oh, true :slight_smile: I totally forgot about repeat.

Thanks!