Add the device of the source entity in the helper entities for Utility Meter (#94734)

Co-authored-by: Franck Nijhof <frenck@frenck.nl>
This commit is contained in:
dougiteixeira 2023-06-26 13:08:13 -03:00 committed by GitHub
parent 403496eb92
commit 39229ce098
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 158 additions and 5 deletions

View file

@ -7,11 +7,22 @@ from homeassistant.components.select import SelectEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_UNIQUE_ID
from homeassistant.core import HomeAssistant
from homeassistant.helpers import (
device_registry as dr,
entity_registry as er,
)
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import CONF_METER, CONF_TARIFFS, DATA_UTILITY, TARIFF_ICON
from .const import (
CONF_METER,
CONF_SOURCE_SENSOR,
CONF_TARIFFS,
DATA_UTILITY,
TARIFF_ICON,
)
_LOGGER = logging.getLogger(__name__)
@ -26,7 +37,35 @@ async def async_setup_entry(
tariffs: list[str] = config_entry.options[CONF_TARIFFS]
unique_id = config_entry.entry_id
tariff_select = TariffSelect(name, tariffs, unique_id)
registry = er.async_get(hass)
source_entity = registry.async_get(config_entry.options[CONF_SOURCE_SENSOR])
dev_reg = dr.async_get(hass)
# Resolve source entity device
if (
(source_entity is not None)
and (source_entity.device_id is not None)
and (
(
device := dev_reg.async_get(
device_id=source_entity.device_id,
)
)
is not None
)
):
device_info = DeviceInfo(
identifiers=device.identifiers,
)
else:
device_info = None
tariff_select = TariffSelect(
name,
tariffs,
unique_id,
device_info=device_info,
)
async_add_entities([tariff_select])
@ -63,10 +102,17 @@ async def async_setup_platform(
class TariffSelect(SelectEntity, RestoreEntity):
"""Representation of a Tariff selector."""
def __init__(self, name, tariffs, unique_id):
def __init__(
self,
name,
tariffs,
unique_id,
device_info: DeviceInfo | None = None,
) -> None:
"""Initialize a tariff selector."""
self._attr_name = name
self._attr_unique_id = unique_id
self._attr_device_info = device_info
self._current_tariff: str | None = None
self._tariffs = tariffs
self._attr_icon = TARIFF_ICON