Calculate Sun Energy - Probably Template or Helper?


is there a way to calculate Sun Energy with a Helper?

I build that in a template, but it has a few Problems, if some counter is NaN or just resets to much :confused:

Any ideas what i can do, that i just get a number there and its just growing up and not starting from 0 again or double the number after a yaml restart or so?

- sensor:
  - name: 'solarcalculation'
    device_class: energy
    unit_of_measurement: kWh
    state_class: total
    state: >
      {% if is_number(states('sensor.solarcalculation')) and is_number(states('sensor.hauseinspeisung_heute')) and is_number(states('sensor.akku_geladen_heute')) and is_number(states('sensor.akku_entnommen_heute')) %}
          {% set new_state = (states('sensor.hauseinspeisung_heute')|float + states('sensor.akku_geladen_heute')|float) - states('sensor.akku_entnommen_heute')|float %}
          {% if new_state >= states('sensor.solarcalculation')|float %}
            {{ new_state }}
          {% else %}
            {{ states('sensor.solarcalculation')|float }}
          {% endif %}
      {% else %}
      {% endif %}

I have two Sensor that puts sunenergy in, and one grabbing it out, so i need to calculate two together and the from the sum i need to subtract the “akku_entnommen_heute”.

But if one is NaN, it goes to 0, if i dont write 0 in else, i get NaN also in solarcalculation, which is bad. It is okay if some of the sensors is NaN, but i need a growing number out of the solarcalculation