Evaluating count of history_stats sensors and assigning a string to a template sensor

Hi all,
I have a history_status counter that counts the amount of times a contact sensor closed or opened. I would like to assign a value to that, for example:

If below 5, string would be “stable”
if 10, string, would be “average”
etc

Could i do that like this:
I suspect my {% if is_state(‘binary_sensor.sensor_2_contact’,<5) %} line is not correct…also would like to know if i can do a else if

  - platform: history_stats
    name: open_close
    entity_id: binary_sensor.sensor_2_contact
    state: 'off'
    type: count
    start: '{{ now().replace(hour=0, minute=0, second=0) }}'
    end: '{{ now() }}'
    
  - platform: template
    sensors:
      person_status:
        friendly_name: "Person Status"
        value_template: >-
          **{% if is_state('binary_sensor.sensor_2_contact',<5) %}**
             Stable
          {% else %} 
             Average
          {% endif %}

You are correct, that is incorrect. :wink: Try:

value_template: >
  {{ 'Stable' if states('binary_sensor.sensor_2_contact') | int < 5 else 'Average' }}
1 Like

Thank you very much :slight_smile: Could i add different strings on different values, like maybe 5 string values using a else if or something similar ?

It kind of depends on how you want to map values to strings. Is it a 1-to-1 mapping? Or some range to one string, another range to another string, another range to another string, …?

A range, i think.

1-5 - Stable
5-20 - Average
20-50 - Flapping
50-100 Alert

Um, you have 5 associated with Stable & Average, and 20 associated with Average and Flapping, etc., and what about values above 100, so not quite sure what you want, but how about something like:

value_template: >
  {% set n = states('binary_sensor.sensor_2_contact') | int %}
  {% if n <= 5 %} Stable
  {% elif n <= 20 %} Average
  {% elif n <= 50 %} Flapping
  {% else %} Alert
  {% endif %}

That would work great i think, i didn’t add higher numbers just to focus on the problem at hand, but i’ll add those as well.

But what if the value is 4, would both <=5 and <= 20 or the remaining statements not also apply ? Or will the first if statement ‘break’ and get out of the if ?

And could i use 2 Words in the string or would i have to put quotes around it ?

Many thanks @pnbruckner

An if - elif - else statement works by evaluating each expression in order and executing the first block whose expression evaluates to true, or the else block if none are true. And, yes, you can put whatever you want “inside” the block. If you put quotes, that will be part of the string, so don’t put quotes if you don’t want the string to contain quotes.

Gotcha. Many thanks for your help.