Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The pvpc_hourly_pricing integration to collect Spain official electric prices."""
2 
3 from homeassistant.config_entries import ConfigEntry
4 from homeassistant.const import CONF_API_TOKEN, Platform
5 from homeassistant.core import HomeAssistant
7 
8 from .const import ATTR_POWER, ATTR_POWER_P3, DOMAIN
9 from .coordinator import ElecPricesDataUpdateCoordinator
10 from .helpers import get_enabled_sensor_keys
11 
12 PLATFORMS: list[Platform] = [Platform.SENSOR]
13 
14 
15 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
16  """Set up pvpc hourly pricing from a config entry."""
17  entity_registry = er.async_get(hass)
18  sensor_keys = get_enabled_sensor_keys(
19  using_private_api=entry.data.get(CONF_API_TOKEN) is not None,
20  entries=er.async_entries_for_config_entry(entity_registry, entry.entry_id),
21  )
22  coordinator = ElecPricesDataUpdateCoordinator(hass, entry, sensor_keys)
23  await coordinator.async_config_entry_first_refresh()
24 
25  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
26  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
27  entry.async_on_unload(entry.add_update_listener(async_update_options))
28  return True
29 
30 
31 async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
32  """Handle options update."""
33  if any(
34  entry.data.get(attrib) != entry.options.get(attrib)
35  for attrib in (ATTR_POWER, ATTR_POWER_P3, CONF_API_TOKEN)
36  ):
37  # update entry replacing data with new options
38  hass.config_entries.async_update_entry(
39  entry, data={**entry.data, **entry.options}
40  )
41  await hass.config_entries.async_reload(entry.entry_id)
42 
43 
44 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
45  """Unload a config entry."""
46  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
47  if unload_ok:
48  hass.data[DOMAIN].pop(entry.entry_id)
49  return unload_ok
set[str] get_enabled_sensor_keys(bool using_private_api, list[RegistryEntry] entries)
Definition: helpers.py:28
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:15
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:44
None async_update_options(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:31