"""Paquet de l'intégration Arkteos.""" from __future__ import annotations from typing import TYPE_CHECKING from .client import ArkteosClient from .const import CONF_HOST, CONF_PORT, DOMAIN, PLATFORMS if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant def _get_client(hass: HomeAssistant, entry: ConfigEntry) -> ArkteosClient | None: """Retourne le client partagé, depuis runtime_data ou le repli structuré.""" client = getattr(entry, "runtime_data", None) if isinstance(client, ArkteosClient): return client return hass.data.get(DOMAIN, {}).get(entry.entry_id) def _store_client(hass: HomeAssistant, entry: ConfigEntry, client: ArkteosClient) -> None: """Stocke le client une fois par config entry.""" if hasattr(entry, "runtime_data"): entry.runtime_data = client return hass.data.setdefault(DOMAIN, {})[entry.entry_id] = client def _remove_client(hass: HomeAssistant, entry: ConfigEntry) -> None: """Supprime les données d'exécution de la config entry.""" if hasattr(entry, "runtime_data"): entry.runtime_data = None domain_data = hass.data.get(DOMAIN) if domain_data is not None: domain_data.pop(entry.entry_id, None) if not domain_data: hass.data.pop(DOMAIN, None) async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Crée et partage le client Arkteos pour cette config entry.""" if _get_client(hass, entry) is not None: return True client = ArkteosClient(entry.data[CONF_HOST], entry.data[CONF_PORT]) _store_client(hass, entry, client) await client.start() try: await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) except Exception: await client.stop() _remove_client(hass, entry) return False return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Décharge les plateformes et arrête le client partagé.""" client = _get_client(hass, entry) if client is None: return True unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if not unload_ok: return False await client.stop() _remove_client(hass, entry) return True