@@ -131,9 +131,9 @@ def _normalize_value(value: Any) -> Any:
131131 async def async_added_to_hass (self ) -> None :
132132 """Restore persistent state for FormulaMetric energy sensors."""
133133
134- # Only restore for:
135- # 1. Total increasing sensors (like cumulative energy)
136- # 2. FormulaMetrics (calculated values)
134+ # Only restore for cumulative FormulaMetric sensors (TOTAL / TOTAL_INCREASING).
135+ # These metrics start from 0 on each HA restart, so we restore the
136+ # previous accumulated value as a baseline and add new increments on top.
137137 should_restore = self .state_class in [
138138 SensorStateClass .TOTAL_INCREASING ,
139139 SensorStateClass .TOTAL ,
@@ -145,23 +145,29 @@ async def async_added_to_hass(self) -> None:
145145 return
146146
147147 last_state = await self .async_get_last_state ()
148- if last_state is None or last_state .state in (None , "unknown" ):
148+ if last_state is None or last_state .state in (None , "unknown" , "unavailable" ):
149149 await super ().async_added_to_hass ()
150150 _LOGGER .info (
151- "Baseline is missing. Probably first load for %s" , self .entity_id
152- )
151+ "Baseline is missing. Probably first load for %s" , self .entity_id
152+ )
153+ return
154+
155+ if not isinstance (self ._attr_native_value , int | float ):
156+ _LOGGER .warning (
157+ "Cannot restore baseline for %s: current value is %r (expected numeric)" ,
158+ self .entity_id ,
159+ self ._attr_native_value ,
160+ )
161+ await super ().async_added_to_hass ()
153162 return
154163
155- assert isinstance (self ._attr_native_value , (int , float )), (
156- "sensor with stored baseline value must be numeric"
157- )
158164 try :
159165 self ._baseline = float (last_state .state )
160166 self ._attr_native_value += self ._baseline
161167 _LOGGER .info (
162168 "Restored baseline of %.3f for %s" , self ._baseline , self .entity_id
163169 )
164- except ValueError :
170+ except ( ValueError , TypeError ) :
165171 _LOGGER .warning (
166172 "Could not restore state for %s: invalid value '%s' (type: %s)" ,
167173 self .entity_id ,
0 commit comments