How to make sure attributes of a template sensor are still defined even when the sensor is unavailable?

Hi,

I am combining some humidity and temperature sensor entities together, so that their values become attributes of one single sensor. The config looks like this:

  - trigger:
      - platform: state
        entity_id:
          - sensor.rht_sensor_temperature_kitchen
          - sensor.rht_sensor_humidity_kitchen
          - binary_sensor.rht_sensor_problem_kitchen
    sensor:
      - name: "RHT Sensor Combined (Kitchen)"
        unique_id: rht_sensor_combined_kitchen
        unit_of_measurement: "°C"
        state_class: measurement
        device_class: temperature
        state: "{{ states('sensor.rht_sensor_temperature_kitchen') }}"
        availability: "{{ states('sensor.rht_sensor_temperature_kitchen') not in ['unavailable', 'unknown', '', None] }}"
        attributes:
          temperature: "{{ states('sensor.rht_sensor_temperature_kitchen') }}"
          humidity: "{{ states('sensor.rht_sensor_humidity_kitchen') }}"
          status: >-
            {% if is_state('binary_sensor.rht_sensor_problem_kitchen','on') %} DOWN
            {% else %} OK
            {% endif %}

You can see there is also a binary sensor which just indicates whether the sensor is still alive or not.

The problem is that when the sensor dies, the values of the source sensors change to “unavailable”, and therefore so does the combined sensor. This is fine, but when this happens, the attributes of the combined sensor are simply missing. See this screenshot, which shows the result for a working sensor and a broken sensor:

I would like the attributes to still be present (and show something like NaN, NaN, and DOWN for the humidity, temperature, and status).

Can this be done?

There’s no way to do what you want. It’s simply just not possible with how the code currently works for the template integration.

Oh I see. Thanks.

I thought it might be at least possible to use templating inside the config for the attributes - would that approach not work then?

No, what you want is simply not possible.

Can you help me see why templating in attributes would not work?

Please understand that I cannot show you why it doesn’t work if you don’t understand the underlying code.

I’m telling you that the code for the integration does not support what you want.

Can you suggest an alternative route for me to achieve something like this? i.e combining sensors into a single entity?

There are no alternate routes that are built into HA that can do this. This is why I’ve been saying:

You would need to remove your availability template so that the sensor never goes unavailable. You could instead make your state template resolve to none when the source entities are unavailable, and in that case the state would show as unknown but the attributes would still be there.

As Petro made clear, there is no way to have attributes when the sensor is unavailable.