improve history_stats accuracy (#6294)

This commit is contained in:
Boris K 2017-02-28 04:52:10 +01:00 committed by Paulus Schoutsen
parent 7ee75d67c5
commit d7bf3920a5
2 changed files with 18 additions and 6 deletions

View File

@ -187,6 +187,12 @@ class HistoryStatsSensor(Entity):
last_state = current_state last_state = current_state
last_time = current_time last_time = current_time
# Count time elapsed between last history state and end of measure
if last_state:
measure_end = min(dt_util.as_timestamp(end), dt_util.as_timestamp(
datetime.datetime.now()))
elapsed += measure_end - last_time
# Save value in hours # Save value in hours
self.value = elapsed / 3600 self.value = elapsed / 3600

View File

@ -71,13 +71,19 @@ class TestHistoryStatsSensor(unittest.TestCase):
def test_measure(self): def test_measure(self):
"""Test the history statistics sensor measure.""" """Test the history statistics sensor measure."""
later = dt_util.utcnow() - timedelta(seconds=15) t0 = dt_util.utcnow() - timedelta(minutes=40)
earlier = later - timedelta(minutes=30) t1 = t0 + timedelta(minutes=20)
t2 = dt_util.utcnow() - timedelta(minutes=10)
# Start t0 t1 t2 End
# |--20min--|--20min--|--10min--|--10min--|
# |---off---|---on----|---off---|---on----|
fake_states = { fake_states = {
'binary_sensor.test_id': [ 'binary_sensor.test_id': [
ha.State('binary_sensor.test_id', 'on', last_changed=earlier), ha.State('binary_sensor.test_id', 'on', last_changed=t0),
ha.State('binary_sensor.test_id', 'off', last_changed=later), ha.State('binary_sensor.test_id', 'off', last_changed=t1),
ha.State('binary_sensor.test_id', 'on', last_changed=t2),
] ]
} }
@ -97,8 +103,8 @@ class TestHistoryStatsSensor(unittest.TestCase):
sensor1.update() sensor1.update()
sensor2.update() sensor2.update()
self.assertEqual(sensor1.value, 0.5) self.assertEqual(round(sensor1.value, 3), 0.5)
self.assertEqual(sensor2.value, 0) self.assertEqual(round(sensor2.value, 3), 0)
self.assertEqual(sensor1.device_state_attributes['ratio'], '50.0%') self.assertEqual(sensor1.device_state_attributes['ratio'], '50.0%')
def test_wrong_date(self): def test_wrong_date(self):