diff --git a/homeassistant/components/shelly/coordinator.py b/homeassistant/components/shelly/coordinator.py index 213d15256cfa..a8af435a3a74 100644 --- a/homeassistant/components/shelly/coordinator.py +++ b/homeassistant/components/shelly/coordinator.py @@ -104,6 +104,13 @@ class ShellyEntryData: type ShellyConfigEntry = ConfigEntry[ShellyEntryData] +# Components whose config changes only affect entity state, so they are +# refreshed on config_changed instead of reloading the entry +RPC_CONFIG_UPDATERS: dict[str, Callable[[RpcDevice], Coroutine[Any, Any, None]]] = { + "plugs_ui": lambda device: device.update_plugs_ui_config(), + "powerstrip_ui": lambda device: device.update_powerstrip_ui_config(), +} + class ShellyCoordinatorBase[_DeviceT: BlockDevice | RpcDevice]( DataUpdateCoordinator[None] @@ -635,6 +642,20 @@ class ShellyRpcCoordinator(ShellyCoordinatorBase[RpcDevice]): return _unsubscribe + async def _async_update_component_config(self, component: str) -> None: + """Fetch the changed component config and update entities.""" + try: + await RPC_CONFIG_UPDATERS[component](self.device) + except (DeviceConnectionError, RpcCallError) as err: + LOGGER.debug( + "Error updating %s config for %s: %s", component, self.name, err + ) + return + except InvalidAuthError: + await self.async_shutdown_device_and_start_reauth() + return + self.async_update_listeners() + @callback def _async_device_event_handler(self, event_data: dict[str, Any]) -> None: """Handle device events.""" @@ -652,8 +673,13 @@ class ShellyRpcCoordinator(ShellyCoordinatorBase[RpcDevice]): for event_callback in self._event_listeners: event_callback(event) - # Plug LED settings do not change any entity, so they need no reload - if event_type == "config_changed" and component == "plugs_ui": + if event_type == "config_changed" and component in RPC_CONFIG_UPDATERS: + self.config_entry.async_create_background_task( + self.hass, + self._async_update_component_config(component), + "rpc device component config update", + eager_start=True, + ) continue if event_type in ("component_added", "component_removed", "config_changed"): diff --git a/homeassistant/components/shelly/icons.json b/homeassistant/components/shelly/icons.json index 67c5d4e1515f..de8bf5d64669 100644 --- a/homeassistant/components/shelly/icons.json +++ b/homeassistant/components/shelly/icons.json @@ -28,6 +28,9 @@ "select": { "effect_palette": { "default": "mdi:palette" + }, + "led_mode": { + "default": "mdi:led-on" } }, "sensor": { diff --git a/homeassistant/components/shelly/select.py b/homeassistant/components/shelly/select.py index 89eaf0b8c789..38ce9a5f73a6 100644 --- a/homeassistant/components/shelly/select.py +++ b/homeassistant/components/shelly/select.py @@ -1,7 +1,7 @@ """Select for Shelly.""" from dataclasses import dataclass -from typing import TYPE_CHECKING, Final, override +from typing import TYPE_CHECKING, Final, cast, override from aioshelly.const import RPC_GENERATIONS @@ -10,6 +10,7 @@ from homeassistant.components.select import ( SelectEntity, SelectEntityDescription, ) +from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback @@ -152,6 +153,27 @@ class RpcLedStripPaletteSelect(RpcSelect): await method(self._id, {self.entity_description.sub_key: option}) +class RpcUiLedModeSelect(RpcSelect): + """Represent a RPC select entity for the plug/power strip LED mode.""" + + @property + @override + def current_option(self) -> str | None: + """Return the selected entity option to represent the entity state.""" + return cast(str, self.coordinator.device.config[self.key]["leds"]["mode"]) + + @rpc_call + @override + async def async_select_option(self, option: str) -> None: + """Change the value.""" + method = getattr(self.coordinator.device, self.entity_description.method) + + if TYPE_CHECKING: + assert method is not None + + await method({"leds": {"mode": option}}) + + RPC_SELECT_ENTITIES: Final = { "cury_mode": RpcSelectDescription( key="cury", @@ -186,6 +208,24 @@ RPC_SELECT_ENTITIES: Final = { supported=lambda _: True, entity_class=RpcLedStripPaletteSelect, ), + "plugs_ui_led_mode": RpcSelectDescription( + key="plugs_ui", + translation_key="led_mode", + entity_category=EntityCategory.CONFIG, + options=["power", "switch", "off"], + method="plugs_ui_setconfig", + supported=lambda _: True, + entity_class=RpcUiLedModeSelect, + ), + "powerstrip_ui_led_mode": RpcSelectDescription( + key="powerstrip_ui", + translation_key="led_mode", + entity_category=EntityCategory.CONFIG, + options=["power", "switch", "off"], + method="powerstrip_ui_setconfig", + supported=lambda _: True, + entity_class=RpcUiLedModeSelect, + ), } diff --git a/homeassistant/components/shelly/strings.json b/homeassistant/components/shelly/strings.json index 6867cbd2adcf..16290811a396 100644 --- a/homeassistant/components/shelly/strings.json +++ b/homeassistant/components/shelly/strings.json @@ -389,6 +389,14 @@ "pastel": "Pastel", "rainbow": "Rainbow" } + }, + "led_mode": { + "name": "LED mode", + "state": { + "off": "[%key:common::state::off%]", + "power": "Power consumption", + "switch": "Switch state" + } } }, "sensor": { diff --git a/tests/components/shelly/snapshots/test_devices.ambr b/tests/components/shelly/snapshots/test_devices.ambr index 12672efd5af6..80d8cba82dec 100644 --- a/tests/components/shelly/snapshots/test_devices.ambr +++ b/tests/components/shelly/snapshots/test_devices.ambr @@ -2784,6 +2784,67 @@ 'state': 'off', }) # --- +# name: test_device[power_strip_gen4][select.test_name_led_mode-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + 'power', + 'switch', + 'off', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'select', + 'entity_category': , + 'entity_id': 'select.test_name_led_mode', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'LED mode', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'LED mode', + 'platform': 'shelly', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'led_mode', + 'unique_id': '123456789ABC-powerstrip_ui-powerstrip_ui_led_mode', + 'unit_of_measurement': None, + }) +# --- +# name: test_device[power_strip_gen4][select.test_name_led_mode-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Test name LED mode', + : list([ + 'power', + 'switch', + 'off', + ]), + }), + 'context': , + 'entity_id': 'select.test_name_led_mode', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- # name: test_device[power_strip_gen4][sensor.test_name_output_0_current-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ diff --git a/tests/components/shelly/snapshots/test_select.ambr b/tests/components/shelly/snapshots/test_select.ambr index 89c3818244bc..1fa2eb5ac453 100644 --- a/tests/components/shelly/snapshots/test_select.ambr +++ b/tests/components/shelly/snapshots/test_select.ambr @@ -62,3 +62,125 @@ 'state': 'ocean', }) # --- +# name: test_rpc_ui_led_mode_select[plugs_ui-update_plugs_ui_config-plugs_ui_setconfig][select.test_name_led_mode-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + 'power', + 'switch', + 'off', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'select', + 'entity_category': , + 'entity_id': 'select.test_name_led_mode', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'LED mode', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'LED mode', + 'platform': 'shelly', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'led_mode', + 'unique_id': '123456789ABC-plugs_ui-plugs_ui_led_mode', + 'unit_of_measurement': None, + }) +# --- +# name: test_rpc_ui_led_mode_select[plugs_ui-update_plugs_ui_config-plugs_ui_setconfig][select.test_name_led_mode-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Test name LED mode', + : list([ + 'power', + 'switch', + 'off', + ]), + }), + 'context': , + 'entity_id': 'select.test_name_led_mode', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_rpc_ui_led_mode_select[powerstrip_ui-update_powerstrip_ui_config-powerstrip_ui_setconfig][select.test_name_led_mode-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + 'power', + 'switch', + 'off', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'select', + 'entity_category': , + 'entity_id': 'select.test_name_led_mode', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'LED mode', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'LED mode', + 'platform': 'shelly', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'led_mode', + 'unique_id': '123456789ABC-powerstrip_ui-powerstrip_ui_led_mode', + 'unit_of_measurement': None, + }) +# --- +# name: test_rpc_ui_led_mode_select[powerstrip_ui-update_powerstrip_ui_config-powerstrip_ui_setconfig][select.test_name_led_mode-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Test name LED mode', + : list([ + 'power', + 'switch', + 'off', + ]), + }), + 'context': , + 'entity_id': 'select.test_name_led_mode', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- diff --git a/tests/components/shelly/test_coordinator.py b/tests/components/shelly/test_coordinator.py index 336e5b9f0885..9c6a027d8729 100644 --- a/tests/components/shelly/test_coordinator.py +++ b/tests/components/shelly/test_coordinator.py @@ -4,7 +4,7 @@ from datetime import timedelta from unittest.mock import AsyncMock, Mock, call, patch from aioshelly.const import MODEL_2PM_G3, MODEL_BULB, MODEL_BUTTON1 -from aioshelly.exceptions import DeviceConnectionError, InvalidAuthError +from aioshelly.exceptions import DeviceConnectionError, InvalidAuthError, RpcCallError from freezegun.api import FrozenDateTimeFactory import pytest from pytest_homeassistant.common import ( @@ -447,13 +447,22 @@ async def test_rpc_reload_on_cfg_change( assert hass.states.get(entity_id) is None -async def test_rpc_no_reload_on_plugs_ui_cfg_change( +@pytest.mark.parametrize( + ("component", "update_method"), + [ + ("plugs_ui", "update_plugs_ui_config"), + ("powerstrip_ui", "update_powerstrip_ui_config"), + ], +) +async def test_rpc_no_reload_on_ui_cfg_change( hass: HomeAssistant, freezer: FrozenDateTimeFactory, mock_rpc_device: Mock, monkeypatch: pytest.MonkeyPatch, + component: str, + update_method: str, ) -> None: - """Test RPC plug LED config change does not reload the entry.""" + """Test RPC UI config change fetches the config without reloading the entry.""" entity_id = "switch.test_name_test_switch_0" monkeypatch.delitem(mock_rpc_device.status, "cover:0") monkeypatch.setitem(mock_rpc_device.status["sys"], "relay_in_thermostat", False) @@ -469,7 +478,7 @@ async def test_rpc_no_reload_on_plugs_ui_cfg_change( { "events": [ { - "component": "plugs_ui", + "component": component, "event": "config_changed", "restart_required": False, "ts": 1668522399.2, @@ -481,6 +490,8 @@ async def test_rpc_no_reload_on_plugs_ui_cfg_change( ) await hass.async_block_till_done() + getattr(mock_rpc_device, update_method).assert_awaited_once() + freezer.tick(timedelta(seconds=ENTRY_RELOAD_COOLDOWN)) async_fire_time_changed(hass) await hass.async_block_till_done() @@ -488,6 +499,49 @@ async def test_rpc_no_reload_on_plugs_ui_cfg_change( assert hass.states.get(entity_id) +@pytest.mark.parametrize( + ("exception", "reauth_flows"), + [ + (DeviceConnectionError, 0), + (RpcCallError(999), 0), + (InvalidAuthError, 1), + ], +) +async def test_rpc_ui_cfg_change_update_error( + hass: HomeAssistant, + mock_rpc_device: Mock, + monkeypatch: pytest.MonkeyPatch, + exception: Exception, + reauth_flows: int, +) -> None: + """Test RPC UI config change when fetching the updated config fails.""" + monkeypatch.setattr( + mock_rpc_device, "update_powerstrip_ui_config", AsyncMock(side_effect=exception) + ) + entry = await init_integration(hass, 2) + + inject_rpc_device_event( + monkeypatch, + mock_rpc_device, + { + "events": [ + { + "component": "powerstrip_ui", + "event": "config_changed", + "restart_required": False, + "ts": 1668522399.2, + "cfg_rev": 16, + }, + ], + "ts": 1668522399.2, + }, + ) + await hass.async_block_till_done() + + assert entry.state is ConfigEntryState.LOADED + assert len(hass.config_entries.flow.async_progress()) == reauth_flows + + async def test_rpc_reload_with_invalid_auth( hass: HomeAssistant, freezer: FrozenDateTimeFactory, diff --git a/tests/components/shelly/test_select.py b/tests/components/shelly/test_select.py index 69b1276bc29e..9317d3498bc8 100644 --- a/tests/components/shelly/test_select.py +++ b/tests/components/shelly/test_select.py @@ -30,6 +30,7 @@ from homeassistant.helpers.entity_registry import EntityRegistry from . import ( init_integration, + inject_rpc_device_event, mutate_rpc_device_status, patch_platforms, register_device, @@ -403,3 +404,68 @@ async def test_rpc_ledstrip_palette_select_availability( assert (state := hass.states.get(LEDSTRIP_ENTITY_ID)) assert state.state == expected_state + + +@pytest.mark.parametrize( + ("component", "update_method", "set_method"), + [ + ("plugs_ui", "update_plugs_ui_config", "plugs_ui_setconfig"), + ("powerstrip_ui", "update_powerstrip_ui_config", "powerstrip_ui_setconfig"), + ], +) +async def test_rpc_ui_led_mode_select( + hass: HomeAssistant, + mock_rpc_device: Mock, + entity_registry: EntityRegistry, + snapshot: SnapshotAssertion, + monkeypatch: pytest.MonkeyPatch, + component: str, + update_method: str, + set_method: str, +) -> None: + """Test RPC plug/power strip LED mode select.""" + entity_id = f"{SELECT_DOMAIN}.test_name_led_mode" + monkeypatch.setitem(mock_rpc_device.status, component, {}) + monkeypatch.setitem(mock_rpc_device.config, component, {"leds": {"mode": "off"}}) + await init_integration(hass, 3) + + assert (state := hass.states.get(entity_id)) + assert state == snapshot(name=f"{entity_id}-state") + + assert (entry := entity_registry.async_get(entity_id)) + assert entry == snapshot(name=f"{entity_id}-entry") + + await hass.services.async_call( + SELECT_DOMAIN, + SERVICE_SELECT_OPTION, + {ATTR_ENTITY_ID: entity_id, ATTR_OPTION: "switch"}, + blocking=True, + ) + getattr(mock_rpc_device, set_method).assert_called_once_with( + {"leds": {"mode": "switch"}} + ) + + # The device reports the change with an event, the new config is then fetched + getattr(mock_rpc_device, update_method).side_effect = lambda: ( + mock_rpc_device.config[component]["leds"].update(mode="switch") + ) + inject_rpc_device_event( + monkeypatch, + mock_rpc_device, + { + "events": [ + { + "component": component, + "event": "config_changed", + "restart_required": False, + "ts": 1668522399.2, + "cfg_rev": 16, + }, + ], + "ts": 1668522399.2, + }, + ) + await hass.async_block_till_done() + + assert (state := hass.states.get(entity_id)) + assert state.state == "switch"