diff --git a/homeassistant/components/aquacell/const.py b/homeassistant/components/aquacell/const.py index 818c96fc53a1..28323d9a59f6 100644 --- a/homeassistant/components/aquacell/const.py +++ b/homeassistant/components/aquacell/const.py @@ -11,3 +11,4 @@ CONF_REFRESH_TOKEN_CREATION_TIME = "refresh_token_creation_time" REFRESH_TOKEN_EXPIRY_TIME = timedelta(days=30) UPDATE_INTERVAL = timedelta(days=1) +STALE_DATA_TIMEOUT = timedelta(days=3) diff --git a/homeassistant/components/aquacell/entity.py b/homeassistant/components/aquacell/entity.py index 8d4fea5d39d0..c136de3899dc 100644 --- a/homeassistant/components/aquacell/entity.py +++ b/homeassistant/components/aquacell/entity.py @@ -1,5 +1,7 @@ """Aquacell entity.""" +from typing import override + from aioaquacell import Softener from homeassistant.helpers.device_registry import DeviceInfo @@ -35,6 +37,12 @@ class AquacellEntity(CoordinatorEntity[AquacellCoordinator]): serial_number=softener_key, ) + @property + @override + def available(self) -> bool: + """Return if the softener is still returned by the API.""" + return super().available and self.softener_key in self.coordinator.data + @property def softener(self) -> Softener: """Handle updated data from the coordinator.""" diff --git a/homeassistant/components/aquacell/sensor.py b/homeassistant/components/aquacell/sensor.py index 256635a5bad8..d714f19e7934 100644 --- a/homeassistant/components/aquacell/sensor.py +++ b/homeassistant/components/aquacell/sensor.py @@ -17,7 +17,9 @@ from homeassistant.const import PERCENTAGE, UnitOfTime from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType +from homeassistant.util import dt as dt_util +from .const import STALE_DATA_TIMEOUT from .coordinator import AquacellConfigEntry, AquacellCoordinator from .entity import AquacellEntity @@ -29,6 +31,7 @@ class SoftenerSensorEntityDescription(SensorEntityDescription): """Describes Softener sensor entity.""" value_fn: Callable[[Softener], StateType | datetime] + available_when_stale: bool = False SENSORS: tuple[SoftenerSensorEntityDescription, ...] = ( @@ -82,6 +85,7 @@ SENSORS: tuple[SoftenerSensorEntityDescription, ...] = ( translation_key="last_update", device_class=SensorDeviceClass.TIMESTAMP, value_fn=lambda softener: softener.diagnostics.last_update, + available_when_stale=True, ), ) @@ -116,6 +120,16 @@ class SoftenerSensor(AquacellEntity, SensorEntity): self.entity_description = description + @property + @override + def available(self) -> bool: + """Return if the softener reported to the cloud recently.""" + return super().available and ( + self.entity_description.available_when_stale + or dt_util.utcnow() - self.softener.diagnostics.last_update + < STALE_DATA_TIMEOUT + ) + @property @override def native_value(self) -> StateType | datetime: diff --git a/tests/components/aquacell/test_sensor.py b/tests/components/aquacell/test_sensor.py index 49f724c6753e..b4e8cfad3673 100644 --- a/tests/components/aquacell/test_sensor.py +++ b/tests/components/aquacell/test_sensor.py @@ -2,16 +2,27 @@ from unittest.mock import AsyncMock +from freezegun.api import FrozenDateTimeFactory +import pytest from syrupy.assertion import SnapshotAssertion +from homeassistant.components.aquacell.const import STALE_DATA_TIMEOUT, UPDATE_INTERVAL +from homeassistant.const import STATE_UNAVAILABLE from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er +from homeassistant.util import dt as dt_util from . import setup_integration -from tests.common import MockConfigEntry, snapshot_platform +from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform + +ENTITY_ID = "sensor.aquacell_name_battery" +LAST_UPDATE_ENTITY_ID = "sensor.aquacell_name_last_update" +# Matches lastUpdate in the softener fixture +LAST_UPDATE = "2024-05-10 07:44:30+00:00" +@pytest.mark.freeze_time(LAST_UPDATE) async def test_sensors( hass: HomeAssistant, mock_aquacell_api: AsyncMock, @@ -22,3 +33,57 @@ async def test_sensors( """Test the creation of Aquacell sensors.""" await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.freeze_time(LAST_UPDATE) +async def test_sensors_unavailable_when_softener_missing( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_aquacell_api: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test sensors become unavailable when the softener is no longer returned.""" + await setup_integration(hass, mock_config_entry) + softeners = mock_aquacell_api.get_all_softeners.return_value + assert hass.states.get(ENTITY_ID).state == "40" + + mock_aquacell_api.get_all_softeners.return_value = [] + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + mock_aquacell_api.get_all_softeners.return_value = softeners + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == "40" + + +@pytest.mark.freeze_time(LAST_UPDATE) +async def test_sensors_unavailable_when_data_is_stale( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_aquacell_api: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test sensors become unavailable when the softener stops reporting.""" + await setup_integration(hass, mock_config_entry) + assert hass.states.get(ENTITY_ID).state == "40" + + freezer.tick(STALE_DATA_TIMEOUT) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + assert hass.states.get(LAST_UPDATE_ENTITY_ID).state == "2024-05-10T07:44:30+00:00" + + softener = mock_aquacell_api.get_all_softeners.return_value[0] + softener.diagnostics.last_update = dt_util.utcnow() + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == "40"