Return no data on template if source null

I have a template that converts a ultrasonic sensor’s reading to a water level percentage:

sensor:
  - platform: template
    sensors:
      rainwater_tank_percentage:
        friendly_name: "Rainwater Tank Percentage"
        unit_of_measurement: "%"
        value_template: >-
          {% set total_height = 1.9 %}
          {% set distance = states('sensor.esphome_web_6d522e_water_level')|float(2) %}
          {% set distance_abs = distance - 0.181 |float(2) %}
          {% set fullness = distance_abs / total_height|float(2) %}
          {{ '%.0f' | format((1-fullness)*100) | float(2)}}

The problem is sometimes the ultrasonic esp32 sensor goes offline but the template still creates “data” causing crazy spikes in my graph. Is there a way to return “NULL” if the source is NULL?

The top graph is the calculated “template” and the bottom is the raw ultrasonic sensor, which have gaps, which is good.

template:
  - sensor:
      - name: "Rainwater Tank Percentage"
        unit_of_measurement: "%"
        state_class: measurement
        state: >
          {% set total_height = 1.9 %}
          {% set distance = states('sensor.esphome_web_6d522e_water_level')|float %}
          {% set distance_abs = distance - 0.181 %}
          {% set fullness = distance_abs / total_height %}
          {{ '%.0f' | format((1-fullness)*100) }}
        availability: "{{ has_value('sensor.esphome_web_6d522e_water_level') }}"
1 Like

Thank you kindly, am I right in saying this will only affect future data?

Yes.