Odd custom sensor behaviour

In order to be able to easily change the source sensor of the “battery” in the future without breaking the energy dashboard history, I created a “battery_charged” sensor based on the original one :“battery_total_charge”.

Unfortunately it happens that sometimes the “fake” sensor reports wrong values, in the following example the original at 10:20 reads 26.5 (kWh), while the fake one 19.9. Except then go back to the right measurement, damaging the energy dashboard.

I attached the plotted graphics of both sensor in Grafana and the tables.

Does anyone know why? did I set the fake sensor wrong?

Thanks!

"Fake sensor"

        - name: battery_charged
          unit_of_measurement: "kWh"
          device_class: energy
          state_class: total_increasing
          state: >
             {{ (states('sensor.battery_total_charge')|float(0) )   }}

which is based on sensor.battery_total_charge

Original sensor details

state_class: total
unit_of_measurement: kWh
device_class: energy
icon: mdi:battery-plus-variant
friendly_name: Battery Total charge



Use an availability template to prevent the unavailable states reporting as zero due to your float filter default:

        - name: battery_charged
          unit_of_measurement: "kWh"
          device_class: energy
          state_class: total_increasing
          state: "{{ (states('sensor.battery_total_charge')|float(0) ) }}"
          availability: "{{ (states('sensor.battery_total_charge')|is_number ) }}"
1 Like

Hi!
Thanks Tom!

I added the float because I thought it would be better to “add” zero instead of a wrong value.
Which approach do you think would be the best one?

Without float

        - name: battery_discharged
          unit_of_measurement: "kWh"
          device_class: energy
          state_class: total_increasing
          state: >
             {{ (states('sensor.battery_total_discharge') )   }}

Or float with availability states such as yours?

Do you know if the availabity sensor could be used to check if the “new value” is equal or greater than the last one?

(states(‘sensor.battery_total_charge’)|float(0) >= states.sensor.battery_charged.state|float(0))

Just use it as I posted it. It will fix your issue.