From d82644099d5803e5db6be37995a695ce4a4f7164 Mon Sep 17 00:00:00 2001 From: Shay Levy Date: Thu, 19 Nov 2026 22:51:33 +0200 Subject: [PATCH] Replace Shelly switch to cover key rewrite with explicit components (#193383) Co-authored-by: Claude Fable 5.2 --- .../components/shelly/binary_sensor.py | 4 ++ homeassistant/components/shelly/entity.py | 10 ++-- homeassistant/components/shelly/sensor.py | 8 +++ homeassistant/components/shelly/switch.py | 49 +++++++------------ homeassistant/components/shelly/utils.py | 3 -- .../shelly/snapshots/test_devices.ambr | 6 +-- tests/components/shelly/test_switch.py | 7 +-- 7 files changed, 43 insertions(+), 44 deletions(-) diff --git a/homeassistant/components/shelly/binary_sensor.py b/homeassistant/components/shelly/binary_sensor.py index 6633ea15aa6a..dba7c15c2bb7 100644 --- a/homeassistant/components/shelly/binary_sensor.py +++ b/homeassistant/components/shelly/binary_sensor.py @@ -271,6 +271,7 @@ RPC_SENSORS: Final = { ), "overtemp": RpcBinarySensorDescription( key="switch", + components=("switch", "cover"), sub_key="errors", translation_key="overheating", device_class=BinarySensorDeviceClass.PROBLEM, @@ -280,6 +281,7 @@ RPC_SENSORS: Final = { ), "overpower": RpcBinarySensorDescription( key="switch", + components=("switch", "cover"), sub_key="errors", translation_key="overpowering", device_class=BinarySensorDeviceClass.PROBLEM, @@ -289,6 +291,7 @@ RPC_SENSORS: Final = { ), "overvoltage": RpcBinarySensorDescription( key="switch", + components=("switch", "cover"), sub_key="errors", translation_key="overvoltage", device_class=BinarySensorDeviceClass.PROBLEM, @@ -298,6 +301,7 @@ RPC_SENSORS: Final = { ), "overcurrent": RpcBinarySensorDescription( key="switch", + components=("switch", "cover"), sub_key="errors", translation_key="overcurrent", device_class=BinarySensorDeviceClass.PROBLEM, diff --git a/homeassistant/components/shelly/entity.py b/homeassistant/components/shelly/entity.py index 9fcd44592fac..908221af5903 100644 --- a/homeassistant/components/shelly/entity.py +++ b/homeassistant/components/shelly/entity.py @@ -198,9 +198,11 @@ def async_setup_rpc_attribute_entities( entities = [] for sensor_id in sensors: description = sensors[sensor_id] - key_instances = get_rpc_key_instances( - coordinator.device.status, description.key - ) + key_instances = [ + key + for component in description.components or (description.key,) + for key in get_rpc_key_instances(coordinator.device.status, component) + ] for key in key_instances: # Filter non-existing sensors @@ -332,6 +334,8 @@ class RpcEntityDescription(EntityDescription): """Class to describe a RPC entity.""" sub_key: str | None = None + # Components the description applies to, defaults to the key + components: tuple[str, ...] | None = None value: Callable[[Any, Any], Any] | None = None available: Callable[[dict], bool] | None = None diff --git a/homeassistant/components/shelly/sensor.py b/homeassistant/components/shelly/sensor.py index 38fb9f2d5dac..8e3ccd0d2802 100644 --- a/homeassistant/components/shelly/sensor.py +++ b/homeassistant/components/shelly/sensor.py @@ -543,6 +543,7 @@ REST_SENSORS: Final = { RPC_SENSORS: Final = { "power": RpcSensorDescription( key="switch", + components=("switch", "cover"), sub_key="apower", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, @@ -674,6 +675,7 @@ RPC_SENSORS: Final = { ), "switch_pf": RpcSensorDescription( key="switch", + components=("switch", "cover"), sub_key="pf", device_class=SensorDeviceClass.POWER_FACTOR, state_class=SensorStateClass.MEASUREMENT, @@ -710,6 +712,7 @@ RPC_SENSORS: Final = { ), "voltage": RpcSensorDescription( key="switch", + components=("switch", "cover"), sub_key="voltage", native_unit_of_measurement=UnitOfElectricPotential.VOLT, value=lambda status, _: None if status is None else float(status), @@ -810,6 +813,7 @@ RPC_SENSORS: Final = { ), "current": RpcSensorDescription( key="switch", + components=("switch", "cover"), sub_key="current", native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, value=lambda status, _: None if status is None else float(status), @@ -921,6 +925,7 @@ RPC_SENSORS: Final = { ), "energy": RpcSensorDescription( key="switch", + components=("switch", "cover"), sub_key="aenergy", native_unit_of_measurement=UnitOfEnergy.WATT_HOUR, suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, @@ -1220,6 +1225,7 @@ RPC_SENSORS: Final = { ), "freq": RpcSensorDescription( key="switch", + components=("switch", "cover"), sub_key="freq", native_unit_of_measurement=UnitOfFrequency.HERTZ, suggested_display_precision=0, @@ -1287,6 +1293,7 @@ RPC_SENSORS: Final = { ), "temperature": RpcSensorDescription( key="switch", + components=("switch", "cover"), sub_key="temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, value=lambda status, _: status["tC"], @@ -1890,6 +1897,7 @@ RPC_SENSORS: Final = { ), "switch_source": RpcSensorDescription( key="switch", + components=("switch", "cover"), sub_key="source", translation_key="last_command_source", device_class=SensorDeviceClass.ENUM, diff --git a/homeassistant/components/shelly/switch.py b/homeassistant/components/shelly/switch.py index 27006eb6a4a8..3e6dc7bdedd2 100644 --- a/homeassistant/components/shelly/switch.py +++ b/homeassistant/components/shelly/switch.py @@ -1,6 +1,6 @@ """Switch for Shelly.""" -from collections.abc import Callable +from collections.abc import Awaitable, Callable from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast, override @@ -83,6 +83,7 @@ class RpcSwitchDescription(RpcEntityDescription, SwitchEntityDescription): """Class to describe a RPC virtual switch.""" is_on: Callable[[dict[str, Any]], bool] + # "{component}" in a method name is replaced by the component of the entity method_on: str method_off: str method_params_fn: Callable[[int | None, bool], tuple] @@ -110,6 +111,17 @@ class RpcSwitch(ShellyRpcAttributeEntity, SwitchEntity): ): self._attr_name = get_rpc_channel_name(coordinator.device, key) + def _get_method(self, name: str) -> Callable[..., Awaitable[Any]]: + """Return the device method, resolved for the component of the entity.""" + method = getattr( + self.coordinator.device, name.format(component=get_rpc_key(self.key)[1]) + ) + + if TYPE_CHECKING: + assert method is not None + + return cast(Callable[..., Awaitable[Any]], method) + @property @override def is_on(self) -> bool: @@ -120,11 +132,7 @@ class RpcSwitch(ShellyRpcAttributeEntity, SwitchEntity): @override async def async_turn_on(self, **kwargs: Any) -> None: """Turn on switch.""" - method = getattr(self.coordinator.device, self.entity_description.method_on) - - if TYPE_CHECKING: - assert method is not None - + method = self._get_method(self.entity_description.method_on) params = self.entity_description.method_params_fn(self._id, True) await method(*params) @@ -132,11 +140,7 @@ class RpcSwitch(ShellyRpcAttributeEntity, SwitchEntity): @override async def async_turn_off(self, **kwargs: Any) -> None: """Turn off switch.""" - method = getattr(self.coordinator.device, self.entity_description.method_off) - - if TYPE_CHECKING: - assert method is not None - + method = self._get_method(self.entity_description.method_off) params = self.entity_description.method_params_fn(self._id, False) await method(*params) @@ -499,31 +503,16 @@ RPC_SWITCHES = { supported=lambda _: True, entity_class=RpcLedStripSwitch, ), - "switch_in_locked": RpcSwitchDescription( + "in_locked": RpcSwitchDescription( key="switch", - translation_key="input_lock", - entity_category=EntityCategory.CONFIG, - entity_registry_enabled_default=False, - # on a device in cover profile the "switch" key resolves to the cover - # component, which is handled by "cover_in_locked" - removal_condition=lambda config, _status, key: ( - get_rpc_key(key)[1] != "switch" or "in_locked" not in config[key] - ), - is_on=lambda config: bool(config["in_locked"]), - method_on="switch_setconfig", - method_off="switch_setconfig", - method_params_fn=lambda id, value: (id, {"in_locked": value}), - entity_class=RpcConfigSwitch, - ), - "cover_in_locked": RpcSwitchDescription( - key="cover", + components=("switch", "cover"), translation_key="input_lock", entity_category=EntityCategory.CONFIG, entity_registry_enabled_default=False, removal_condition=lambda config, _status, key: "in_locked" not in config[key], is_on=lambda config: bool(config["in_locked"]), - method_on="cover_setconfig", - method_off="cover_setconfig", + method_on="{component}_setconfig", + method_off="{component}_setconfig", method_params_fn=lambda id, value: (id, {"in_locked": value}), entity_class=RpcConfigSwitch, ), diff --git a/homeassistant/components/shelly/utils.py b/homeassistant/components/shelly/utils.py index 97dd19b3bcd2..12a5902da710 100644 --- a/homeassistant/components/shelly/utils.py +++ b/homeassistant/components/shelly/utils.py @@ -488,9 +488,6 @@ def get_rpc_key_instances( if key in keys_dict: return [key] - if key == "switch" and "cover:0" in keys_dict: - key = "cover" - if key in All_LIGHT_TYPES and all_lights: return [k for k in keys_dict if k.startswith(All_LIGHT_TYPES)] diff --git a/tests/components/shelly/snapshots/test_devices.ambr b/tests/components/shelly/snapshots/test_devices.ambr index 002a45963b40..1ece11477737 100644 --- a/tests/components/shelly/snapshots/test_devices.ambr +++ b/tests/components/shelly/snapshots/test_devices.ambr @@ -8917,7 +8917,7 @@ 'suggested_object_id': None, 'supported_features': 0, 'translation_key': 'input_lock', - 'unique_id': '123456789ABC-cover:0-cover_in_locked', + 'unique_id': '123456789ABC-cover:0-in_locked', 'unit_of_measurement': None, }) # --- @@ -11068,7 +11068,7 @@ 'suggested_object_id': None, 'supported_features': 0, 'translation_key': 'input_lock', - 'unique_id': '123456789ABC-switch:0-switch_in_locked', + 'unique_id': '123456789ABC-switch:0-in_locked', 'unit_of_measurement': None, }) # --- @@ -11168,7 +11168,7 @@ 'suggested_object_id': None, 'supported_features': 0, 'translation_key': 'input_lock', - 'unique_id': '123456789ABC-switch:1-switch_in_locked', + 'unique_id': '123456789ABC-switch:1-in_locked', 'unit_of_measurement': None, }) # --- diff --git a/tests/components/shelly/test_switch.py b/tests/components/shelly/test_switch.py index 8bf126357988..13541bdd8a92 100644 --- a/tests/components/shelly/test_switch.py +++ b/tests/components/shelly/test_switch.py @@ -779,7 +779,7 @@ async def test_rpc_switch_input_lock( assert (state := hass.states.get(entity_id)) assert state.state == STATE_OFF assert (entry := entity_registry.async_get(entity_id)) - assert entry.unique_id == "123456789ABC-switch:0-switch_in_locked" + assert entry.unique_id == "123456789ABC-switch:0-in_locked" assert entry.entity_category is EntityCategory.CONFIG await hass.services.async_call( @@ -836,10 +836,7 @@ async def test_rpc_cover_input_lock( assert (state := hass.states.get(entity_id)) assert state.state == STATE_ON assert (entry := entity_registry.async_get(entity_id)) - assert entry.unique_id == "123456789ABC-cover:0-cover_in_locked" - - # the switch component of a device in cover profile is not used - assert hass.states.get("switch.test_name_test_switch_0_input_lock") is None + assert entry.unique_id == "123456789ABC-cover:0-in_locked" await hass.services.async_call( SWITCH_DOMAIN,