How to do sensor math the right way

I have some ESPhome devices which reads data via RS from some hardware. Of course this sensors getting unavailible sometimes, during updates etc.

If i look at the graph of this sensors it looks correct.

Now i need to summarize three sensors, in this case they are in one ESPhome device, but i want a solution to do the math outside of ESPhome, if i want to summarize two sensors from different devices.

So i have do a template like this:

template:
  - sensor:
    - name: 'Moc czynna przyłącze'
      unit_of_measurement: 'kW'
      device_class: power
      state_class: measurement
      state: >
        {% set moc_a = states('sensor.mew_przylacze_a_moc_czynna') | float %}
        {% set moc_b = states('sensor.mew_przylacze_b_moc_czynna') | float %}
        {% set moc_h7 = states('sensor.mew_przylacze_h7_moc_czynna') | float %}
        {% if ((moc_a + moc_b + moc_h7) > -1000) %}
        {{ ( moc_a + moc_b + moc_h7) | round(1) }}
        {% endif %}

It works, but if the sensors are not availible this template returns 0, i dont want “0”, because it create a negative spike in the graph and also shows wrong value.

Can You help me out?

add an availability template to that and you shouldn’t have to touch your template.

      availability: >
        {{ expand('sensor.mew_przylacze_a_moc_czynna', 'sensor.mew_przylacze_b_moc_czynna', 'sensor.mew_przylacze_h7_moc_czynna') | rejectattr('state','is_number') | list | count == 0 }}
1 Like

Thx, this solved the issue.
So now it looks:

template:
  - sensor:
    - name: 'Moc czynna przyłącze'
      unit_of_measurement: 'kW'
      device_class: power
      state_class: measurement
      state: >
        {% set moc_a = states('sensor.mew_przylacze_a_moc_czynna') | float %}
        {% set moc_b = states('sensor.mew_przylacze_b_moc_czynna') | float %}
        {% set moc_h7 = states('sensor.mew_przylacze_h7_moc_czynna') | float %}
        {{ ( moc_a + moc_b + moc_h7) | round(1) }}
      availability: >
        {{ expand('sensor.mew_przylacze_a_moc_czynna', 'sensor.mew_przylacze_b_moc_czynna', 'sensor.mew_przylacze_h7_moc_czynna') | rejectattr('state','is_number') | list | count == 0 }}

Will it render unavailable if any of the sensors failes, or need all sensors to fail?

yes, any sensor that fails will make this unavailable and the calc will not appear in your energy

1 Like

That can be changed too if needed