"""device_tracker: каждое устройство из инвентаря хаба.""" from __future__ import annotations import logging from homeassistant.components.device_tracker import ScannerEntity, SourceType from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: coordinator = hass.data[DOMAIN][entry.entry_id] known: set[str] = set() @callback def _add_new() -> None: new_entities = [] for key, dev in (coordinator.data or {}).items(): uid = f"{DOMAIN}_{key}" if uid in known: continue known.add(uid) new_entities.append(HubDevice(coordinator, key, dev)) _LOGGER.warning("hub_devices: добавляю сущностей %s", len(new_entities)) if new_entities: async_add_entities(new_entities, update_before_add=False) _LOGGER.warning("hub_devices: платформа запущена, устройств в данных: %s", len(coordinator.data or {})) _add_new() coordinator.async_add_listener(_add_new) class HubDevice(CoordinatorEntity, ScannerEntity): """Устройство сети как трекер присутствия.""" _attr_source_type = SourceType.ROUTER _attr_entity_registry_enabled_default = True def __init__(self, coordinator, key: str, dev: dict) -> None: super().__init__(coordinator) self._key = key self._dev = dev self._attr_unique_id = f"{DOMAIN}_{key}" self._attr_name = dev.get("name") or dev.get("ip") or key self._attr_mac_address = dev.get("mac") or None @property def _current(self) -> dict: return (self.coordinator.data or {}).get(self._key, self._dev) @property def is_connected(self) -> bool: return bool(self._current.get("online")) @property def ip_address(self) -> str | None: return self._current.get("ip") or None @property def extra_state_attributes(self) -> dict: cur = self._current return { "тип": cur.get("type"), "бренд": cur.get("vendor"), "mac": cur.get("mac"), "ip": cur.get("ip"), }