Fix 0 value when home-assistant restarts (#12874)

This commit is contained in:
Boris K 2018-03-03 22:59:25 +01:00 committed by Pascal Vizeli
parent f0d9844dfb
commit 95176b0666
2 changed files with 12 additions and 5 deletions

View File

@ -106,8 +106,8 @@ class HistoryStatsSensor(Entity):
self._unit_of_measurement = UNITS[sensor_type]
self._period = (datetime.datetime.now(), datetime.datetime.now())
self.value = 0
self.count = 0
self.value = None
self.count = None
def force_refresh(*args):
"""Force the component to refresh."""
@ -127,6 +127,9 @@ class HistoryStatsSensor(Entity):
@property
def state(self):
"""Return the state of the sensor."""
if self.value is None or self.count is None:
return None
if self._type == CONF_TYPE_TIME:
return round(self.value, 2)
@ -149,6 +152,9 @@ class HistoryStatsSensor(Entity):
@property
def device_state_attributes(self):
"""Return the state attributes of the sensor."""
if self.value is None:
return {}
hsh = HistoryStatsHelper
return {
ATTR_VALUE: hsh.pretty_duration(self.value),

View File

@ -4,6 +4,7 @@ from datetime import timedelta
import unittest
from unittest.mock import patch
from homeassistant.const import STATE_UNKNOWN
from homeassistant.setup import setup_component
from homeassistant.components.sensor.history_stats import HistoryStatsSensor
import homeassistant.core as ha
@ -43,8 +44,8 @@ class TestHistoryStatsSensor(unittest.TestCase):
self.assertTrue(setup_component(self.hass, 'sensor', config))
state = self.hass.states.get('sensor.test').as_dict()
self.assertEqual(state['state'], '0')
state = self.hass.states.get('sensor.test')
self.assertEqual(state.state, STATE_UNKNOWN)
def test_period_parsing(self):
"""Test the conversion from templates to period."""
@ -132,7 +133,7 @@ class TestHistoryStatsSensor(unittest.TestCase):
sensor4.update()
self.assertEqual(sensor1.state, 0.5)
self.assertEqual(sensor2.state, 0)
self.assertEqual(sensor2.state, None)
self.assertEqual(sensor3.state, 2)
self.assertEqual(sensor4.state, 50)