72 lines
2.8 KiB
Python
72 lines
2.8 KiB
Python
import logging
|
|
from homeassistant.core import HomeAssistant
|
|
from homeassistant.helpers import device_registry as dr
|
|
from .const import DOMAIN
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
async def async_setup(hass: HomeAssistant, config: dict):
|
|
return True
|
|
|
|
async def async_setup_entry(hass: HomeAssistant, entry):
|
|
"""Set up entry, create devices, and clean up old orphaned devices."""
|
|
hass.data.setdefault(DOMAIN, {})
|
|
hass.data[DOMAIN][entry.entry_id] = entry.data
|
|
|
|
device_registry = dr.async_get(hass)
|
|
|
|
# 1. Automatisches Aufräumen von alten Geister-Geräten
|
|
active_entry_ids = set(hass.config_entries.async_entries(DOMAIN))
|
|
active_ids = {e.entry_id for e in active_entry_ids}
|
|
|
|
# Durchsuche die HA-Datenbank nach Geräten unserer Integration
|
|
devices_to_clean = [
|
|
dev for dev in device_registry.devices.values()
|
|
if any(identifier[0] == DOMAIN for identifier in dev.identifiers)
|
|
]
|
|
|
|
for device in devices_to_clean:
|
|
# Falls ein Gerät zu einem gelöschten Config Entry gehört -> Löschen!
|
|
# Der globale Hub ("global_bridge_hub") wird ignoriert und bleibt erhalten.
|
|
for config_id in device.config_entries:
|
|
if config_id not in active_ids and not any(idx == "global_bridge_hub" for _, idx in device.identifiers):
|
|
_LOGGER.info(f"Entferne verwaistes WhatsApp-Gerät: {device.name}")
|
|
device_registry.async_remove_device(device.id)
|
|
|
|
# 2. Eigenes Gerät SPEZIFISCH für dieses aktive Konto anlegen
|
|
device_registry.async_get_or_create(
|
|
config_entry_id=entry.entry_id,
|
|
identifiers={(DOMAIN, entry.entry_id)},
|
|
name=f"WhatsApp {entry.title}",
|
|
manufacturer="Bahmcloud",
|
|
model="Kontakt-Endpunkt",
|
|
sw_version="0.2.4",
|
|
)
|
|
|
|
# 3. Zentralen System-Hub anlegen mit erzwungener config_entry_id Bindung (HA Core Anforderung)
|
|
# Nutzt Multi-Entry-Zusammenführung über den fixen "global_bridge_hub" Identifier.
|
|
device_registry.async_get_or_create(
|
|
config_entry_id=entry.entry_id,
|
|
identifiers={(DOMAIN, "global_bridge_hub")},
|
|
name="WhatsApp Bridge Hub",
|
|
manufacturer="Bahmcloud",
|
|
model="Bridge Server",
|
|
sw_version="0.2.4",
|
|
)
|
|
|
|
# Forward the setup to the sensor platform to create entities
|
|
await hass.config_entries.async_forward_entry_setups(entry, ["sensor"])
|
|
|
|
# Registriere den Service (nur beim ersten Mal)
|
|
if not hass.services.has_service(DOMAIN, "send_message"):
|
|
from .services import async_setup_services
|
|
await async_setup_services(hass)
|
|
|
|
return True
|
|
|
|
async def async_unload_entry(hass: HomeAssistant, entry):
|
|
"""Unload a config entry."""
|
|
unload_ok = await hass.config_entries.async_unload_platforms(entry, ["sensor"])
|
|
if unload_ok:
|
|
hass.data[DOMAIN].pop(entry.entry_id)
|
|
return unload_ok |