How to handle mqtt sensor with different json payloads?

I have a MQTT based sensor that is giving me a bit of an headache and I’m hoping some templating kung-fu might help me out.

Basically, the sensor will will report one of two different payloads to the same mqtt topic. One containing temperature and humidity and one containing the battery state. The battery state payload is only sent once every 12 hour, and Home Assistant is giving me warnings every time a temperature payload is received complaining about the lack of the battery json element, and visa versa. Furthermore, it sets the sensor value to 0 every time it’s not detected in the payload.

Is there a way to specify that if a json element is missing, it should either be ignored or just revert to the previous entity value?

Current configuration as an example:

- name: 'Temperature Sensor'
  state_topic: 'sensor/tempsensor/rx'
  device_class: 'voltage'
  unit_of_measurement: "V"
  value_template: "{{ value_json.battery_voltage }}"

Is there a elegant solution to this?

If the battery_voltage key is defined display its value otherwise report the sensor’s existing value.

  value_template: >
    {{ value_json.battery_voltage if value_json.battery_voltage is defined else states('sensor.temperature_sensor`) }}"
1 Like

That’s some weird if-statement syntax but it was exactly what I was looking for. Thanks!

1 Like