2022-03-27 03:29:36 +02:00
|
|
|
"""Mikrotik HA shared entity model"""
|
2023-08-08 00:50:09 +02:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2022-03-27 03:29:36 +02:00
|
|
|
from collections.abc import Mapping
|
2023-08-08 00:50:09 +02:00
|
|
|
from logging import getLogger
|
2023-08-09 23:00:00 +02:00
|
|
|
from typing import Any, Callable, TypeVar
|
2023-08-08 00:50:09 +02:00
|
|
|
|
|
|
|
from homeassistant.config_entries import ConfigEntry
|
2022-03-27 03:29:36 +02:00
|
|
|
from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, CONF_HOST
|
2023-08-08 00:50:09 +02:00
|
|
|
from homeassistant.core import HomeAssistant, callback
|
|
|
|
from homeassistant.helpers import (
|
|
|
|
entity_platform as ep,
|
|
|
|
entity_registry as er,
|
|
|
|
)
|
|
|
|
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
|
|
|
from homeassistant.helpers.entity import DeviceInfo, Entity
|
|
|
|
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
|
|
|
from homeassistant.util import slugify
|
|
|
|
|
2022-03-27 03:29:36 +02:00
|
|
|
from .const import (
|
|
|
|
DOMAIN,
|
|
|
|
ATTRIBUTION,
|
|
|
|
CONF_SENSOR_PORT_TRAFFIC,
|
|
|
|
DEFAULT_SENSOR_PORT_TRAFFIC,
|
|
|
|
CONF_TRACK_HOSTS,
|
|
|
|
DEFAULT_TRACK_HOSTS,
|
2022-04-06 17:37:55 +02:00
|
|
|
CONF_SENSOR_PORT_TRACKER,
|
|
|
|
DEFAULT_SENSOR_PORT_TRACKER,
|
2022-03-27 03:29:36 +02:00
|
|
|
)
|
2023-08-09 23:00:00 +02:00
|
|
|
from .coordinator import MikrotikCoordinator, MikrotikTrackerCoordinator
|
2023-08-08 00:50:09 +02:00
|
|
|
from .helper import format_attribute
|
2022-03-27 03:29:36 +02:00
|
|
|
|
|
|
|
_LOGGER = getLogger(__name__)
|
|
|
|
|
|
|
|
|
2023-08-08 00:50:09 +02:00
|
|
|
def _skip_sensor(config_entry, entity_description, data, uid) -> bool:
|
2022-08-19 14:04:13 +02:00
|
|
|
# Sensors
|
|
|
|
if (
|
2023-08-08 00:50:09 +02:00
|
|
|
entity_description.func == "MikrotikInterfaceTrafficSensor"
|
2022-08-19 14:04:13 +02:00
|
|
|
and not config_entry.options.get(
|
|
|
|
CONF_SENSOR_PORT_TRAFFIC, DEFAULT_SENSOR_PORT_TRAFFIC
|
|
|
|
)
|
|
|
|
):
|
|
|
|
return True
|
|
|
|
|
|
|
|
if (
|
2023-08-08 00:50:09 +02:00
|
|
|
entity_description.func == "MikrotikInterfaceTrafficSensor"
|
|
|
|
and data[uid]["type"] == "bridge"
|
2022-08-19 14:04:13 +02:00
|
|
|
):
|
|
|
|
return True
|
|
|
|
|
|
|
|
if (
|
2023-08-09 11:54:08 +02:00
|
|
|
entity_description.data_path == "client_traffic"
|
2023-08-08 00:50:09 +02:00
|
|
|
and entity_description.data_attribute not in data[uid].keys()
|
2022-08-19 14:04:13 +02:00
|
|
|
):
|
|
|
|
return True
|
|
|
|
|
|
|
|
# Binary sensors
|
|
|
|
if (
|
2023-08-08 00:50:09 +02:00
|
|
|
entity_description.func == "MikrotikPortBinarySensor"
|
|
|
|
and data[uid]["type"] == "wlan"
|
2022-08-19 14:04:13 +02:00
|
|
|
):
|
|
|
|
return True
|
|
|
|
|
2023-08-08 00:50:09 +02:00
|
|
|
if (
|
|
|
|
entity_description.func == "MikrotikPortBinarySensor"
|
|
|
|
and not config_entry.options.get(
|
|
|
|
CONF_SENSOR_PORT_TRACKER, DEFAULT_SENSOR_PORT_TRACKER
|
|
|
|
)
|
2022-08-19 14:04:13 +02:00
|
|
|
):
|
|
|
|
return True
|
|
|
|
|
|
|
|
# Device Tracker
|
|
|
|
if (
|
|
|
|
# Skip if host tracking is disabled
|
2023-08-08 00:50:09 +02:00
|
|
|
entity_description.func == "MikrotikHostDeviceTracker"
|
2022-08-19 14:04:13 +02:00
|
|
|
and not config_entry.options.get(CONF_TRACK_HOSTS, DEFAULT_TRACK_HOSTS)
|
|
|
|
):
|
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2022-03-27 03:29:36 +02:00
|
|
|
# ---------------------------
|
2023-08-08 00:50:09 +02:00
|
|
|
# async_add_entities
|
2022-03-27 03:29:36 +02:00
|
|
|
# ---------------------------
|
2023-08-08 00:50:09 +02:00
|
|
|
async def async_add_entities(
|
|
|
|
hass: HomeAssistant, config_entry: ConfigEntry, dispatcher: dict[str, Callable]
|
2022-03-27 03:29:36 +02:00
|
|
|
):
|
2023-08-08 00:50:09 +02:00
|
|
|
"""Add entities."""
|
|
|
|
platform = ep.async_get_current_platform()
|
|
|
|
services = platform.platform.SENSOR_SERVICES
|
|
|
|
descriptions = platform.platform.SENSOR_TYPES
|
2022-03-27 03:29:36 +02:00
|
|
|
|
2023-08-08 00:50:09 +02:00
|
|
|
for service in services:
|
2022-03-27 03:29:36 +02:00
|
|
|
platform.async_register_entity_service(service[0], service[1], service[2])
|
|
|
|
|
|
|
|
@callback
|
2023-08-08 00:50:09 +02:00
|
|
|
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)
|
2022-03-27 03:29:36 +02:00
|
|
|
):
|
2023-08-08 00:50:09 +02:00
|
|
|
_LOGGER.debug("Add entity %s", entity_id)
|
|
|
|
await platform.async_add_entities([obj])
|
2022-03-27 03:29:36 +02:00
|
|
|
|
2023-08-08 00:50:09 +02:00
|
|
|
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:
|
2022-03-27 03:29:36 +02:00
|
|
|
continue
|
2023-08-08 00:50:09 +02:00
|
|
|
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)
|
|
|
|
|
2023-08-09 23:00:00 +02:00
|
|
|
await async_update_controller(
|
|
|
|
hass.data[DOMAIN][config_entry.entry_id].data_coordinator
|
|
|
|
)
|
|
|
|
|
2023-08-08 00:50:09 +02:00
|
|
|
unsub = async_dispatcher_connect(hass, "update_sensors", async_update_controller)
|
|
|
|
config_entry.async_on_unload(unsub)
|
2022-03-27 03:29:36 +02:00
|
|
|
|
|
|
|
|
2023-08-09 23:00:00 +02:00
|
|
|
_MikrotikCoordinatorT = TypeVar(
|
|
|
|
"_MikrotikCoordinatorT",
|
|
|
|
bound=MikrotikCoordinator | MikrotikTrackerCoordinator,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2022-03-27 03:29:36 +02:00
|
|
|
# ---------------------------
|
|
|
|
# MikrotikEntity
|
|
|
|
# ---------------------------
|
2023-08-09 23:00:00 +02:00
|
|
|
class MikrotikEntity(CoordinatorEntity[_MikrotikCoordinatorT], Entity):
|
2022-03-27 03:29:36 +02:00
|
|
|
"""Define entity"""
|
|
|
|
|
2022-08-18 09:29:55 +02:00
|
|
|
_attr_has_entity_name = True
|
|
|
|
|
2022-03-27 03:29:36 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
2023-08-08 00:50:09 +02:00
|
|
|
coordinator: MikrotikCoordinator,
|
2022-03-27 03:29:36 +02:00
|
|
|
entity_description,
|
2023-08-08 00:50:09 +02:00
|
|
|
uid: str | None = None,
|
2022-03-27 03:29:36 +02:00
|
|
|
):
|
|
|
|
"""Initialize entity"""
|
2023-08-08 00:50:09 +02:00
|
|
|
super().__init__(coordinator)
|
2022-03-27 03:29:36 +02:00
|
|
|
self.entity_description = entity_description
|
2023-08-08 00:50:09 +02:00
|
|
|
self._inst = coordinator.config_entry.data[CONF_NAME]
|
|
|
|
self._config_entry = self.coordinator.config_entry
|
2022-03-27 03:29:36 +02:00
|
|
|
self._attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION}
|
|
|
|
self._uid = uid
|
2023-08-08 00:50:09 +02:00
|
|
|
self._data = coordinator.data[self.entity_description.data_path]
|
|
|
|
if self._uid:
|
|
|
|
self._data = coordinator.data[self.entity_description.data_path][self._uid]
|
|
|
|
|
|
|
|
@callback
|
|
|
|
def _handle_coordinator_update(self) -> None:
|
|
|
|
self._data = self.coordinator.data[self.entity_description.data_path]
|
2022-03-27 03:29:36 +02:00
|
|
|
if self._uid:
|
2023-08-08 00:50:09 +02:00
|
|
|
self._data = self.coordinator.data[self.entity_description.data_path][
|
2022-03-27 03:29:36 +02:00
|
|
|
self._uid
|
|
|
|
]
|
2023-08-08 00:50:09 +02:00
|
|
|
super()._handle_coordinator_update()
|
2022-03-27 03:29:36 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def name(self) -> str:
|
|
|
|
"""Return the name for this entity"""
|
|
|
|
if not self._uid:
|
|
|
|
if self.entity_description.data_name_comment and self._data["comment"]:
|
2022-08-18 09:29:55 +02:00
|
|
|
return f"{self._data['comment']}"
|
|
|
|
|
|
|
|
return f"{self.entity_description.name}"
|
2022-03-27 03:29:36 +02:00
|
|
|
|
2022-08-18 09:29:55 +02:00
|
|
|
if self.entity_description.data_name_comment and self._data["comment"]:
|
|
|
|
return f"{self._data['comment']}"
|
2022-03-27 03:29:36 +02:00
|
|
|
|
|
|
|
if self.entity_description.name:
|
2022-08-18 09:29:55 +02:00
|
|
|
if (
|
|
|
|
self._data[self.entity_description.data_reference]
|
|
|
|
== self._data[self.entity_description.data_name]
|
|
|
|
):
|
|
|
|
return f"{self.entity_description.name}"
|
2022-03-27 03:29:36 +02:00
|
|
|
|
2022-08-18 09:29:55 +02:00
|
|
|
return f"{self._data[self.entity_description.data_name]} {self.entity_description.name}"
|
2022-03-27 03:29:36 +02:00
|
|
|
|
2022-08-18 09:29:55 +02:00
|
|
|
return f"{self._data[self.entity_description.data_name]}"
|
2022-03-27 03:29:36 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def unique_id(self) -> str:
|
|
|
|
"""Return a unique id for this entity"""
|
|
|
|
if self._uid:
|
2023-08-08 00:50:09 +02:00
|
|
|
return f"{self._inst.lower()}-{self.entity_description.key}-{slugify(str(self._data[self.entity_description.data_reference]).lower())}"
|
2022-03-27 03:29:36 +02:00
|
|
|
else:
|
|
|
|
return f"{self._inst.lower()}-{self.entity_description.key}"
|
|
|
|
|
2023-08-09 02:32:35 +02:00
|
|
|
# @property
|
|
|
|
# def available(self) -> bool:
|
|
|
|
# """Return if controller is available"""
|
|
|
|
# return self.coordinator.connected()
|
2022-03-27 03:29:36 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def device_info(self) -> DeviceInfo:
|
|
|
|
"""Return a description for device registry."""
|
|
|
|
dev_connection = DOMAIN
|
|
|
|
dev_connection_value = self.entity_description.data_reference
|
|
|
|
dev_group = self.entity_description.ha_group
|
|
|
|
if self.entity_description.ha_group == "System":
|
2023-08-08 00:50:09 +02:00
|
|
|
dev_group = self.coordinator.data["resource"]["board-name"]
|
|
|
|
dev_connection_value = self.coordinator.data["routerboard"]["serial-number"]
|
2022-03-27 03:29:36 +02:00
|
|
|
|
|
|
|
if self.entity_description.ha_group.startswith("data__"):
|
|
|
|
dev_group = self.entity_description.ha_group[6:]
|
|
|
|
if dev_group in self._data:
|
|
|
|
dev_group = self._data[dev_group]
|
|
|
|
dev_connection_value = dev_group
|
|
|
|
|
|
|
|
if self.entity_description.ha_connection:
|
|
|
|
dev_connection = self.entity_description.ha_connection
|
|
|
|
|
|
|
|
if self.entity_description.ha_connection_value:
|
|
|
|
dev_connection_value = self.entity_description.ha_connection_value
|
|
|
|
if dev_connection_value.startswith("data__"):
|
|
|
|
dev_connection_value = dev_connection_value[6:]
|
|
|
|
dev_connection_value = self._data[dev_connection_value]
|
|
|
|
|
2023-08-09 11:33:38 +02:00
|
|
|
if self.entity_description.ha_group == "System":
|
|
|
|
info = DeviceInfo(
|
|
|
|
connections={(dev_connection, f"{dev_connection_value}")},
|
|
|
|
identifiers={(dev_connection, f"{dev_connection_value}")},
|
|
|
|
name=f"{self._inst} {dev_group}",
|
|
|
|
model=f"{self.coordinator.data['resource']['board-name']}",
|
|
|
|
manufacturer=f"{self.coordinator.data['resource']['platform']}",
|
|
|
|
sw_version=f"{self.coordinator.data['resource']['version']}",
|
|
|
|
configuration_url=f"http://{self.coordinator.config_entry.data[CONF_HOST]}",
|
|
|
|
)
|
2023-08-09 23:00:00 +02:00
|
|
|
elif "mac-address" in self.entity_description.data_reference:
|
2022-03-27 03:29:36 +02:00
|
|
|
dev_group = self._data[self.entity_description.data_name]
|
|
|
|
dev_manufacturer = ""
|
2023-08-08 00:50:09 +02:00
|
|
|
if dev_connection_value in self.coordinator.data["host"]:
|
|
|
|
dev_group = self.coordinator.data["host"][dev_connection_value][
|
|
|
|
"host-name"
|
|
|
|
]
|
|
|
|
dev_manufacturer = self.coordinator.data["host"][dev_connection_value][
|
2022-03-27 03:29:36 +02:00
|
|
|
"manufacturer"
|
|
|
|
]
|
|
|
|
|
|
|
|
info = DeviceInfo(
|
|
|
|
connections={(dev_connection, f"{dev_connection_value}")},
|
|
|
|
default_name=f"{dev_group}",
|
|
|
|
default_manufacturer=f"{dev_manufacturer}",
|
|
|
|
via_device=(
|
|
|
|
DOMAIN,
|
2023-08-08 00:50:09 +02:00
|
|
|
f"{self.coordinator.data['routerboard']['serial-number']}",
|
2022-03-27 03:29:36 +02:00
|
|
|
),
|
|
|
|
)
|
2023-08-09 23:00:00 +02:00
|
|
|
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']}",
|
|
|
|
),
|
|
|
|
)
|
2022-03-27 03:29:36 +02:00
|
|
|
|
|
|
|
return info
|
|
|
|
|
|
|
|
@property
|
|
|
|
def extra_state_attributes(self) -> Mapping[str, Any]:
|
|
|
|
"""Return the state attributes."""
|
|
|
|
attributes = super().extra_state_attributes
|
|
|
|
for variable in self.entity_description.data_attributes_list:
|
|
|
|
if variable in self._data:
|
|
|
|
attributes[format_attribute(variable)] = self._data[variable]
|
|
|
|
|
|
|
|
return attributes
|
|
|
|
|
|
|
|
async def start(self):
|
|
|
|
"""Dummy run function"""
|
2023-08-08 00:50:09 +02:00
|
|
|
raise NotImplementedError()
|
2022-03-27 03:29:36 +02:00
|
|
|
|
|
|
|
async def stop(self):
|
|
|
|
"""Dummy stop function"""
|
2023-08-08 00:50:09 +02:00
|
|
|
raise NotImplementedError()
|
2022-03-27 03:29:36 +02:00
|
|
|
|
|
|
|
async def restart(self):
|
|
|
|
"""Dummy restart function"""
|
2023-08-08 00:50:09 +02:00
|
|
|
raise NotImplementedError()
|
2022-03-27 03:29:36 +02:00
|
|
|
|
|
|
|
async def reload(self):
|
|
|
|
"""Dummy reload function"""
|
2023-08-08 00:50:09 +02:00
|
|
|
raise NotImplementedError()
|