Dynamically selecting sensor value based on availability of remote home assistant sensor

I figured I’d share here since I couldn’t find it documented anywhere in my google searching. But I was able to make ESPHome fallback to a local temperature sensor instead of using a home assistant provided sensor using a template sensor with the following code where active_temp is a value that either contains the home assistant value if available or the local value if not. I haven’t tested without home assistant online yet, but with unplugging the mbr_temp sensor remotely I can confirm it switches back and forth!

The lambda of the active_temp sensor is doing all the heavy lifting, the isnan function is checking to see if it is not a number, as that’s what it returns once it becomes unavailable, if it’s not a number then it changes the value to the fallback sensor.

  - platform: homeassistant
    id: remote_temp
    entity_id: sensor.remote_sensor_temperature
      - lambda: return (x - 32) *(5.0/9.0);
  - platform: dallas
    address: <address>
    name: "Utility Room Temperature"
    id: utility_room_temp
  - platform: template
    name: "Active Furnace Input Temp"
    id: active_temp
    lambda: |-
      if (isnan(id(remote_temp).state)){
        return id(utility_room_temp).state;
      } else {
        return id(remote_temp).state;
    update_interval: 20s

I’m using this for a fully local thermostat on the esp that has the temperature sourced remotely. But I’ve had issues where home assistant locks up and then causes the A/C or the Heater to hang on or not turn on and I needed a fallback that was local to the ESP.

1 Like

this doesnt seem to work when home assistant goes offline…
have any solutions for that?
it seems to also only work when you reboot the device otherwise it doesn’t refresh