Determining the duration of the previous state of entity

Hey!

I would like to come up with an elegant way to check the previous state of an input_boolean.

Below is the automation of the toilet freshener. According to the ID - free, the air freshener works 2 times, I would like to add a condition through which it would be possible to find out whether the switch was turned on (before turning off) for 2 minutes or more, can this be implemented?

An additional history stat sensor comes to mind, but I don’t really understand the correctness yet. I could of course add additional switches for this definition, but I thought maybe I could make do with a template…

- alias: toilet_airwick_actions
  initial_state: true
  trigger:
  - platform: state
    entity_id: input_boolean.toilet_occupancy
    to: 'off'
    id: free
  - platform: state
    entity_id: input_boolean.toilet_occupancy
    to: 'on'
    for:
      minutes: 15
    id: 15min
  action:
  - choose:
    - conditions:
      # Trigger - free
        condition: trigger
        id: free
      sequence:
      - repeat:
          count: 2
          sequence:
          - service: switch.turn_on
            entity_id: switch.toilet_airwick_valve
          - delay: 4
    - conditions:
      # Trigger - busy within 15 minutes
        condition: trigger
        id: 15min
      sequence:
        service: switch.turn_on
        entity_id: switch.toilet_airwick_valve

The main idea of this check is to remove unnecessary/false runs of the air freshener, in other words, saving the cylinder.

Okay, it looks like I will still need to use an additional binary sensor and use it as a trigger, most likely I will close the topic…

"{{ is_state('input_boolean.toilet_occupancy', 'on')
    and now() > states.input_boolean.toilet_occupancy.last_changed + timedelta(seconds=120) }}"

…and only when this sensor goes into the off state - turn on the air freshener.