@@ -246,6 +246,7 @@ def __init__(
246246
247247 async def async_added_to_hass (self ) -> None :
248248 """When entity is added to hass."""
249+ # Handle the coordinator listeners manually as we have 2
249250 self .async_on_remove (
250251 self .coordinator_sessions .async_add_listener (
251252 self ._handle_sessions_update , None
@@ -257,6 +258,7 @@ async def async_added_to_hass(self) -> None:
257258 )
258259 )
259260
261+ # Stats only run every hour so make sure they run at init
260262 self ._handle_sessions_update ()
261263 self ._handle_statistics_update ()
262264
@@ -272,7 +274,7 @@ def _handle_statistics_update(self) -> None:
272274 self ._stats_state = self .coordinator_statistics .data ['energyChargedTotalWh' ]
273275
274276 # If session not in progress, use the statistics data alone
275- if self .coordinator_sessions .data ["mode" ] == "DISCONNECTED" or self . coordinator_sessions . data [ "mode" ] == "FINISHED_CHARGE" :
277+ if self .coordinator_sessions .data ["mode" ] == "DISCONNECTED" :
276278 _LOGGER .debug (f"Stats: using stats data only" )
277279 self ._state = self ._stats_state
278280 self ._last_updated = utcnow ()
@@ -287,9 +289,14 @@ def _handle_sessions_update(self) -> None:
287289 return
288290
289291 # If session in progress, use statistics + charge data
290- if self ._stats_state and not ( self .coordinator_sessions .data ["mode" ] == "DISCONNECTED" or self . coordinator_sessions . data [ "mode" ] == "FINISHED_CHARGE" ) :
292+ if self ._stats_state and not self .coordinator_sessions .data ["mode" ] == "DISCONNECTED" :
291293 _LOGGER .debug (f"Sessions: using stats + session" )
292- self ._state = self ._stats_state + max (0 , self .coordinator_sessions .data ['batterySoc' ]['wh' ])
294+ # Calculate new state as stats total + session total
295+ new_state = self ._stats_state + max (0 , self .coordinator_sessions .data ['batterySoc' ]['wh' ])
296+
297+ # This tends to go backwards? Make sure it only goes up
298+ self ._state = max (self ._state or 0 , new_state )
299+
293300 self ._last_updated = utcnow ()
294301 self .async_write_ha_state ()
295302
@@ -530,7 +537,7 @@ def icon(self):
530537 def _handle_coordinator_update (self ) -> None :
531538 """Get value from data returned from API by coordinator"""
532539 if self .coordinator .data and self .coordinator .data ['car' ] and self .coordinator .data ['car' ]['batterySoc' ]:
533- self ._state = self .coordinator .data ['car' ]['batterySoc' ]['percent' ]
540+ self ._state = self .coordinator .data ['car' ]['batterySoc' ]['percent' ] or self . coordinator . data [ 'batterySoc' ][ 'percent' ]
534541
535542 self ._last_updated = utcnow ()
536543 self .async_write_ha_state ()
0 commit comments