Skip to content

Commit 79b10c4

Browse files
dgomesballoob
andauthored
Ignore utility_meter restore state if state is invalid (home-assistant#57010)
Co-authored-by: Paulus Schoutsen <[email protected]>
1 parent 255ffe8 commit 79b10c4

File tree

1 file changed

+24
-13
lines changed
  • homeassistant/components/utility_meter

1 file changed

+24
-13
lines changed

homeassistant/components/utility_meter/sensor.py

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Utility meter from sensors providing raw data."""
22
from datetime import date, datetime, timedelta
3+
import decimal
34
from decimal import Decimal, DecimalException
45
import logging
56

@@ -323,19 +324,29 @@ async def async_added_to_hass(self):
323324

324325
state = await self.async_get_last_state()
325326
if state:
326-
self._state = Decimal(state.state)
327-
self._unit_of_measurement = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
328-
self._last_period = (
329-
float(state.attributes.get(ATTR_LAST_PERIOD))
330-
if state.attributes.get(ATTR_LAST_PERIOD)
331-
else 0
332-
)
333-
self._last_reset = dt_util.as_utc(
334-
dt_util.parse_datetime(state.attributes.get(ATTR_LAST_RESET))
335-
)
336-
if state.attributes.get(ATTR_STATUS) == COLLECTING:
337-
# Fake cancellation function to init the meter in similar state
338-
self._collecting = lambda: None
327+
try:
328+
self._state = Decimal(state.state)
329+
except decimal.InvalidOperation:
330+
_LOGGER.error(
331+
"Could not restore state <%s>. Resetting utility_meter.%s",
332+
state.state,
333+
self.name,
334+
)
335+
else:
336+
self._unit_of_measurement = state.attributes.get(
337+
ATTR_UNIT_OF_MEASUREMENT
338+
)
339+
self._last_period = (
340+
float(state.attributes.get(ATTR_LAST_PERIOD))
341+
if state.attributes.get(ATTR_LAST_PERIOD)
342+
else 0
343+
)
344+
self._last_reset = dt_util.as_utc(
345+
dt_util.parse_datetime(state.attributes.get(ATTR_LAST_RESET))
346+
)
347+
if state.attributes.get(ATTR_STATUS) == COLLECTING:
348+
# Fake cancellation function to init the meter in similar state
349+
self._collecting = lambda: None
339350

340351
@callback
341352
def async_source_tracking(event):

0 commit comments

Comments
 (0)