Skip to content

Commit

Permalink
Ripristino automatico valori precedenti all'avvio
Browse files Browse the repository at this point in the history
  • Loading branch information
virtualdj committed Mar 4, 2023
1 parent 66c6db0 commit b694335
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,4 @@ Ovviamente non ho alcuna certezza che tutto questo sia la maniera giusta di proc
- [bruxy70/Garbage-Collection](https://github.com/bruxy70/Garbage-Collection/blob/ae73818b3b0786ebcf72b16a6f27428e516686e6/custom_components/garbage_collection/sensor.py)
- [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`
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.0b3"
"version": "0.3.0"
}
43 changes: 41 additions & 2 deletions custom_components/pun_sensor/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import DiscoveryInfoType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.helpers.restore_state import (
RestoreEntity,
ExtraStoredData,
RestoredExtraData
)
from typing import Any, Dict

from . import PUNDataUpdateCoordinator
Expand Down Expand Up @@ -47,7 +52,7 @@ def fmt_float(num: float):
"""Formatta la media come numero decimale con 6 decimali"""
return format(round(num, 6), '.6f')

class PUNSensorEntity(CoordinatorEntity, SensorEntity):
class PUNSensorEntity(CoordinatorEntity, SensorEntity, RestoreEntity):
"""Sensore PUN relativo al prezzo medio mensile per fasce"""

def __init__(self, coordinator: PUNDataUpdateCoordinator, tipo: int) -> None:
Expand Down Expand Up @@ -83,6 +88,23 @@ def _handle_coordinator_update(self) -> None:
if (self._available): self._native_value = self.coordinator.pun[self.tipo]
self.async_write_ha_state()

@property
def extra_restore_state_data(self) -> ExtraStoredData:
"""Determina i dati da salvare per il ripristino successivo"""
return RestoredExtraData(dict(
native_value = self._native_value if self._available else None
))

async def async_added_to_hass(self) -> None:
"""Entità aggiunta ad Home Assistant"""
await super().async_added_to_hass()

# Recupera lo stato precedente, se esiste
if (old_data := await self.async_get_last_extra_data()) is not None:
if (old_native_value := old_data.as_dict().get('native_value')) is not None:
self._available = True
self._native_value = old_native_value

@property
def should_poll(self) -> bool:
"""Determina l'aggiornamento automatico"""
Expand Down Expand Up @@ -184,7 +206,7 @@ def name(self) -> str:
"""Restituisce il nome del sensore"""
return "Fascia corrente"

class PrezzoFasciaPUNSensorEntity(FasciaPUNSensorEntity):
class PrezzoFasciaPUNSensorEntity(FasciaPUNSensorEntity, RestoreEntity):
"""Sensore che rappresenta il prezzo PUN della fascia corrente"""

def __init__(self, coordinator: PUNDataUpdateCoordinator) -> None:
Expand Down Expand Up @@ -221,6 +243,23 @@ def _handle_coordinator_update(self) -> None:
self._native_value = 0
self.async_write_ha_state()

@property
def extra_restore_state_data(self) -> ExtraStoredData:
"""Determina i dati da salvare per il ripristino successivo"""
return RestoredExtraData(dict(
native_value = self._native_value if self._available else None
))

async def async_added_to_hass(self) -> None:
"""Entità aggiunta ad Home Assistant"""
await super().async_added_to_hass()

# Recupera lo stato precedente, se esiste
if (old_data := await self.async_get_last_extra_data()) is not None:
if (old_native_value := old_data.as_dict().get('native_value')) is not None:
self._available = True
self._native_value = old_native_value

@property
def available(self) -> bool:
"""Determina se il valore è disponibile"""
Expand Down

0 comments on commit b694335

Please sign in to comment.