96 lines
2.9 KiB
Python
96 lines
2.9 KiB
Python
"""SolarEdge Optimizers integration."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import timedelta
|
|
|
|
from homeassistant.config_entries import ConfigEntry
|
|
from homeassistant.const import CONF_URL, Platform
|
|
from homeassistant.core import HomeAssistant
|
|
from homeassistant.helpers import device_registry as dr
|
|
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
|
|
|
from .api import SolarEdgeOptimizerApiClient
|
|
from .const import (
|
|
CONF_SCAN_INTERVAL,
|
|
CONFIG_ENTRY_VERSION,
|
|
DEFAULT_SCAN_INTERVAL,
|
|
DOMAIN,
|
|
LOGGER,
|
|
)
|
|
from .coordinator import SolarEdgeOptimizerCoordinator
|
|
|
|
PLATFORMS = [Platform.SENSOR]
|
|
type SolarEdgeOptimizerConfigEntry = ConfigEntry[SolarEdgeOptimizerCoordinator]
|
|
|
|
|
|
async def async_migrate_entry(
|
|
hass: HomeAssistant, entry: SolarEdgeOptimizerConfigEntry
|
|
) -> bool:
|
|
"""Migrate optimizer devices to one site device."""
|
|
if entry.version > CONFIG_ENTRY_VERSION:
|
|
LOGGER.error(
|
|
"Cannot migrate config entry from version %s to %s",
|
|
entry.version,
|
|
CONFIG_ENTRY_VERSION,
|
|
)
|
|
return False
|
|
|
|
if entry.version < 2:
|
|
site_id = entry.unique_id
|
|
if site_id:
|
|
device_registry = dr.async_get(hass)
|
|
legacy_prefix = f"{site_id}_"
|
|
for device in dr.async_entries_for_config_entry(
|
|
device_registry, entry.entry_id
|
|
):
|
|
if any(
|
|
domain == DOMAIN and identifier.startswith(legacy_prefix)
|
|
for domain, identifier in device.identifiers
|
|
):
|
|
device_registry.async_remove_device(device.id)
|
|
|
|
hass.config_entries.async_update_entry(
|
|
entry,
|
|
version=CONFIG_ENTRY_VERSION,
|
|
)
|
|
|
|
return True
|
|
|
|
|
|
async def async_setup_entry(
|
|
hass: HomeAssistant, entry: SolarEdgeOptimizerConfigEntry
|
|
) -> bool:
|
|
"""Set up SolarEdge Optimizers from a config entry."""
|
|
scan_seconds = entry.data.get(
|
|
CONF_SCAN_INTERVAL, int(DEFAULT_SCAN_INTERVAL.total_seconds())
|
|
)
|
|
client = SolarEdgeOptimizerApiClient(
|
|
entry.data[CONF_URL], async_get_clientsession(hass)
|
|
)
|
|
coordinator = SolarEdgeOptimizerCoordinator(
|
|
hass,
|
|
client,
|
|
timedelta(seconds=scan_seconds),
|
|
)
|
|
await coordinator.async_config_entry_first_refresh()
|
|
|
|
entry.runtime_data = coordinator
|
|
entry.async_on_unload(entry.add_update_listener(_async_reload_entry))
|
|
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
|
return True
|
|
|
|
|
|
async def async_unload_entry(
|
|
hass: HomeAssistant, entry: SolarEdgeOptimizerConfigEntry
|
|
) -> bool:
|
|
"""Unload a config entry."""
|
|
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
|
|
|
|
|
async def _async_reload_entry(
|
|
hass: HomeAssistant, entry: SolarEdgeOptimizerConfigEntry
|
|
) -> None:
|
|
"""Reload after the entry is reconfigured."""
|
|
await hass.config_entries.async_reload(entry.entry_id)
|