Add websocket support to MELCloud Home (#176527)

Co-authored-by: Joostlek <joostlek@outlook.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Erwin Douna
2026-10-20 12:34:48 +02:00
committed by GitHub
co-authored by Joostlek Claude Opus 5.5 Copilot Autofix powered by AI
parent 9f265809d9
commit b13f770d15
6 changed files with 478 additions and 18 deletions
@@ -47,6 +47,8 @@ async def async_setup_entry(
coordinator=coordinator,
telemetry_coordinator=telemetry_coordinator,
)
coordinator.async_start_live_updates()
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
@@ -7,7 +7,7 @@ from datetime import datetime, timedelta
import logging
from typing import Any, override
from aiomelcloudhome import ATAUnit, ATWUnit, MELCloudHome, UserContext
from aiomelcloudhome import ATAUnit, ATWUnit, MELCloudHome, UnitStateDelta, UserContext
from aiomelcloudhome.exceptions import (
MelCloudHomeAuthenticationError,
MelCloudHomeConnectionError,
@@ -22,11 +22,12 @@ from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util.dt import utcnow
from .const import DOMAIN
from .const import DEVICE_ATA, DEVICE_ATW, DOMAIN
_LOGGER = logging.getLogger(__name__)
UPDATE_INTERVAL = timedelta(seconds=60)
LIVE_UPDATE_INTERVAL = timedelta(minutes=10)
TELEMETRY_UPDATE_INTERVAL = timedelta(minutes=15)
# ATA telemetry reports Wh, ATW telemetry kWh per interval
@@ -65,21 +66,19 @@ class MelCloudHomeCoordinator(DataUpdateCoordinator[UserContext]):
update_interval=UPDATE_INTERVAL,
)
self.client = client
self.websocket = client.websocket()
self.ata_units: dict[str, ATAUnit] = {}
self.atw_units: dict[str, ATWUnit] = {}
self.known_ata: set[str] = set()
self.known_atw: set[str] = set()
self.new_ata_callbacks: list[Callable[[list[ATAUnit]], None]] = []
self.new_atw_callbacks: list[Callable[[list[ATWUnit]], None]] = []
self._deltas_during_fetch: list[UnitStateDelta] | None = None
def _async_sync_units(self, data: UserContext) -> None:
def _async_sync_units(self) -> 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
]
current_ata = list(self.ata_units.values())
current_atw_units = list(self.atw_units.values())
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")
@@ -124,6 +123,8 @@ class MelCloudHomeCoordinator(DataUpdateCoordinator[UserContext]):
@override
async def _async_update_data(self) -> UserContext:
"""Fetch data from the MELCloud Home API."""
deltas: list[UnitStateDelta] = []
self._deltas_during_fetch = deltas
try:
data = await self.client.get_context()
except MelCloudHomeAuthenticationError as err:
@@ -146,6 +147,8 @@ class MelCloudHomeCoordinator(DataUpdateCoordinator[UserContext]):
translation_domain=DOMAIN,
translation_key="api_error",
) from err
finally:
self._deltas_during_fetch = None
self.ata_units = {
unit.id: unit
@@ -157,6 +160,9 @@ class MelCloudHomeCoordinator(DataUpdateCoordinator[UserContext]):
for building in data.buildings
for unit in building.air_to_water_units
}
# The snapshot can predate deltas that arrived while it was fetched
for delta in deltas:
self._apply_delta(delta)
return data
@@ -165,7 +171,78 @@ 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._async_sync_units(self.data)
self._async_sync_units()
@callback
def async_start_live_updates(self) -> None:
"""Receive live updates until the config entry unloads."""
entry = self.config_entry
# Unload callbacks run in reverse, so the socket closes after unregistering
entry.async_on_unload(self.websocket.close)
entry.async_on_unload(
self.websocket.register_delta_callback(self.async_handle_delta)
)
entry.async_on_unload(
self.websocket.register_connection_callback(self.async_handle_connection)
)
entry.async_create_background_task(
self.hass, self._async_listen(), f"{DOMAIN}_websocket"
)
async def _async_listen(self) -> None:
"""Receive live updates until the websocket is closed."""
try:
await self.websocket.listen()
except MelCloudHomeAuthenticationError:
self.config_entry.async_start_reauth(self.hass)
@callback
def async_handle_delta(self, delta: UnitStateDelta) -> None:
"""Apply a websocket delta to the cached unit."""
_LOGGER.debug("Received websocket delta: %s", delta)
if self._deltas_during_fetch is not None:
self._deltas_during_fetch.append(delta)
if not self._apply_delta(delta):
return
# An in-flight fetch decides availability when it finishes
if self._deltas_during_fetch is None:
self.last_update_success = True
self.async_update_listeners()
def _apply_delta(self, delta: UnitStateDelta) -> bool:
"""Apply a delta to the cached unit of its type; return whether it changed."""
if delta.unit_type == DEVICE_ATA:
return _apply_unit_delta(self.ata_units, delta)
if delta.unit_type == DEVICE_ATW:
return _apply_unit_delta(self.atw_units, delta)
return False
@callback
def async_handle_connection(self, connected: bool) -> None:
"""Poll less often while live updates arrive."""
_LOGGER.debug("Live updates %s", "connected" if connected else "disconnected")
if connected:
self.update_interval = LIVE_UPDATE_INTERVAL
return
self.update_interval = UPDATE_INTERVAL
# Shutdown would wait for this request
if self.hass.is_stopping:
return
# Catches up on missed changes and reschedules polling at the shorter interval
self.config_entry.async_create_task(self.hass, self.async_request_refresh())
def _apply_unit_delta[_UnitT: (ATAUnit, ATWUnit)](
units: dict[str, _UnitT], delta: UnitStateDelta
) -> bool:
"""Apply a websocket delta to a cached unit; return whether it changed."""
# Unknown units are discovered by the regular poll
if (unit := units.get(delta.unit_id)) is None:
return False
if (updated := delta.apply_to(unit)) is unit:
return False
units[delta.unit_id] = updated
return True
@dataclass(kw_only=True, frozen=True)
@@ -6,7 +6,7 @@
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/melcloud_home",
"integration_type": "hub",
"iot_class": "cloud_polling",
"iot_class": "cloud_push",
"loggers": ["aiomelcloudhome"],
"quality_scale": "silver",
"requirements": ["aiomelcloudhome==0.3.1"]
+1 -1
View File
@@ -6992,7 +6992,7 @@
"melcloud_home": {
"integration_type": "hub",
"config_flow": true,
"iot_class": "cloud_polling",
"iot_class": "cloud_push",
"categories": [
"climate.heat_pumps_air_conditioning"
],
+9 -2
View File
@@ -3,7 +3,7 @@
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
from aiomelcloudhome import MELCloudHome, UserContext
from aiomelcloudhome import MELCloudHome, MELCloudHomeWebSocket, UserContext
from aiomelcloudhome.models.telemetry import TelemetryValue
import pytest
from pytest_homeassistant.common import (
@@ -36,9 +36,16 @@ def mock_setup_entry() -> Generator[AsyncMock]:
@pytest.fixture
def mock_melcloud_client() -> Generator[AsyncMock]:
def mock_websocket() -> AsyncMock:
"""Mock the MELCloud Home websocket."""
return AsyncMock(MELCloudHomeWebSocket)
@pytest.fixture
def mock_melcloud_client(mock_websocket: AsyncMock) -> Generator[AsyncMock]:
"""Mock MELCloud Home client."""
client = AsyncMock(MELCloudHome)
client.websocket.return_value = mock_websocket
client.get_context.return_value = UserContext.model_validate(
load_json_object_fixture("context.json", DOMAIN)
)
+378 -4
View File
@@ -2,7 +2,7 @@
from unittest.mock import AsyncMock
from aiomelcloudhome import UserContext
from aiomelcloudhome import UnitStateDelta, UserContext
from aiomelcloudhome.exceptions import (
MelCloudHomeAuthenticationError,
MelCloudHomeConnectionError,
@@ -13,36 +13,57 @@ from freezegun.api import FrozenDateTimeFactory
import pytest
from pytest_homeassistant.common import (
MockConfigEntry,
async_capture_events,
async_fire_time_changed,
async_load_json_object_fixture,
)
from homeassistant.components.climate import ATTR_CURRENT_TEMPERATURE, HVACMode
from homeassistant.components.melcloud_home.const import DOMAIN
from homeassistant.components.melcloud_home.coordinator import (
TELEMETRY_UPDATE_INTERVAL,
UPDATE_INTERVAL,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.const import (
ATTR_TEMPERATURE,
EVENT_STATE_CHANGED,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import CoreState, HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import setup_integration
from .conftest import MOCK_USER_INPUT
ATA_ENTITY_ID = "climate.living_room_ac"
ATW_ZONE1_ENTITY_ID = "climate.heat_pump_zone_1"
def _send_delta(mock_websocket: AsyncMock, delta: UnitStateDelta) -> None:
"""Pass a delta to the callback the integration registered."""
mock_websocket.register_delta_callback.call_args.args[0](delta)
@pytest.mark.usefixtures("mock_melcloud_client")
async def test_entry_setup_unload(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
) -> None:
"""Test integration setup and unload."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
mock_websocket.listen.assert_awaited_once()
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
mock_websocket.close.assert_awaited_once()
mock_websocket.register_delta_callback.return_value.assert_called_once()
mock_websocket.register_connection_callback.return_value.assert_called_once()
@pytest.mark.parametrize(
@@ -286,6 +307,359 @@ async def test_new_atw_unit_callback(
assert atw_entities
async def test_websocket_delta_updates_ata_state(
hass: HomeAssistant,
mock_melcloud_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
) -> None:
"""Test a websocket delta updates ATA state without triggering a poll."""
await setup_integration(hass, mock_config_entry)
state = hass.states.get(ATA_ENTITY_ID)
assert state.state == HVACMode.HEAT
_send_delta(
mock_websocket,
UnitStateDelta(
unit_id="ata-unit-uuid-1",
unit_type="ata",
changes={"Power": False, "SetTemperature": 25.0},
),
)
await hass.async_block_till_done()
state = hass.states.get(ATA_ENTITY_ID)
assert state.state == HVACMode.OFF
assert state.attributes[ATTR_TEMPERATURE] == 25.0
assert mock_melcloud_client.get_context.call_count == 1
@pytest.mark.usefixtures("mock_melcloud_client")
async def test_websocket_delta_updates_atw_zone_state(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
) -> None:
"""Test a websocket delta updates ATW zone state."""
await setup_integration(hass, mock_config_entry)
state = hass.states.get(ATW_ZONE1_ENTITY_ID)
assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 20.0
assert state.attributes[ATTR_TEMPERATURE] == 21.0
_send_delta(
mock_websocket,
UnitStateDelta(
unit_id="atw-unit-uuid-1",
unit_type="atw",
changes={"RoomTemperatureZone1": 21.5, "SetTemperatureZone1": 22.0},
),
)
await hass.async_block_till_done()
state = hass.states.get(ATW_ZONE1_ENTITY_ID)
assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 21.5
assert state.attributes[ATTR_TEMPERATURE] == 22.0
@pytest.mark.parametrize(
"delta",
[
pytest.param(
UnitStateDelta(
unit_id="unknown-unit", unit_type="ata", changes={"Power": False}
),
id="unknown_unit_id",
),
pytest.param(
UnitStateDelta(
unit_id="ata-unit-uuid-1",
unit_type="unknown",
changes={"Power": False},
),
id="unknown_unit_type",
),
pytest.param(
UnitStateDelta(
unit_id="ata-unit-uuid-1",
unit_type="ata",
changes={"OperationMode": None},
),
id="all_none_changes",
),
],
)
@pytest.mark.usefixtures("mock_melcloud_client")
async def test_websocket_delta_ignored(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
delta: UnitStateDelta,
) -> None:
"""Test deltas that change nothing do not write entity states."""
await setup_integration(hass, mock_config_entry)
last_reported = hass.states.get(ATA_ENTITY_ID).last_reported
_send_delta(mock_websocket, delta)
await hass.async_block_till_done()
assert hass.states.get(ATA_ENTITY_ID).last_reported == last_reported
@pytest.mark.usefixtures("mock_melcloud_client")
async def test_websocket_delta_unknown_setting(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
) -> None:
"""Test an unknown setting name does not change entity state."""
await setup_integration(hass, mock_config_entry)
before = hass.states.get(ATA_ENTITY_ID)
_send_delta(
mock_websocket,
UnitStateDelta(
unit_id="ata-unit-uuid-1",
unit_type="ata",
changes={"SomethingNew": "value"},
),
)
await hass.async_block_till_done()
after = hass.states.get(ATA_ENTITY_ID)
assert after.state == before.state
assert after.attributes == before.attributes
@pytest.mark.usefixtures("mock_melcloud_client")
async def test_websocket_delta_skips_none_values(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
) -> None:
"""Test None change values are skipped while others are applied."""
await setup_integration(hass, mock_config_entry)
_send_delta(
mock_websocket,
UnitStateDelta(
unit_id="ata-unit-uuid-1",
unit_type="ata",
changes={"OperationMode": None, "SetTemperature": 25.0},
),
)
await hass.async_block_till_done()
state = hass.states.get(ATA_ENTITY_ID)
assert state.state == HVACMode.HEAT
assert state.attributes[ATTR_TEMPERATURE] == 25.0
async def test_websocket_delta_during_fetch_kept(
hass: HomeAssistant,
mock_melcloud_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test a delta received while the context is fetched survives the older snapshot."""
await setup_integration(hass, mock_config_entry)
context = mock_melcloud_client.get_context.return_value
async def _get_context_with_delta() -> UserContext:
_send_delta(
mock_websocket,
UnitStateDelta(
unit_id="ata-unit-uuid-1", unit_type="ata", changes={"Power": False}
),
)
return context
mock_melcloud_client.get_context.side_effect = _get_context_with_delta
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_melcloud_client.get_context.call_count == 2
assert hass.states.get(ATA_ENTITY_ID).state == HVACMode.OFF
async def test_websocket_delta_restores_availability(
hass: HomeAssistant,
mock_melcloud_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test a websocket delta makes entities available again after a failed poll."""
await setup_integration(hass, mock_config_entry)
mock_melcloud_client.get_context.side_effect = MelCloudHomeConnectionError
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ATA_ENTITY_ID).state == STATE_UNAVAILABLE
_send_delta(
mock_websocket,
UnitStateDelta(
unit_id="ata-unit-uuid-1", unit_type="ata", changes={"Power": False}
),
)
await hass.async_block_till_done()
assert hass.states.get(ATA_ENTITY_ID).state == HVACMode.OFF
async def test_websocket_delta_during_failed_fetch_keeps_unavailable(
hass: HomeAssistant,
mock_melcloud_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test a delta during a failing retry does not mark entities available."""
await setup_integration(hass, mock_config_entry)
mock_melcloud_client.get_context.side_effect = MelCloudHomeConnectionError
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ATA_ENTITY_ID).state == STATE_UNAVAILABLE
async def _get_context_with_delta() -> UserContext:
_send_delta(
mock_websocket,
UnitStateDelta(
unit_id="ata-unit-uuid-1", unit_type="ata", changes={"Power": False}
),
)
raise MelCloudHomeConnectionError
mock_melcloud_client.get_context.side_effect = _get_context_with_delta
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_melcloud_client.get_context.call_count == 3
assert hass.states.get(ATA_ENTITY_ID).state == STATE_UNAVAILABLE
async def test_new_unit_gets_delta_received_during_fetch(
hass: HomeAssistant,
mock_melcloud_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test a unit discovered by a fetch starts with deltas received during it."""
fixture = await async_load_json_object_fixture(hass, "context.json", DOMAIN)
mock_melcloud_client.get_context.return_value = UserContext.model_validate(
{
**fixture,
"buildings": [
{**building, "airToAirUnits": []} for building in fixture["buildings"]
],
}
)
await setup_integration(hass, mock_config_entry)
assert hass.states.get(ATA_ENTITY_ID) is None
async def _get_context_with_delta() -> UserContext:
_send_delta(
mock_websocket,
UnitStateDelta(
unit_id="ata-unit-uuid-1", unit_type="ata", changes={"Power": False}
),
)
return UserContext.model_validate(fixture)
mock_melcloud_client.get_context.side_effect = _get_context_with_delta
events = async_capture_events(hass, EVENT_STATE_CHANGED)
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert [
event.data["new_state"].state
for event in events
if event.data["entity_id"] == ATA_ENTITY_ID
] == [HVACMode.OFF]
async def test_live_updates_slow_down_polling(
hass: HomeAssistant,
mock_melcloud_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test polling slows down while connected and catches up after a disconnect."""
await setup_integration(hass, mock_config_entry)
assert mock_melcloud_client.get_context.call_count == 1
on_connection = mock_websocket.register_connection_callback.call_args.args[0]
on_connection(True)
# The refresh scheduled before connecting still runs at the old interval
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_melcloud_client.get_context.call_count == 2
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_melcloud_client.get_context.call_count == 2
on_connection(False)
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_melcloud_client.get_context.call_count == 3
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_melcloud_client.get_context.call_count == 4
async def test_live_updates_disconnect_while_stopping(
hass: HomeAssistant,
mock_melcloud_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
) -> None:
"""Test a disconnect during shutdown does not start a catch-up refresh."""
await setup_integration(hass, mock_config_entry)
on_connection = mock_websocket.register_connection_callback.call_args.args[0]
hass.set_state(CoreState.stopping)
on_connection(False)
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_melcloud_client.get_context.call_count == 1
@pytest.mark.usefixtures("mock_melcloud_client")
async def test_live_updates_auth_failure_starts_reauth(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_websocket: AsyncMock,
) -> None:
"""Test an authentication error from the websocket starts reauthentication."""
mock_websocket.listen.side_effect = MelCloudHomeAuthenticationError("bad creds")
await setup_integration(hass, mock_config_entry)
await hass.async_block_till_done(wait_background_tasks=True)
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["context"]["source"] == SOURCE_REAUTH
@pytest.mark.parametrize(
"exception",
[