From 00edce723914423fed3fae14525c6f010b7e6dcc Mon Sep 17 00:00:00 2001 From: Snuffy2 Date: Sun, 3 Nov 2024 15:13:00 -0500 Subject: [PATCH] Prevent Device Name duplication in Sensor Name --- custom_components/variable/sensor.py | 54 ++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/custom_components/variable/sensor.py b/custom_components/variable/sensor.py index 427f126..024f975 100644 --- a/custom_components/variable/sensor.py +++ b/custom_components/variable/sensor.py @@ -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 @@ -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) @@ -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}" )