66"""
77
88from typing import Any
9+ import logging
910
1011from victron_mqtt import (
1112 Device as VictronVenusDevice ,
13+ FormulaMetric as VictronFormulaMetric ,
1214 Metric as VictronVenusMetric ,
1315 MetricKind ,
1416)
1517
16- from homeassistant .components .sensor import SensorEntity
18+ from homeassistant .components .sensor import SensorEntity , SensorStateClass
1719from homeassistant .config_entries import ConfigEntry
1820from homeassistant .core import HomeAssistant , callback
1921from homeassistant .helpers .device_registry import DeviceInfo
2022from homeassistant .helpers .entity_platform import AddConfigEntryEntitiesCallback
23+ from homeassistant .helpers .restore_state import RestoreEntity
2124
2225from .entity import VictronBaseEntity
2326from .hub import Hub
2427
28+ _LOGGER = logging .getLogger (__name__ )
2529
2630async def async_setup_entry (
2731 hass : HomeAssistant ,
@@ -53,8 +57,10 @@ def on_new_metric(
5357 hub .register_new_metric_callback (MetricKind .SENSOR , on_new_metric )
5458
5559
56- class VictronSensor (VictronBaseEntity , SensorEntity ):
60+ class VictronSensor (VictronBaseEntity , SensorEntity , RestoreEntity ): # type: ignore[misc]
5761 """Implementation of a Victron Venus sensor."""
62+
63+ _baseline : float | None = None
5864
5965 def __init__ (
6066 self ,
@@ -65,15 +71,48 @@ def __init__(
6571 installation_id : str ,
6672 ) -> None :
6773 """Initialize the sensor."""
68- self ._attr_native_value = metric .value
6974 super ().__init__ (
7075 device , metric , device_info , "sensor" , simple_naming , installation_id
7176 )
7277
73-
7478 @callback
7579 def _on_update_task (self , value : Any ) -> None :
80+ if self ._baseline is not None :
81+ value += self ._baseline
7682 if self ._attr_native_value == value :
7783 return
7884 self ._attr_native_value = value
7985 self .async_write_ha_state ()
86+
87+ async def async_added_to_hass (self ) -> None :
88+ """Restore persistent state for FormulaMetric energy sensors."""
89+
90+ # Only restore for:
91+ # 1. Total increasing sensors (like cumulative energy)
92+ # 2. FormulaMetrics (calculated values)
93+ should_restore = (
94+ self ._attr_state_class in [SensorStateClass .TOTAL_INCREASING , SensorStateClass .TOTAL ]
95+ and isinstance (self ._metric , VictronFormulaMetric )
96+ )
97+ self ._attr_native_value = self ._metric .value
98+ if not should_restore :
99+ # Call parent to register update callbacks
100+ await super ().async_added_to_hass ()
101+ return
102+
103+ last_state = await self .async_get_last_state ()
104+ if last_state is not None and last_state .state is not None :
105+ assert isinstance (self ._attr_native_value , (int , float )), "sensor with stored baseline value must be numeric"
106+ try :
107+ self ._baseline = float (last_state .state )
108+ self ._attr_native_value += self ._baseline
109+ except ValueError :
110+ _LOGGER .warning (
111+ "Could not restore state for %s: invalid value '%s'" ,
112+ self .entity_id ,
113+ last_state .state ,
114+ )
115+ _LOGGER .info ("Restored baseline of %.3f for %s" , self ._baseline , self .entity_id )
116+ # Call parent to register update callbacks
117+ await super ().async_added_to_hass ()
118+
0 commit comments