New sensor not working

I have a wemos pro 4 connected to an ultrasonic module to detect the water level in the tank. It works perfectly and gives me the distance from the ultrasonic sensor to the surface of the water.

Now I wanted to transform this distance into percentage 0 - 100% of the tank
I created a sensor that detects the distance and based on a table generates the data in % but it doesn’t work for me. The whole thing is activated by an automation with trigger on the variation of the measurement of the ultrasonic sensor.

The % level sensor always gives me “unknown”

  - platform: template
    sensors:
       tank_fill_percentage:
         friendly_name: "Percentuale Riempimento Serbatoio"
         unit_of_measurement: "%"
         value_template: >-
            {% set distance = state_attr('sensor.tasmota_livello_serbatoi_sr04_distance', 'distance') | float %}

            36: 100,
            46: 90,
            56: 80,
            66: 70,
            76: 60,
            86: 50,
            96: 40,
            106: 30,
            116: 20,
            126: 10,
            136: 0
            # Aggiungi altri valori se necessario
            } %} {% set nearest_distance = capacity_table | map(attribute='key') | map('float') | map('abs') | list | sort | first %} {% set percentage_fill = capacity_table[nearest_distance] %} {{ percentage_fill | default(0) }}

thanks for help
  • The dictionary isn’t being declared as a variable.
  • map("key") is not a valid filter to call on a dictionary. I don’t really get what you were trying to go for in the rest of the definition of nearest_distance.
  • That is not how comments are used in Jinja.
  - platform: template
    sensors:
      tank_fill_percentage:
        friendly_name: "Percentuale Riempimento Serbatoio"
        unit_of_measurement: "%"
        value_template: >-
          {% set distance = state_attr('sensor.tasmota_livello_serbatoi_sr04_distance', 'distance') | int %}
          {% set capacity_table = {
          36: 100, 46: 90, 56: 80,
          66: 70, 76: 60, 86: 50,
          96: 40, 106: 30, 116: 20,
          126: 10, 136: 0 } %} 
          {# Aggiungi altri valori se necessario #}
          {% set nearest_distance = (capacity_table.keys()
          | map('int') | list + [distance]) | sort %}
          {% set dis_ind = nearest_distance.index(distance) %}
          {{ capacity_table.get(nearest_distance[dis_ind+1]) }}
value_template: "{{ (value |float(0) - 136) | abs }}"

Try this. I use it in a similar fashion as you.