Automation condition: Person in specific zone X Time ago

I am trying to set up an automation that triggers when I enter my home zone, but is conditional if i was in a different zone 30 minutes ago.

Person zone tracking is enabled for my phone and it seems to accurately place me in each zone i have defined. I can clearly see in my history tab for my person entity that it tracks my location.

So the question is: how do i get a condition to reference an entities historical state some amount of time previous to when the trigger happens?

you can use the history stats integration to get a sensor for where you were 30 minutes prior by making the start time 30 minutes ago with a duration of however long it takes to make the zone location at that time reliable.

You could use a trigger-based template sensor to store the previous zone and a timestamp.

template:
  - trigger:
      - platform: state
        entity_id: person.taako
        to: not_home  
        not_from:
          - not_home
          - unknown
          - unavailable
    sensor:
      - name: Taako last known zone
        state: "{{ trigger.from_state.state }}"
        attributes:
          datetime: "{{ now() }}"

Then the condition in your automation would be something like:

condition:
  - condition: state
    entity_id: sensor.taako_last_known_zone
    state: "Zone X"
  - "{{ now() <= state_attr('sensor.taako_last_known_zone', 'datetime') + timedelta(minutes = 30) }}"

@Didgeridrew
I like this solution but i’m a little confused (i’m still new to HA automations and triggers). I spent some time reading the docs on template sensors and triggers

Wouldn’t the Taako last known zone sensor update when i leave Zone X and move into the Away state? Then the condition wouldn’t be met because my last zone was Away?

Secondly, if this only updates when i enter zones, then the datetime won’t update when i leave Zone X?

I guess i need a sensor that updates when i leave Zone X and stores the datetime. then the condition checks that date time

To make things more concrete. I have a Work zone and when i commute home i go from Work => Away (AKA not any defined zone) => Home. I want to the condition to be that I was at Work zone 30 minutes before i entered Home zone.

@finity, how do i make the stats integration start time always ā€œ30 minutes before nowā€?

Did you look at the documentation?

I’m pretty sure it gives examples there.

i did, but its not super clear. I’m guessing it want something like

# Example configuration.yaml entry
sensor:
  - platform: history_stats
    name: My Previous Location
    entity_id: device_tracker.pixel_6_pro
    state: "Work"
    type: count (NOT SURE ABOUT THIS)
    end: "{{ now() - timedelta(minutes = 30) }}"
    duration:
        minutes: 2

but then how exactly do i query it? Count is a strange thing to track for zones…

Yes, that is what this does. The sensor would update when you leave a defined zone.

If you are solely interested in getting the time you left the Work zone, you can change the trigger.

For that I would use something like the following. After the first triggering event, the sensor state should only ever be either ā€œhomeā€ or ā€œWorkā€.

template:
  - trigger:
      - platform: state
        id: work
        entity_id: person.taako
        to: not_home  
        from:
          - Work
      - platform: state
        entity_id: person.taako
        to: home  
        from: not_home
        for: "00:10:00"
    sensor:
      - name: Taako last known zone
        state: >
          {{ iif(trigger.id == 'work', trigger.from_state.state, trigger.to_state.state) }}
        attributes:
          datetime: "{{ now() }}"

Then your automation would be something like:

trigger:
  - platform: state
    entity_id: person.taako
    to: home
condition:
  - condition: state
    entity_id: sensor.taako_last_known_zone
    state: "Work"
  - "{{ now() <= state_attr('sensor.taako_last_known_zone', 'datetime') + timedelta(minutes = 30) }}"
action:
....

You may need to alter the time in the second condition to give yourself some wiggle room.


If you want to use History stats, don’t use count, use time:

# Example configuration.yaml entry
sensor:
  - platform: history_stats
    name: My Previous Location
    entity_id: device_tracker.pixel_6_pro
    state: "Work"
    type: time
    end: "{{ now() - timedelta(minutes = 30) }}"
    duration:
        minutes: 10

With this method, you would use a Numeric state condition:

condition:
  - condition: numeric_state
    above: 0
    entity_id: sensor.my_previous_location

I think that count is exactly what you should use.

it means that if the history stats sensor’s state is 1 you were in the work zone once 30 minutes ago.

if it’s 0 then you weren’t.

at least I’m pretty sure that should work.

Thanks for this!

I’ll try it out tomorrow. I like the templated sensor method since it’s easier for me to understand. It’s all set up in my home assistant now so hopefully tomorrow when i come home it triggers!

unfortunately it seems the sensor failed to trigger today

automation_sensors.yaml

- trigger:
    - platform: state
      id: work
      entity_id: person.taako
      to: not_home
      from:
        - Work
    - platform: state
      entity_id: person.taako
      to: home
      from: not_home
      for: '00:10:00'
  sensor:
    - name: Taako Last at Work
      state: >
        {{ iif(trigger.id == 'work', trigger.from_state.state,
        trigger.to_state.state) }}
      attributes:
        datetime: '{{ now() }}'

and in my config i have

template: !include automation_sensors.yaml

The entity shows up but today when i left the Work zone into Away it did not seem to update

EDIT:

actually, it seems that it did trigger to the Home state when i was at home for 10 minutes. So only the Work → Away trigger failed…

My dumb self called ā€œWorkā€ zone ā€œTaako Workā€ and didn’t update the template sensor you gave me. Will update and try again tomorrow

One question, should i be using all lower case and underscore for this line:

      from:
        - Work

be

    from
      - taako_work

i.e., all lowercase for state name with underscore for space? how are zone names with spaces and capitals represented for templates?

IIRC, you want to use the actual zone name, not the object id… So it should be:

    from
      - Taako Work

thanks! i’ll try that for tomorrows attempt (it’s a shame i only really get at most one shot to check this per day)

A random question since you seem to know a ton about HA. How does it handle overlapping zones? I want my home zone to be pretty small radius. But that means sometimes it takes a while for me to hang around that zone for the location to update. I am considering doing a ā€œnearby homeā€ zone thats a bit larger to guarantee that by the time i arrive home the trigger has launched.

Alternatively is there any way to check if i’m within X distance of a zone, and trigger when that distance is less than X. Then i wont need to define a larger zone

Accurate and reliable presence detection is a never-ending rabbit hole… :slight_smile:
To get your home zone as reliable as possible it is helpful to have both GPS and stationary(router/network or Bluetooth-based) trackers attached to your person entities.

You will definitely want to take a look at the [Proximity integration] (Proximity - Home Assistant).

Nested zones can work if you set your larger zone as passive and then use Zone triggers in your automations. Otherwise, you may find your person entity’s state bouncing between the zones. I’ve never tried multiple degrees of nesting… it’s probably not recommended, but if you try it, let me know how it goes.

oh i only have my pixel 6, how do i set up my wifi network as in ā€œhomeā€ zone?

thanks i’ll take a look!

Also passive zones could work as well, thanks for pointing that out!

There are many ways to detect that your phone or other devices have connected to your network… check out the available presence integrations. There are integrations for specific brands of routers as well as ones that use common network tools like NMAP or ping.

If you have a bluetooth receiver on the computer you run HA on, you can likely set it up
to work as as a stationary device tracker as well, to detect the transmitter from you phone.

I see, sorry i was under the impression that my phone could be used to report my zone as ā€œhomeā€ when it connects to a specific wifi network.

It seems that you’re saying that i need an integration specific to my router to use a static location sensor. I use unifi devices so i think i just need to set up this UniFi Network - Home Assistant

another day, another failed trigger. This time the Last At Work sensor worked fine but the condition wasn’t met because i left the State as Work instead of Taako Work

Tomorrow will be the day, i can feel it!

1 Like

I decided to just spin up node red and use that. It has a get history node which i can set for last 30 minutes and then use a for loop to search each state in the last 30 minute for my person entity. If any element of the 30minute history arrray has state = ā€˜work’ i fire call_service.

Node Red is SO MUCH SIMPLER than HA. It did not require any helper sensors since get_history does exactly what i need.

I really appreciate your help @Didgeridrew, it definitely taught me a lot about template sensors and conditions in HA. But node red just ended up being way easier.