I’m monitoring the EV battery state of charge (SoC) during charging. It’s a BMW and the BMW API only updates the SoC with relatively long intervals, so I’m attempting to estimate the SoC between BMW API updates.
Approach:
Feed charging power to a utility_meter sensor (to get the charging energy) and add that charging energy to the latest API SoC.
When the API SoC changes, reset the utility meter to zero and continue
This works well, but when the API SoC updates, the template sensor acts before the automation has time to reset the utility meter sensor, causing a short duration peak in the estimated SoC sensor:
Do you even need a utility meter and an automation here?
What if the template triggered on both changes to the SoC from the BMW api and also from changes in your power meter.
When the SoC changes you update the state and also store the current power meter reading in an attribute.
And then when the power meter changes you use the difference from current power to what is saved in the attribute to add to the state. Plus, handling the case of the attribute not being set.
I’m intrigued, but to estimate the state of charge, I need to calculate the amount of energy put into the battery - not only the power - and the utility meter path is a straight-forward way to calculate that and at the same time providing an easy way to reset the «delta» energy each time the API SoC updates.
By storing the power and timestamps in attributes and triggering on power changes, I might be able to calculate the delta energy without the utility meter, but I suspect the template sensor will be more complex to configure.
So, I’ll stay with @Troon’s suggested solution for now, but keep your idea in mind. It’s an interesting challenge
It gives the same results as the utility meter, delayed template sensor and automation approach as suggested by @Troon. The yellow line in the graph below is the @Troon style sensor. It hides the blue line which is the @busman style template sensor. The red line is the SoC reported by BMW.
(It would probably have been nicer to calculate delta_percent as a variable as suggested by @busman, but I was confused by a DisallowedExtraPropWarning in the Studio Code Server editor, so it ended up in the state and attribute templates.)
EDIT: On the first attempt, I mixed up the yellow and blue lines in the graph.