1 """Coordinator for Tibber sensors."""
3 from __future__
import annotations
5 from datetime
import timedelta
7 from typing
import cast
14 async_add_external_statistics,
16 statistics_during_period,
24 from .const
import DOMAIN
as TIBBER_DOMAIN
26 FIVE_YEARS = 5 * 365 * 24
28 _LOGGER = logging.getLogger(__name__)
32 """Handle Tibber data and insert statistics."""
34 config_entry: ConfigEntry
36 def __init__(self, hass: HomeAssistant, tibber_connection: tibber.Tibber) ->
None:
37 """Initialize the data handler."""
41 name=f
"Tibber {tibber_connection.name}",
47 """Update data via API."""
52 except tibber.RetryableHttpExceptionError
as err:
53 raise UpdateFailed(f
"Error communicating with API ({err.status})")
from err
54 except tibber.FatalHttpExceptionError:
56 self.
hasshass.async_create_task(
57 self.
hasshass.config_entries.async_reload(self.
config_entryconfig_entry.entry_id)
61 """Insert Tibber statistics."""
63 sensors: list[tuple[str, bool, str]] = []
64 if home.hourly_consumption_data:
65 sensors.append((
"consumption",
False, UnitOfEnergy.KILO_WATT_HOUR))
66 sensors.append((
"totalCost",
False, home.currency))
67 if home.hourly_production_data:
68 sensors.append((
"production",
True, UnitOfEnergy.KILO_WATT_HOUR))
69 sensors.append((
"profit",
True, home.currency))
71 for sensor_type, is_production, unit
in sensors:
73 f
"{TIBBER_DOMAIN}:energy_"
74 f
"{sensor_type.lower()}_"
75 f
"{home.home_id.replace('-', '')}"
79 get_last_statistics, self.
hasshass, 1, statistic_id,
True, set()
84 hourly_data = await home.get_historic_data(
85 5 * 365 * 24, production=is_production
89 last_stats_time =
None
96 home.hourly_production_data
98 else home.hourly_consumption_data
101 from_time = dt_util.parse_datetime(hourly_data[0][
"from"])
102 if from_time
is None:
106 statistics_during_period,
115 if statistic_id
in stat:
116 first_stat = stat[statistic_id][0]
117 _sum = cast(float, first_stat[
"sum"])
118 last_stats_time = first_stat[
"start"]
120 hourly_data = await home.get_historic_data(
121 FIVE_YEARS, production=is_production
124 last_stats_time =
None
128 last_stats_time_dt = (
129 dt_util.utc_from_timestamp(last_stats_time)
134 for data
in hourly_data:
135 if data.get(sensor_type)
is None:
138 from_time = dt_util.parse_datetime(data[
"from"])
139 if from_time
is None or (
140 last_stats_time_dt
is not None
141 and from_time <= last_stats_time_dt
145 _sum += data[sensor_type]
150 state=data[sensor_type],
158 name=f
"{home.name} {sensor_type}",
159 source=TIBBER_DOMAIN,
160 statistic_id=statistic_id,
161 unit_of_measurement=unit,
None _async_update_data(self)
None __init__(self, HomeAssistant hass, tibber.Tibber tibber_connection)
None _insert_statistics(self)
None async_add_external_statistics(HomeAssistant hass, StatisticMetaData metadata, Iterable[StatisticData] statistics)
Recorder get_instance(HomeAssistant hass)