Compare commits

...

20 Commits

Author SHA1 Message Date
Artur Pragacz
fe7fab1345 Improve error handling 2026-02-25 01:02:47 +01:00
Artur Pragacz
046c1a7e7d Improve tests 2026-02-25 00:51:19 +01:00
Artur Pragacz
aa2e9c0398 Use dict 2026-02-25 00:15:40 +01:00
Ludovic BOUÉ
7d97424a22 Remove invalid segment ID test from vacuum clean area tests 2026-02-19 23:20:55 +01:00
Ludovic BOUÉ
76114c9ded Remove redundant error handling for segment ID conversion in MatterVacuum 2026-02-19 23:20:02 +01:00
Ludovic BOUÉ
0334dad2f8 Add service area feature map tracking to MatterVacuum for improved state management 2026-02-19 23:19:10 +01:00
Ludovic BOUÉ
2dd65172b0 Refactor MatterVacuum to use property for current segments and simplify segment comparison logic 2026-02-19 23:17:08 +01:00
Ludovic BOUÉ
4532fd379e Add validation for segment IDs in Matter vacuum clean area action 2026-02-19 22:55:10 +01:00
Ludovic BOUÉ
578b2b3d43 Refactor Matter vacuum area selection to resolve run mode before sending commands 2026-02-19 22:52:31 +01:00
Ludovic BOUÉ
9bb2f56fbe Merge branch 'dev' into matter_clean_area 2026-02-19 22:40:31 +01:00
Ludovic BOUÉ
a7d209f1f5 Enhance Matter vacuum support for clean area by checking Map feature availability 2026-02-19 22:38:53 +01:00
Ludovic BOUÉ
83d73dce5c Add SupportedAreas as optional_attributes 2026-02-19 22:18:45 +01:00
Ludovic BOUÉ
d84f81daf2 Enhance vacuum tests to verify segment issue handling and update command assertions 2026-02-19 21:55:17 +01:00
Ludovic BOUÉ
79d4f5c8cf Refactor segment handling to add last_seen_segments 2026-02-19 21:53:54 +01:00
Ludovic BOUÉ
e9e1abb604 Remove debug log for area reset before cleaning
Removed debug logging for resetting selected areas.
2026-02-19 21:42:01 +01:00
Ludovic BOUÉ
9a97541253 Revert unwanted change 2026-02-19 21:39:19 +01:00
Ludovic BOUÉ
fd39f3c431 Add support for unconstrained area selection in vacuum
Reset selected areas for full clean operation when starting the vacuum.
2026-02-19 21:37:43 +01:00
Ludovic BOUÉ
2cc4a77746 Remove Segment group
Co-authored-by: Artur Pragacz <49985303+arturpragacz@users.noreply.github.com>
2026-02-19 20:02:41 +01:00
Ludovic BOUÉ
d7ef65e562 Add test for vacuum clean_area action and update supported features 2026-02-18 17:48:16 +00:00
Ludovic BOUÉ
e765c1652c Add support for cleaning specific segments in Matter vacuum 2026-02-18 17:45:05 +00:00
4 changed files with 303 additions and 15 deletions

View File

@@ -285,9 +285,9 @@ class MatterEntity(Entity):
self,
command: ClusterCommand,
**kwargs: Any,
) -> None:
) -> Any:
"""Send device command on the primary attribute's endpoint."""
await self.matter_client.send_device_command(
return await self.matter_client.send_device_command(
node_id=self._endpoint.node.node_id,
endpoint_id=self._endpoint.endpoint_id,
command=command,

View File

@@ -10,6 +10,7 @@ from chip.clusters import Objects as clusters
from matter_server.client.models import device_types
from homeassistant.components.vacuum import (
Segment,
StateVacuumEntity,
StateVacuumEntityDescription,
VacuumActivity,
@@ -70,6 +71,7 @@ class MatterVacuum(MatterEntity, StateVacuumEntity):
"""Representation of a Matter Vacuum cleaner entity."""
_last_accepted_commands: list[int] | None = None
_last_service_area_feature_map: int | None = None
_supported_run_modes: (
dict[int, clusters.RvcRunMode.Structs.ModeOptionStruct] | None
) = None
@@ -136,6 +138,16 @@ class MatterVacuum(MatterEntity, StateVacuumEntity):
"No supported run mode found to start the vacuum cleaner."
)
# Reset selected areas to an unconstrained selection to ensure start
# performs a full clean and does not reuse a previous area-targeted
# selection.
if VacuumEntityFeature.CLEAN_AREA in self.supported_features:
# Matter ServiceArea: an empty NewAreas list means unconstrained
# operation (full clean).
await self.send_device_command(
clusters.ServiceArea.Commands.SelectAreas(newAreas=[])
)
await self.send_device_command(
clusters.RvcRunMode.Commands.ChangeToMode(newMode=mode.mode)
)
@@ -144,6 +156,66 @@ class MatterVacuum(MatterEntity, StateVacuumEntity):
"""Pause the cleaning task."""
await self.send_device_command(clusters.RvcOperationalState.Commands.Pause())
@property
def _current_segments(self) -> dict[str, Segment]:
"""Return the current cleanable segments reported by the device."""
supported_areas: list[clusters.ServiceArea.Structs.AreaStruct] = (
self.get_matter_attribute_value(
clusters.ServiceArea.Attributes.SupportedAreas
)
)
segments: dict[str, Segment] = {}
for area in supported_areas:
area_name = None
if area.areaInfo and area.areaInfo.locationInfo:
area_name = area.areaInfo.locationInfo.locationName
if area_name:
segment_id = str(area.areaID)
segments[segment_id] = Segment(id=segment_id, name=area_name)
return segments
async def async_get_segments(self) -> list[Segment]:
"""Get the segments that can be cleaned.
Returns a list of segments containing their ids and names.
"""
return list(self._current_segments.values())
async def async_clean_segments(self, segment_ids: list[str], **kwargs: Any) -> None:
"""Clean the specified segments.
Args:
segment_ids: List of segment IDs to clean.
**kwargs: Additional arguments (unused).
"""
area_ids = [int(segment_id) for segment_id in segment_ids]
mode = self._get_run_mode_by_tag(ModeTag.CLEANING)
if mode is None:
raise HomeAssistantError(
"No supported run mode found to start the vacuum cleaner."
)
response = await self.send_device_command(
clusters.ServiceArea.Commands.SelectAreas(newAreas=area_ids)
)
if (
response
and response.status != clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess
):
raise HomeAssistantError(
f"Failed to select areas: {response.statusText or response.status.name}"
)
await self.send_device_command(
clusters.RvcRunMode.Commands.ChangeToMode(newMode=mode.mode)
)
@callback
def _update_from_device(self) -> None:
"""Update from device."""
@@ -176,16 +248,34 @@ class MatterVacuum(MatterEntity, StateVacuumEntity):
state = VacuumActivity.CLEANING
self._attr_activity = state
if (
VacuumEntityFeature.CLEAN_AREA in self.supported_features
and self.registry_entry is not None
and (last_seen_segments := self.last_seen_segments) is not None
and self._current_segments != {s.id: s for s in last_seen_segments}
):
self.async_create_segments_issue()
@callback
def _calculate_features(self) -> None:
"""Calculate features for HA Vacuum platform."""
accepted_operational_commands: list[int] = self.get_matter_attribute_value(
clusters.RvcOperationalState.Attributes.AcceptedCommandList
)
# in principle the feature set should not change, except for the accepted commands
if self._last_accepted_commands == accepted_operational_commands:
service_area_feature_map: int | None = self.get_matter_attribute_value(
clusters.ServiceArea.Attributes.FeatureMap
)
# In principle the feature set should not change, except for accepted
# commands and service area feature map.
if (
self._last_accepted_commands == accepted_operational_commands
and self._last_service_area_feature_map == service_area_feature_map
):
return
self._last_accepted_commands = accepted_operational_commands
self._last_service_area_feature_map = service_area_feature_map
supported_features: VacuumEntityFeature = VacuumEntityFeature(0)
supported_features |= VacuumEntityFeature.START
supported_features |= VacuumEntityFeature.STATE
@@ -212,6 +302,12 @@ class MatterVacuum(MatterEntity, StateVacuumEntity):
in accepted_operational_commands
):
supported_features |= VacuumEntityFeature.RETURN_HOME
# Check if Map feature is enabled for clean area support
if (
service_area_feature_map is not None
and service_area_feature_map & clusters.ServiceArea.Bitmaps.Feature.kMaps
):
supported_features |= VacuumEntityFeature.CLEAN_AREA
self._attr_supported_features = supported_features
@@ -228,6 +324,10 @@ DISCOVERY_SCHEMAS = [
clusters.RvcRunMode.Attributes.CurrentMode,
clusters.RvcOperationalState.Attributes.OperationalState,
),
optional_attributes=(
clusters.ServiceArea.Attributes.FeatureMap,
clusters.ServiceArea.Attributes.SupportedAreas,
),
device_type=(device_types.RoboticVacuumCleaner,),
allow_none_value=True,
),

View File

@@ -29,7 +29,7 @@
'platform': 'matter',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': <VacuumEntityFeature: 12828>,
'supported_features': <VacuumEntityFeature: 29212>,
'translation_key': 'vacuum',
'unique_id': '00000000000004D2-000000000000002F-MatterNodeDevice-1-MatterVacuumCleaner-84-1',
'unit_of_measurement': None,
@@ -39,7 +39,7 @@
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'ecodeebot',
'supported_features': <VacuumEntityFeature: 12828>,
'supported_features': <VacuumEntityFeature: 29212>,
}),
'context': <ANY>,
'entity_id': 'vacuum.ecodeebot',
@@ -79,7 +79,7 @@
'platform': 'matter',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': <VacuumEntityFeature: 12828>,
'supported_features': <VacuumEntityFeature: 29212>,
'translation_key': 'vacuum',
'unique_id': '00000000000004D2-0000000000000028-MatterNodeDevice-1-MatterVacuumCleaner-84-1',
'unit_of_measurement': None,
@@ -89,7 +89,7 @@
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': '2BAVS-AB6031X-44PE',
'supported_features': <VacuumEntityFeature: 12828>,
'supported_features': <VacuumEntityFeature: 29212>,
}),
'context': <ANY>,
'entity_id': 'vacuum.2bavs_ab6031x_44pe',
@@ -129,7 +129,7 @@
'platform': 'matter',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': <VacuumEntityFeature: 12316>,
'supported_features': <VacuumEntityFeature: 28700>,
'translation_key': 'vacuum',
'unique_id': '00000000000004D2-0000000000000042-MatterNodeDevice-1-MatterVacuumCleaner-84-1',
'unit_of_measurement': None,
@@ -139,7 +139,7 @@
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'Mock Vacuum',
'supported_features': <VacuumEntityFeature: 12316>,
'supported_features': <VacuumEntityFeature: 28700>,
}),
'context': <ANY>,
'entity_id': 'vacuum.mock_vacuum',
@@ -179,7 +179,7 @@
'platform': 'matter',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': <VacuumEntityFeature: 12316>,
'supported_features': <VacuumEntityFeature: 28700>,
'translation_key': 'vacuum',
'unique_id': '00000000000004D2-0000000000000061-MatterNodeDevice-1-MatterVacuumCleaner-84-1',
'unit_of_measurement': None,
@@ -189,7 +189,7 @@
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'K11+',
'supported_features': <VacuumEntityFeature: 12316>,
'supported_features': <VacuumEntityFeature: 28700>,
}),
'context': <ANY>,
'entity_id': 'vacuum.k11',

View File

@@ -7,10 +7,11 @@ from matter_server.client.models.node import MatterNode
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.vacuum import DOMAIN as VACUUM_DOMAIN
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from homeassistant.setup import async_setup_component
from .common import (
@@ -19,6 +20,8 @@ from .common import (
trigger_subscription_callback,
)
from tests.typing import WebSocketGenerator
@pytest.mark.usefixtures("matter_devices")
async def test_vacuum(
@@ -71,8 +74,13 @@ async def test_vacuum_actions(
blocking=True,
)
assert matter_client.send_device_command.call_count == 1
assert matter_client.send_device_command.call_args == call(
assert matter_client.send_device_command.call_count == 2
assert matter_client.send_device_command.call_args_list[0] == call(
node_id=matter_node.node_id,
endpoint_id=1,
command=clusters.ServiceArea.Commands.SelectAreas(newAreas=[]),
)
assert matter_client.send_device_command.call_args_list[1] == call(
node_id=matter_node.node_id,
endpoint_id=1,
command=clusters.RvcRunMode.Commands.ChangeToMode(newMode=1),
@@ -289,5 +297,185 @@ async def test_vacuum_actions_no_supported_run_modes(
blocking=True,
)
component = hass.data["vacuum"]
entity = component.get_entity(entity_id)
assert entity is not None
with pytest.raises(
HomeAssistantError,
match="No supported run mode found to start the vacuum cleaner",
):
await entity.async_clean_segments(["7"])
# Ensure no commands were sent to the device
assert matter_client.send_device_command.call_count == 0
@pytest.mark.parametrize("node_fixture", ["mock_vacuum_cleaner"])
async def test_vacuum_get_segments(
hass: HomeAssistant,
matter_client: MagicMock,
matter_node: MatterNode,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test vacuum get_segments websocket command."""
await async_setup_component(hass, "homeassistant", {})
entity_id = "vacuum.mock_vacuum"
state = hass.states.get(entity_id)
assert state
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{"type": "vacuum/get_segments", "entity_id": entity_id}
)
msg = await client.receive_json()
assert msg["success"]
segments = msg["result"]["segments"]
assert len(segments) == 3
assert segments[0] == {"id": "7", "name": "My Location A", "group": None}
assert segments[1] == {"id": "1234567", "name": "My Location B", "group": None}
assert segments[2] == {"id": "2290649224", "name": "My Location C", "group": None}
@pytest.mark.parametrize("node_fixture", ["mock_vacuum_cleaner"])
async def test_vacuum_clean_area(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
matter_client: MagicMock,
matter_node: MatterNode,
) -> None:
"""Test vacuum clean_area service action."""
await async_setup_component(hass, "homeassistant", {})
entity_id = "vacuum.mock_vacuum"
state = hass.states.get(entity_id)
assert state
# Set up area_mapping so the service can map area IDs to segment IDs
entity_registry.async_update_entity_options(
entity_id,
VACUUM_DOMAIN,
{
"area_mapping": {"area_1": ["7", "1234567"]},
"last_seen_segments": [
{"id": "7", "name": "My Location A", "group": None},
{"id": "1234567", "name": "My Location B", "group": None},
{"id": "2290649224", "name": "My Location C", "group": None},
],
},
)
# Mock a successful SelectAreasResponse
matter_client.send_device_command.return_value = (
clusters.ServiceArea.Commands.SelectAreasResponse(
status=clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess,
)
)
await hass.services.async_call(
VACUUM_DOMAIN,
"clean_area",
{"entity_id": entity_id, "cleaning_area_id": ["area_1"]},
blocking=True,
)
# Verify both commands were sent: SelectAreas followed by ChangeToMode
assert matter_client.send_device_command.call_count == 2
assert matter_client.send_device_command.call_args_list[0] == call(
node_id=matter_node.node_id,
endpoint_id=1,
command=clusters.ServiceArea.Commands.SelectAreas(newAreas=[7, 1234567]),
)
assert matter_client.send_device_command.call_args_list[1] == call(
node_id=matter_node.node_id,
endpoint_id=1,
command=clusters.RvcRunMode.Commands.ChangeToMode(newMode=1),
)
@pytest.mark.parametrize("node_fixture", ["mock_vacuum_cleaner"])
async def test_vacuum_clean_area_select_areas_failure(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
matter_client: MagicMock,
matter_node: MatterNode,
) -> None:
"""Test vacuum clean_area raises error when SelectAreas fails."""
await async_setup_component(hass, "homeassistant", {})
entity_id = "vacuum.mock_vacuum"
state = hass.states.get(entity_id)
assert state
# Set up area_mapping so the service can map area IDs to segment IDs
entity_registry.async_update_entity_options(
entity_id,
VACUUM_DOMAIN,
{
"area_mapping": {"area_1": ["7", "1234567"]},
"last_seen_segments": [
{"id": "7", "name": "My Location A", "group": None},
{"id": "1234567", "name": "My Location B", "group": None},
{"id": "2290649224", "name": "My Location C", "group": None},
],
},
)
# Mock a failed SelectAreasResponse
matter_client.send_device_command.return_value = (
clusters.ServiceArea.Commands.SelectAreasResponse(
status=clusters.ServiceArea.Enums.SelectAreasStatus.kUnsupportedArea,
statusText="Area 7 not supported",
)
)
with pytest.raises(HomeAssistantError, match="Failed to select areas"):
await hass.services.async_call(
VACUUM_DOMAIN,
"clean_area",
{"entity_id": entity_id, "cleaning_area_id": ["area_1"]},
blocking=True,
)
# Verify only SelectAreas was sent, ChangeToMode should NOT be sent
assert matter_client.send_device_command.call_count == 1
assert matter_client.send_device_command.call_args == call(
node_id=matter_node.node_id,
endpoint_id=1,
command=clusters.ServiceArea.Commands.SelectAreas(newAreas=[7, 1234567]),
)
@pytest.mark.parametrize("node_fixture", ["mock_vacuum_cleaner"])
async def test_vacuum_raise_segments_changed_issue(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
matter_client: MagicMock,
matter_node: MatterNode,
) -> None:
"""Test that issue is raised on segments change."""
entity_id = "vacuum.mock_vacuum"
entity_entry = entity_registry.async_get(entity_id)
assert entity_entry is not None
entity_registry.async_update_entity_options(
entity_id,
VACUUM_DOMAIN,
{
"last_seen_segments": [
{
"id": "7",
"name": "Old location A",
"group": None,
}
]
},
)
set_node_attribute(matter_node, 1, 97, 4, 0x02)
await trigger_subscription_callback(hass, matter_client)
issue_reg = ir.async_get(hass)
issue = issue_reg.async_get_issue(
VACUUM_DOMAIN, f"segments_changed_{entity_entry.id}"
)
assert issue is not None