Skip to content

Commit

Permalink
Ignore utility_meter restore state if state is invalid (home-assistan…
Browse files Browse the repository at this point in the history
…t#57010)

Co-authored-by: Paulus Schoutsen <[email protected]>
  • Loading branch information
dgomes and balloob authored Oct 4, 2021
1 parent 255ffe8 commit 79b10c4
Showing 1 changed file with 24 additions and 13 deletions.
37 changes: 24 additions & 13 deletions homeassistant/components/utility_meter/sensor.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Utility meter from sensors providing raw data."""
from datetime import date, datetime, timedelta
import decimal
from decimal import Decimal, DecimalException
import logging

Expand Down Expand Up @@ -323,19 +324,29 @@ async def async_added_to_hass(self):

state = await self.async_get_last_state()
if state:
self._state = Decimal(state.state)
self._unit_of_measurement = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
self._last_period = (
float(state.attributes.get(ATTR_LAST_PERIOD))
if state.attributes.get(ATTR_LAST_PERIOD)
else 0
)
self._last_reset = dt_util.as_utc(
dt_util.parse_datetime(state.attributes.get(ATTR_LAST_RESET))
)
if state.attributes.get(ATTR_STATUS) == COLLECTING:
# Fake cancellation function to init the meter in similar state
self._collecting = lambda: None
try:
self._state = Decimal(state.state)
except decimal.InvalidOperation:
_LOGGER.error(
"Could not restore state <%s>. Resetting utility_meter.%s",
state.state,
self.name,
)
else:
self._unit_of_measurement = state.attributes.get(
ATTR_UNIT_OF_MEASUREMENT
)
self._last_period = (
float(state.attributes.get(ATTR_LAST_PERIOD))
if state.attributes.get(ATTR_LAST_PERIOD)
else 0
)
self._last_reset = dt_util.as_utc(
dt_util.parse_datetime(state.attributes.get(ATTR_LAST_RESET))
)
if state.attributes.get(ATTR_STATUS) == COLLECTING:
# Fake cancellation function to init the meter in similar state
self._collecting = lambda: None

@callback
def async_source_tracking(event):
Expand Down

0 comments on commit 79b10c4

Please sign in to comment.