YAML Code need optimising when Sensor not available

I need another YAML code for the code below:

If one of the sensors (sensor.toon_p1_power_use_low) or (sensor.toon_p1_power_use_high)
is unavailble they must not be used, because i get an error when this happens on the dasboard graph.

My YAML code :slight_smile:

platform: template
sensors:
energie_verbruik_totaal:
friendly_name: “Energie Verbruik (totaal)”
unit_of_measurement: ‘W’
value_template: “{{states(‘sensor.toon_p1_power_use_low’) | float(0)+ states(‘sensor.toon_p1_power_use_high’) | float(0) }}”

  1. Next time: https://community.home-assistant.io/t/how-to-help-us-help-you-or-how-to-ask-a-good-question/114371#oneone-format-it-properly-16

  2. Do not confuse energy and power. They are two different things.

  3. Use the new template format for new template sensors.

  4. Use an availability template to ensure your source sensors have valid states.

configuration.yaml

template:
  - sensor:
      - name: "Power Verbruik (totaal)"
        unit_of_measurement: "W"
        device_class: power
        state_class: measurement 
        state: "{{ states('sensor.toon_p1_power_use_low') | float(0) + states('sensor.toon_p1_power_use_high') | float(0) }}"
        availability: "{{ states('sensor.toon_p1_power_use_low') | is_number and states('sensor.toon_p1_power_use_high') | is_number }}"

Many thanks,

How is the availability template working ?
Sometimes (sensor.toon_p1_power_use_low) or sometimes (sensor.toon_p1_power_use_high) are not available and then i need still the input of one of these sensors depending on which is available.

greetings Eric

The availability template makes the template sensor unavailable if either of the source sensors are unavailable. This will show as a gap on your graph.

If you want the last good value to be shown instead then you will have to do this:

template:
  - sensor:
      - name: "Power Verbruik (totaal)"
        unit_of_measurement: "W"
        device_class: power
        state_class: measurement 
        state: >
          {% if states('sensor.toon_p1_power_use_low') | is_number and states('sensor.toon_p1_power_use_high') | is_number %}
            {{ states('sensor.toon_p1_power_use_low') | float(0) + states('sensor.toon_p1_power_use_high') | float(0) }}"
          {% else %}
            {{ this.state }}
          {% endif %}

Note you will have no way of knowing when this happens or for how long. The availability and graph gap is much more informative.

I’m looking for a best bractise example to define sensors and have read Template - Home Assistant.

Can this example serve as a best practise example for all template sensors? Can I assume that availability is first checked before any calculation in state is performed to avoid throwing errors in the logfiles during startup and such? Shouldn’t there be a default somethere? I’m confused.

Previously, no. But I’m pretty sure that is implemented now.