added coordinator for device tracker

This commit is contained in:
Tomaae 2023-08-09 23:00:00 +02:00
parent ebee5a34e2
commit efe3de0c20
No known key found for this signature in database
GPG key ID: 2F97770867DAA4E6
4 changed files with 658 additions and 475 deletions

View file

@ -13,7 +13,7 @@ from .const import (
DOMAIN, DOMAIN,
RUN_SCRIPT_COMMAND, RUN_SCRIPT_COMMAND,
) )
from .coordinator import MikrotikCoordinator from .coordinator import MikrotikData, MikrotikCoordinator, MikrotikTrackerCoordinator
SCRIPT_SCHEMA = vol.Schema( SCRIPT_SCHEMA = vol.Schema(
{vol.Required("router"): cv.string, vol.Required("script"): cv.string} {vol.Required("router"): cv.string, vol.Required("script"): cv.string}
@ -27,7 +27,13 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
"""Set up a config entry.""" """Set up a config entry."""
coordinator = MikrotikCoordinator(hass, config_entry) coordinator = MikrotikCoordinator(hass, config_entry)
await coordinator.async_config_entry_first_refresh() await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})[config_entry.entry_id] = coordinator coordinatorTracker = MikrotikTrackerCoordinator(hass, config_entry, coordinator)
await coordinatorTracker.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})[config_entry.entry_id] = MikrotikData(
data_coordinator=coordinator,
tracker_coordinator=coordinatorTracker,
)
# hass.data.setdefault(DOMAIN, {})[config_entry.entry_id]["coordinator"] = coordinator
await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS) await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)

File diff suppressed because it is too large Load diff

View file

@ -8,17 +8,24 @@ from typing import Any
from homeassistant.components.device_tracker.config_entry import ScannerEntity from homeassistant.components.device_tracker.config_entry import ScannerEntity
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant, callback
from homeassistant.const import STATE_NOT_HOME from homeassistant.const import STATE_NOT_HOME
from homeassistant.helpers import (
entity_platform as ep,
entity_registry as er,
)
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import slugify
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
from homeassistant.components.device_tracker.const import SourceType from homeassistant.components.device_tracker.const import SourceType
from .device_tracker_types import SENSOR_TYPES, SENSOR_SERVICES from .device_tracker_types import SENSOR_TYPES, SENSOR_SERVICES
from .entity import MikrotikEntity, async_add_entities from .entity import _skip_sensor, MikrotikEntity # , async_add_entities
from .helper import format_attribute from .helper import format_attribute
from .const import ( from .const import (
DOMAIN,
CONF_TRACK_HOSTS, CONF_TRACK_HOSTS,
DEFAULT_TRACK_HOSTS, DEFAULT_TRACK_HOSTS,
CONF_TRACK_HOSTS_TIMEOUT, CONF_TRACK_HOSTS_TIMEOUT,
@ -28,6 +35,66 @@ from .const import (
_LOGGER = getLogger(__name__) _LOGGER = getLogger(__name__)
async def async_add_entities(
hass: HomeAssistant, config_entry: ConfigEntry, dispatcher: dict[str, Callable]
):
"""Add entities."""
# coordinator = hass.data[DOMAIN][config_entry.entry_id].data_coordinator
platform = ep.async_get_current_platform()
services = platform.platform.SENSOR_SERVICES
descriptions = platform.platform.SENSOR_TYPES
for service in services:
platform.async_register_entity_service(service[0], service[1], service[2])
@callback
async def async_update_controller(coordinator):
"""Update the values of the controller."""
async def async_check_exist(obj, coordinator, uid: None) -> None:
"""Check entity exists."""
entity_registry = er.async_get(hass)
if uid:
unique_id = f"{obj._inst.lower()}-{obj.entity_description.key}-{slugify(str(obj._data[obj.entity_description.data_reference]).lower())}"
else:
unique_id = f"{obj._inst.lower()}-{obj.entity_description.key}"
entity_id = entity_registry.async_get_entity_id(
platform.domain, DOMAIN, unique_id
)
entity = entity_registry.async_get(entity_id)
if entity is None or (
(entity_id not in platform.entities) and (entity.disabled is False)
):
_LOGGER.debug("Add entity %s", entity_id)
await platform.async_add_entities([obj])
for entity_description in descriptions:
data = coordinator.data[entity_description.data_path]
if not entity_description.data_reference:
if data.get(entity_description.data_attribute) is None:
continue
obj = dispatcher[entity_description.func](
coordinator, entity_description
)
await async_check_exist(obj, coordinator, None)
else:
for uid in data:
if _skip_sensor(config_entry, entity_description, data, uid):
continue
obj = dispatcher[entity_description.func](
coordinator, entity_description, uid
)
await async_check_exist(obj, coordinator, uid)
await async_update_controller(
hass.data[DOMAIN][config_entry.entry_id].tracker_coordinator
)
unsub = async_dispatcher_connect(hass, "update_sensors", async_update_controller)
config_entry.async_on_unload(unsub)
# --------------------------- # ---------------------------
# async_setup_entry # async_setup_entry
# --------------------------- # ---------------------------

View file

@ -3,7 +3,7 @@ from __future__ import annotations
from collections.abc import Mapping from collections.abc import Mapping
from logging import getLogger from logging import getLogger
from typing import Any, Callable from typing import Any, Callable, TypeVar
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, CONF_HOST from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, CONF_HOST
@ -27,7 +27,7 @@ from .const import (
CONF_SENSOR_PORT_TRACKER, CONF_SENSOR_PORT_TRACKER,
DEFAULT_SENSOR_PORT_TRACKER, DEFAULT_SENSOR_PORT_TRACKER,
) )
from .coordinator import MikrotikCoordinator from .coordinator import MikrotikCoordinator, MikrotikTrackerCoordinator
from .helper import format_attribute from .helper import format_attribute
_LOGGER = getLogger(__name__) _LOGGER = getLogger(__name__)
@ -88,7 +88,7 @@ async def async_add_entities(
hass: HomeAssistant, config_entry: ConfigEntry, dispatcher: dict[str, Callable] hass: HomeAssistant, config_entry: ConfigEntry, dispatcher: dict[str, Callable]
): ):
"""Add entities.""" """Add entities."""
coordinator = hass.data[DOMAIN][config_entry.entry_id] # coordinator = hass.data[DOMAIN][config_entry.entry_id].data_coordinator
platform = ep.async_get_current_platform() platform = ep.async_get_current_platform()
services = platform.platform.SENSOR_SERVICES services = platform.platform.SENSOR_SERVICES
descriptions = platform.platform.SENSOR_TYPES descriptions = platform.platform.SENSOR_TYPES
@ -136,15 +136,24 @@ async def async_add_entities(
) )
await async_check_exist(obj, coordinator, uid) await async_check_exist(obj, coordinator, uid)
await async_update_controller(coordinator) await async_update_controller(
hass.data[DOMAIN][config_entry.entry_id].data_coordinator
)
unsub = async_dispatcher_connect(hass, "update_sensors", async_update_controller) unsub = async_dispatcher_connect(hass, "update_sensors", async_update_controller)
config_entry.async_on_unload(unsub) config_entry.async_on_unload(unsub)
_MikrotikCoordinatorT = TypeVar(
"_MikrotikCoordinatorT",
bound=MikrotikCoordinator | MikrotikTrackerCoordinator,
)
# --------------------------- # ---------------------------
# MikrotikEntity # MikrotikEntity
# --------------------------- # ---------------------------
class MikrotikEntity(CoordinatorEntity[MikrotikCoordinator], Entity): class MikrotikEntity(CoordinatorEntity[_MikrotikCoordinatorT], Entity):
"""Define entity""" """Define entity"""
_attr_has_entity_name = True _attr_has_entity_name = True
@ -247,19 +256,7 @@ class MikrotikEntity(CoordinatorEntity[MikrotikCoordinator], Entity):
sw_version=f"{self.coordinator.data['resource']['version']}", sw_version=f"{self.coordinator.data['resource']['version']}",
configuration_url=f"http://{self.coordinator.config_entry.data[CONF_HOST]}", configuration_url=f"http://{self.coordinator.config_entry.data[CONF_HOST]}",
) )
else: elif "mac-address" in self.entity_description.data_reference:
info = DeviceInfo(
connections={(dev_connection, f"{dev_connection_value}")},
default_name=f"{self._inst} {dev_group}",
default_model=f"{self.coordinator.data['resource']['board-name']}",
default_manufacturer=f"{self.coordinator.data['resource']['platform']}",
via_device=(
DOMAIN,
f"{self.coordinator.data['routerboard']['serial-number']}",
),
)
if "mac-address" in self.entity_description.data_reference:
dev_group = self._data[self.entity_description.data_name] dev_group = self._data[self.entity_description.data_name]
dev_manufacturer = "" dev_manufacturer = ""
if dev_connection_value in self.coordinator.data["host"]: if dev_connection_value in self.coordinator.data["host"]:
@ -279,6 +276,17 @@ class MikrotikEntity(CoordinatorEntity[MikrotikCoordinator], Entity):
f"{self.coordinator.data['routerboard']['serial-number']}", f"{self.coordinator.data['routerboard']['serial-number']}",
), ),
) )
else:
info = DeviceInfo(
connections={(dev_connection, f"{dev_connection_value}")},
default_name=f"{self._inst} {dev_group}",
default_model=f"{self.coordinator.data['resource']['board-name']}",
default_manufacturer=f"{self.coordinator.data['resource']['platform']}",
via_device=(
DOMAIN,
f"{self.coordinator.data['routerboard']['serial-number']}",
),
)
return info return info