@@ -102,21 +102,28 @@ async def async_added_to_hass(self) -> None:
102102 return
103103
104104 last_state = await self .async_get_last_state ()
105- if last_state is not None and last_state .state is not None :
106- assert isinstance (self ._attr_native_value , (int , float )), (
107- "sensor with stored baseline value must be numeric"
108- )
109- try :
110- self ._baseline = float (last_state .state )
111- self ._attr_native_value += self ._baseline
112- _LOGGER .info (
113- "Restored baseline of %.3f for %s" , self ._baseline , self .entity_id
114- )
115- except ValueError :
116- _LOGGER .warning (
117- "Could not restore state for %s: invalid value '%s'" ,
118- self .entity_id ,
119- last_state .state ,
105+ if last_state is None or last_state .state in (None , "unknown" ):
106+ await super ().async_added_to_hass ()
107+ _LOGGER .info (
108+ "Baseline is missing. Probably first load for %s" , self .entity_id
120109 )
110+ return
111+
112+ assert isinstance (self ._attr_native_value , (int , float )), (
113+ "sensor with stored baseline value must be numeric"
114+ )
115+ try :
116+ self ._baseline = float (last_state .state )
117+ self ._attr_native_value += self ._baseline
118+ _LOGGER .info (
119+ "Restored baseline of %.3f for %s" , self ._baseline , self .entity_id
120+ )
121+ except ValueError :
122+ _LOGGER .warning (
123+ "Could not restore state for %s: invalid value '%s' (type: %s)" ,
124+ self .entity_id ,
125+ last_state .state ,
126+ type (last_state .state ).__name__ ,
127+ )
121128 # Call parent to register update callbacks
122129 await super ().async_added_to_hass ()
0 commit comments