Help with mapping sensor values to a word

Hi all,

I’ve added two Ikea VINDRIKTNING air quality sensors to my HA using Esphome, and although I can see them on a gauge with the raw values, I would like the sensor to report as a word rather than the number readings to make it more user friendly and understandable, a bit like the LEDs on the front of the sensor itself- is this possible?

For example;

0-30 = Good

30-100 = Medium

100+ = Bad

Thanks for the help !

Make a template sensor using if statements to check the state

e.g. template

{% if states('sensor.xyz') | float(-1) < 0 %}
  Error
{% elif 0 <= states('sensor.xyz') | float(-1) < 30 %}
  Good
... etc ...
{% endif }
1 Like

Thanks @petro !

I’ve set up the below;

template:
  - sensor:
      - name: "Bedroom air quality"
        state: >
          {% if is_state('sensor.bedroomairquality') | float(-1) < 0 %}
            Error
          {% elif 0 <= states('sensor.bedroomairquality') | float(-1) < 30 %}
            Good
          {% elif 0 <= states('sensor.bedroomairquality') | float(-1) < 100 %}
            Medium
          {% elif 0 <= states('sensor.bedroomairquality') | float(-1)< 500 %}
            Bad
          {% endif %}

However the sensor is just returning ‘unknown’ - I initially thought it was due to the unit of measurement being in µg/m³ rather than a %, I changed sensor.bedroomairquality to a % but still no luck!

Any advice is appreciated!

Cheers

Had a quick look in template editor and can make it report good, medium and bad and error - provided the value is below 500.
Can you post a screenshot of the (source) sensor in the states page in developer tools?

Example in Developer Tools:

        {% set airqual = 32 %}
          {% if airqual < 0 %}
            Error
          {% elif airqual < 31 %}
            Good
          {% elif airqual < 101 %}
            Medium
          {% elif airqual < 500 %}
            Bad
          {% endif %}

Produces the result ‘Medium’
If i change airqual to ‘no’ it correctly produces ‘Error’

Thanks! I never thought to test it on template editor - in doing so I found a wrongly placed is_ on the first line that I added when trying something earlier, removing it has fixed this, thanks both!

1 Like

Note in my example - you could just change the set line to:
{% set airqual = states('sensor.bedroomairquality')|float(-1) %}
and then in the rest of the template you don’t have to keep using states and converting to float for each comparison.

For your consideration, another way to do it:

template:
  - sensor:
      - name: "Bedroom air quality"
        state: >
          {% set x = { 0: 'Error', 30: 'Good', 100: 'Medium', 500: 'Bad' } %}
          {{ x.get((x.keys() | select('>', states('sensor.bedroomairquality') | float(-1)) | first)) }}
2 Likes