Skip to content

Commit

Permalink
Implementazioni arrotondamenti da UI in HA 2023.3
Browse files Browse the repository at this point in the history
  • Loading branch information
virtualdj committed Mar 9, 2023
1 parent a35eec5 commit 19f270b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion custom_components/pun_sensor/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
"config_flow": true,
"requirements": ["holidays", "bs4"],
"iot_class": "local_polling",
"version": "0.3.2"
"version": "0.3.3"
}
32 changes: 29 additions & 3 deletions custom_components/pun_sensor/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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))
Expand All @@ -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):
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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'))
}
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -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'))
}
Expand Down

0 comments on commit 19f270b

Please sign in to comment.