Skip to content

Commit

Permalink
Prevent Device Name duplication in Sensor Name
Browse files Browse the repository at this point in the history
  • Loading branch information
Snuffy2 committed Nov 3, 2024
1 parent d15c235 commit 00edce7
Showing 1 changed file with 48 additions and 6 deletions.
54 changes: 48 additions & 6 deletions custom_components/variable/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,15 @@
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers import entity_platform
from homeassistant.helpers import (
config_validation as cv,
)
from homeassistant.helpers import (
device_registry as dr,
)
from homeassistant.helpers import (
entity_platform,
)
from homeassistant.helpers.device import async_device_info_to_link_from_device_id
from homeassistant.helpers.entity import generate_entity_id
from homeassistant.util import slugify
Expand Down Expand Up @@ -166,9 +173,7 @@ def __init__(
hass,
config.get(CONF_DEVICE_ID),
)
_LOGGER.debug(
f"({self._attr_name}) [init] device_id: {config.get(CONF_DEVICE_ID)}, device_info: {self._attr_device_info}"
)
# _LOGGER.debug(f"({self._attr_name}) [init] device_id: {config.get(CONF_DEVICE_ID)}, device_info: {self.device_info}")
if (
config.get(CONF_ATTRIBUTES) is not None
and config.get(CONF_ATTRIBUTES)
Expand Down Expand Up @@ -241,7 +246,44 @@ async def async_added_to_hass(self):
self._attr_extra_state_attributes.pop(
CONF_UNIT_OF_MEASUREMENT, None
)

if self._attr_device_info:
device_registry = dr.async_get(self._hass)
device = device_registry.async_get_device(
identifiers=self._attr_device_info.get(
"identifiers",
)
)
# _LOGGER.debug(f"({self._attr_name}) [restored] device: {device}")
if (
hasattr(device, "name")
and isinstance(device.name, str)
and self._attr_name.lower().strip()
!= device.name.lower().strip()
and self._attr_name.lower().startswith(device.name.lower())
):
old_name = self._attr_name
self._attr_name = self._attr_name.replace(
device.name, "", 1
).strip()
_LOGGER.debug(
f"({self._attr_name}) [restored] Truncated: {old_name}"
)
elif (
hasattr(device, "name_by_user")
and isinstance(device.name_by_user, str)
and self._attr_name.lower().strip()
!= device.name_by_user.lower().strip()
and self._attr_name.lower().startswith(
device.name_by_user.lower()
)
):
old_name = self._attr_name
self._attr_name = self._attr_name.replace(
device.name_by_user, "", 1
).strip()
_LOGGER.debug(
f"({self._attr_name}) [restored] Truncated: {old_name}"
)
_LOGGER.debug(
f"({self._attr_name}) [restored] _attr_native_value: {self._attr_native_value}"
)
Expand Down

0 comments on commit 00edce7

Please sign in to comment.