diff --git a/README.md b/README.md index e359148..5850726 100644 --- a/README.md +++ b/README.md @@ -45,3 +45,4 @@ Ovviamente non ho alcuna certezza che tutto questo sia la maniera giusta di proc - [dcmeglio/alarmdecoder-hass](https://github.com/dcmeglio/alarmdecoder-hass/blob/a898ae18cc5562b2a5fc3a73511302b6d242fd07/custom_components/alarmdecoder/__init__.py) - [BenPru/luxtronik](https://github.com/BenPru/luxtronik/blob/a6c5adfe91532237075fe17df63b59120a8b7098/custom_components/luxtronik/sensor.py#L856-L857) e [collse/Home-AssistantConfig](https://github.com/collse/Home-AssistantConfig/blob/e4a1bc6ee3c470619e4169ac903b88f5dad3b6a8/custom_components/elastic/sensor.py#L66) per due esempi di come assegnare un _entity-id_ predeterminato quando si usa anche l'_unique_id_ senza ricevere errori `AttributeError: can't set attribute 'entity_id'` (altra cosa non sufficientemente documentata di HomeAssistant) - [dlashua/bolted](https://github.com/dlashua/bolted/blob/50065eba8ffb4abe498587cd889aa9ff7873aeb3/custom_components/bolted/entity_manager.py), [pippyn/Home-Assistant-Sensor-Afvalbeheer](https://github.com/pippyn/Home-Assistant-Sensor-Afvalbeheer/blob/master/custom_components/afvalbeheer/sensor.py) e [questo articolo](https://aarongodfrey.dev/programming/restoring-an-entity-in-home-assistant/) per come salvare e ripristinare lo stato di una entità con `RestoreEntity` +- Il componente di Home Assistant [energyzero](https://github.com/home-assistant/core/tree/dev/homeassistant/components/energyzero) per il blocco del `config_flow` già configurato e per esprimere correttamente le unità di misura diff --git a/custom_components/pun_sensor/manifest.json b/custom_components/pun_sensor/manifest.json index 68e167b..675a0a3 100644 --- a/custom_components/pun_sensor/manifest.json +++ b/custom_components/pun_sensor/manifest.json @@ -7,5 +7,5 @@ "config_flow": true, "requirements": ["holidays", "bs4"], "iot_class": "local_polling", - "version": "0.3.2" + "version": "0.3.3" } diff --git a/custom_components/pun_sensor/sensor.py b/custom_components/pun_sensor/sensor.py index fae71f9..7f189f3 100644 --- a/custom_components/pun_sensor/sensor.py +++ b/custom_components/pun_sensor/sensor.py @@ -24,6 +24,10 @@ PUN_FASCIA_F2, PUN_FASCIA_F3, ) + +from awesomeversion.awesomeversion import AwesomeVersion +from homeassistant.const import __version__ as HA_VERSION +from homeassistant.const import CURRENCY_EURO, UnitOfEnergy ATTR_ROUNDED_DECIMALS = "rounded_decimals" async def async_setup_entry(hass: HomeAssistant, config: ConfigEntry, @@ -34,6 +38,10 @@ async def async_setup_entry(hass: HomeAssistant, config: ConfigEntry, # Restituisce il coordinator coordinator = hass.data[DOMAIN][config.entry_id] + # Verifica la versione di Home Assistant + global has_suggested_display_precision + has_suggested_display_precision = (AwesomeVersion(HA_VERSION) >= AwesomeVersion("2023.3.0")) + # Crea i sensori (legati al coordinator) entities = [] entities.append(PUNSensorEntity(coordinator, PUN_FASCIA_MONO)) @@ -49,7 +57,13 @@ async def async_setup_entry(hass: HomeAssistant, config: ConfigEntry, def fmt_float(num: float): - """Formatta la media come numero decimale con 6 decimali""" + """Formatta adeguatamente il numero decimale""" + if has_suggested_display_precision: + return num + + # In versioni precedenti di Home Assistant che non supportano + # l'attributo 'suggested_display_precision' restituisce il numero + # decimale già adeguatamente formattato come stringa return format(round(num, 6), '.6f') class PUNSensorEntity(CoordinatorEntity, SensorEntity, RestoreEntity): @@ -79,6 +93,7 @@ def __init__(self, coordinator: PUNDataUpdateCoordinator, tipo: int) -> None: # Inizializza le proprietà comuni self._attr_state_class = SensorStateClass.MEASUREMENT self._attr_device_class = SensorDeviceClass.MONETARY + self._attr_suggested_display_precision = 6 self._available = False self._native_value = 0 @@ -123,7 +138,7 @@ def native_value(self) -> float: @property def native_unit_of_measurement(self) -> str: """Unita' di misura""" - return "€/kWh" + return f"{CURRENCY_EURO}/{UnitOfEnergy.KILO_WATT_HOUR}" @property def state(self) -> str: @@ -151,6 +166,11 @@ def name(self) -> str: @property def extra_state_attributes(self) -> Dict[str, Any]: """Restituisce gli attributi di stato""" + if has_suggested_display_precision: + return None + + # Nelle versioni precedenti di Home Assistant + # restituisce un valore arrotondato come attributo state_attr = { ATTR_ROUNDED_DECIMALS: str(format(round(self.native_value, 3), '.3f')) } @@ -220,6 +240,7 @@ def __init__(self, coordinator: PUNDataUpdateCoordinator) -> None: # Inizializza le proprietà comuni self._attr_state_class = SensorStateClass.MEASUREMENT self._attr_device_class = SensorDeviceClass.MONETARY + self._attr_suggested_display_precision = 6 self._available = False self._native_value = 0 @@ -273,7 +294,7 @@ def native_value(self) -> float: @property def native_unit_of_measurement(self) -> str: """Unita' di misura""" - return "€/kWh" + return f"{CURRENCY_EURO}/{UnitOfEnergy.KILO_WATT_HOUR}" @property def state(self) -> str: @@ -292,6 +313,11 @@ def name(self) -> str: @property def extra_state_attributes(self) -> Dict[str, Any]: """Restituisce gli attributi di stato""" + if has_suggested_display_precision: + return None + + # Nelle versioni precedenti di Home Assistant + # restituisce un valore arrotondato come attributo state_attr = { ATTR_ROUNDED_DECIMALS: str(format(round(self.native_value, 3), '.3f')) }