MQTT Template help required

Hi,

I have an MQTT sensor that reports the SOC of my storage battery, I have several autoimations that depend on that sensor value. Last night all the MQTT sensors from the REST went offline/unavailable and therefore my automations (to charge the battery) did not pass their conditional requirements.

I also have the same SOC value available via an integration but it lags by some time compered to the MQTT value. So what I would like to do is template the MQTT sensor so that it first uses the MQTT value, but if that is unavailable to use the integration sensor value.

This is what i tried to do but it doesn’t pass configuration checks:

   -  name: "Battery SOC MQTT fallback"
      state_topic: "Sofar2mqtt/state"
      value_template: "{{ value_json.batterySOC }}"
      availability:
        - topic: "Sofar2mqtt/state"
      payload_available: "online"
      payload_not_available: "{{ ('sensor.sofar_battery_soc') }}"
      unit_of_measurement: '%'

Could any one with more experience help to guide me to fix the template or is there another / better way to substitute a sensor value?

Thank you,

value_template: "{{ value_json.batterySOC if value_json.batterySOC is defined else states('sensor.sofar_battery_soc') }}"
1 Like

Thank you Tom!

I turned my attention to the UI automation while hoping for a slick solution that you have provided. Would this have worked in the automation conditions to check the Sofar2mqtt for unavailable or unknown and then to allow the condition to use either the mqtt value or the Sofar sensor value?

condition: or
conditions:
  - condition: state
    entity_id: sensor.battery_soc_mqtt
    state: unavailable
  - condition: state
    entity_id: sensor.battery_soc_mqtt
    state: unknown
  - condition: numeric_state
    entity_id: sensor.sofar_battery_soc
    below: 85
  - condition: or
    conditions:
      - condition: numeric_state
        entity_id: sensor.battery_soc_mqtt
        below: 85