mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Add LED mode select for Shelly plugs and power strips (#190178)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
f174ae833f
commit
6c756b2716
@@ -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"):
|
||||
|
||||
@@ -28,6 +28,9 @@
|
||||
"select": {
|
||||
"effect_palette": {
|
||||
"default": "mdi:palette"
|
||||
},
|
||||
"led_mode": {
|
||||
"default": "mdi:led-on"
|
||||
}
|
||||
},
|
||||
"sensor": {
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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({
|
||||
<SelectEntityCapabilityAttribute.OPTIONS: 'options'>: list([
|
||||
'power',
|
||||
'switch',
|
||||
'off',
|
||||
]),
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('shelly', '123456789ABC')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'select',
|
||||
'entity_category': <EntityCategory.CONFIG: 'config'>,
|
||||
'entity_id': 'select.test_name_led_mode',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'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({
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Test name LED mode',
|
||||
<SelectEntityCapabilityAttribute.OPTIONS: 'options'>: list([
|
||||
'power',
|
||||
'switch',
|
||||
'off',
|
||||
]),
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'select.test_name_led_mode',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'off',
|
||||
})
|
||||
# ---
|
||||
# name: test_device[power_strip_gen4][sensor.test_name_output_0_current-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
|
||||
@@ -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({
|
||||
<SelectEntityCapabilityAttribute.OPTIONS: 'options'>: list([
|
||||
'power',
|
||||
'switch',
|
||||
'off',
|
||||
]),
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('shelly', '123456789ABC')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'select',
|
||||
'entity_category': <EntityCategory.CONFIG: 'config'>,
|
||||
'entity_id': 'select.test_name_led_mode',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'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({
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Test name LED mode',
|
||||
<SelectEntityCapabilityAttribute.OPTIONS: 'options'>: list([
|
||||
'power',
|
||||
'switch',
|
||||
'off',
|
||||
]),
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'select.test_name_led_mode',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'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({
|
||||
<SelectEntityCapabilityAttribute.OPTIONS: 'options'>: list([
|
||||
'power',
|
||||
'switch',
|
||||
'off',
|
||||
]),
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('shelly', '123456789ABC')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'select',
|
||||
'entity_category': <EntityCategory.CONFIG: 'config'>,
|
||||
'entity_id': 'select.test_name_led_mode',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'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({
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Test name LED mode',
|
||||
<SelectEntityCapabilityAttribute.OPTIONS: 'options'>: list([
|
||||
'power',
|
||||
'switch',
|
||||
'off',
|
||||
]),
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'select.test_name_led_mode',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'off',
|
||||
})
|
||||
# ---
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user