Template sensor working in the template section but not in the dashboard

What is wrong here?

from configuration.yaml


  - platform: template
    sensors:
      pompa_di_calore_on:
       value_template: >
        {% if states('sensor.shelly3em_potenza_totale')|float > 200 %}
          1
        {% else %}
          0
        {% endif %}


  - platform: history_stats
    name: Duty Cycle Pompa di Calore
    entity_id: sensor.pompa_di_calore_on
    state: "1"
    type: time
    start: "{{ now() - timedelta(hours=24) }}"
    duration:
      hours: 24
  - platform: template
    sensors:
      duty_cycle_percentage:
        unit_of_measurement: "%"
        value_template: >
          {% set total_time = 60 * 60 %}  # 1 ora in secondi
          {% set on_time = states('sensor.duty_cycle_pompa_di_calore')|float * 60 %}  # Tempo acceso in secondi
          {{(on_time / total_time * 100) | round(2)|float}}

image

You cannot use YAML comments n Jinja templates.

e.g. change

to

{% set total_time = 60 * 60 %}  {# 1 ora in secondi #}

I was getting there @tom_l:smile:

@jacoscar

I’m a little confused by the math you are using for the template sensor.

Your source sensor duty_cycle_pompa_di_calore is the number of hours over the past 24 hours that the pump has been running.

The second line of the template is converting the source value into minutes of runtime, not seconds. So you are ending up with a unit of % min/sec…?

  - platform: template
    sensors:
      duty_cycle_percentage:
        unit_of_measurement: "%"
        value_template: >
          {# Tempo acceso in ore #}
          {% set on_time = states('sensor.duty_cycle_pompa_di_calore') | float(0) %}
          {# Percentuale di tempo acceso per 24 ore #}
          {{ ((on_time / 24) * 100) | round(2) }}

FWIW, the History Stats sensor supports doing this automatically if you use the ratio type:

  - platform: history_stats
    name: Duty Cycle Pompa di Calore
    entity_id: sensor.pompa_di_calore_on
    state: "1"
    type: ratio
    start: "{{ now() - timedelta(hours=24) }}"
    duration:
      hours: 24

Thanks, yes, I just noticed that; it was originally built using ChatGPT and the example was calculating the duty cycle in the last hour rather than 24h.
Removing the comments did the trick, thanks everyone!