diff --git a/homeassistant/components/esphome/assist_satellite.py b/homeassistant/components/esphome/assist_satellite.py index 40180e10f6d6..589df9480a92 100644 --- a/homeassistant/components/esphome/assist_satellite.py +++ b/homeassistant/components/esphome/assist_satellite.py @@ -20,7 +20,6 @@ from aioesphomeapi import ( VoiceAssistantEventType, VoiceAssistantExternalWakeWord, VoiceAssistantFeature, - VoiceAssistantTimerEventType, VoiceAssistantWakeWordAudio, ) import probatio @@ -36,11 +35,6 @@ from homeassistant.components.assist_pipeline import ( async_get_pipeline, ) from homeassistant.components.http import StaticPathConfig -from homeassistant.components.intent import ( - TimerEventType, - TimerInfo, - async_register_timer_handler, -) from homeassistant.components.media_player import async_process_play_media_url from homeassistant.components.tts import TextToSpeechCommonOption from homeassistant.const import Platform @@ -54,6 +48,7 @@ from homeassistant.util.hass_dict import HassKey from .const import ( ASSIST_SATELLITE_KEY, DOMAIN, + TIMER_LIST_KEY, WAKE_WORDS_API_PATH, WAKE_WORDS_DIR_NAME, ) @@ -107,25 +102,6 @@ _VOICE_ASSISTANT_EVENT_TYPES: EsphomeEnumMapper[ } ) -_TIMER_EVENT_TYPES: EsphomeEnumMapper[VoiceAssistantTimerEventType, TimerEventType] = ( - EsphomeEnumMapper( - { - VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_STARTED: ( - TimerEventType.STARTED - ), - VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_UPDATED: ( - TimerEventType.UPDATED - ), - VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_CANCELLED: ( - TimerEventType.CANCELLED - ), - VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_FINISHED: ( - TimerEventType.FINISHED - ), - } - ) -) - _ANNOUNCEMENT_TIMEOUT_SEC = 5 * 60 # 5 minutes _AUDIO_BYTES_PER_MS = 32 # 16Khz 16-bit mono _CONFIG_TIMEOUT_SEC = 5 @@ -191,14 +167,16 @@ class EsphomeAssistSatellite( self._audio_channel_fixed = False self._has_multi_channel_audio = False - def _get_entity_id(self, suffix: str) -> str | None: + def _get_entity_id( + self, suffix: str, platform: Platform = Platform.SELECT + ) -> str | None: """Return the entity id for pipeline select, etc.""" if self._entry_data.device_info is None: return None ent_reg = er.async_get(self.hass) return ent_reg.async_get_entity_id( - Platform.SELECT, + platform, DOMAIN, f"{self._entry_data.device_info.mac_address}-{suffix}", ) @@ -225,6 +203,12 @@ class EsphomeAssistSatellite( """Return the entity ID of the VAD sensitivity for the next conversation.""" return self._get_entity_id("vad_sensitivity") + @property + @override + def timer_list_entity_id(self) -> str | None: + """Return the entity ID of the timer list that holds the device's timers.""" + return self._get_entity_id(TIMER_LIST_KEY, Platform.TIMER_LIST) + @callback @override def async_get_configuration( @@ -368,17 +352,6 @@ class EsphomeAssistSatellite( ) ) - if feature_flags & VoiceAssistantFeature.TIMERS: - # Device supports timers - assert (self.registry_entry is not None) and ( - self.registry_entry.device_id is not None - ) - self.async_on_remove( - async_register_timer_handler( - self.hass, self.registry_entry.device_id, self.handle_timer_event - ) - ) - assert self._attr_supported_features is not None if feature_flags & VoiceAssistantFeature.ANNOUNCE: # Device supports announcements @@ -789,25 +762,6 @@ class EsphomeAssistSatellite( self._active_pipeline_index = 0 _LOGGER.debug("Pipeline finished") - def handle_timer_event( - self, event_type: TimerEventType, timer_info: TimerInfo - ) -> None: - """Handle timer events.""" - try: - native_event_type = _TIMER_EVENT_TYPES.from_hass(event_type) - except KeyError: - _LOGGER.debug("Received unknown timer event type: %s", event_type) - return - - self.cli.send_voice_assistant_timer_event( - native_event_type, - timer_info.id, - timer_info.name, - timer_info.created_seconds, - timer_info.seconds_left, - timer_info.is_active, - ) - async def handle_announcement_finished( self, announce_finished: VoiceAssistantAnnounceFinished ) -> None: diff --git a/homeassistant/components/esphome/const.py b/homeassistant/components/esphome/const.py index a7c3ebfe13d3..313e576dd25d 100644 --- a/homeassistant/components/esphome/const.py +++ b/homeassistant/components/esphome/const.py @@ -50,6 +50,7 @@ WAKE_WORDS_API_PATH = "/api/esphome/wake_words" # Built from the device info, so a cleanup path has to name them. ASSIST_SATELLITE_KEY: Final[str] = "assist_satellite" +TIMER_LIST_KEY: Final[str] = "timer_list" VOICE_ASSISTANT_SELECT_COUNT: Final[int] = 2 VOICE_ASSISTANT_SELECT_KEYS: Final[tuple[str, ...]] = ( *( diff --git a/homeassistant/components/esphome/manager.py b/homeassistant/components/esphome/manager.py index 6b4a70dfc6c9..c1d3e29ffa00 100644 --- a/homeassistant/components/esphome/manager.py +++ b/homeassistant/components/esphome/manager.py @@ -30,6 +30,7 @@ from aioesphomeapi import ( SupportsResponseType, UserService, UserServiceArgType, + VoiceAssistantFeature, ZWaveProxyRequest, ZWaveProxyRequestType, parse_log_message, @@ -101,6 +102,7 @@ from .const import ( PROJECT_URLS, STABLE_BLE_VERSION, STABLE_BLE_VERSION_STR, + TIMER_LIST_KEY, VOICE_ASSISTANT_SELECT_KEYS, ) from .dashboard import async_get_dashboard @@ -823,7 +825,10 @@ class ESPHomeManager: hass, device_info.bluetooth_mac_address or device_info.mac_address ) - if device_info.voice_assistant_feature_flags_compat(api_version): + voice_assistant_flags = device_info.voice_assistant_feature_flags_compat( + api_version + ) + if voice_assistant_flags: if Platform.ASSIST_SATELLITE not in entry_data.loaded_platforms: # Create assist satellite entity await self.hass.config_entries.async_forward_entry_setups( @@ -834,6 +839,17 @@ class ESPHomeManager: # Neither platform is reliably loaded here, so removal cannot live in them. _async_remove_voice_assistant_entities(hass, device_info.mac_address) + # Unlike the satellite, the timer list stays loaded across disconnects so + # that its timers keep running. + if voice_assistant_flags & VoiceAssistantFeature.TIMERS: + if Platform.TIMER_LIST not in entry_data.loaded_platforms: + await self.hass.config_entries.async_forward_entry_setups( + self.entry, [Platform.TIMER_LIST] + ) + entry_data.loaded_platforms.add(Platform.TIMER_LIST) + else: + await self._async_remove_timer_list(device_info.mac_address) + # Setup can wait for this, so only after the platforms are forwarded entry_data.first_connect_done.set() @@ -930,6 +946,20 @@ class ESPHomeManager: self.entry_data.loaded_platforms.remove(Platform.ASSIST_SATELLITE) + async def _async_remove_timer_list(self, mac_address: str) -> None: + """Remove the timer list of a device that no longer offers timers.""" + if Platform.TIMER_LIST in self.entry_data.loaded_platforms: + await self.hass.config_entries.async_unload_platforms( + self.entry, [Platform.TIMER_LIST] + ) + self.entry_data.loaded_platforms.remove(Platform.TIMER_LIST) + + ent_reg = er.async_get(self.hass) + if entity_id := ent_reg.async_get_entity_id( + Platform.TIMER_LIST, DOMAIN, f"{mac_address}-{TIMER_LIST_KEY}" + ): + ent_reg.async_remove(entity_id) + async def on_connect_error(self, err: Exception) -> None: """Start reauth flow if appropriate connect error type.""" if not isinstance( diff --git a/homeassistant/components/esphome/manifest.json b/homeassistant/components/esphome/manifest.json index b4a0336262f4..bac62b5dbffe 100644 --- a/homeassistant/components/esphome/manifest.json +++ b/homeassistant/components/esphome/manifest.json @@ -6,7 +6,7 @@ "codeowners": ["@jesserockz", "@kbx81", "@bdraco", "@arturpragacz"], "config_flow": true, "connectivity": ["esphome"], - "dependencies": ["assist_pipeline", "bluetooth", "intent", "ffmpeg", "http"], + "dependencies": ["assist_pipeline", "bluetooth", "ffmpeg", "http"], "dhcp": [ { "registered_devices": true diff --git a/homeassistant/components/esphome/strings.json b/homeassistant/components/esphome/strings.json index e88f9c9f2ccf..4eaefb1b2b43 100644 --- a/homeassistant/components/esphome/strings.json +++ b/homeassistant/components/esphome/strings.json @@ -133,6 +133,11 @@ "okay_nabu": "[%key:component::esphome::entity::select::wake_word::state::okay_nabu%]" } } + }, + "timer_list": { + "timers": { + "name": "Timers" + } } }, "exceptions": { diff --git a/homeassistant/components/esphome/timer_list.py b/homeassistant/components/esphome/timer_list.py new file mode 100644 index 000000000000..4accd4a82025 --- /dev/null +++ b/homeassistant/components/esphome/timer_list.py @@ -0,0 +1,112 @@ +"""Timer lists for ESPHome voice satellites.""" + +import math +from typing import TYPE_CHECKING, override + +from aioesphomeapi import VoiceAssistantTimerEventType + +from homeassistant.components.timer_list import ( + InMemoryTimerListEntity, + TimerListEvent, + TimerListEventType, + TimerStatus, +) +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import device_registry as dr +from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.util import dt as dt_util + +from .const import TIMER_LIST_KEY +from .entry_data import ESPHomeConfigEntry, RuntimeEntryData + +PARALLEL_UPDATES = 0 + +# The firmware has a single event for every change to a running timer. +_TIMER_EVENT_TYPES: dict[TimerListEventType, VoiceAssistantTimerEventType] = { + TimerListEventType.CREATED: VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_STARTED, + TimerListEventType.PAUSED: VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_UPDATED, + TimerListEventType.UNPAUSED: ( + VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_UPDATED + ), + TimerListEventType.TIME_CHANGED: ( + VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_UPDATED + ), + TimerListEventType.CANCELLED: ( + VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_CANCELLED + ), + TimerListEventType.FINISHED: ( + VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_FINISHED + ), +} + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ESPHomeConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the timer list of an ESPHome voice satellite.""" + entry_data = entry.runtime_data + device_info = entry_data.device_info + if TYPE_CHECKING: + assert device_info is not None + async_add_entities([EsphomeTimerList(entry_data, device_info.mac_address)]) + + +class EsphomeTimerList(InMemoryTimerListEntity): + """Timers of an ESPHome voice satellite, which the device shows and rings. + + Timers are kept in Home Assistant, so they keep running while the device is + disconnected; it misses the changes made in the meantime. + """ + + _attr_has_entity_name = True + _attr_translation_key = "timers" + + def __init__(self, entry_data: RuntimeEntryData, mac_address: str) -> None: + """Initialize the timer list.""" + super().__init__() + self._entry_data = entry_data + self._attr_unique_id = f"{mac_address}-{TIMER_LIST_KEY}" + self._attr_device_info = DeviceInfo( + connections={(dr.CONNECTION_NETWORK_MAC, mac_address)} + ) + + @override + async def async_added_to_hass(self) -> None: + """Send timer changes to the device.""" + await super().async_added_to_hass() + self.async_on_remove(self.async_subscribe_updates(self._async_send_event)) + + @callback + def _async_send_event(self, event: TimerListEvent) -> None: + """Send a timer change to the device.""" + if not self._entry_data.available: + return + + item = event.item + if event.event_type == TimerListEventType.REMOVED: + if item.status not in (TimerStatus.ACTIVE, TimerStatus.PAUSED): + return + # The device still has the timer, which it only drops when cancelled + native_event_type = ( + VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_CANCELLED + ) + seconds_left = 0 + is_active = False + else: + native_event_type = _TIMER_EVENT_TYPES[event.event_type] + seconds_left = math.ceil( + item.remaining_at(dt_util.utcnow()).total_seconds() + ) + is_active = item.status == TimerStatus.ACTIVE + + self._entry_data.client.send_voice_assistant_timer_event( + native_event_type, + item.timer_id, + item.name, + math.ceil(item.total_duration.total_seconds()), + seconds_left, + is_active, + ) diff --git a/tests/components/esphome/test_assist_satellite.py b/tests/components/esphome/test_assist_satellite.py index 1b2790009010..8826425de4a8 100644 --- a/tests/components/esphome/test_assist_satellite.py +++ b/tests/components/esphome/test_assist_satellite.py @@ -7,7 +7,7 @@ import io import socket import struct from typing import Any -from unittest.mock import ANY, AsyncMock, Mock, patch +from unittest.mock import AsyncMock, Mock, patch import wave from aioesphomeapi import ( @@ -20,7 +20,6 @@ from aioesphomeapi import ( VoiceAssistantCommandFlag, VoiceAssistantEventType, VoiceAssistantFeature, - VoiceAssistantTimerEventType, VoiceAssistantWakeWordAudio, ) import pytest @@ -792,118 +791,6 @@ async def test_pipeline_media_player( assert satellite.state == AssistSatelliteState.IDLE -async def test_timer_events( - hass: HomeAssistant, - device_registry: dr.DeviceRegistry, - mock_client: APIClient, - mock_esphome_device: MockESPHomeDeviceType, -) -> None: - """Test that injecting timer events results in the correct api client calls.""" - - mock_device = await mock_esphome_device( - mock_client=mock_client, - device_info={ - "voice_assistant_feature_flags": VoiceAssistantFeature.VOICE_ASSISTANT - | VoiceAssistantFeature.TIMERS - }, - ) - await hass.async_block_till_done() - dev = device_registry.async_get_device_by_connection( - (dr.CONNECTION_NETWORK_MAC, mock_device.entry.unique_id), - mock_device.entry.entry_id, - ) - - total_seconds = (1 * 60 * 60) + (2 * 60) + 3 - await intent_helper.async_handle( - hass, - "test", - intent_helper.INTENT_START_TIMER, - { - "name": {"value": "test timer"}, - "hours": {"value": 1}, - "minutes": {"value": 2}, - "seconds": {"value": 3}, - }, - device_id=dev.id, - ) - - mock_client.send_voice_assistant_timer_event.assert_called_with( - VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_STARTED, - ANY, - "test timer", - total_seconds, - total_seconds, - True, - ) - - # Increase timer beyond original time and check total_seconds has increased - mock_client.send_voice_assistant_timer_event.reset_mock() - - total_seconds += 5 * 60 - await intent_helper.async_handle( - hass, - "test", - intent_helper.INTENT_INCREASE_TIMER, - { - "name": {"value": "test timer"}, - "minutes": {"value": 5}, - }, - device_id=dev.id, - ) - - mock_client.send_voice_assistant_timer_event.assert_called_with( - VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_UPDATED, - ANY, - "test timer", - total_seconds, - ANY, - True, - ) - - -async def test_unknown_timer_event( - hass: HomeAssistant, - device_registry: dr.DeviceRegistry, - mock_client: APIClient, - mock_esphome_device: MockESPHomeDeviceType, -) -> None: - """Test that unknown (new) timer event types do not result in api calls.""" - - mock_device = await mock_esphome_device( - mock_client=mock_client, - device_info={ - "voice_assistant_feature_flags": VoiceAssistantFeature.VOICE_ASSISTANT - | VoiceAssistantFeature.TIMERS - }, - ) - await hass.async_block_till_done() - assert mock_device.entry.unique_id is not None - dev = device_registry.async_get_device_by_connection( - (dr.CONNECTION_NETWORK_MAC, mock_device.entry.unique_id), - mock_device.entry.entry_id, - ) - assert dev is not None - - with patch( - "homeassistant.components.esphome.assist_satellite._TIMER_EVENT_TYPES.from_hass", - side_effect=KeyError, - ): - await intent_helper.async_handle( - hass, - "test", - intent_helper.INTENT_START_TIMER, - { - "name": {"value": "test timer"}, - "hours": {"value": 1}, - "minutes": {"value": 2}, - "seconds": {"value": 3}, - }, - device_id=dev.id, - ) - - mock_client.send_voice_assistant_timer_event.assert_not_called() - - async def test_streaming_tts_errors( hass: HomeAssistant, mock_client: APIClient, diff --git a/tests/components/esphome/test_timer_list.py b/tests/components/esphome/test_timer_list.py new file mode 100644 index 000000000000..a7b5a175efa2 --- /dev/null +++ b/tests/components/esphome/test_timer_list.py @@ -0,0 +1,325 @@ +"""Test ESPHome timer lists.""" + +from datetime import timedelta +from typing import Any +from unittest.mock import ANY, call + +from aioesphomeapi import APIClient, VoiceAssistantFeature, VoiceAssistantTimerEventType +from freezegun.api import FrozenDateTimeFactory +import pytest +from pytest_homeassistant.common import async_fire_time_changed + +from homeassistant.components.esphome.const import DOMAIN +from homeassistant.components.timer_list import DOMAIN as TIMER_LIST_DOMAIN +from homeassistant.const import Platform, TargetKey +from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr, entity_registry as er, intent + +from .common import get_satellite_entity +from .conftest import ( + MockESPHomeDevice, + MockESPHomeDeviceType, + reconnect_with_updated_entity_info, +) + +TIMER_FLAGS = VoiceAssistantFeature.VOICE_ASSISTANT | VoiceAssistantFeature.TIMERS +STARTED = VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_STARTED +UPDATED = VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_UPDATED +CANCELLED = VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_CANCELLED +FINISHED = VoiceAssistantTimerEventType.VOICE_ASSISTANT_TIMER_FINISHED + + +@pytest.fixture +async def mock_device( + hass: HomeAssistant, + mock_client: APIClient, + mock_esphome_device: MockESPHomeDeviceType, +) -> MockESPHomeDevice: + """Set up an ESPHome voice satellite that supports timers.""" + device = await mock_esphome_device( + mock_client=mock_client, + device_info={"voice_assistant_feature_flags": TIMER_FLAGS}, + ) + await hass.async_block_till_done() + return device + + +def _timer_list_entity_id(hass: HomeAssistant, device: MockESPHomeDevice) -> str | None: + """Return the entity id of the device's timer list.""" + return er.async_get(hass).async_get_entity_id( + Platform.TIMER_LIST, DOMAIN, f"{device.device_info.mac_address}-timer_list" + ) + + +def _device_id(hass: HomeAssistant, device: MockESPHomeDevice) -> str: + """Return the device registry id of the ESPHome device.""" + assert device.entry.unique_id is not None + device_entry = dr.async_get(hass).async_get_device_by_connection( + (dr.CONNECTION_NETWORK_MAC, device.entry.unique_id), device.entry.entry_id + ) + assert device_entry is not None + return device_entry.id + + +async def _handle( + hass: HomeAssistant, device: MockESPHomeDevice, intent_type: str, **slots: Any +) -> None: + """Handle a timer intent spoken on the device.""" + await intent.async_handle( + hass, + "test", + intent_type, + {name: {"value": value} for name, value in slots.items()}, + device_id=_device_id(hass, device), + ) + + +async def _call(hass: HomeAssistant, entity_id: str, service: str, **data: Any) -> Any: + """Call a timer list action.""" + result = await hass.services.async_call( + TIMER_LIST_DOMAIN, + service, + data, + target={TargetKey.ENTITY_ID: entity_id}, + blocking=True, + return_response=service == "create_timer", + ) + return result[entity_id] if result else None + + +@pytest.mark.usefixtures("freezer") +async def test_voice_timer_events( + hass: HomeAssistant, mock_client: APIClient, mock_device: MockESPHomeDevice +) -> None: + """Test changes to a voice timer are sent to the device.""" + entity_id = _timer_list_entity_id(hass, mock_device) + assert entity_id == "timer_list.test_timers" + + await _handle( + hass, + mock_device, + intent.INTENT_START_TIMER, + name="test timer", + hours=1, + minutes=2, + seconds=3, + ) + await _handle(hass, mock_device, intent.INTENT_INCREASE_TIMER, minutes=5) + await _handle(hass, mock_device, intent.INTENT_PAUSE_TIMER) + await _handle(hass, mock_device, intent.INTENT_UNPAUSE_TIMER) + await _handle(hass, mock_device, intent.INTENT_DECREASE_TIMER, minutes=10) + await _handle(hass, mock_device, intent.INTENT_CANCEL_TIMER) + + assert hass.states.get(entity_id).state == "0" + assert mock_client.send_voice_assistant_timer_event.mock_calls == [ + call(STARTED, ANY, "test timer", 3723, 3723, True), + # Added time raises the total + call(UPDATED, ANY, "test timer", 4023, 4023, True), + call(UPDATED, ANY, "test timer", 4023, 4023, False), + call(UPDATED, ANY, "test timer", 4023, 4023, True), + # Removed time does not lower it + call(UPDATED, ANY, "test timer", 4023, 3423, True), + call(CANCELLED, ANY, "test timer", 4023, 0, False), + ] + timer_ids = { + event.args[1] + for event in mock_client.send_voice_assistant_timer_event.mock_calls + } + assert len(timer_ids) == 1 + + +@pytest.mark.usefixtures("freezer") +@pytest.mark.parametrize( + ("duration_seconds", "expected_seconds"), [(0.4, 1), (10.2, 11)] +) +async def test_fractional_duration_timer_event( + hass: HomeAssistant, + mock_client: APIClient, + mock_device: MockESPHomeDevice, + duration_seconds: float, + expected_seconds: int, +) -> None: + """Round fractional durations up consistently in device timer events.""" + entity_id = _timer_list_entity_id(hass, mock_device) + assert entity_id is not None + + result = await _call( + hass, entity_id, "create_timer", duration={"seconds": duration_seconds} + ) + + mock_client.send_voice_assistant_timer_event.assert_called_once_with( + STARTED, result["timer_id"], None, expected_seconds, expected_seconds, True + ) + + +async def test_pause_unpause_fractional_second( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_client: APIClient, + mock_device: MockESPHomeDevice, +) -> None: + """Keep positive remaining time visible when pausing and resuming a timer.""" + entity_id = _timer_list_entity_id(hass, mock_device) + assert entity_id is not None + result = await _call(hass, entity_id, "create_timer", duration={"seconds": 1}) + timer_id = result["timer_id"] + mock_client.send_voice_assistant_timer_event.reset_mock() + + freezer.tick(timedelta(milliseconds=600)) + await _call(hass, entity_id, "pause_timer", timer_id=timer_id) + freezer.tick(timedelta(seconds=1)) + await _call(hass, entity_id, "unpause_timer", timer_id=timer_id) + + assert mock_client.send_voice_assistant_timer_event.mock_calls == [ + call(UPDATED, timer_id, None, 1, 1, False), + call(UPDATED, timer_id, None, 1, 1, True), + ] + + +async def test_timer_finished( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_client: APIClient, + mock_device: MockESPHomeDevice, +) -> None: + """Test the device is told when a timer finishes, so it rings.""" + entity_id = _timer_list_entity_id(hass, mock_device) + assert entity_id is not None + result = await _call(hass, entity_id, "create_timer", duration={"seconds": 60}) + mock_client.send_voice_assistant_timer_event.reset_mock() + + freezer.tick(timedelta(seconds=60)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + mock_client.send_voice_assistant_timer_event.assert_called_once_with( + FINISHED, result["timer_id"], None, 60, 0, False + ) + + +@pytest.mark.usefixtures("freezer") +@pytest.mark.parametrize( + ("setup_services", "expected_calls"), + [ + pytest.param([], [call(CANCELLED, ANY, None, 60, 0, False)], id="active"), + pytest.param( + ["pause_timer"], [call(CANCELLED, ANY, None, 60, 0, False)], id="paused" + ), + pytest.param(["cancel_timer"], [], id="cancelled"), + pytest.param(["finish_timer"], [], id="finished"), + ], +) +async def test_remove_timer( + hass: HomeAssistant, + mock_client: APIClient, + mock_device: MockESPHomeDevice, + setup_services: list[str], + expected_calls: list[Any], +) -> None: + """Test removing a timer the device still shows cancels it there.""" + entity_id = _timer_list_entity_id(hass, mock_device) + assert entity_id is not None + result = await _call(hass, entity_id, "create_timer", duration={"seconds": 60}) + for service in setup_services: + await _call(hass, entity_id, service, timer_id=result["timer_id"]) + mock_client.send_voice_assistant_timer_event.reset_mock() + + await _call(hass, entity_id, "remove_timer", timer_id=result["timer_id"]) + + assert mock_client.send_voice_assistant_timer_event.mock_calls == expected_calls + + +@pytest.mark.usefixtures("freezer") +async def test_timers_kept_while_disconnected( + hass: HomeAssistant, mock_client: APIClient, mock_device: MockESPHomeDevice +) -> None: + """Test timers keep running while the device is disconnected.""" + entity_id = _timer_list_entity_id(hass, mock_device) + assert entity_id is not None + result = await _call(hass, entity_id, "create_timer", duration={"seconds": 60}) + mock_client.send_voice_assistant_timer_event.reset_mock() + + await mock_device.mock_disconnect(expected_disconnect=False) + await hass.async_block_till_done() + await _call( + hass, + entity_id, + "add_time", + timer_id=result["timer_id"], + duration={"seconds": 30}, + ) + + mock_client.send_voice_assistant_timer_event.assert_not_called() + assert hass.states.get(entity_id).state == "1" + + await mock_device.mock_connect() + await hass.async_block_till_done() + await _call(hass, entity_id, "pause_timer", timer_id=result["timer_id"]) + + assert hass.states.get(entity_id).state == "0" + mock_client.send_voice_assistant_timer_event.assert_called_once_with( + UPDATED, result["timer_id"], None, 90, 90, False + ) + + +async def test_no_timer_list_without_timers( + hass: HomeAssistant, + mock_client: APIClient, + mock_esphome_device: MockESPHomeDeviceType, +) -> None: + """Test a voice satellite without timers has no timer list.""" + device = await mock_esphome_device( + mock_client=mock_client, + device_info={ + "voice_assistant_feature_flags": VoiceAssistantFeature.VOICE_ASSISTANT + }, + ) + await hass.async_block_till_done() + + assert _timer_list_entity_id(hass, device) is None + assert Platform.TIMER_LIST not in device.entry.runtime_data.loaded_platforms + satellite = get_satellite_entity(hass, device.device_info.mac_address) + assert satellite is not None + assert satellite.timer_list_entity_id is None + + +async def test_satellite_timer_list_entity_id( + hass: HomeAssistant, mock_device: MockESPHomeDevice +) -> None: + """Test the satellite names its device's timer list.""" + satellite = get_satellite_entity(hass, mock_device.device_info.mac_address) + assert satellite is not None + + assert satellite.timer_list_entity_id == "timer_list.test_timers" + + +@pytest.mark.parametrize( + "flags", + [ + pytest.param(VoiceAssistantFeature.VOICE_ASSISTANT, id="timers_gone"), + pytest.param(0, id="voice_assistant_gone"), + ], +) +async def test_timer_list_follows_timers_feature( + hass: HomeAssistant, mock_device: MockESPHomeDevice, flags: int +) -> None: + """Test the timer list goes and comes back with the timers feature.""" + assert _timer_list_entity_id(hass, mock_device) is not None + + await reconnect_with_updated_entity_info( + hass, mock_device, [], device_info={"voice_assistant_feature_flags": flags} + ) + + assert _timer_list_entity_id(hass, mock_device) is None + assert Platform.TIMER_LIST not in mock_device.entry.runtime_data.loaded_platforms + + await reconnect_with_updated_entity_info( + hass, + mock_device, + [], + device_info={"voice_assistant_feature_flags": TIMER_FLAGS}, + ) + + entity_id = _timer_list_entity_id(hass, mock_device) + assert entity_id is not None + assert hass.states.get(entity_id).state == "0"