Stop automation when motion is detected

Hi
I’m still pretty new to HA but I am enjoying both a great community and loads of youtube guides. But there is still a pretty steep learning curve for me, which may be because english is not my native language and sometimes I’m just unsure what to search for to find what I need. That said, I do enjoy just playing around with HA and exploring the possibilties.

Right now though, Im stuck trying to configure an automation which turns off everything when my wife or I leave the house - unless motion is detected within 15 minutes from the moment HA register that we are not home.

My guess is I got some logic wrong, but also maybe I’m not using the correct condition (should I even configure it as a condition?)?

The geo-detection is working fine, and everyting turns off as it should. It’s only the motion-detection part I can’t figure out…

Any help is very appriciated!

YAML code

alias: Leaving home, geo
description: ""
trigger:
  - platform: numeric_state
    entity_id: zone.home
    for:
      hours: 0
      minutes: 5
      seconds: 0
    below: 1
condition: []
action:
  - if:
      - condition: or
        conditions:
          - type: is_motion
            condition: device
            device_id: ad42e93269c6253102a3b3b58d0ba6bf
            entity_id: binary_sensor.sensor_entre_motion
            domain: binary_sensor
            for:
              hours: 0
              minutes: 15
              seconds: 0
          - type: is_motion
            condition: device
            device_id: def0697f653d65ce96bcd4a90e3feb98
            entity_id: binary_sensor.hue_motion_sensor_1_motion
            domain: binary_sensor
            for:
              hours: 0
              minutes: 15
              seconds: 0
          - type: is_motion
            condition: device
            device_id: 3742e88dcd556112c116ca4f7fd5019b
            entity_id: binary_sensor.kaeldersensor_motion
            domain: binary_sensor
            for:
              hours: 0
              minutes: 15
              seconds: 0
    then:
      - device_id: cc3e9a9a411780d609f148fe66bea640
        domain: mobile_app
        type: notify
        message: Leaving home automation was stopped because motion was detected
        title: Leaving home automation was stopped
      - stop: Motion was detected
    else:
      - service: automation.trigger
        data:
          skip_condition: true
        target:
          entity_id: automation.sluk_alt
      - device_id: cc3e9a9a411780d609f148fe66bea640
        domain: mobile_app
        type: notify
        message: Home Assistant detected no one is home and has turned off everything
        title: Leaving home, geofence
mode: single

I think you have two options.

one is that you could reverse the trigger and conditions in the if statement.

i.e. make the trigger that therer has been no motion for 15 minutes and then the condition is zone.home is 0.

alias: Leaving home, geo
description: ""
trigger:
  - platform: state
    entity_id: 
      - binary_sensor.sensor_entre_motion
      - binary_sensor.hue_motion_sensor_1_motion
      - binary_sensor.kaeldersensor_motion
    to: 'off'
    for:
      minutes: 15
  condition:
    - condition: numeric_state
      entity_id: zone.home
      below: 1
action:
  - service: automation.trigger
    data:
      skip_condition: true
    target:
      entity_id: automation.sluk_alt
  - device_id: cc3e9a9a411780d609f148fe66bea640
    domain: mobile_app
    type: notify
    message: Home Assistant detected no one is home and has turned off everything
    title: Leaving home, geofence
mode: single

the only downside (if you can even call it that) is that the automation will trigger every time whenever there is no motion for 15 minutes. But it won’t actually run the actions if zone is greater than 0. So I wouldn’t really call that a problem.

the other option is to use a wait_for_trigger for 15 minutes to expire before deciding what actions to take:

alias: Leaving home, geo
description: ""
trigger:
  - platform: numeric_state
    entity_id: zone.home
    for:
      hours: 0
      minutes: 5
      seconds: 0
    below: 1
condition: []
action:
  - wait_for_trigger:
      - platform: state
        entity_id: 
          - binary_sensor.sensor_entre_motion
          - binary_sensor.hue_motion_sensor_1_motion
          - binary_sensor.kaeldersensor_motion
        to: 'on'
        timeout:
          minutes: 15
  - if:
    - "{{ not wait.completed }}"
  then:
    - service: automation.trigger
      data:
        skip_condition: true
      target:
        entity_id: automation.sluk_alt
    - device_id: cc3e9a9a411780d609f148fe66bea640
      domain: mobile_app
      type: notify
      message: Home Assistant detected no one is home and has turned off everything
      title: Leaving home, geofence
  else:
    - device_id: cc3e9a9a411780d609f148fe66bea640
      domain: mobile_app
      type: notify
      message: Leaving home automation was stopped because motion was detected
      title: Leaving home automation was stopped
mode: single

note that neither of these have been tested and are just off the cuff ideas.

But if I had to choose I think the second one is the one I would go with.

1 Like

Post the contents of this automation: automation.sluk_alt

Thanks. Those are some really good ideas/suggestions. However, the first one is a bit inconvenient as it will require movement at least every 15 minutes. (if I understand it correctly?) The idea of the automation (which perhaps I should have also mentioned at the beginning) is that the light does not switch off automatically if we have guests who are not registered in HA and they are home alone.

I’m guessing the second one is perfect for that scenario, but when I try to copy/paste your code I can’t save?
I’ve tried different editing to fix it, but the closest I can get is that the save-button gets visible, but gives me the error message:

Message malformed: required key not provided @ data[‘action’][1][‘then’]

Any suggestions to what may be the problem?

And by the way, thanks for “trimming” the code :slight_smile:

Hi. It’s just my automation for turning everything off (“sluk alt” means “turn of everything” in danish :slight_smile: )

But I guess there is no harm in posting it:

alias: Sluk alt
description: ""
trigger: []
condition: []
action:
  - service: media_player.media_stop
    data: {}
    target:
      area_id:
        - kokken
        - stue_etage
        - stue
  - service: light.turn_off
    data:
      transition: 3
    target:
      area_id:
        - alle
        - stue_etage
        - 1_sal
        - udendorslys
        - kaelder
  - type: turn_off
    device_id: f0509752b2d131381342d68b0e46a5c5
    entity_id: light.love_wins_neon
    domain: light
  - type: turn_off
    device_id: 6119d9aef650e0516c1b05a5631675fc
    entity_id: light.terrasse_lys
    domain: light
  - service: media_player.turn_off
    data: {}
    target:
      entity_id: media_player.fjernsyn
      area_id:
        - stue_etage
        - kokken
        - stue
  - service: media_player.media_stop
    data: {}
    target:
      area_id: stue_etage
mode: single

An automation without any triggers isn’t an automation. Effectively, you created a script out of an automation.

Is there any particular reason why you created this lobotomized automation (as opposed to a true script)?

I don’t know what a script is (still very new to this as I mentioned)
The “automation” was the best I could come up with, for creating something I wanted to use multiple times without having to enter the same stuff every time I wanted the same to happen :slightly_smiling_face:

Do you have anything I can read about scripts to help me do this in a smarter way?

In the official documentation:

In the Settings menu:

That requirement can be fulfilled by either a script or a scene.

How many other automations have you created that use automation.trigger to trigger automation.sluk_alt?

1 Like

Thank you so much… I think I overlooked scripts a bit because it sounded way too advanced to me.
But I see now, that it is isn’t. Quite the opposite actually :slightly_smiling_face:

I haven’t used it in many actual automations yet, so the damage isn’t that bad. I did create other “automations” though, so I do have some cleaning up to do… :joy::sob:

I think I screwed up the indentation (I did warn that it was untested, right? :wink:)

I think this is correct now.

alias: Leaving home, geo
description: ""
trigger:
  - platform: numeric_state
    entity_id: zone.home
    for:
      hours: 0
      minutes: 5
      seconds: 0
    below: 1
condition: []
action:
  - wait_for_trigger:
      - platform: state
        entity_id: 
          - binary_sensor.sensor_entre_motion
          - binary_sensor.hue_motion_sensor_1_motion
          - binary_sensor.kaeldersensor_motion
        to: 'on'
        timeout:
          minutes: 15
  - if:
      - "{{ not wait.completed }}"
    then:
      - service: automation.trigger
        data:
          skip_condition: true
        target:
          entity_id: automation.sluk_alt
      - device_id: cc3e9a9a411780d609f148fe66bea640
        domain: mobile_app
        type: notify
        message: Home Assistant detected no one is home and has turned off everything
        title: Leaving home, geofence
    else:
      - device_id: cc3e9a9a411780d609f148fe66bea640
        domain: mobile_app
        type: notify
        message: Leaving home automation was stopped because motion was detected
        title: Leaving home automation was stopped
mode: single
1 Like

Thank you for all your effort, Finity! Unfortunately I still can’t get it to work though.
When trying to save, I’m getting the following error:

Message malformed: extra keys not allowed @ data['timeout']

I’ve tried different editing, but to be honest, I’m really in deep water with this. So far i’ve done most of my automation/stuff with the visual editor.

well, crap!

another typo…

alias: Leaving home, geo
description: ""
trigger:
  - platform: numeric_state
    entity_id: zone.home
    for:
      hours: 0
      minutes: 5
      seconds: 0
    below: 1
condition: []
action:
  - wait_for_trigger:
      - platform: state
        entity_id: 
          - binary_sensor.sensor_entre_motion
          - binary_sensor.hue_motion_sensor_1_motion
          - binary_sensor.kaeldersensor_motion
        to: 'on'
    timeout:
      minutes: 15
  - if:
      - "{{ not wait.completed }}"
    then:
      - service: automation.trigger
        data:
          skip_condition: true
        target:
          entity_id: automation.sluk_alt
      - device_id: cc3e9a9a411780d609f148fe66bea640
        domain: mobile_app
        type: notify
        message: Home Assistant detected no one is home and has turned off everything
        title: Leaving home, geofence
    else:
      - device_id: cc3e9a9a411780d609f148fe66bea640
        domain: mobile_app
        type: notify
        message: Leaving home automation was stopped because motion was detected
        title: Leaving home automation was stopped
mode: single

this time I actually tested it in my own system and got no errors. hopefully it gets no errors this time.

sorry about that.

1 Like

Awesome - thank you once again. I’m gonna see if it works when the next time I leave home - but I can only imagine that it does :slight_smile:

I’m really curious both how you are able to see where the typo was (when I put the code in and switch to visual editor, I can see some of the configuration, but a lot of it is hidden) but also how you figured out to write the code in the first place? Is it “just” experience with HA and/or do you have some sort of coding education/been taking courses?
To me this automation idea doesn’t seem that complicated or special … or?

yaml is big on indentation.

It’s just like any other coding language. It requires that certain syntax rules are followed for it’s compiler to interpret and convert “human readable” code (which is in the eye of the beholder :grinning_face_with_smiling_eyes:) into the machine code that works in the system.

The first automation I posted I noticed I didn’t indent everything past the “if” far enough in.

The second was that the timeout was indented too far in.

Both were the result of copy/pasting snippets of code from different places and missing the indents required. But the error clued me in to what to specifically look at.

As far as how I learned it I never took any instruction.

I have a background in PLC controls and coding but nothing like yaml. So the “logic mindset” if you can call it that I’ve been using for a long time.

Most of the HA specific stuff I learned as I went along.

The advantage I feel I’ve had (along with all the others who have been around for a while) is that in the beginning EVERYTHING was done in yaml through configuration files.

Now with the UI being used for almost everything the new user really never gets a chance to use yaml on the basic stuff. So when things get more complicated or when there is something that can’t be done via the UI then the new user is stuck trying to dig into info on how to use yaml and constantly playing catch-up until they get the hang of it.

I almost never use the UI for things unless I have to or unless it’s basic system admin stuff - renaming entities is a big one.

I always have said that the UI is nice for beginners but not many people stay beginners forever. Then those users will start to appreciate the ability to use yaml configs.

Very interesting - and impressive!
The part about indenting the text was also something I was trying to figure out. I guess I should have started taking a little more interest in coding at an earlier stage in my life… well, better late than never :slight_smile:
My approach to understanding/learning HA/Yaml will probably be roughly the same as yours; leaning along the way - but in my case with a lot more trial and error :smiley:

Okay, to get back on topic, unfortunately the automation still didn’t work. It starts as it should, but doesn’t wait the 15 minutes to check for movement before everything turns off.

I fully understand if you can’t spend more time on this - you’ve bothered enough.
I’ll link the JSON trace of the timeline of the automation in case you, or someone else, still finds it interesting to look at what might be wrong (if anything else is needed, please let me know):

Json trace (onedrive)

I think I have the logic backwards.

try reversing the “if”:

  - if:
      - "{{ wait.completed }}"

but be aware if the wait detects any motion in that 15 minute period then the wait gets triggered before it times out and the automation.sluk_alt gets cancelled.

it won’t wait for 15 minutes after the last motion is detected.

the automation will need triggered again (based on zone state) before it will wait again.

so if the zone goes to 0 and then there is motion after that you get the automation stopped message and everything stops at that point.

1 Like

That’s exactly what I want!
If there is motion after we left the house (or a phone dies or so, and can’t get location), it means that someone is still home and the automation should stop until next time home zone get from 1 to 0.
I’m gonna try it out tomorrow…
Thank you

I’m sorry, but it still didn’t work as intended.
Went away today, and instead of turning off everything, it went to ‘else’ and sent me notification that it had stopped because motion was detected (it wasn’t).

it seems I misread the docs for the wait variable. the “wait.completed” variable is only available for the wait_template not wait_for_trigger action.

since it’s not available then it will always be false.

so, that said try this:

  - if:
      - "{{ wait.trigger == 'none' }}"

or it might be this (but I would try the one above first):

  - if:
      - "{{ wait.trigger == none }}"
1 Like

Worked :partying_face:

Thank you!

1 Like