Fallback last known value for unavailable entities without using template

Hi! I’ve searched quite long for the answer to this question, but I’m not able to find anything relevant (I am maybe searching for the wrong terms, in this case I’d love if you could point out to an appropriate thread).

I have some entities (say around 100) which are automatically imported by an integration, and it may happen that they are not available for some time, due to poor wifi connection.

I’m fine with this, however, since they are displayed in lovecace cards, when this happen I get many “unavailable” parts of the sensor, and I wish they would display the last known value as fallback instead.

Now, I’ve look here for ways to do that, and all I’ve found only these two possibilities:

  • creating a template entity to deal with the unknown value
  • creating a helper number and update it via automation

Now, while they are both feasible in theory, in my situation both have the issue of duplicating the number of entities, which would be a problem in my specific case.

My question: is there a way to achieve this without duplicating the entities?

Thank you for your answer,
R

In this situation I would write some kind of script that generates the YAML config for every sensor for which I want a fallback.

The most simple implementation of this would be to create a jinja template and try it out in the developer tools. If you were to label all your fallback sensor entities with a ‘fallback’ label, you could use your jinja template to spit out the entire yaml you need for all these sensors.

You could then paste this into a yaml file and into your configuration.

No, I don’t believe so.

Great idea: something like this:

{% set el = integration_entities('esphome')|select('search','^sensor.')|list %}
template:
  - sensor:
{% for e in el %}
      - name: {{ e ~ '_fallback' }}
        state: >
          {{ "{% if states('" ~ e ~ "') in ('unknown', 'unavailable') %}" }}
          {{ "  {{ this.state }}" }}
          {{ "{% else %}" }}
          {{ "  {{ states('" ~ e ~ "') }}" }}
          {{ "{% endif %}" }}
      {% if 'unit_of_measurement' in states[e].attributes -%}
        {{ "  unit_of_measurement: '" ~ states[e].attributes.unit_of_measurement ~"'" }}
      {% endif -%}
{% endfor -%}

Replace my esphome with your integration id which you can get from the end of the URL of the integration’s screen in HA; and do any other filtering necessary to get the list of sensors you want. That should generate a swathe of YAML which you can copy into your config.

A potential issue of this approach is that you have no way of knowing how long an entity has been offline: could be weeks…