mirror of
https://github.com/home-assistant/core.git
synced 2026-12-04 20:59:22 -04:00
Keep MELCloud Home devices when the account returns no units (#185729)
This commit is contained in:
@@ -67,11 +67,18 @@ class MelCloudHomeCoordinator(DataUpdateCoordinator[UserContext]):
|
||||
self.new_ata_callbacks: list[Callable[[list[ATAUnit]], None]] = []
|
||||
self.new_atw_callbacks: list[Callable[[list[ATWUnit]], None]] = []
|
||||
|
||||
def _notify_new_units(self, data: UserContext) -> None:
|
||||
"""Notify callbacks when new units are discovered."""
|
||||
def _async_sync_units(self, data: UserContext) -> None:
|
||||
"""Add entities for new units and remove devices of units that are gone."""
|
||||
current_ata = [
|
||||
unit for building in data.buildings for unit in building.air_to_air_units
|
||||
]
|
||||
current_atw_units = [
|
||||
unit for building in data.buildings for unit in building.air_to_water_units
|
||||
]
|
||||
if not current_ata and not current_atw_units:
|
||||
# An empty context is more likely an API glitch than every unit removed
|
||||
_LOGGER.debug("No units in the account, skipping stale device removal")
|
||||
return
|
||||
|
||||
current_ata_ids = {unit.id for unit in current_ata}
|
||||
self.known_ata &= current_ata_ids
|
||||
@@ -83,10 +90,6 @@ class MelCloudHomeCoordinator(DataUpdateCoordinator[UserContext]):
|
||||
for ata_callback in self.new_ata_callbacks:
|
||||
ata_callback(new_ata_units)
|
||||
|
||||
current_atw_units = [
|
||||
unit for building in data.buildings for unit in building.air_to_water_units
|
||||
]
|
||||
|
||||
current_atw_ids = {unit.id for unit in current_atw_units}
|
||||
self.known_atw &= current_atw_ids
|
||||
new_atw_ids = current_atw_ids - self.known_atw
|
||||
@@ -134,11 +137,16 @@ class MelCloudHomeCoordinator(DataUpdateCoordinator[UserContext]):
|
||||
translation_key="timeout_connect",
|
||||
) from err
|
||||
|
||||
for building in data.buildings:
|
||||
for ata_unit in building.air_to_air_units:
|
||||
self.ata_units[ata_unit.id] = ata_unit
|
||||
for atw_unit in building.air_to_water_units:
|
||||
self.atw_units[atw_unit.id] = atw_unit
|
||||
self.ata_units = {
|
||||
unit.id: unit
|
||||
for building in data.buildings
|
||||
for unit in building.air_to_air_units
|
||||
}
|
||||
self.atw_units = {
|
||||
unit.id: unit
|
||||
for building in data.buildings
|
||||
for unit in building.air_to_water_units
|
||||
}
|
||||
|
||||
return data
|
||||
|
||||
@@ -147,7 +155,7 @@ class MelCloudHomeCoordinator(DataUpdateCoordinator[UserContext]):
|
||||
def _async_refresh_finished(self) -> None:
|
||||
"""Notify entity callbacks after coordinator data has been updated."""
|
||||
if self.data is not None:
|
||||
self._notify_new_units(self.data)
|
||||
self._async_sync_units(self.data)
|
||||
|
||||
|
||||
@dataclass(kw_only=True, frozen=True)
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import override
|
||||
from aiomelcloudhome import ATAUnit, ATWUnit
|
||||
from yarl import URL
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.entity import EntityDescription
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
@@ -35,6 +36,7 @@ class MelCloudHomeUnitEntity[_UnitT: (ATAUnit, ATWUnit)](MelCloudHomeEntity):
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = entity_description
|
||||
self._unit_id = unit.id
|
||||
self._unit: _UnitT = unit
|
||||
self._attr_unique_id = f"{unit.id}_{self.entity_description.key}"
|
||||
self._attr_device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, unit.id)},
|
||||
@@ -55,10 +57,18 @@ class MelCloudHomeUnitEntity[_UnitT: (ATAUnit, ATWUnit)](MelCloudHomeEntity):
|
||||
"""Return if the entity is available."""
|
||||
return super().available and self._unit_id in self._units_dict()
|
||||
|
||||
@callback
|
||||
@override
|
||||
def _handle_coordinator_update(self) -> None:
|
||||
"""Keep the last known unit state while the unit is missing."""
|
||||
if (unit := self._units_dict().get(self._unit_id)) is not None:
|
||||
self._unit = unit
|
||||
super()._handle_coordinator_update()
|
||||
|
||||
@property
|
||||
def unit(self) -> _UnitT:
|
||||
"""Return the current unit state from coordinator data."""
|
||||
return self._units_dict()[self._unit_id]
|
||||
"""Return the latest known unit state."""
|
||||
return self._unit
|
||||
|
||||
|
||||
class MelCloudHomeATAUnitEntity(MelCloudHomeUnitEntity[ATAUnit]):
|
||||
|
||||
@@ -112,50 +112,113 @@ async def test_new_ata_unit_callback(
|
||||
assert ata_entities
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"removed_units_key",
|
||||
"removed_unit_id",
|
||||
"removed_entity_id",
|
||||
"kept_unit_id",
|
||||
"kept_entity_id",
|
||||
),
|
||||
[
|
||||
pytest.param(
|
||||
"airToAirUnits",
|
||||
"ata-unit-uuid-1",
|
||||
"climate.living_room_ac",
|
||||
"atw-unit-uuid-1",
|
||||
"climate.heat_pump_zone_1",
|
||||
id="ata",
|
||||
),
|
||||
pytest.param(
|
||||
"airToWaterUnits",
|
||||
"atw-unit-uuid-1",
|
||||
"climate.heat_pump_zone_1",
|
||||
"ata-unit-uuid-1",
|
||||
"climate.living_room_ac",
|
||||
id="atw",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_stale_devices_removed(
|
||||
hass: HomeAssistant,
|
||||
mock_melcloud_client: AsyncMock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
removed_units_key: str,
|
||||
removed_unit_id: str,
|
||||
removed_entity_id: str,
|
||||
kept_unit_id: str,
|
||||
kept_entity_id: str,
|
||||
) -> None:
|
||||
"""Test that devices are removed when units disappear from the account."""
|
||||
fixture = await async_load_json_object_fixture(hass, "context.json", DOMAIN)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
assert device_registry.async_get_device_by_identifier(
|
||||
(DOMAIN, removed_unit_id), mock_config_entry.entry_id
|
||||
)
|
||||
|
||||
mock_melcloud_client.get_context.return_value = UserContext.model_validate(
|
||||
{
|
||||
**fixture,
|
||||
"buildings": [
|
||||
{**building, removed_units_key: []} for building in fixture["buildings"]
|
||||
],
|
||||
}
|
||||
)
|
||||
freezer.tick(UPDATE_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert (
|
||||
device_registry.async_get_device_by_identifier(
|
||||
(DOMAIN, removed_unit_id), mock_config_entry.entry_id
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert device_registry.async_get_device_by_identifier(
|
||||
(DOMAIN, kept_unit_id), mock_config_entry.entry_id
|
||||
)
|
||||
assert hass.states.get(removed_entity_id) is None
|
||||
assert (state := hass.states.get(kept_entity_id))
|
||||
assert state.state != STATE_UNAVAILABLE
|
||||
|
||||
|
||||
async def test_empty_context_keeps_devices(
|
||||
hass: HomeAssistant,
|
||||
mock_melcloud_client: AsyncMock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test that a context without any units keeps the devices but marks them unavailable."""
|
||||
fixture = await async_load_json_object_fixture(hass, "context.json", DOMAIN)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
mock_melcloud_client.get_context.return_value = UserContext.model_validate(
|
||||
{**fixture, "buildings": [], "guestBuildings": []}
|
||||
)
|
||||
freezer.tick(UPDATE_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert device_registry.async_get_device_by_identifier(
|
||||
(DOMAIN, "ata-unit-uuid-1"), mock_config_entry.entry_id
|
||||
)
|
||||
assert device_registry.async_get_device_by_identifier(
|
||||
(DOMAIN, "atw-unit-uuid-1"), mock_config_entry.entry_id
|
||||
)
|
||||
assert hass.states.get("climate.living_room_ac").state == STATE_UNAVAILABLE
|
||||
assert hass.states.get("climate.heat_pump_zone_1").state == STATE_UNAVAILABLE
|
||||
|
||||
# Poof, now they're gone
|
||||
mock_melcloud_client.get_context.return_value = UserContext.model_validate(
|
||||
{
|
||||
**fixture,
|
||||
"buildings": [
|
||||
{**building, "airToAirUnits": [], "airToWaterUnits": []}
|
||||
for building in fixture["buildings"]
|
||||
],
|
||||
}
|
||||
)
|
||||
mock_melcloud_client.get_context.return_value = UserContext.model_validate(fixture)
|
||||
freezer.tick(UPDATE_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert (
|
||||
device_registry.async_get_device_by_identifier(
|
||||
(DOMAIN, "ata-unit-uuid-1"), mock_config_entry.entry_id
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert (
|
||||
device_registry.async_get_device_by_identifier(
|
||||
(DOMAIN, "atw-unit-uuid-1"), mock_config_entry.entry_id
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert hass.states.get("climate.living_room_ac").state != STATE_UNAVAILABLE
|
||||
assert hass.states.get("climate.heat_pump_zone_1").state != STATE_UNAVAILABLE
|
||||
|
||||
|
||||
async def test_new_atw_unit_callback(
|
||||
|
||||
Reference in New Issue
Block a user