|
1 | 1 | """Utility meter from sensors providing raw data."""
|
2 | 2 | from datetime import date, datetime, timedelta
|
| 3 | +import decimal |
3 | 4 | from decimal import Decimal, DecimalException
|
4 | 5 | import logging
|
5 | 6 |
|
@@ -323,19 +324,29 @@ async def async_added_to_hass(self):
|
323 | 324 |
|
324 | 325 | state = await self.async_get_last_state()
|
325 | 326 | 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 |
339 | 350 |
|
340 | 351 | @callback
|
341 | 352 | def async_source_tracking(event):
|
|
0 commit comments