Skip to content

Commit 629297d

Browse files
committed
Improve restore state logging
1 parent 2d0b462 commit 629297d

2 files changed

Lines changed: 24 additions & 16 deletions

File tree

.vscode/settings.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@
66
"python.testing.pytestEnabled": true,
77
"files.encoding": "utf8",
88
"files.autoGuessEncoding": false,
9-
"files.eol": "\n"
9+
"files.eol": "\n",
10+
"python-envs.defaultEnvManager": "ms-python.python:system"
1011
}

custom_components/victron_mqtt/sensor.py

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)