Best way to check how long you've been in an area you just exited?

Hi,

I have an automation that fires whenever I exit an area. Works fine, but annoying when I’m just passing by into the same area without the intent to fire the automation (sends a notification to my wife that I’m on my home).

I would like to add a condition that ensures that I have been in that area for at least 30 minutes to fire the action. Since the automation triggers by me leaving the area I want to check, I’m not sure about the best way to go about this.

I saw some other topics mentioning History Stats, but I’m curious to what the best and simplest solution would be?

I made a History Stats sensor and condition that solves this.

Here is my sensor code for configuration.yaml:

sensor: 
  - platform: history_stats
    name: Recent Office Time
    entity_id: person.xxx
    state: "Work"
    type: time
    duration: "00:30:00"
    end: "{{ now() }}"

I used duration instead of start to make sure it always checks the last 30 minutes. Otherwise the condition may be accepted from a previous visit.

Here is my condition:

    condition:
      - condition: numeric_state
        entity_id: sensor.recent_office_time
        above: 0.25

This checks if the sensor is above 15 minutes (0,25 hours).

I also added a time condition in combination to the above to make sure it only triggers when I’m actually going home, and not out for lunch etc.

Since I’m just starting out with home assistant I’m curious if this is best practice in this case. And if so hope it can help somebody. :slight_smile:

If your person entity’s state is stable while you’re in the target zone, you can use its last_changed property.

sensor: 
  - platform: history_stats
    name: Recent Office Time
    entity_id: person.example
    state: "Work"
    type: time
    start: '{{ states.person.example.last_changed | default(now()) }}'
    end: "{{ now() }}"

Interesting… wouldn’t last changed reset once I’m leaving the zone though? Since that is what I’m triggering with.

Yes, once you leave the zone the sensor is set to 0. Maybe a better option, since your automation triggers off leaving the zone, would be just a template condition that references the previous last_changed.

trigger:
  - platform: state
    entity_id: person.example
    from: Work
condition:
  - condition: template
    value_template: >
      {{ now() - trigger.from_state.last_changed >= timedelta(minutes=30) }}
1 Like