Query recent activity

Hello,
I’m trying to create an automation (in node red) that will turn on an extractor based on the time the room was occupied.

I can trigger an automation when a light is turned off.
At this point I want to know how long the light was on for.

This is to set the ventilator if it is needed.

Visit duration:
< 5 minutes - do nothing

5 & < 10 minutes - ventilator for 5 minutes
10 minutes - ventilator for 45 minutes

How can i query the recent history of device ?
or
How do I define a trigger that matches turn off after 5 minutes of on?

Steve

trigger:
  - id: light
    platform: state
    entity_id: light.example
    id: light
    to: 'off'
    from: 'on'
    variables:
      minutes: "{{ (now() - trigger.from_state.last_changed).total_seconds() / 60 }}"
  - id: timer
    platform: event
    event_type: timer.finished
    event_data:
      entity_id: timer.fan_example
condition:
  - "{{ trigger.platform == 'event' or minutes >= 5 }}"
action:
  - choose:
      - conditions:
          - condition: trigger
            id: timer
        sequence:
          - service: fan.turn_off
            target:
              entity_id: fan.example
      - conditions:
          - condition: trigger
            id: light
        sequence:
          - service: fan.turn_on
            target:
              entity_id: fan.example
          - service: timer.start
            target:
              entity_id: timer.fan_example
            data:
              duration:
                minutes: "{{ 5 if minutes >= 10 else 45 }}"  
1 Like