diff --git a/homeassistant/components/matter/strings.json b/homeassistant/components/matter/strings.json index bed7d774817a..d98ab89fd8bf 100644 --- a/homeassistant/components/matter/strings.json +++ b/homeassistant/components/matter/strings.json @@ -737,6 +737,9 @@ "privacy_mode_button": { "name": "Privacy mode button" }, + "reverse_motor_direction": { + "name": "Reverse motor direction" + }, "speaker_mute": { "name": "Mute" }, @@ -776,6 +779,12 @@ "addon_stop_failed": { "message": "Failed to stop the Matter Server app." }, + "bitmap_write_failed": { + "message": "Failed to change {name}: the device returned status {status}." + }, + "bitmap_write_not_supported": { + "message": "The device does not support changing {name}." + }, "credential_type_not_supported": { "message": "The lock does not support credential type `{credential_type}`." }, diff --git a/homeassistant/components/matter/switch.py b/homeassistant/components/matter/switch.py index 0252efde5fe1..90e807c49f37 100644 --- a/homeassistant/components/matter/switch.py +++ b/homeassistant/components/matter/switch.py @@ -18,8 +18,10 @@ from homeassistant.components.switch import ( ) from homeassistant.const import EntityCategory, Platform from homeassistant.core import HomeAssistant, callback +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from .const import DOMAIN from .entity import MatterEntity, MatterEntityDescription from .helpers import MatterConfigEntry from .models import MatterDiscoverySchema @@ -172,6 +174,87 @@ class MatterGenericCommandSwitchEntityDescription(MatterSwitchEntityDescription) command_timeout: int | None = None +@dataclass(frozen=True, kw_only=True) +class MatterBitmapSwitchEntityDescription(MatterSwitchEntityDescription): + """Describe Matter switch entities that map to a single bit of a bitmap attribute.""" + + bitmask: int + + +def _write_error_status(result: Any) -> int | None: + """Return the first unsuccessful Matter status of a write response, if any. + + A write is answered with a list of per-path results rather than an error, so + a device rejecting the write otherwise looks like a successful service call. + """ + if not isinstance(result, list): + return None + for item in result: + status: int | None = item.get("Status") if isinstance(item, dict) else None + if status: + return status + return None + + +class MatterBitmapSwitch(MatterSwitch): + """Representation of a single bit of a Matter bitmap attribute as a Switch entity. + + Writes read the other bits from the last reported value, so two entities on + the same attribute would race: both compose from that value and the second + write drops the first one's bit. Discovery prevents this today by claiming + the attribute for one schema, so giving a second bit of the same attribute + an entity needs allow_multi plus serialization, as MatterAlarmEnabledSwitch + does for AlarmsEnabled. + """ + + entity_description: MatterBitmapSwitchEntityDescription + + async def _async_set_bit(self, value: bool) -> None: + """Set or clear the bit in the bitmap attribute, preserving the other bits.""" + current_value: int = self.get_matter_attribute_value( + self._entity_info.primary_attribute + ) + # inverting an IntFlag is bounded by the flags the cluster declares, so + # mask as a plain int to preserve bits outside of those + bitmask = int(self.entity_description.bitmask) + new_value = current_value | bitmask if value else current_value & ~bitmask + result = await self.write_attribute(value=new_value) + if status := _write_error_status(result): + # the spec answers an unsupported mode bit with CONSTRAINT_ERROR + unsupported = status == clusters.Globals.Enums.status.kConstraintError + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key=( + "bitmap_write_not_supported" + if unsupported + else "bitmap_write_failed" + ), + translation_placeholders={ + "name": str(self.name), + "status": str(status), + }, + ) + + @override + async def async_turn_on(self, **kwargs: Any) -> None: + """Set the bit.""" + await self._async_set_bit(True) + + @override + async def async_turn_off(self, **kwargs: Any) -> None: + """Clear the bit.""" + await self._async_set_bit(False) + + @callback + @override + def _update_from_device(self) -> None: + """Update from device.""" + value = self.get_matter_attribute_value(self._entity_info.primary_attribute) + self._attr_is_on = ( + None if value is None else bool(value & self.entity_description.bitmask) + ) + + @dataclass(frozen=True, kw_only=True) class MatterNumericSwitchEntityDescription(MatterSwitchEntityDescription): """Describe Matter Numeric Switch entities.""" @@ -499,4 +582,18 @@ DISCOVERY_SCHEMAS = [ featuremap_contains=BOOLEAN_STATE_CONFIGURATION_FEATURE_AUDIBLE, allow_multi=True, ), + MatterDiscoverySchema( + platform=Platform.SWITCH, + entity_description=MatterBitmapSwitchEntityDescription( + key="WindowCoveringReverseMotorDirection", + entity_category=EntityCategory.CONFIG, + translation_key="reverse_motor_direction", + bitmask=clusters.WindowCovering.Bitmaps.Mode.kMotorDirectionReversed, + ), + entity_class=MatterBitmapSwitch, + required_attributes=(clusters.WindowCovering.Attributes.Mode,), + # Mode is mandatory on every covering, but the bit reverses the lift + # direction, so a tilt-only covering has nothing to configure + featuremap_contains=clusters.WindowCovering.Bitmaps.Feature.kLift, + ), ] diff --git a/tests/components/matter/snapshots/test_device.ambr b/tests/components/matter/snapshots/test_device.ambr index a6c36c481d22..23dbc92e570b 100644 --- a/tests/components/matter/snapshots/test_device.ambr +++ b/tests/components/matter/snapshots/test_device.ambr @@ -138,6 +138,7 @@ 'sensor.aqara_shutter_switch_h2_eu_thread_routing_role': 'Thread routing role', 'sensor.aqara_shutter_switch_h2_eu_uptime': 'Uptime', 'sensor.aqara_shutter_switch_h2_eu_voltage': 'Voltage', + 'switch.aqara_shutter_switch_h2_eu_reverse_motor_direction': 'Reverse motor direction', 'update.aqara_shutter_switch_h2_eu_firmware': 'Firmware', }), 'name': 'Aqara Shutter Switch H2 EU', @@ -220,6 +221,8 @@ 'sensor.smartwings_levitate_with_ductech_thread_routing_role': 'Thread routing role', 'sensor.smartwings_levitate_with_ductech_uptime': 'Uptime', 'switch.smartwings_levitate_with_ductech': None, + 'switch.smartwings_levitate_with_ductech_reverse_motor_direction_1': 'Reverse motor direction (1)', + 'switch.smartwings_levitate_with_ductech_reverse_motor_direction_2': 'Reverse motor direction (2)', 'update.smartwings_levitate_with_ductech_firmware': 'Firmware', }), 'name': 'SmartWings Levitate with DUCTECH', diff --git a/tests/components/matter/snapshots/test_switch.ambr b/tests/components/matter/snapshots/test_switch.ambr index 5e5c5bc5a7b7..a8b879df4f5a 100644 --- a/tests/components/matter/snapshots/test_switch.ambr +++ b/tests/components/matter/snapshots/test_switch.ambr @@ -99,6 +99,56 @@ 'state': 'on', }) # --- +# name: test_switches[aqara_shutter_switch_h2][switch.aqara_shutter_switch_h2_eu_reverse_motor_direction-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.aqara_shutter_switch_h2_eu_reverse_motor_direction', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Reverse motor direction', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Reverse motor direction', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'reverse_motor_direction', + 'unique_id': '00000000000004D2-00000000000000C1-MatterNodeDevice-1-WindowCoveringReverseMotorDirection-258-23', + 'unit_of_measurement': None, + }) +# --- +# name: test_switches[aqara_shutter_switch_h2][switch.aqara_shutter_switch_h2_eu_reverse_motor_direction-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Aqara Shutter Switch H2 EU Reverse motor direction', + }), + 'context': , + 'entity_id': 'switch.aqara_shutter_switch_h2_eu_reverse_motor_direction', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- # name: test_switches[aqara_u200][switch.aqara_smart_lock_u200_one_touch_locking-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ @@ -353,6 +403,106 @@ 'state': 'off', }) # --- +# name: test_switches[ductech_smartwings_levitate][switch.smartwings_levitate_with_ductech_reverse_motor_direction_1-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.smartwings_levitate_with_ductech_reverse_motor_direction_1', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Reverse motor direction (1)', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Reverse motor direction (1)', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'reverse_motor_direction', + 'unique_id': '00000000000004D2-0000000000000057-MatterNodeDevice-1-WindowCoveringReverseMotorDirection-258-23', + 'unit_of_measurement': None, + }) +# --- +# name: test_switches[ductech_smartwings_levitate][switch.smartwings_levitate_with_ductech_reverse_motor_direction_1-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'SmartWings Levitate with DUCTECH Reverse motor direction (1)', + }), + 'context': , + 'entity_id': 'switch.smartwings_levitate_with_ductech_reverse_motor_direction_1', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_switches[ductech_smartwings_levitate][switch.smartwings_levitate_with_ductech_reverse_motor_direction_2-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.smartwings_levitate_with_ductech_reverse_motor_direction_2', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Reverse motor direction (2)', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Reverse motor direction (2)', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'reverse_motor_direction', + 'unique_id': '00000000000004D2-0000000000000057-MatterNodeDevice-2-WindowCoveringReverseMotorDirection-258-23', + 'unit_of_measurement': None, + }) +# --- +# name: test_switches[ductech_smartwings_levitate][switch.smartwings_levitate_with_ductech_reverse_motor_direction_2-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'SmartWings Levitate with DUCTECH Reverse motor direction (2)', + }), + 'context': , + 'entity_id': 'switch.smartwings_levitate_with_ductech_reverse_motor_direction_2', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- # name: test_switches[eve_energy_20ecn4101][switch.eve_energy_20ecn4101_child_lock_top-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ @@ -757,6 +907,56 @@ 'state': 'off', }) # --- +# name: test_switches[eve_shutter][switch.eve_shutter_switch_20eci1701_reverse_motor_direction-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.eve_shutter_switch_20eci1701_reverse_motor_direction', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Reverse motor direction', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Reverse motor direction', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'reverse_motor_direction', + 'unique_id': '00000000000004D2-0000000000000094-MatterNodeDevice-1-WindowCoveringReverseMotorDirection-258-23', + 'unit_of_measurement': None, + }) +# --- +# name: test_switches[eve_shutter][switch.eve_shutter_switch_20eci1701_reverse_motor_direction-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Eve Shutter Switch 20ECI1701 Reverse motor direction', + }), + 'context': , + 'entity_id': 'switch.eve_shutter_switch_20eci1701_reverse_motor_direction', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- # name: test_switches[eve_thermo_v4][switch.eve_thermo_20ebp1701_child_lock-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ @@ -2175,6 +2375,206 @@ 'state': 'off', }) # --- +# name: test_switches[mock_window_covering_full][switch.mock_full_window_covering_reverse_motor_direction-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.mock_full_window_covering_reverse_motor_direction', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Reverse motor direction', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Reverse motor direction', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'reverse_motor_direction', + 'unique_id': '00000000000004D2-0000000000000032-MatterNodeDevice-1-WindowCoveringReverseMotorDirection-258-23', + 'unit_of_measurement': None, + }) +# --- +# name: test_switches[mock_window_covering_full][switch.mock_full_window_covering_reverse_motor_direction-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Mock Full Window Covering Reverse motor direction', + }), + 'context': , + 'entity_id': 'switch.mock_full_window_covering_reverse_motor_direction', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_switches[mock_window_covering_lift][switch.mock_lift_window_covering_reverse_motor_direction-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.mock_lift_window_covering_reverse_motor_direction', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Reverse motor direction', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Reverse motor direction', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'reverse_motor_direction', + 'unique_id': '00000000000004D2-0000000000000033-MatterNodeDevice-1-WindowCoveringReverseMotorDirection-258-23', + 'unit_of_measurement': None, + }) +# --- +# name: test_switches[mock_window_covering_lift][switch.mock_lift_window_covering_reverse_motor_direction-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Mock Lift Window Covering Reverse motor direction', + }), + 'context': , + 'entity_id': 'switch.mock_lift_window_covering_reverse_motor_direction', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_switches[mock_window_covering_pa_lift][switch.longan_link_wncv_da01_reverse_motor_direction-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.longan_link_wncv_da01_reverse_motor_direction', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Reverse motor direction', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Reverse motor direction', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'reverse_motor_direction', + 'unique_id': '00000000000004D2-0000000000000027-MatterNodeDevice-1-WindowCoveringReverseMotorDirection-258-23', + 'unit_of_measurement': None, + }) +# --- +# name: test_switches[mock_window_covering_pa_lift][switch.longan_link_wncv_da01_reverse_motor_direction-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Longan link WNCV DA01 Reverse motor direction', + }), + 'context': , + 'entity_id': 'switch.longan_link_wncv_da01_reverse_motor_direction', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_switches[mock_window_covering_pa_lift_null_tilt][switch.shelly_2pm_gen4_reverse_motor_direction-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.shelly_2pm_gen4_reverse_motor_direction', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Reverse motor direction', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Reverse motor direction', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'reverse_motor_direction', + 'unique_id': '00000000000004D2-0000000000000190-MatterNodeDevice-1-WindowCoveringReverseMotorDirection-258-23', + 'unit_of_measurement': None, + }) +# --- +# name: test_switches[mock_window_covering_pa_lift_null_tilt][switch.shelly_2pm_gen4_reverse_motor_direction-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Shelly 2PM Gen4 Reverse motor direction', + }), + 'context': , + 'entity_id': 'switch.shelly_2pm_gen4_reverse_motor_direction', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- # name: test_switches[silabs_evse_charging][switch.evse_enable_charging-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ @@ -2939,6 +3339,56 @@ 'state': 'on', }) # --- +# name: test_switches[wago_home_blind_control][switch.home_blind_wi_fi_reverse_motor_direction-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.home_blind_wi_fi_reverse_motor_direction', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Reverse motor direction', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Reverse motor direction', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'reverse_motor_direction', + 'unique_id': '00000000000004D2-0000000000000157-MatterNodeDevice-1-WindowCoveringReverseMotorDirection-258-23', + 'unit_of_measurement': None, + }) +# --- +# name: test_switches[wago_home_blind_control][switch.home_blind_wi_fi_reverse_motor_direction-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Home Blind Wi-Fi Reverse motor direction', + }), + 'context': , + 'entity_id': 'switch.home_blind_wi_fi_reverse_motor_direction', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- # name: test_switches[wago_home_relay_16a][switch.home_relay_16a_thread-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ @@ -3041,3 +3491,53 @@ 'state': 'on', }) # --- +# name: test_switches[zemismart_mt25b][switch.zemismart_mt25b_roller_motor_reverse_motor_direction-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.zemismart_mt25b_roller_motor_reverse_motor_direction', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Reverse motor direction', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Reverse motor direction', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'reverse_motor_direction', + 'unique_id': '00000000000004D2-000000000000007A-MatterNodeDevice-1-WindowCoveringReverseMotorDirection-258-23', + 'unit_of_measurement': None, + }) +# --- +# name: test_switches[zemismart_mt25b][switch.zemismart_mt25b_roller_motor_reverse_motor_direction-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Zemismart MT25B Roller Motor Reverse motor direction', + }), + 'context': , + 'entity_id': 'switch.zemismart_mt25b_roller_motor_reverse_motor_direction', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- diff --git a/tests/components/matter/test_switch.py b/tests/components/matter/test_switch.py index cdc7130485f4..f7c2b1ecfec9 100644 --- a/tests/components/matter/test_switch.py +++ b/tests/components/matter/test_switch.py @@ -1,6 +1,7 @@ """Test Matter switches.""" import asyncio +from typing import Any from unittest.mock import MagicMock, call from chip.clusters import Objects as clusters @@ -22,6 +23,10 @@ from .common import ( trigger_subscription_callback, ) +REVERSE_MOTOR_DIRECTION_ENTITY_ID = ( + "switch.mock_full_window_covering_reverse_motor_direction" +) + @pytest.mark.usefixtures("matter_devices") async def test_switches( @@ -495,3 +500,136 @@ async def test_door_lock_one_touch_locking( node_id=matter_node.node_id, attribute_path=attribute_path, value=False ) assert matter_client.write_attribute.call_count == 2 + + +@pytest.mark.parametrize("node_fixture", ["mock_window_covering_full"]) +async def test_window_covering_reverse_motor_direction( + hass: HomeAssistant, + matter_client: MagicMock, + matter_node: MatterNode, +) -> None: + """Test switch entity for the WindowCovering MotorDirectionReversed mode bit.""" + state = hass.states.get(REVERSE_MOTOR_DIRECTION_ENTITY_ID) + assert state + assert state.state == "off" + + set_node_attribute(matter_node, 1, 258, 23, 1) + await trigger_subscription_callback(hass, matter_client) + state = hass.states.get(REVERSE_MOTOR_DIRECTION_ENTITY_ID) + assert state.state == "on" + + # only the MotorDirectionReversed bit drives the state + set_node_attribute(matter_node, 1, 258, 23, 8) + await trigger_subscription_callback(hass, matter_client) + state = hass.states.get(REVERSE_MOTOR_DIRECTION_ENTITY_ID) + assert state.state == "off" + + +@pytest.mark.parametrize("node_fixture", ["mock_window_covering_full"]) +@pytest.mark.parametrize( + ("mode", "service", "written_value"), + [ + pytest.param(8, "turn_on", 9, id="set_keeps_led_feedback"), + pytest.param(9, "turn_off", 8, id="clear_keeps_led_feedback"), + # bits outside the Mode bitmap must survive the read-modify-write too + pytest.param(0x10, "turn_on", 0x11, id="set_keeps_undeclared_bit"), + pytest.param(0x11, "turn_off", 0x10, id="clear_keeps_undeclared_bit"), + ], +) +async def test_window_covering_reverse_motor_direction_write( + hass: HomeAssistant, + matter_client: MagicMock, + matter_node: MatterNode, + mode: int, + service: str, + written_value: int, +) -> None: + """Test writing the mode bit preserves the other bits of the Mode bitmap.""" + set_node_attribute(matter_node, 1, 258, 23, mode) + await trigger_subscription_callback(hass, matter_client) + + await hass.services.async_call( + "switch", + service, + {"entity_id": REVERSE_MOTOR_DIRECTION_ENTITY_ID}, + blocking=True, + ) + assert matter_client.write_attribute.call_count == 1 + assert matter_client.write_attribute.call_args == call( + node_id=matter_node.node_id, + attribute_path=create_attribute_path_from_attribute( + endpoint_id=1, + attribute=clusters.WindowCovering.Attributes.Mode, + ), + value=written_value, + ) + + +def _write_response(status: int) -> list[dict[str, Any]]: + """Build a write response as the Matter Server reports it.""" + return [ + { + "Path": {"EndpointId": 1, "ClusterId": 258, "AttributeId": 23}, + "Status": status, + } + ] + + +@pytest.mark.parametrize("node_fixture", ["mock_window_covering_full"]) +@pytest.mark.parametrize( + ("status", "expected_error"), + [ + pytest.param( + clusters.Globals.Enums.status.kConstraintError, + "does not support changing", + id="constraint_error", + ), + pytest.param( + clusters.Globals.Enums.status.kUnsupportedWrite, + "returned status", + id="unsupported_write", + ), + pytest.param( + clusters.Globals.Enums.status.kBusy, + "returned status", + id="busy", + ), + ], +) +async def test_window_covering_reverse_motor_direction_rejected( + hass: HomeAssistant, + matter_client: MagicMock, + matter_node: MatterNode, + status: int, + expected_error: str, +) -> None: + """Test a device rejecting the write raises a meaningful error.""" + matter_client.write_attribute.return_value = _write_response(status) + + with pytest.raises(HomeAssistantError, match=expected_error): + await hass.services.async_call( + "switch", + "turn_on", + {"entity_id": REVERSE_MOTOR_DIRECTION_ENTITY_ID}, + blocking=True, + ) + + +@pytest.mark.parametrize("node_fixture", ["mock_window_covering_full"]) +async def test_window_covering_reverse_motor_direction_accepted( + hass: HomeAssistant, + matter_client: MagicMock, + matter_node: MatterNode, +) -> None: + """Test a successful write response does not raise.""" + matter_client.write_attribute.return_value = _write_response( + clusters.Globals.Enums.status.kSuccess + ) + + await hass.services.async_call( + "switch", + "turn_on", + {"entity_id": REVERSE_MOTOR_DIRECTION_ENTITY_ID}, + blocking=True, + ) + assert matter_client.write_attribute.call_count == 1