Using value_template in with MQTT help

I have a temperature probe sensor that works great using MQTT. However, when my probe is not connected, I would like the state value to default to “0” rather than “unknown”. I have read the documentation and tried a few things in my configuration file to no avail. Clearly I am doing something wrong as the state is always “unknown”. Any help would be greatly appreciated. Below is my simple entry in my config file.

sensor:
  - platform: mqtt
    state_topic: "bbq/grill/probe1"
    name: "Probe 1"
    qos: 0
    unit_of_measurement: "°F"
    value_template: "0"

Whatever you put in value_template is used when a payload is received. It there’s no payload received, the value_template isn’t used.

If your BBQ temperature sensor disconnects from the MQTT broker, the broker informs all subscribers (like Home Assistant) that the source for the topic bbq/grill/probe1 has disconnected. Unless the payload was published to the topic as a retained message (i.e. stored on the broker) there’s no record of the payload anymore. Home Assistant reports this as unknown (because that’s the true state of affairs).

As far as I know, you can’t replace the word unknown with something else (no more than you can replace unavailable). I think you may have to implement a workaround in the form of a Template Sensor that normally reports the MQTT Sensor’s values verbatim except when the value is unknown (it reports it as 0).

template:
  - sensor:
      - name: Probe 1A
        unit_of_measurement: "°F"
        device_class: temperature
        state: >
          {% set t = states('sensor.probe_1') %}
          {{ t if t != 'unknown' else 0 }}
1 Like

Awesome, this is exactly what I needed! Thank you very much

1 Like