Template bin sensor if other sensor's value is above/below a certain value for x minutes

Hi there,

I need some help with a template binary sensor. I want to achieve that the binary sensor is on/off if another sensor’s value is above/below a certain value/threshold for x minutes:

  - binary_sensor:
      - name: Wohnzimmer-BM-Helper
        state: >
         {% if state_attr('sensor.bm_wohnzimmer_letzte_10m') | float(0) > 20 and now() >=  states.sensor.bm_wohnzimmer_letzte_10m.last_changed + timedelta(minutes = 2) %}
           on
         {% if state_attr('sensor.bm_wohnzimmer_letzte_10m') | float(0) < 20 and now() >=  states.sensor.bm_wohnzimmer_letzte_10m.last_changed + timedelta(minutes = 5) %}
           off
         {% else %}
           off
         {% endif %}  

Is that right? How to correct this? Many Thanks!

Probably best to use a trigger-based template binary sensor.
The trigger part is the same as for automation, so support the numeric_state platform with for: keyword.

example trigger from doc:

  trigger:
    - platform: numeric_state
      entity_id: sensor.temperature
      # If given, will trigger when the value of the given attribute for the given entity changes..
      attribute: attribute_name
      # ..or alternatively, will trigger when the value given by this evaluated template changes.
      value_template: "{{ state.attributes.value - 5 }}"
      # At least one of the following required
      above: 17
      below: 25
      # If given, will trigger when the condition has been true for X time; you can also use days and milliseconds.
      for:
        hours: 1
        minutes: 10
        seconds: 5

ok, it seems to work, as now it turns to “on”, but not to off after 5 mins:

  - trigger:
      - platform: numeric_state
        entity_id: sensor.bm_wohnzimmer_letzte_10m
        above: 20
        for:
          minutes: 1
          seconds: 30
    binary_sensor: 
      - name: Wohnzimmer-BM-Helper
        state: "{{states('sensor.bm_wohnzimmer_letzte_10m') | float(0) > 20.0}}"

Do I need a second template bin sensor?

  - trigger:
      - platform: numeric_state
        entity_id: sensor.bm_wohnzimmer_letzte_10m
        above: 20
        for:
          minutes: 1
          seconds: 30
      - platform: numeric_state
        entity_id: sensor.bm_wohnzimmer_letzte_10m
        below: 20.1
        for:
          minutes: 1
          seconds: 30
    binary_sensor: 
      - name: Wohnzimmer-BM-Helper
        state: "{{states('sensor.bm_wohnzimmer_letzte_10m') | float(0) > 20.0}}"
1 Like

sensor.bm_wohnzimmer_letzte_10m:

Well, unfortunately, it does not go to off, even after 5 mins

EDIT: okay, maybe it was stuck, now it works!

I have to reopen the issue as it still does not work properly. The thing is that the template does not change to on or off.

Do you have an idea where there might be the problem?