From c70878a9e9abf66ea32ac01abbc3f03ce1012e35 Mon Sep 17 00:00:00 2001 From: Shay Levy Date: Sat, 21 Nov 2026 15:16:10 +0200 Subject: [PATCH] Add Shelly Wall Display brightness entities (#193226) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/shelly/const.py | 2 + homeassistant/components/shelly/icons.json | 9 ++ homeassistant/components/shelly/number.py | 96 ++++++++++- homeassistant/components/shelly/strings.json | 9 ++ homeassistant/components/shelly/switch.py | 53 ++++++ homeassistant/components/shelly/utils.py | 17 +- .../shelly/snapshots/test_number.ambr | 120 ++++++++++++++ .../shelly/snapshots/test_switch.ambr | 50 ++++++ tests/components/shelly/test_number.py | 151 +++++++++++++++++- tests/components/shelly/test_switch.py | 114 ++++++++++++- 10 files changed, 617 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/shelly/const.py b/homeassistant/components/shelly/const.py index deb3543d5d81..e37fe33fb3ad 100644 --- a/homeassistant/components/shelly/const.py +++ b/homeassistant/components/shelly/const.py @@ -252,6 +252,8 @@ OPEN_WIFI_AP_ISSUE_ID = "open_wifi_ap_{unique}" RTSP_DISABLED_ISSUE_ID = "rtsp_disabled_{unique}" IR_RAW_RECEIVE_DISABLED_ISSUE_ID = "ir_raw_receive_disabled_{unique}" IR_RAW_RECEIVE_MIN_FIRMWARE = 20260903 +# Older firmware reports the brightness level as the 0-255 backlight value +WALL_DISPLAY_UI_MIN_FIRMWARE = "2.6.2" COIOT_UNCONFIGURED_ISSUE_ID = "coiot_unconfigured_{unique}" diff --git a/homeassistant/components/shelly/icons.json b/homeassistant/components/shelly/icons.json index 4fa53e6f23fc..96b0dce16822 100644 --- a/homeassistant/components/shelly/icons.json +++ b/homeassistant/components/shelly/icons.json @@ -24,6 +24,9 @@ } }, "number": { + "display_brightness": { + "default": "mdi:brightness-6" + }, "effect_intensity": { "default": "mdi:brightness-percent" }, @@ -33,6 +36,9 @@ "external_temperature": { "default": "mdi:thermometer-check" }, + "min_auto_display_brightness": { + "default": "mdi:brightness-4" + }, "valve_position": { "default": "mdi:pipe-valve" } @@ -126,6 +132,9 @@ } }, "switch": { + "auto_brightness": { + "default": "mdi:brightness-auto" + }, "boost": { "default": "mdi:rocket-launch" }, diff --git a/homeassistant/components/shelly/number.py b/homeassistant/components/shelly/number.py index dabd49d17aaf..5df9cdb11007 100644 --- a/homeassistant/components/shelly/number.py +++ b/homeassistant/components/shelly/number.py @@ -2,11 +2,12 @@ from collections.abc import Callable from dataclasses import dataclass -from typing import TYPE_CHECKING, Final, cast, override +from typing import TYPE_CHECKING, Any, Final, cast, override from aioshelly.block_device import Block from aioshelly.const import RPC_GENERATIONS from aioshelly.exceptions import DeviceConnectionError, InvalidAuthError +from aioshelly.rpc_device.models import ShellyWallDisplayUiBrightness from homeassistant.components.number import ( DOMAIN as NUMBER_DOMAIN, @@ -40,6 +41,7 @@ from .entity import ( BlockEntityDescription, RpcEntityDescription, ShellyRpcAttributeEntity, + ShellyRpcEntity, ShellySleepingBlockAttributeEntity, async_setup_entry_block, async_setup_entry_rpc, @@ -52,6 +54,7 @@ from .utils import ( get_virtual_component_ids, get_virtual_component_unit, is_rpc_ledstrip_control_available, + is_rpc_wall_display_brightness_supported, is_view_for_platform, ) @@ -168,6 +171,62 @@ class RpcLedStripNumber(RpcNumber): await method(self._id, {self.entity_description.sub_key: round(value)}) +@dataclass(frozen=True, kw_only=True) +class RpcWallDisplayBrightnessNumberDescription(NumberEntityDescription): + """Class to describe a RPC Wall Display brightness number.""" + + entity_class: type[RpcWallDisplayBrightnessNumber] + + +class RpcWallDisplayBrightnessNumber(ShellyRpcEntity, NumberEntity): + """Represent a RPC Wall Display brightness config number.""" + + entity_description: RpcWallDisplayBrightnessNumberDescription + + def __init__( + self, + coordinator: ShellyRpcCoordinator, + description: RpcWallDisplayBrightnessNumberDescription, + ) -> None: + """Initialize Wall Display brightness number.""" + super().__init__(coordinator, "ui") + self.entity_description = description + self._attr_unique_id = f"{coordinator.mac}-ui-{description.key}" + + @property + def brightness_config(self) -> dict[str, Any]: + """Display brightness config.""" + return cast(dict[str, Any], self.coordinator.device.config["ui"]["brightness"]) + + @property + @override + def native_value(self) -> float: + """Return the brightness config value.""" + return cast(float, self.brightness_config[self.entity_description.key]) + + @rpc_call + @override + async def async_set_native_value(self, value: float) -> None: + """Change the brightness config value.""" + brightness = cast( + ShellyWallDisplayUiBrightness, {self.entity_description.key: round(value)} + ) + await self.coordinator.device.wall_display_ui_setconfig( + {"brightness": brightness} + ) + + +class RpcWallDisplayLevelNumber(RpcWallDisplayBrightnessNumber): + """Represent a RPC Wall Display brightness level number.""" + + @property + @override + def available(self) -> bool: + """Return if entity is available.""" + # The device ignores the level while auto brightness is on + return super().available and not self.brightness_config["auto"] + + class RpcBluTrvNumber(RpcNumber): """Represent a RPC BluTrv number.""" @@ -399,6 +458,32 @@ RPC_NUMBERS: Final = ( ) +WALL_DISPLAY_BRIGHTNESS_NUMBERS: Final = ( + RpcWallDisplayBrightnessNumberDescription( + key="level", + translation_key="display_brightness", + entity_category=EntityCategory.CONFIG, + native_min_value=0, + native_max_value=100, + native_step=1, + mode=NumberMode.SLIDER, + native_unit_of_measurement=UnitOfRatio.PERCENTAGE, + entity_class=RpcWallDisplayLevelNumber, + ), + RpcWallDisplayBrightnessNumberDescription( + key="min_level", + translation_key="min_auto_display_brightness", + entity_category=EntityCategory.CONFIG, + native_min_value=1, + native_max_value=50, + native_step=1, + mode=NumberMode.SLIDER, + native_unit_of_measurement=UnitOfRatio.PERCENTAGE, + entity_class=RpcWallDisplayBrightnessNumber, + ), +) + + async def async_setup_entry( hass: HomeAssistant, config_entry: ShellyConfigEntry, @@ -442,6 +527,15 @@ def _async_setup_rpc_entry( hass, config_entry, async_add_entities, RPC_NUMBERS, RpcNumber ) + # The Wall Display does not report the ui component in the status + if is_rpc_wall_display_brightness_supported(coordinator): + brightness = coordinator.device.config["ui"]["brightness"] + async_add_entities( + description.entity_class(coordinator, description) + for description in WALL_DISPLAY_BRIGHTNESS_NUMBERS + if description.key in brightness + ) + # the user can remove virtual components from the device configuration, so # we need to remove orphaned entities virtual_number_ids = get_virtual_component_ids( diff --git a/homeassistant/components/shelly/strings.json b/homeassistant/components/shelly/strings.json index 75be4186e018..09ca7df0d559 100644 --- a/homeassistant/components/shelly/strings.json +++ b/homeassistant/components/shelly/strings.json @@ -350,6 +350,9 @@ "current_limit": { "name": "Current limit" }, + "display_brightness": { + "name": "Display brightness" + }, "effect_intensity": { "name": "Effect intensity" }, @@ -362,6 +365,9 @@ "left_slot_intensity": { "name": "Left slot intensity" }, + "min_auto_display_brightness": { + "name": "Minimum auto display brightness" + }, "right_slot_intensity": { "name": "Right slot intensity" }, @@ -803,6 +809,9 @@ } }, "switch": { + "auto_brightness": { + "name": "Auto display brightness" + }, "boost": { "name": "Boost" }, diff --git a/homeassistant/components/shelly/switch.py b/homeassistant/components/shelly/switch.py index f90fcafaddf4..fc16a9be8e95 100644 --- a/homeassistant/components/shelly/switch.py +++ b/homeassistant/components/shelly/switch.py @@ -37,6 +37,7 @@ from .entity import ( RpcEntityDescription, ShellyBlockAttributeEntity, ShellyRpcAttributeEntity, + ShellyRpcEntity, ShellySleepingBlockAttributeEntity, async_setup_entry_block, async_setup_entry_rpc, @@ -51,6 +52,7 @@ from .utils import ( is_block_exclude_from_relay, is_rpc_exclude_from_relay, is_rpc_ledstrip_control_available, + is_rpc_wall_display_brightness_supported, is_view_for_platform, ) @@ -243,6 +245,47 @@ class RpcLedStripSwitch(RpcSwitch): ) +class RpcWallDisplayAutoBrightnessSwitch(ShellyRpcEntity, SwitchEntity): + """Represent a RPC Wall Display auto brightness switch.""" + + def __init__( + self, coordinator: ShellyRpcCoordinator, description: SwitchEntityDescription + ) -> None: + """Initialize Wall Display auto brightness switch.""" + super().__init__(coordinator, "ui") + self.entity_description = description + self._attr_unique_id = f"{coordinator.mac}-ui-{description.key}" + + @property + @override + def is_on(self) -> bool: + """Return true if auto brightness is on.""" + return cast(bool, self.coordinator.device.config["ui"]["brightness"]["auto"]) + + @rpc_call + @override + async def async_turn_on(self, **kwargs: Any) -> None: + """Turn on auto brightness.""" + await self.coordinator.device.wall_display_ui_setconfig( + {"brightness": {"auto": True}} + ) + + @rpc_call + @override + async def async_turn_off(self, **kwargs: Any) -> None: + """Turn off auto brightness.""" + await self.coordinator.device.wall_display_ui_setconfig( + {"brightness": {"auto": False}} + ) + + +WALL_DISPLAY_AUTO_BRIGHTNESS_SWITCH = SwitchEntityDescription( + key="auto", + translation_key="auto_brightness", + entity_category=EntityCategory.CONFIG, +) + + RPC_SWITCHES = ( RpcSwitchDescription( key="switch", @@ -601,6 +644,16 @@ def _async_setup_rpc_entry( hass, config_entry, async_add_entities, RPC_SWITCHES, RpcSwitch ) + # The Wall Display does not report the ui component in the status + if is_rpc_wall_display_brightness_supported(coordinator): + async_add_entities( + [ + RpcWallDisplayAutoBrightnessSwitch( + coordinator, WALL_DISPLAY_AUTO_BRIGHTNESS_SWITCH + ) + ] + ) + # the user can remove virtual components from the device configuration, so we need # to remove orphaned entities virtual_switch_ids = get_virtual_component_ids( diff --git a/homeassistant/components/shelly/utils.py b/homeassistant/components/shelly/utils.py index b9bf0bae6b39..45632c78c54e 100644 --- a/homeassistant/components/shelly/utils.py +++ b/homeassistant/components/shelly/utils.py @@ -28,6 +28,7 @@ from aioshelly.const import ( from aioshelly.exceptions import NotInitialized from aioshelly.rpc_device import RpcDevice, WsServer from aioshelly.rpc_device.models import ShellyLedStripEffect +from awesomeversion import AwesomeVersion from yarl import URL from homeassistant.components import network @@ -77,11 +78,12 @@ from .const import ( SHIX3_1_INPUTS_EVENTS_TYPES, VIRTUAL_COMPONENTS, WALL_DISPLAY_RELEASE_URL, + WALL_DISPLAY_UI_MIN_FIRMWARE, All_LIGHT_TYPES, ) if TYPE_CHECKING: - from .coordinator import ShellyConfigEntry + from .coordinator import ShellyConfigEntry, ShellyRpcCoordinator @callback @@ -587,6 +589,19 @@ def brightness_to_percentage(brightness: int) -> int: return int(100 * (brightness + 1) / 255) +def is_rpc_wall_display_brightness_supported( + coordinator: ShellyRpcCoordinator, +) -> bool: + """Return true if the device has a supported Wall Display brightness config.""" + device = coordinator.device + return ( + coordinator.model.startswith(SHELLY_WALL_DISPLAY_MODEL_PREFIX) + and "brightness" in device.config.get("ui", {}) + and AwesomeVersion(device.shelly["ver"]) + >= AwesomeVersion(WALL_DISPLAY_UI_MIN_FIRMWARE) + ) + + def percentage_to_brightness(percentage: int) -> int: """Convert percentage to brightness level.""" return round(255 * percentage / 100) diff --git a/tests/components/shelly/snapshots/test_number.ambr b/tests/components/shelly/snapshots/test_number.ambr index 0cea8a33cb8e..a0696a46e9cc 100644 --- a/tests/components/shelly/snapshots/test_number.ambr +++ b/tests/components/shelly/snapshots/test_number.ambr @@ -360,3 +360,123 @@ 'state': '33', }) # --- +# name: test_rpc_wall_display_brightness_numbers[number.test_name_display_brightness-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : 100, + : 0, + : , + : 1, + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'number', + 'entity_category': , + 'entity_id': 'number.test_name_display_brightness', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Display brightness', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Display brightness', + 'platform': 'shelly', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'display_brightness', + 'unique_id': '123456789ABC-ui-level', + 'unit_of_measurement': , + }) +# --- +# name: test_rpc_wall_display_brightness_numbers[number.test_name_display_brightness-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Test name Display brightness', + : 100, + : 0, + : , + : 1, + : , + }), + 'context': , + 'entity_id': 'number.test_name_display_brightness', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '40', + }) +# --- +# name: test_rpc_wall_display_brightness_numbers[number.test_name_minimum_auto_display_brightness-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : 50, + : 1, + : , + : 1, + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'number', + 'entity_category': , + 'entity_id': 'number.test_name_minimum_auto_display_brightness', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Minimum auto display brightness', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Minimum auto display brightness', + 'platform': 'shelly', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'min_auto_display_brightness', + 'unique_id': '123456789ABC-ui-min_level', + 'unit_of_measurement': , + }) +# --- +# name: test_rpc_wall_display_brightness_numbers[number.test_name_minimum_auto_display_brightness-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Test name Minimum auto display brightness', + : 50, + : 1, + : , + : 1, + : , + }), + 'context': , + 'entity_id': 'number.test_name_minimum_auto_display_brightness', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '3', + }) +# --- diff --git a/tests/components/shelly/snapshots/test_switch.ambr b/tests/components/shelly/snapshots/test_switch.ambr index 5bbdd50a50b0..0fe9f53d5f04 100644 --- a/tests/components/shelly/snapshots/test_switch.ambr +++ b/tests/components/shelly/snapshots/test_switch.ambr @@ -299,3 +299,53 @@ 'state': 'on', }) # --- +# name: test_rpc_wall_display_auto_brightness_switch[switch.test_name_auto_display_brightness-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.test_name_auto_display_brightness', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Auto display brightness', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Auto display brightness', + 'platform': 'shelly', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'auto_brightness', + 'unique_id': '123456789ABC-ui-auto', + 'unit_of_measurement': None, + }) +# --- +# name: test_rpc_wall_display_auto_brightness_switch[switch.test_name_auto_display_brightness-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Test name Auto display brightness', + }), + 'context': , + 'entity_id': 'switch.test_name_auto_display_brightness', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- diff --git a/tests/components/shelly/test_number.py b/tests/components/shelly/test_number.py index 52e9173dec48..c925fe96fd62 100644 --- a/tests/components/shelly/test_number.py +++ b/tests/components/shelly/test_number.py @@ -4,7 +4,7 @@ from copy import deepcopy from typing import Any from unittest.mock import AsyncMock, Mock -from aioshelly.const import MODEL_BLU_GATEWAY_G3 +from aioshelly.const import MODEL_BLU_GATEWAY_G3, MODEL_PLUS_2PM, MODEL_WALL_DISPLAY from aioshelly.exceptions import DeviceConnectionError, InvalidAuthError, RpcCallError import pytest from pytest_homeassistant.common import mock_restore_cache_with_extra_data @@ -36,6 +36,7 @@ from homeassistant.helpers.entity_registry import EntityRegistry from . import ( init_integration, + inject_rpc_device_event, mutate_rpc_device_status, patch_platforms, register_device, @@ -49,6 +50,10 @@ from .conftest import ( DEVICE_BLOCK_ID = 4 LEDSTRIP_ENTITY_ID = f"{NUMBER_DOMAIN}.test_name_effect_speed" +DISPLAY_BRIGHTNESS_ENTITY_ID = f"{NUMBER_DOMAIN}.test_name_display_brightness" +MIN_AUTO_DISPLAY_BRIGHTNESS_ENTITY_ID = ( + f"{NUMBER_DOMAIN}.test_name_minimum_auto_display_brightness" +) @pytest.fixture(autouse=True) @@ -748,3 +753,147 @@ async def test_rpc_ledstrip_speed_number_availability( assert (state := hass.states.get(LEDSTRIP_ENTITY_ID)) assert state.state == expected_state + + +async def test_rpc_wall_display_brightness_numbers( + hass: HomeAssistant, + mock_rpc_device: Mock, + entity_registry: EntityRegistry, + snapshot: SnapshotAssertion, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Test RPC Wall Display brightness numbers.""" + monkeypatch.setitem(mock_rpc_device.shelly, "ver", "2.8.5") + monkeypatch.setitem( + mock_rpc_device.config, + "ui", + {"brightness": {"auto": False, "level": 40, "min_level": 3}}, + ) + await init_integration(hass, 2, model=MODEL_WALL_DISPLAY) + + for entity_id in ( + DISPLAY_BRIGHTNESS_ENTITY_ID, + MIN_AUTO_DISPLAY_BRIGHTNESS_ENTITY_ID, + ): + 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( + NUMBER_DOMAIN, + NumberService.SET_VALUE, + { + TargetKey.ENTITY_ID: DISPLAY_BRIGHTNESS_ENTITY_ID, + NumberServiceArgument.VALUE: 55, + }, + blocking=True, + ) + mock_rpc_device.wall_display_ui_setconfig.assert_called_once_with( + {"brightness": {"level": 55}} + ) + + mock_rpc_device.wall_display_ui_setconfig.reset_mock() + await hass.services.async_call( + NUMBER_DOMAIN, + NumberService.SET_VALUE, + { + TargetKey.ENTITY_ID: MIN_AUTO_DISPLAY_BRIGHTNESS_ENTITY_ID, + NumberServiceArgument.VALUE: 10, + }, + blocking=True, + ) + mock_rpc_device.wall_display_ui_setconfig.assert_called_once_with( + {"brightness": {"min_level": 10}} + ) + + # The device ignores the level while auto brightness is on + def _update_component_config(key: str) -> set[str]: + mock_rpc_device.config[key]["brightness"].update(auto=True, min_level=10) + return {"brightness"} + + mock_rpc_device.update_component_config.side_effect = _update_component_config + inject_rpc_device_event( + monkeypatch, + mock_rpc_device, + { + "events": [ + { + "component": "ui", + "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(DISPLAY_BRIGHTNESS_ENTITY_ID)) + assert state.state == STATE_UNAVAILABLE + assert (state := hass.states.get(MIN_AUTO_DISPLAY_BRIGHTNESS_ENTITY_ID)) + assert state.state == "10" + + +@pytest.mark.parametrize( + ("model", "firmware", "ui_config", "has_level", "has_min_level"), + [ + pytest.param( + MODEL_WALL_DISPLAY, + "2.6.2", + {"brightness": {"auto": True, "level": 40, "min_level": 3}}, + True, + True, + id="min_firmware", + ), + pytest.param( + MODEL_WALL_DISPLAY, + "2.6.2", + {"brightness": {"auto": True, "level": 40}}, + True, + False, + id="no_min_level", + ), + pytest.param( + MODEL_WALL_DISPLAY, + "2.6.1", + {"brightness": {"auto": True, "level": 40, "min_level": 3}}, + False, + False, + id="old_firmware", + ), + pytest.param( + MODEL_WALL_DISPLAY, "2.8.5", {}, False, False, id="no_brightness_config" + ), + pytest.param( + MODEL_PLUS_2PM, + "2.8.5", + {"brightness": {"auto": True, "level": 40, "min_level": 3}}, + False, + False, + id="not_wall_display", + ), + ], +) +async def test_rpc_wall_display_brightness_numbers_supported( + hass: HomeAssistant, + mock_rpc_device: Mock, + monkeypatch: pytest.MonkeyPatch, + model: str, + firmware: str, + ui_config: dict[str, Any], + has_level: bool, + has_min_level: bool, +) -> None: + """Test RPC Wall Display brightness numbers depend on model, firmware and config.""" + monkeypatch.setitem(mock_rpc_device.shelly, "ver", firmware) + monkeypatch.setitem(mock_rpc_device.config, "ui", ui_config) + await init_integration(hass, 2, model=model) + + assert (hass.states.get(DISPLAY_BRIGHTNESS_ENTITY_ID) is not None) is has_level + assert ( + hass.states.get(MIN_AUTO_DISPLAY_BRIGHTNESS_ENTITY_ID) is not None + ) is has_min_level diff --git a/tests/components/shelly/test_switch.py b/tests/components/shelly/test_switch.py index 13541bdd8a92..24437f5c231d 100644 --- a/tests/components/shelly/test_switch.py +++ b/tests/components/shelly/test_switch.py @@ -5,7 +5,13 @@ from datetime import timedelta from typing import Any from unittest.mock import AsyncMock, Mock -from aioshelly.const import MODEL_1PM, MODEL_CAMERA, MODEL_MOTION, MODEL_WALL_DISPLAY +from aioshelly.const import ( + MODEL_1PM, + MODEL_CAMERA, + MODEL_MOTION, + MODEL_PLUS_2PM, + MODEL_WALL_DISPLAY, +) from aioshelly.exceptions import DeviceConnectionError, InvalidAuthError, RpcCallError from freezegun.api import FrozenDateTimeFactory import pytest @@ -1418,3 +1424,109 @@ async def test_rpc_ledstrip_reverse_switch_availability( assert (state := hass.states.get(LEDSTRIP_ENTITY_ID)) assert state.state == expected_state + + +async def test_rpc_wall_display_auto_brightness_switch( + hass: HomeAssistant, + mock_rpc_device: Mock, + entity_registry: EntityRegistry, + snapshot: SnapshotAssertion, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Test RPC Wall Display auto brightness switch.""" + entity_id = f"{SWITCH_DOMAIN}.test_name_auto_display_brightness" + monkeypatch.setitem(mock_rpc_device.shelly, "ver", "2.8.5") + monkeypatch.setitem( + mock_rpc_device.config, + "ui", + {"brightness": {"auto": True, "level": 40, "min_level": 3}}, + ) + await init_integration(hass, 2, model=MODEL_WALL_DISPLAY) + + 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( + SWITCH_DOMAIN, + SwitchService.TURN_OFF, + {TargetKey.ENTITY_ID: entity_id}, + blocking=True, + ) + mock_rpc_device.wall_display_ui_setconfig.assert_called_once_with( + {"brightness": {"auto": False}} + ) + + mock_rpc_device.wall_display_ui_setconfig.reset_mock() + await hass.services.async_call( + SWITCH_DOMAIN, + SwitchService.TURN_ON, + {TargetKey.ENTITY_ID: entity_id}, + blocking=True, + ) + mock_rpc_device.wall_display_ui_setconfig.assert_called_once_with( + {"brightness": {"auto": True}} + ) + + # The device reports the change with an event, the new config is then fetched + def _update_component_config(key: str) -> set[str]: + mock_rpc_device.config[key]["brightness"].update(auto=False) + return {"brightness"} + + mock_rpc_device.update_component_config.side_effect = _update_component_config + inject_rpc_device_event( + monkeypatch, + mock_rpc_device, + { + "events": [ + { + "component": "ui", + "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 == STATE_OFF + + +@pytest.mark.parametrize( + ("model", "firmware", "ui_config"), + [ + pytest.param( + MODEL_WALL_DISPLAY, + "2.6.1", + {"brightness": {"auto": True, "level": 40}}, + id="old_firmware", + ), + pytest.param(MODEL_WALL_DISPLAY, "2.8.5", {}, id="no_brightness_config"), + pytest.param( + MODEL_PLUS_2PM, + "2.8.5", + {"brightness": {"auto": True, "level": 40}}, + id="not_wall_display", + ), + ], +) +async def test_rpc_wall_display_auto_brightness_switch_not_supported( + hass: HomeAssistant, + mock_rpc_device: Mock, + monkeypatch: pytest.MonkeyPatch, + model: str, + firmware: str, + ui_config: dict[str, Any], +) -> None: + """Test RPC Wall Display auto brightness switch needs model, firmware and config.""" + monkeypatch.setitem(mock_rpc_device.shelly, "ver", firmware) + monkeypatch.setitem(mock_rpc_device.config, "ui", ui_config) + await init_integration(hass, 2, model=model) + + assert hass.states.get(f"{SWITCH_DOMAIN}.test_name_auto_display_brightness") is None