Add handling for program updates when active program finishes at Home Connect (#184128)

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
J. Diego Rodríguez Royo
2026-11-03 19:37:20 +01:00
committed by GitHub
co-authored by Copilot Autofix powered by AI
parent 1076095232
commit bc20fdfd6e
4 changed files with 390 additions and 72 deletions
@@ -295,7 +295,7 @@ class HomeConnectApplianceCoordinator(DataUpdateCoordinator[HomeConnectAppliance
self.global_listeners = global_listeners
self.data = HomeConnectApplianceData.empty(appliance)
self._execution_tracker: list[float] = []
self._program_run_ended = False
self.last_fetched_program: tuple[EventKey, ProgramKey] | None = None
def _get_listeners_for_event_key(self, event_key: EventKey) -> list[CALLBACK_TYPE]:
return [
@@ -327,24 +327,42 @@ class HomeConnectApplianceCoordinator(DataUpdateCoordinator[HomeConnectAppliance
"""Match event with listener for event type."""
# Clear before storing the items, as the message can
# already contain the progress of the new program run.
cleared_event_keys = self._clear_progress_of_ended_program_run(event_message)
(
operation_state_finished,
operation_state_changed,
program_finished,
active_program_changed,
) = self._get_program_finished_info(event_message)
cleared_event_keys = self._clear_progress_of_ended_program_run(
(operation_state_finished and operation_state_changed)
or program_finished
or active_program_changed is not None
)
await self._fetch_selected_program_if_just_finished(
operation_state_finished
and program_finished
and (operation_state_changed or active_program_changed) is True,
event_message,
)
match event_message.type:
case EventType.STATUS:
statuses = self.data.status
for event in event_message.data.items:
status_key = StatusKey(event.key)
status_value = event.value
if status_key in statuses:
statuses[status_key].value = event.value
statuses[status_key].value = status_value
else:
statuses[status_key] = Status(
key=status_key,
raw_key=status_key.value,
value=event.value,
value=status_value,
)
if (
status_key == StatusKey.BSH_COMMON_OPERATION_STATE
and event.value == BSH_OPERATION_STATE_PAUSE
and status_value == BSH_OPERATION_STATE_PAUSE
and CommandKey.BSH_COMMON_RESUME_PROGRAM
not in (commands := self.data.commands)
):
@@ -357,6 +375,7 @@ class HomeConnectApplianceCoordinator(DataUpdateCoordinator[HomeConnectAppliance
) in self.global_listeners.values():
if EventKey.BSH_COMMON_APPLIANCE_DEPAIRED not in context:
listener()
self._call_event_listener(event_message)
case EventType.NOTIFY:
@@ -381,13 +400,21 @@ class HomeConnectApplianceCoordinator(DataUpdateCoordinator[HomeConnectAppliance
EventKey.BSH_COMMON_ROOT_ACTIVE_PROGRAM,
EventKey.BSH_COMMON_ROOT_SELECTED_PROGRAM,
) and isinstance(event_value, str):
program_update_event_value = ProgramKey(event_value)
program_update_event_value = (
event_key,
ProgramKey(event_value),
)
events[event_key] = event
# Process program update after all events to ensure
# BSH_COMMON_OPTION_BASE_PROGRAM event is available for
# favorite program resolution
# favorite program resolution.
# Also avoid redundant program fetches if the
# program hasn't changed since the last fetch.
if program_update_event_value:
await self.update_options(program_update_event_value)
await self.update_options(program_update_event_value[1])
self.last_fetched_program = program_update_event_value
self._call_event_listener(event_message)
case EventType.EVENT:
@@ -427,18 +454,63 @@ class HomeConnectApplianceCoordinator(DataUpdateCoordinator[HomeConnectAppliance
for listener in self._get_listeners_for_event_key(event.key):
listener()
def _update_program_run(self, event_message: EventMessage) -> bool:
"""Track the program run and return whether the message ends or replaces it."""
def _get_program_finished_info(
self, event_message: EventMessage
) -> tuple[bool, bool | None, bool, bool | None]:
"""Return information to know if a program just finished.
A program is truly finished when the operation state is INACTIVE or READY
and the active program is cleared.
Then the old stuff from the active program can be cleared.
To verify if it just finished, we need check the previous operation state
and the previous active program.
"""
operation_state_status: Status | Event | None = None
prev_operation_state = (
operation_state_status.value
if (
operation_state_status := self.data.status.get(
StatusKey.BSH_COMMON_OPERATION_STATE
)
)
else None
)
operation_state_truly_finished = (
(prev_operation_state := operation_state_status.value)
in (BSH_OPERATION_STATE_INACTIVE, BSH_OPERATION_STATE_READY)
if operation_state_status is not None
else False
)
operation_state = None
prev_program = (
prev_program_event.value
if (
prev_program_event := self.data.events.get(
EventKey.BSH_COMMON_ROOT_ACTIVE_PROGRAM
)
)
else None
)
active_program_finished = prev_program is None
program = None
match event_message.type:
case EventType.STATUS:
if any(
event.key == EventKey.BSH_COMMON_STATUS_OPERATION_STATE
and event.value
in (BSH_OPERATION_STATE_INACTIVE, BSH_OPERATION_STATE_READY)
for event in event_message.data.items
):
self._program_run_ended = True
return True
operation_state_status = next(
(
status
for status in event_message.data.items
if status.key == EventKey.BSH_COMMON_STATUS_OPERATION_STATE
),
None,
)
if operation_state_status:
operation_state = operation_state_status.value
operation_state_truly_finished = operation_state in (
BSH_OPERATION_STATE_INACTIVE,
BSH_OPERATION_STATE_READY,
)
case EventType.NOTIFY:
program_event = next(
(
@@ -448,31 +520,24 @@ class HomeConnectApplianceCoordinator(DataUpdateCoordinator[HomeConnectAppliance
),
None,
)
if program_event is None:
return False
if not program_event.value:
self._program_run_ended = True
return True
# Progress received after the previous run ended
# belongs to the program that is starting now.
program_run_ended = self._program_run_ended
self._program_run_ended = False
previous_event = self.data.events.get(
EventKey.BSH_COMMON_ROOT_ACTIVE_PROGRAM
)
return (
not program_run_ended
and previous_event is not None
and bool(previous_event.value)
and program_event.value != previous_event.value
)
return False
if program_event is not None and (
program := program_event.value is None
):
active_program_finished = True
return (
operation_state_truly_finished,
operation_state != prev_operation_state
if operation_state is not None
else None,
active_program_finished,
program != prev_program if program is not None else None,
)
def _clear_progress_of_ended_program_run(
self, event_message: EventMessage
self, program_finished: bool
) -> list[EventKey]:
"""Remove the progress events of a program run that has ended."""
if not self._update_program_run(event_message):
if not program_finished:
return []
events = self.data.events
return [
@@ -481,6 +546,47 @@ class HomeConnectApplianceCoordinator(DataUpdateCoordinator[HomeConnectAppliance
if events.pop(event_key, None) is not None
]
async def _fetch_selected_program_if_just_finished(
self, program_just_finished: bool, event_message: EventMessage
) -> None:
"""Fetch the selected program if the active program just finished.
Except for the case where the selected program is changes already in the event message,
in which case we don't need to fetch it.
"""
if not (
program_just_finished
and (
selected_program_event := self.data.events.get(
EventKey.BSH_COMMON_ROOT_SELECTED_PROGRAM
)
)
and isinstance(selected_program := selected_program_event.value, str)
and self.last_fetched_program
!= (
EventKey.BSH_COMMON_ROOT_SELECTED_PROGRAM,
program := ProgramKey(selected_program),
)
and all( # If there's already a select program event, don't fetch
event.key != EventKey.BSH_COMMON_ROOT_SELECTED_PROGRAM
for event in event_message.data.items
)
):
return
# When the active program is cleared, refresh options from the selected
# program so the UI doesn't keep showing the completed program's options.
# Wait for READY; earlier requests fail.
await self.update_options(program)
self.last_fetched_program = (
EventKey.BSH_COMMON_ROOT_SELECTED_PROGRAM,
program,
)
# Notify listeners to discover entities for the refreshed options.
for listener in self._get_listeners_for_event_key(
EventKey.BSH_COMMON_ROOT_SELECTED_PROGRAM
):
listener()
@callback
def _call_listeners_for_missing_event_keys(
self, event_keys: list[EventKey]
@@ -645,6 +751,7 @@ class HomeConnectApplianceCoordinator(DataUpdateCoordinator[HomeConnectAppliance
if option.key == OptionKey.BSH_COMMON_BASE_PROGRAM:
current_program_key = ProgramKey(option.value)
break
self.last_fetched_program = (event_key, current_program_key)
if current_program_key:
options = await self.get_options_definitions(current_program_key)
@@ -685,11 +792,6 @@ class HomeConnectApplianceCoordinator(DataUpdateCoordinator[HomeConnectAppliance
status=status,
)
)
operation_state = self.data.status.get(StatusKey.BSH_COMMON_OPERATION_STATE)
self._program_run_ended = operation_state is not None and (
operation_state.value
in (BSH_OPERATION_STATE_INACTIVE, BSH_OPERATION_STATE_READY)
)
async def get_options_definitions(
self, program_key: ProgramKey
@@ -5,7 +5,7 @@ from datetime import timedelta
from http import HTTPStatus
import re
from typing import Any, cast
from unittest.mock import AsyncMock, MagicMock, patch
from unittest.mock import AsyncMock, MagicMock, call, patch
from aiohomeconnect.const import OAUTH2_TOKEN
from aiohomeconnect.model import (
@@ -33,6 +33,7 @@ from aiohomeconnect.model.error import (
UnauthorizedError,
)
from aiohomeconnect.model.program import (
EnumerateProgram,
Option,
OptionKey,
Program,
@@ -51,6 +52,8 @@ from homeassistant.components.home_connect.const import (
BSH_DOOR_STATE_LOCKED,
BSH_DOOR_STATE_OPEN,
BSH_EVENT_PRESENT_STATE_PRESENT,
BSH_OPERATION_STATE_FINISHED,
BSH_OPERATION_STATE_READY,
BSH_POWER_OFF,
DOMAIN,
)
@@ -774,8 +777,8 @@ async def test_paired_event(
# called twice. One when creating the coordinator,
# and another on first coordinator refresh (to get connected status)
assert client.get_specific_appliance.call_count == 2
for call in client.get_specific_appliance.call_args_list:
assert call.args[0] == appliance.ha_id
for _call in client.get_specific_appliance.call_args_list:
assert _call.args[0] == appliance.ha_id
for method in INITIAL_FETCH_CLIENT_METHODS:
getattr(client, method).assert_awaited_once()
@@ -810,8 +813,8 @@ async def test_paired_disconnected_devices_not_fetching(
# called twice. One when creating the coordinator,
# and another on first coordinator refresh (to get connected status)
assert client.get_specific_appliance.call_count == 2
for call in client.get_specific_appliance.call_args_list:
assert call.args[0] == appliance.ha_id
for _call in client.get_specific_appliance.call_args_list:
assert _call.args[0] == appliance.ha_id
for method in INITIAL_FETCH_CLIENT_METHODS:
getattr(client, method).assert_not_awaited()
@@ -1190,6 +1193,232 @@ async def test_fetch_base_program_options_when_favorite_program_event(
)
@pytest.mark.parametrize(
("event_order", "initially_selected_program", "programs_fetched"),
[
pytest.param(
[0, 1, 2],
ProgramKey.DISHCARE_DISHWASHER_AUTO_1,
[ProgramKey.DISHCARE_DISHWASHER_ECO_50],
id="active_program_selected_program_operation_state",
),
pytest.param(
[0, 2, 1],
ProgramKey.DISHCARE_DISHWASHER_AUTO_1,
[
ProgramKey.DISHCARE_DISHWASHER_AUTO_1,
ProgramKey.DISHCARE_DISHWASHER_ECO_50,
],
id="active_program_operation_state_selected_program",
),
pytest.param(
[1, 0, 2],
ProgramKey.DISHCARE_DISHWASHER_AUTO_1,
[ProgramKey.DISHCARE_DISHWASHER_ECO_50],
id="selected_program_active_program_operation_state",
),
pytest.param(
[1, 2, 0],
ProgramKey.DISHCARE_DISHWASHER_AUTO_1,
[ProgramKey.DISHCARE_DISHWASHER_ECO_50],
id="selected_program_operation_state_active_program",
),
pytest.param(
[2, 1, 0],
ProgramKey.DISHCARE_DISHWASHER_AUTO_1,
[ProgramKey.DISHCARE_DISHWASHER_ECO_50],
id="operation_state_selected_program_active_program",
),
pytest.param(
[2, 0, 1],
ProgramKey.DISHCARE_DISHWASHER_AUTO_1,
[
ProgramKey.DISHCARE_DISHWASHER_AUTO_1,
ProgramKey.DISHCARE_DISHWASHER_ECO_50,
],
id="operation_state_active_program_selected_program",
),
# When the selected program is the default, no selected-program event
# is emitted.
pytest.param(
[0, 2],
ProgramKey.DISHCARE_DISHWASHER_ECO_50,
[ProgramKey.DISHCARE_DISHWASHER_ECO_50],
id="active_program_operation_state",
),
pytest.param(
[2, 0],
ProgramKey.DISHCARE_DISHWASHER_ECO_50,
[ProgramKey.DISHCARE_DISHWASHER_ECO_50],
id="operation_state_active_program",
),
],
)
@pytest.mark.parametrize("appliance", ["Dishwasher"], indirect=True)
async def test_fetch_options_for_selected_program_when_active_program_finishes(
hass: HomeAssistant,
client: MagicMock,
config_entry: MockConfigEntry,
integration_setup: Callable[[MagicMock], Awaitable[bool]],
appliance: HomeAppliance,
event_order: list[int],
initially_selected_program: ProgramKey,
programs_fetched: list[ProgramKey],
) -> None:
"""Test selected program options are fetched when the active program finishes.
This should update the options to the selected program options; otherwise,
we would keep the options from the last active program, which is no longer active.
If the selected program has already been fetched, it should not be fetched again
if it is the same.
"""
appliance_ha_id = appliance.ha_id
events = [
EventMessage(
appliance_ha_id,
EventType.NOTIFY,
data=ArrayOfEvents(
[
Event(
key=EventKey.BSH_COMMON_ROOT_ACTIVE_PROGRAM,
raw_key=EventKey.BSH_COMMON_ROOT_ACTIVE_PROGRAM.value,
timestamp=0,
level="",
handling="",
value=None,
)
]
),
),
EventMessage(
appliance_ha_id,
EventType.NOTIFY,
data=ArrayOfEvents(
[
Event(
key=EventKey.BSH_COMMON_ROOT_SELECTED_PROGRAM,
raw_key=EventKey.BSH_COMMON_ROOT_SELECTED_PROGRAM.value,
timestamp=0,
level="",
handling="",
value=ProgramKey.DISHCARE_DISHWASHER_ECO_50.value,
)
]
),
),
EventMessage(
appliance_ha_id,
EventType.STATUS,
data=ArrayOfEvents(
[
Event(
key=StatusKey.BSH_COMMON_OPERATION_STATE,
raw_key=StatusKey.BSH_COMMON_OPERATION_STATE.value,
timestamp=0,
level="",
handling="",
value=BSH_OPERATION_STATE_READY,
)
]
),
),
]
events = [events[i] for i in event_order]
client.get_all_programs = AsyncMock(
return_value=ArrayOfPrograms(
[
EnumerateProgram(
ProgramKey.DISHCARE_DISHWASHER_AUTO_1,
ProgramKey.DISHCARE_DISHWASHER_AUTO_1.value,
)
],
Program(
key=ProgramKey.DISHCARE_DISHWASHER_AUTO_1,
options=[
Option(
value=True,
key=OptionKey.DISHCARE_DISHWASHER_SILENCE_ON_DEMAND,
)
],
),
Program(
key=initially_selected_program,
),
)
)
client.get_available_program = AsyncMock(
return_value=ProgramDefinition(
ProgramKey.DISHCARE_DISHWASHER_AUTO_1,
options=[
ProgramDefinitionOption(
OptionKey.DISHCARE_DISHWASHER_SILENCE_ON_DEMAND,
"Boolean",
constraints=ProgramDefinitionConstraints(default=False),
)
],
)
)
assert await integration_setup(client)
assert config_entry.state is ConfigEntryState.LOADED
selected_program_option_entity_id = "switch.dishwasher_half_load"
active_program_option_entity_id = "switch.dishwasher_silence_on_demand"
await hass.async_block_till_done()
await client.add_events(
[
EventMessage(
appliance_ha_id,
EventType.STATUS,
data=ArrayOfEvents(
[
Event(
key=StatusKey.BSH_COMMON_OPERATION_STATE,
raw_key=StatusKey.BSH_COMMON_OPERATION_STATE.value,
timestamp=0,
level="",
handling="",
value=BSH_OPERATION_STATE_FINISHED,
)
]
),
)
]
)
await hass.async_block_till_done()
assert not hass.states.is_state(active_program_option_entity_id, STATE_UNAVAILABLE)
assert not hass.states.get(selected_program_option_entity_id)
client.get_available_program = AsyncMock(
side_effect=[
ProgramDefinition(
program_key,
options=[
ProgramDefinitionOption(
OptionKey.DISHCARE_DISHWASHER_HALF_LOAD,
"Boolean",
constraints=ProgramDefinitionConstraints(default=False),
)
],
)
for program_key in programs_fetched
]
)
await client.add_events(events)
await hass.async_block_till_done()
assert client.get_available_program.await_args_list == [
call(appliance_ha_id, program_key=program_key)
for program_key in programs_fetched
]
assert hass.states.is_state(active_program_option_entity_id, STATE_UNAVAILABLE)
selected_program_option_state = hass.states.get(selected_program_option_entity_id)
assert selected_program_option_state
assert selected_program_option_state.state != STATE_UNAVAILABLE
@pytest.mark.parametrize("appliance", ["Dishwasher"], indirect=True)
@pytest.mark.parametrize(
"event_key",
+2 -2
View File
@@ -544,7 +544,7 @@ async def test_supported_features(
client.get_available_program = AsyncMock(
return_value=ProgramDefinition(
ProgramKey.HEATING_VENTILATION_AIR_CONDITIONING_AIR_CONDITIONER_AUTO,
ProgramKey.HEATING_VENTILATION_AIR_CONDITIONING_AIR_CONDITIONER_COOL,
options=[],
)
)
@@ -561,7 +561,7 @@ async def test_supported_features(
timestamp=0,
level="",
handling="",
value=ProgramKey.HEATING_VENTILATION_AIR_CONDITIONING_AIR_CONDITIONER_AUTO,
value=ProgramKey.HEATING_VENTILATION_AIR_CONDITIONING_AIR_CONDITIONER_COOL.value,
)
]
),
+8 -21
View File
@@ -1106,16 +1106,6 @@ async def test_program_finish_time_not_carried_over_to_next_program(
"0",
id="new_program_with_timer_reported_before_program",
),
pytest.param(
{
EventKey.BSH_COMMON_ROOT_ACTIVE_PROGRAM: (
ProgramKey.COOKING_OVEN_HEATING_MODE_HOT_AIR.value
)
},
"2021-01-09T12:30:00+00:00",
"10",
id="same_program",
),
],
)
async def test_program_finish_time_on_program_change_while_running(
@@ -1256,12 +1246,9 @@ async def test_program_finish_time_after_reconnection(
@pytest.mark.parametrize(
"start_event_order",
[
pytest.param((0, 1, 2), id="progress_program_operation_state"),
pytest.param((0, 2, 1), id="progress_operation_state_program"),
pytest.param((1, 0, 2), id="program_progress_operation_state"),
pytest.param((1, 2, 0), id="program_operation_state_progress"),
pytest.param((2, 0, 1), id="operation_state_progress_program"),
pytest.param((2, 1, 0), id="operation_state_program_progress"),
pytest.param((0, 1, 2), id="program_progress_operation_state"),
pytest.param((0, 2, 1), id="program_operation_state_progress"),
pytest.param((2, 0, 1), id="operation_state_program_progress"),
],
)
async def test_program_finish_time_on_program_start(
@@ -1306,17 +1293,17 @@ async def test_program_finish_time_on_program_start(
appliance.ha_id,
EventType.NOTIFY,
{
EventKey.BSH_COMMON_OPTION_REMAINING_PROGRAM_TIME: 1200,
EventKey.BSH_COMMON_OPTION_PROGRAM_PROGRESS: 0,
EventKey.BSH_COMMON_ROOT_ACTIVE_PROGRAM: (
ProgramKey.COOKING_OVEN_HEATING_MODE_TOP_BOTTOM_HEATING.value
)
},
),
create_event_message(
appliance.ha_id,
EventType.NOTIFY,
{
EventKey.BSH_COMMON_ROOT_ACTIVE_PROGRAM: (
ProgramKey.COOKING_OVEN_HEATING_MODE_TOP_BOTTOM_HEATING.value
)
EventKey.BSH_COMMON_OPTION_REMAINING_PROGRAM_TIME: 1200,
EventKey.BSH_COMMON_OPTION_PROGRAM_PROGRESS: 0,
},
),
create_event_message(