Missing JSON key in MQTT enum sensor

I have an online service that publishes multiple sensors to the same MQTT topic, but with a unique identifier in the JSON payload.

to accomodate for this I have a value template that checks if the identifier matches a specific value and returns the data value if true:

      value_template: >-
        {%if value_json.mmsi == 219025528 and
          ((value_json.type == 1 ) or 
            (value_json.type == 2 ) or
            (value_json.type == 3 )) %}
          {{ value_json.status_text}}
        {%endif%}

This works very well for number based sensors, but for sensor relying on text strings, like:

device_class: "timestamp"
device_class: "enum"

The status sensor value is either blanked or unknown respectively when a JSON payload is received that does not pass the initial test.

So my question is how can make a value template that only updates the value for string based sensors, if the initial check passes?

      value_template: >
        {% your test here %}
           Result
        {% else %}
          {{ this.state }} {# keeps the last value #}
        {% endif %}

Awesome! This has been nagging me forever :slight_smile:

There’s one catch you should be aware of.

If the first time the template evaluates the else case is performed then there will be no value for {{ this.state }} which will raise an error and prevent the sensor from functioning.

You can add to your template something like {{ if this is defined }} and if it isn’t then supply a default value.

1 Like