Calculating value from a few sources doesn't work into template

Hi,

I’ve very frustrating issue (or it’s lack of my knowledge) - I can’t calculate total value from three sensors (3 phases). I need to calculate total imported power as one value. I tried to use template as below:

- sensor:
  - name: Total energy import
    unit_of_measurement: "kWh"
    device_class: energy
    state: >   
        {% set state =  (
                        (states('sensor.sdm630_energy_total_0') | float(0)) +
                        (states('sensor.sdm630_energy_total_1') | float(0)) +
                        (states('sensor.sdm630_energy_total_2_2') | float(0)) 
                        )
        %}

But the result of calculation is still 0 (zero):

image

Of course, particular variables for phases are available and visible:

type: vertical-stack
cards:
  - type: entities
    entities:
      - entity: sensor.sdm630_energy_total_0
      - entity: sensor.sdm630_energy_total_1
      - entity: sensor.sdm630_energy_total_2_2
      - entity: sensor.total_energy_import
    title: Imported Energy
    state_color: false
    show_header_toggle: true

Where the problem is? I used similar method in older HA version using value_template directive but in new HA this is not usable…

I’m using Home Assistant Core 2023.1.7, Frontend 20230110.0 - latest

Best Regards,
pancio

- sensor:
  - name: Total energy import
    unit_of_measurement: "kWh"
    device_class: energy
    state: >   
        {{
          states('sensor.sdm630_energy_total_0') | float(0) +
          states('sensor.sdm630_energy_total_1') | float(0) +
          states('sensor.sdm630_energy_total_2_2') | float(0)         
        }}
    availability: >   
        {{
          states('sensor.sdm630_energy_total_0') | is_number and
          states('sensor.sdm630_energy_total_1') | is_number and
          states('sensor.sdm630_energy_total_2_2') | is_number                
        }}

Many thanks! @tom_l,
Now my sensor return good value.

I understand, I had syntax issue with ‘set state’ or other?
Is the availability directive use to avoid visible when particular sensor not exist or has undefined state?

Best Regards,

Yes compare your template to mine.

You could also have done this:

    state: >   
        {% set state =  (
                        (states('sensor.sdm630_energy_total_0') | float(0)) +
                        (states('sensor.sdm630_energy_total_1') | float(0)) +
                        (states('sensor.sdm630_energy_total_2_2') | float(0)) 
                        )
        %}
        {{ state }}

But it is a bit redundant. The main take-away is:

Also yes, the availability template will make the state unavailable if one or more of your source sensors are unavailable.