Help with if statement in template

I’m very new to templating. I’ve got the Snoo integration running and it produces values of “ONLINE”, “BASELINE”, “LEVEL 1”, etc. These appear to be strings. I would like to convert them to numbers so I can use a Lovelace gauge card to display the status. Something along the lines of this.

template:
  - sensor:
      - name: Baby Monitor
        state: >
          {if sensor.parker_s_snoo == "ONLINE" { 0 }
           if sensor.parker_s_snoo == "BASELINE" {0}
           if sensor.parker_s_snoo == "LEVEL 1 {1}
           if sensor.parker_s_snoo == "LEVEL 2 {2}
           if sensor.parker_s_snoo == "LEVEL3 {3}}

My syntax is probably a disaster, can anyone help point me in the right direction?

template:
  - sensor:
      - name: Baby Monitor
        unit_of_measurement: "Lvl"
        state: >
          {% set snoo = states('sensor.parker_s_snoo') }}
          {% if snoo in ["ONLINE", "BASELINE"] %}
            0
          {% elif snoo == "LEVEL 1" %}
            1
          {% elif snoo == "LEVEL 2" %}
            2
          {% elif snoo == "LEVEL 3" %}
            3
          {% else %}
            Undefined 
          {% endif %}
        availability: "{{ states('sensor.parker_s_snoo') in ["ONLINE", "BASELINE", "LEVEL 1", "LEVEL 2", "LEVEL 3] }}"

Yes, thank you. I also realized that I didn’t do a good job of reading the docs. There is a good example here:

My current working code looks like this (took me a while to figure out it’s “LEVEL1”, not “LEVEL 1”):

template:
   - sensor:
      - name: Snoo Level
        state: >
          {% if is_state('sensor.parker_s_snoo', 'ONLINE')%}
            0
          {% elif is_state('sensor.parker_s_snoo', 'BASELINE')%}
            0
          {% elif is_state('sensor.parker_s_snoo', 'LEVEL1')%}
            1
          {% elif is_state('sensor.parker_s_snoo', 'LEVEL2')%}
            2
          {% elif is_state('sensor.parker_s_snoo', 'LEVEL3')%}
            3
          {% elif is_state('sensor.parker_s_snoo', 'LEVEL3')%}
            4
          {% else %}
            failed
          {% endif %}

I like your use of in ["ONLINE, “BASELINE”], that’s cleaner than mine, I’ll change it now. Thanks for the help.

You also need a unit of measurement for graphs, not sure about the gauge card but I suspect so.

You should also use an availability template or your gauge card will complain with an ugly message about that non numeric else state if it ever happens.

Sorry @tom_l , but this doesn’t look like a correct use of quotation marks. :wink: :slight_smile:

Shouldn’t it be:

availability: "{{ states('sensor.parker_s_snoo') in ['ONLINE', 'BASELINE', 'LEVEL 1', 'LEVEL 2', 'LEVEL 3'] }}"
1 Like

Yes it should. Thanks.

1 Like