From 3a78f1fce6cbb6b41c465536a4991aa6feff7d02 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Tue, 17 Aug 2021 23:05:31 +0200 Subject: [PATCH] Force STATE_CLASS_TOTAL_INCREASING to reset to 0 (#54751) * Force STATE_CLASS_TOTAL_INCREASING to reset to 0 * Tweak * Correct detection of new cycle * Fix typing --- homeassistant/components/sensor/recorder.py | 8 ++++++-- tests/components/sensor/test_recorder.py | 4 ++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/sensor/recorder.py b/homeassistant/components/sensor/recorder.py index 66366934d27..48f80bab5c2 100644 --- a/homeassistant/components/sensor/recorder.py +++ b/homeassistant/components/sensor/recorder.py @@ -308,7 +308,7 @@ def compile_statistics( elif old_state is None and last_reset is None: reset = True elif state_class == STATE_CLASS_TOTAL_INCREASING and ( - old_state is None or fstate < old_state + old_state is None or (new_state is not None and fstate < new_state) ): reset = True @@ -319,7 +319,11 @@ def compile_statistics( # ..and update the starting point new_state = fstate old_last_reset = last_reset - old_state = new_state + # Force a new cycle for STATE_CLASS_TOTAL_INCREASING to start at 0 + if state_class == STATE_CLASS_TOTAL_INCREASING and old_state: + old_state = 0 + else: + old_state = new_state else: new_state = fstate diff --git a/tests/components/sensor/test_recorder.py b/tests/components/sensor/test_recorder.py index 45d81e4b678..d4dee872823 100644 --- a/tests/components/sensor/test_recorder.py +++ b/tests/components/sensor/test_recorder.py @@ -383,7 +383,7 @@ def test_compile_hourly_sum_statistics_total_increasing( "min": None, "last_reset": None, "state": approx(factor * seq[5]), - "sum": approx(factor * 40.0), + "sum": approx(factor * 50.0), }, { "statistic_id": "sensor.test1", @@ -393,7 +393,7 @@ def test_compile_hourly_sum_statistics_total_increasing( "min": None, "last_reset": None, "state": approx(factor * seq[8]), - "sum": approx(factor * 70.0), + "sum": approx(factor * 80.0), }, ] }