Mqtt sensor working with json and variables

I do get only one value from my mqtt topic.
I am using the rtl2mqtt to seperate the values. Let’s imagin from mqtt I do get on topic
sensor/rtl_433/Fine Offset Electronics WH1080/WH3080 Weather Station/101/direction_deg

the special value of an angle.
112

now I created a sensor:

- platform: mqtt
  state_topic: 'sensor/rtl_433/Fine Offset Electronics WH1080/WH3080 Weather Station/101/direction_deg'
  name: 'Wind Direction'
  unit_of_measurement: ''

this is showing me the value. Now I wanna do a campare

value_template: >-
      {% set wd = value_json | int %}
      {% if wd <= 11 or wd > 348 %}North
      {% elif wd >11 and wd <=34 %}North North East
      {% elif wd >34 and wd <=56 %}North East
      {% elif wd >56 and wd <=79 %}East North East
      {% elif wd >79 and wd <=101 %}East
      {% elif wd >101 and wd <=124 %}East South East
      {% elif wd >124 and wd <=146 %}South East
      {% elif wd >146 and wd <=169 %}South South East
      {% elif wd >169 and wd <=191 %}South
      {% elif wd >191 and wd <=214 %}South South West
      {% elif wd >214 and wd <=236 %}South West
      {% elif wd >236 and wd <=259 %}West South West
      {% elif wd >259 and wd <=281 %}West
      {% elif wd >281 and wd <=304 %}West North West
      {% elif wd >304 and wd <=326 %}West North West
      {% elif wd >326 and wd <=348 %}North North West

what I do see is a "unknown"state. I know how to work with attributes, but here I do not hav one. How can I get this value

If the payload of the MQTT message is just a simple number the maybe you should be using value rather than value_json in the value_template: definition? According to https://www.home-assistant.io/docs/configuration/templating/#processing-incoming-data that should be available to be used.

1 Like

Use value instead of value_json as @lmamakos suggested. Also the first part in your elif statements is not needed, e.g. you don’t need to check if the value is larger than 11 in the first elif statement, because if it is smaller or equal to 11 it will already be captured in the first if statement.

Or maybe something like this for your template:

{% set labels = ['N', 'NNE', 'NE', 'ENE',
                 'E', 'ESE', 'SE', 'SSE',
                 'S', 'SSW', 'SW', 'WSW',
                 'W', 'WNW', 'NW', 'NNW'] %}
{% set max_input = 360 %}
{% set nlabels = labels | length %}
{% set b = ((value/max_input * nlabels) + 0.5) % nlabels %}
{{ labels[b|int] }}

Paste this into the “template” developer tool, and play with it. Just add a {% set value = 56 %} or similar in front of it to test different values. Season to taste.

2 Likes

Love the logic
I even unstand it