Example of if statement for template sensor

Hi,

I just got helped on Discord with my setup, so I just want to share it, it could be useful for some people :slight_smile:

I have meteo station which send direction of wind. Here is example of if statement for sensor (template):

- platform: mqtt
   state_topic: "meteo/winddir"
   name: "Wind direction"
   qos: 1
   expire_after: 3600
   value_template: >-
     {% if value == 0 %}N
     {% elif value == "1" %}NNE
     {% elif value == "2" %}NE
     {% elif value == "3" %}ENE
     {% elif value == "4" %}E
     {% elif value == "5" %}ESE
     {% elif value == "6" %}SE
     {% elif value == "7" %}SSE
     {% elif value == "8" %}S
     {% elif value == "9" %}SSW
     {% elif value == "10" %}SW
     {% elif value == "11" %}WSW
     {% elif value == "12" %}W
     {% elif value == "13" %}WNW
     {% elif value == "14" %}NW
     {% elif value == "15" %}NNW
     {% endif %}
7 Likes

Am I reading this right to assume your sensor outputs 0-15 and this template changes it to a cardinal direction?

Exactly :slight_smile:

Hey @ronnicek, thanks for posting this. It just helped me solve a similar problem I have been working on for a few days.
Thanks!!!

Thanks a lot for posting this

Helped me solve something similar too! Here is another example of something similar. I had a lot of trouble getting the syntax right and also had to restart HA rather than just reloading the template entities. I use this as my projector can’t be controlled with IR commands when it is stopping or starting. The same command is used to stop and start so it is very state dependant.

  - sensor:
      - name: "Projector State"
        state: >
          {% if (states('sensor.projector_checker_current_consumption') | int < 1) %} off
          {% elif (states('sensor.projector_checker_current_consumption') | int > 260) %} on
          {% else %} transition
          {% endif %}