How to Avoid Custom Sensor Spikes

Hi there,

I am new to HA and working on custom sensors and templates. One problem that seems to pop up every now and then is that the sensor history shows spikes. I assume that when it calculated, one of the variables or other referenced sensors was unavailable or something and so depending on the calculations, the sensor either spikes to a very high value or it drops to zero, but only for a moment and within seconds it comes back to normal.

Here is an example of the graph:

And this is the code for that sensor:

    current_total_solar_production:
      friendly_name: "Current Solar Production"
      unit_of_measurement: "kWh"
      value_template: "{{((states('sensor.inverter_pv1_power') | float | default(0) + states('sensor.inverter_pv2_power') | float | default(0)) / 1000 ) | round(2)}}"

How can I handle this to avoid these spikes? I can’t seem to find a way to handle exceptions in sensors (like TRY-CATCH) - any suggestions?

Thanks
David

You appear to have the wrong unit. kWh is a measure of energy not power. You should use kW.

You can add an availability template to avoid the spikes. And float(0) is equivalent to |float | default(0)

    current_total_solar_production:
      friendly_name: "Current Solar Production"
      unit_of_measurement: "kW"
      value_template: "{{((states('sensor.inverter_pv1_power') | float(0) + states('sensor.inverter_pv2_power') | float(0)) / 1000 ) | round(2)}}"
      availability_template: "{{ states('sensor.inverter_pv1_power') | is_number and states('sensor.inverter_pv2_power') | is_number }}"

You should really be using the new format for template sensors which would be:

configuration.yaml

template:
  sensor
    - name: "Current Total Solar Production"
      unit_of_measurement: "kW"
      state_class: measurement
      device_class: power
      state: "{{ ((states('sensor.inverter_pv1_power') | float(0) + states('sensor.inverter_pv2_power') | float(0)) / 1000 ) | round(2) }}"
      availability: "{{ states('sensor.inverter_pv1_power') | is_number and states('sensor.inverter_pv2_power') | is_number }}"
1 Like

Wow this is very helpful - thank you! I know it’s basic stuff but like I said I am learning, so this will set my path in a better direction going forward :slight_smile: And yes, I should have been using kW instead of kWh - thanks for pointing that out

1 Like