From efe937a785301357fb8a4f6a86e2f04a4146204a Mon Sep 17 00:00:00 2001 From: Alessandro Del Prete Date: Wed, 28 Feb 2024 01:29:04 +0100 Subject: [PATCH] Created to_unique_id function to fix entities unique_id --- custom_components/sinapsi_alfa/sensor.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/custom_components/sinapsi_alfa/sensor.py b/custom_components/sinapsi_alfa/sensor.py index 1649501..1d23593 100644 --- a/custom_components/sinapsi_alfa/sensor.py +++ b/custom_components/sinapsi_alfa/sensor.py @@ -4,6 +4,7 @@ """ import logging +import re from typing import Any from homeassistant.components.sensor import SensorEntity @@ -52,6 +53,19 @@ async def async_setup_entry(hass: HomeAssistant, config_entry, async_add_entitie return True +def to_unique_id(raw: str): + """Convert string to unique_id.""" + string = ( + re.sub(r"(?<=[a-z0-9:_])(?=[A-Z])|[^a-zA-Z0-9:_]", " ", raw) + .strip() + .replace(" ", "_") + ) + result = "".join(string.lower()) + while "__" in result: + result = result.replace("__", "_") + return result + + class SinapsiAlfaSensor(CoordinatorEntity, SensorEntity): """Representation of a Sinapsi Alfa sensor.""" @@ -141,7 +155,7 @@ def should_poll(self) -> bool: @property def unique_id(self): """Return a unique ID to use for this entity.""" - return f"{DOMAIN}_{self._device_sn}_{self._key}" + return to_unique_id(f"{self._device_sn}_{self._key}") @property def device_info(self):