IF and calculations in template sensor

Hello

I’m trying to have a template sensor created that would check if “sensor.solis_dc_power_pv1”
has a value greater than 0 then do a calculation else it would set the sensor to 0

Current code looks like this and it is not working

  - platform: template
    sensors:
      energiayhteiso_test_calc:
        friendly_name: "Test"
        unit_of_measurement: "W"
        device_class: power
        value_template: >-
          {% set excess_power = states('sensor.solis_dc_power_pv1') | float %}
          {% if (('excess_power') >0) %}
          {{ state('excess_power') * 0.0132 }}
          {% else %}
          {{ state('energiayhteiso_test_calc') = 0 }}
          {% endif %}

I’m not surprised. You’re thinking it’s more complicated than it is.

  - platform: template
    sensors:
      energiayhteiso_test_calc:
        friendly_name: "Test"
        unit_of_measurement: "W"
        device_class: power
        value_template: >-
          {% set excess_power = states('sensor.solis_dc_power_pv1') | float(0) %}
          {% if excess_power > 0 %}
            {{ excess_power * 0.0132 }}
          {% else %}
            0
          {% endif %}

You can try this in the Developer Tools / Template editor to check and debug it.

Better to use the modern template sensor format, though, and here with a shorter template that does the same thing:

template:
  - sensor:
      - name: energiayhteiso_test_calc
        unit_of_measurement: "W"
        device_class: power
        value_template: "{{ max(states('sensor.solis_dc_power_pv1')|float(0)*0.0132, 0) }}"

Thank you very much!
Got it working :slight_smile:

@Troon Thank you!
The shorter one also works and is a lot nicer what come sto the code

1 Like