Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """DataUpdateCoordinator for the Forecast.Solar integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 
7 from forecast_solar import Estimate, ForecastSolar, ForecastSolarConnectionError
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers.aiohttp_client import async_get_clientsession
13 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
14 
15 from .const import (
16  CONF_AZIMUTH,
17  CONF_DAMPING_EVENING,
18  CONF_DAMPING_MORNING,
19  CONF_DECLINATION,
20  CONF_INVERTER_SIZE,
21  CONF_MODULES_POWER,
22  DOMAIN,
23  LOGGER,
24 )
25 
26 
28  """The Forecast.Solar Data Update Coordinator."""
29 
30  config_entry: ConfigEntry
31 
32  def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
33  """Initialize the Forecast.Solar coordinator."""
34  self.config_entryconfig_entryconfig_entry = entry
35 
36  # Our option flow may cause it to be an empty string,
37  # this if statement is here to catch that.
38  api_key = entry.options.get(CONF_API_KEY) or None
39 
40  if (
41  inverter_size := entry.options.get(CONF_INVERTER_SIZE)
42  ) is not None and inverter_size > 0:
43  inverter_size = inverter_size / 1000
44 
45  self.forecastforecast = ForecastSolar(
46  api_key=api_key,
47  session=async_get_clientsession(hass),
48  latitude=entry.data[CONF_LATITUDE],
49  longitude=entry.data[CONF_LONGITUDE],
50  declination=entry.options[CONF_DECLINATION],
51  azimuth=(entry.options[CONF_AZIMUTH] - 180),
52  kwp=(entry.options[CONF_MODULES_POWER] / 1000),
53  damping_morning=entry.options.get(CONF_DAMPING_MORNING, 0.0),
54  damping_evening=entry.options.get(CONF_DAMPING_EVENING, 0.0),
55  inverter=inverter_size,
56  )
57 
58  # Free account have a resolution of 1 hour, using that as the default
59  # update interval. Using a higher value for accounts with an API key.
60  update_interval = timedelta(hours=1)
61  if api_key is not None:
62  update_interval = timedelta(minutes=30)
63 
64  super().__init__(hass, LOGGER, name=DOMAIN, update_interval=update_interval)
65 
66  async def _async_update_data(self) -> Estimate:
67  """Fetch Forecast.Solar estimates."""
68  try:
69  return await self.forecastforecast.estimate()
70  except ForecastSolarConnectionError as error:
71  raise UpdateFailed(error) from error
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)