From 830e8d7b946c1e7c37509884e60c82b9c21974e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Hjelseth=20H=C3=B8yer?= Date: Wed, 24 Apr 2024 20:00:06 +0200 Subject: [PATCH] Fix statistic bug in Tibber sensor (#116112) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Handle keyError in Tibber sensor Signed-off-by: Daniel Hjelseth Høyer * Constant Signed-off-by: Daniel Hjelseth Høyer --------- Signed-off-by: Daniel Hjelseth Høyer --- homeassistant/components/tibber/sensor.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/tibber/sensor.py b/homeassistant/components/tibber/sensor.py index da2fd881a5446..7da0a2b794772 100644 --- a/homeassistant/components/tibber/sensor.py +++ b/homeassistant/components/tibber/sensor.py @@ -53,6 +53,8 @@ from .const import DOMAIN as TIBBER_DOMAIN, MANUFACTURER +FIVE_YEARS = 5 * 365 * 24 + _LOGGER = logging.getLogger(__name__) ICON = "mdi:currency-usd" @@ -724,9 +726,16 @@ async def _insert_statistics(self) -> None: None, {"sum"}, ) - first_stat = stat[statistic_id][0] - _sum = cast(float, first_stat["sum"]) - last_stats_time = first_stat["start"] + if statistic_id in stat: + first_stat = stat[statistic_id][0] + _sum = cast(float, first_stat["sum"]) + last_stats_time = first_stat["start"] + else: + hourly_data = await home.get_historic_data( + FIVE_YEARS, production=is_production + ) + _sum = 0.0 + last_stats_time = None statistics = []