MQTT Sensor Value Template Question..Do I need two sensors?

Right now, this is my code. I have a mqtt sensor, then a template sensor that takes whatever the mqtt sensor is and displays something else (motion/clear).

- platform: mqtt
  name: "Kitchen Motion Sensor"
  state_topic: "smartthings/Kitchen Motion Sensor/motion"
  retain: true

- platform: template
  sensors:
    kitchen_motion_sensor:
      value_template: >-
        {%- if is_state("sensor.kitchen_motion_sensor_mqtt", "active") %}
            motion
        {%- elif is_state("sensor.kitchen_motion_sensor_mqtt", "inactive") %}
            clear
        {% else %}
            failed
        {%- endif %}
      friendly_name: Kitchen Motion Sensor

I was trying to combine this into one MQTT Sensor, but I don’t think it’s working using the value_template. I think the template in a way is working, but since the template changes the state from ‘active’ to ‘motion’, the template re-reads it and doesn’t see ‘motion’ as an option, so it changes to ‘failed’.

- platform: mqtt
  name: "Kitchen Motion Sensor"
  state_topic: "smartthings/Kitchen Motion Sensor/motion"
  retain: true
  value_template:  >-
    {%- if is_state("sensor.kitchen_motion_sensor", "active") %}
        motion
    {%- elif is_state("sensor.kitchen_motion_sensor", "inactive") %}
        clear
    {% else %}
        failed
    {%- endif %}

Is there a way to make this work as one sensor?

I suggest try write the value_template code in inline mode first, the conf file is very sensitive to space, tab etc. For me personally, writing the value_template in inline mode sometimes helps avoid such troubles.

Edit:
Another tips, also try the value_template code in the dev_template page first in the front end

I have the formatting down, so inline won’t matter.

I am trying it in the frontend first, but from what I am finding, I am correct that because the template changes the sensor’s own state, it loops back again and returns “failed” because the new state “inactive” is not one of the template’s options.

It would be pretty cool if there was a way to implement this so that I wouldn’t need a separate sensor for every sensor I want a template for.

Can you try this:

'{% if value is equalto "active" %} motion {% elif value is equalto "inactive"%} clear {% else %} failed {% endif %}'

Notice there are tick marks bracketing the code.

Edit:
I am not sure if tick mark is required in down formatting or not; it seems it is needed in inline formatting.

1 Like

Ah, that line worked perfectly. I didn’t know I could just use ‘value’.

Thanks!