Bump matter-python-client to 1.5.0 (#187593)

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Ludovic BOUÉ
2026-10-21 08:07:15 +02:00
committed by GitHub
co-authored by Claude Sonnet 5
parent 7246de96a6
commit a9eb7e0bd4
17 changed files with 758 additions and 79 deletions
+7 -5
View File
@@ -66,15 +66,17 @@ def get_matter_device_info(
hass: HomeAssistant, device_id: str
) -> MatterDeviceInfo | None:
"""Return Matter device info or None if device does not exist."""
if not hass.config_entries.async_loaded_entries(DOMAIN) or not (
node := node_from_ha_device_id(hass, device_id)
if (
not hass.config_entries.async_loaded_entries(DOMAIN)
or not (node := node_from_ha_device_id(hass, device_id))
or (device_info := node.device_info) is None
):
return None
return MatterDeviceInfo(
unique_id=node.device_info.uniqueID or "",
vendor_id=hex(node.device_info.vendorID),
product_id=hex(node.device_info.productID),
unique_id=device_info.uniqueID or "",
vendor_id=hex(device_info.vendorID),
product_id=hex(device_info.productID),
)
+50 -11
View File
@@ -8,18 +8,27 @@ from matter_server.common.models import EventType, ServerInfoMessage
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import UNDEFINED, UndefinedType
from .const import DOMAIN, ID_TYPE_DEVICE_ID, ID_TYPE_SERIAL, LOGGER
from .discovery import async_discover_entities
from .helpers import MatterConfigEntry, get_device_endpoint, get_device_id
from .helpers import (
MatterConfigEntry,
get_device_endpoint,
get_device_id,
get_discovery_key,
get_entity_unique_id,
get_legacy_device_id,
)
if TYPE_CHECKING:
from matter_server.client import MatterClient
from matter_server.client.models.node import MatterEndpoint, MatterNode
from .models import MatterEntityInfo
def get_clean_name(name: str | None) -> str | None:
"""Strip spaces and null char from the name."""
@@ -173,7 +182,9 @@ class MatterAdapter:
# so derive that entry from the compose parent for every one of them.
endpoint = get_device_endpoint(endpoint)
basic_info = endpoint.device_info
# a Bridged Node without BridgedDeviceBasicInformation gets a device without its info
basic_info = endpoint.device_info or clusters.BridgedDeviceBasicInformation()
node_info = endpoint.node.device_info
# use (first) DeviceType of the endpoint as fallback product name
device_type = next(
(
@@ -220,7 +231,8 @@ class MatterAdapter:
# which would make the identifier resolve to the bridge's device
and not (
isinstance(basic_info, clusters.BridgedDeviceBasicInformation)
and basic_info_serial_number == endpoint.node.device_info.serialNumber
and node_info is not None
and basic_info_serial_number == node_info.serialNumber
)
):
# prefix identifier with 'serial_' to be able to filter it
@@ -264,7 +276,7 @@ class MatterAdapter:
hw_version=basic_info.hardwareVersionString,
sw_version=basic_info.softwareVersionString,
manufacturer=basic_info.vendorName
or endpoint.node.device_info.vendorName,
or (node_info.vendorName if node_info is not None else None),
model=model_name,
model_id=model_id,
serial_number=serial_number,
@@ -276,16 +288,18 @@ class MatterAdapter:
"""Set up a MatterEndpoint as HA Device."""
# pre-create device registry entry
self._create_device_registry(endpoint)
server_info = cast(ServerInfoMessage, self.matter_client.server_info)
device_id = get_device_id(server_info, endpoint)
legacy_device_id = get_legacy_device_id(server_info, endpoint)
# run platform discovery from device type instances
for entity_info in async_discover_entities(endpoint):
discovery_key = (
f"{entity_info.platform}_{endpoint.node.node_id}_{endpoint.endpoint_id}_"
f"{entity_info.primary_attribute.cluster_id}_"
f"{entity_info.primary_attribute.attribute_id}_"
f"{entity_info.entity_description.key}"
)
discovery_key = get_discovery_key(endpoint, entity_info)
if discovery_key in self.discovered_entities:
continue
if legacy_device_id != device_id:
self._migrate_legacy_unique_id(
endpoint, entity_info, legacy_device_id, device_id
)
LOGGER.debug(
"Creating %s entity for %s",
entity_info.platform,
@@ -296,3 +310,28 @@ class MatterAdapter:
self.matter_client, endpoint, entity_info
)
self.platform_handlers[entity_info.platform]([new_entity])
def _migrate_legacy_unique_id(
self,
endpoint: MatterEndpoint,
entity_info: MatterEntityInfo,
legacy_device_id: str,
device_id: str,
) -> None:
"""Rename an entity registry entry still using the pre-1.5.0 unique_id.
matter-python-client 1.5.0 changed `get_compose_parent()` to resolve to the
top of a composition instead of the closest parent, which changes the
unique_id of a part nested below another part. Rename the entity registry
entry so its entity_id (and any automation referencing it) survives the
client upgrade, instead of orphaning it and creating a new entity.
"""
legacy_unique_id = get_entity_unique_id(legacy_device_id, endpoint, entity_info)
entity_registry = er.async_get(self.hass)
if entity_id := entity_registry.async_get_entity_id(
entity_info.platform, DOMAIN, legacy_unique_id
):
entity_registry.async_update_entity(
entity_id,
new_unique_id=get_entity_unique_id(device_id, endpoint, entity_info),
)
+3 -2
View File
@@ -550,8 +550,9 @@ class MatterClimate(MatterEntity, ClimateEntity):
if self._feature_map == feature_map:
return
self._feature_map = feature_map
product_id = self._endpoint.node.device_info.productID
vendor_id = self._endpoint.node.device_info.vendorID
device_info = self._endpoint.node.device_info
product_id = device_info.productID if device_info is not None else None
vendor_id = device_info.vendorID if device_info is not None else None
self._attr_hvac_modes: list[HVACMode] = [HVACMode.OFF]
self._attr_supported_features = (
ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.TURN_OFF
+6 -9
View File
@@ -99,23 +99,20 @@ def async_discover_entities(
primary_attribute = schema.required_attributes[0]
# check vendor_id
if (
schema.vendor_id is not None
and device_info.vendorID not in schema.vendor_id
if schema.vendor_id is not None and (
device_info is None or device_info.vendorID not in schema.vendor_id
):
continue
# check product_id
if (
schema.product_id is not None
and device_info.productID not in schema.product_id
if schema.product_id is not None and (
device_info is None or device_info.productID not in schema.product_id
):
continue
# check product_name
if (
schema.product_name is not None
and device_info.productName not in schema.product_name
if schema.product_name is not None and (
device_info is None or device_info.productName not in schema.product_name
):
continue
+77 -16
View File
@@ -25,7 +25,12 @@ from homeassistant.helpers.entity import Entity, EntityDescription
from homeassistant.helpers.typing import UndefinedType
from .const import DOMAIN, FEATUREMAP_ATTRIBUTE_ID, ID_TYPE_DEVICE_ID
from .helpers import get_device_id
from .helpers import (
MatterConfigEntry,
get_device_id,
get_discovery_key,
get_entity_unique_id,
)
if TYPE_CHECKING:
from matter_server.client import MatterClient
@@ -100,6 +105,7 @@ class MatterEntity(Entity):
# to coalesce attribute updates which arrive as separate events.
_write_state_debounce_cooldown: float | None = None
_write_state_debouncer: Debouncer[None] | None = None
_removal_scheduled = False
def __init__(
self,
@@ -118,12 +124,8 @@ class MatterEntity(Entity):
server_info = cast(ServerInfoMessage, self.matter_client.server_info)
# create unique_id based on "Operational Instance Name" and endpoint/device type
node_device_id = get_device_id(server_info, endpoint)
self._attr_unique_id = (
f"{node_device_id}-"
f"{endpoint.endpoint_id}-"
f"{entity_info.entity_description.key}-"
f"{entity_info.primary_attribute.cluster_id}-"
f"{entity_info.primary_attribute.attribute_id}"
self._attr_unique_id = get_entity_unique_id(
node_device_id, endpoint, entity_info
)
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, f"{ID_TYPE_DEVICE_ID}_{node_device_id}")}
@@ -160,8 +162,12 @@ class MatterEntity(Entity):
"""Find all labels for a Matter entity."""
device_info = self._endpoint.device_info
labeling_list = VENDOR_LABELING_LIST.get(device_info.vendorID, {}).get(
device_info.productID
labeling_list = (
VENDOR_LABELING_LIST.get(device_info.vendorID, {}).get(
device_info.productID
)
if device_info is not None
else None
)
# get the labels from the UserLabel and FixedLabel clusters
@@ -330,6 +336,9 @@ class MatterEntity(Entity):
@callback
def _on_matter_event(self, event: EventType, data: Any = None) -> None:
"""Call on update from the device."""
if event is EventType.NODE_UPDATED and self._required_attribute_removed():
self._async_remove_unsupported()
return
self._attr_available = (
self._endpoint.node.available and self._get_bridged_reachable()
)
@@ -345,18 +354,70 @@ class MatterEntity(Entity):
if data is None:
return
# handle edge case where a Feature is removed from a cluster
if (
self._entity_info.discovery_schema.featuremap_contains is not None
and not bool(data & self._entity_info.discovery_schema.featuremap_contains)
):
if self._feature_removed(data):
# this entity is no longer supported by the device
ent_reg = er.async_get(self.hass)
ent_reg.async_remove(self.entity_id)
self._async_remove_unsupported()
return
# all other cases, just update the entity
self._on_matter_event(event, data)
@callback
def _feature_removed(self, feature_map: int | None) -> bool:
"""Return if the FeatureMap no longer has the feature this entity needs."""
featuremap_contains = self._entity_info.discovery_schema.featuremap_contains
return (
feature_map is not None
and featuremap_contains is not None
and not bool(feature_map & featuremap_contains)
)
@callback
def _required_attribute_removed(self) -> bool:
"""Return if the node data no longer has a required attribute."""
# Entities of an endpoint that left the node data are left to the endpoint removal
if not self._endpoint.has_attribute(
None, clusters.Descriptor.Attributes.DeviceTypeList
):
return False
return not all(
self._endpoint.has_attribute(None, attribute)
for attribute in self._entity_info.discovery_schema.required_attributes
)
@callback
def _unsupported(self) -> bool:
"""Return if the device no longer supports this entity."""
return self._required_attribute_removed() or self._feature_removed(
self._endpoint.get_attribute_value(
self._entity_info.primary_attribute.cluster_id,
FEATUREMAP_ATTRIBUTE_ID,
)
)
@callback
def _async_remove_unsupported(self) -> None:
"""Remove this entity because the device no longer supports it."""
if self._removal_scheduled:
return
self._removal_scheduled = True
# Removing unsubscribes the entity, which must wait until the client has
# finished calling the subscribers of the current event
self.hass.loop.call_soon(self._async_remove_from_registry)
@callback
def _async_remove_from_registry(self) -> None:
"""Remove this entity from the entity registry if it is still unsupported."""
self._removal_scheduled = False
# a later event of the same batch may have restored the support
if not self._unsupported():
return
entry = cast(MatterConfigEntry, self.platform.config_entry)
# let discovery add the entity again if the device supports it later
entry.runtime_data.adapter.discovered_entities.discard(
get_discovery_key(self._endpoint, self._entity_info)
)
er.async_get(self.hass).async_remove(self.entity_id)
@callback
def _update_from_device(self) -> None:
"""Update data from Matter device."""
+2
View File
@@ -230,12 +230,14 @@ class MatterFan(MatterEntity, FanEntity):
elif (
self._attr_preset_modes
and PRESET_NATURAL_WIND in self._attr_preset_modes
and wind_setting is not None
and wind_setting & WindBitmap.kNaturalWind
):
self._attr_preset_mode = PRESET_NATURAL_WIND
elif (
self._attr_preset_modes
and PRESET_SLEEP_WIND in self._attr_preset_modes
and wind_setting is not None
and wind_setting & WindBitmap.kSleepWind
):
self._attr_preset_mode = PRESET_SLEEP_WIND
+60 -9
View File
@@ -17,6 +17,7 @@ if TYPE_CHECKING:
from matter_server.common.models import ServerInfoMessage
from .adapter import MatterAdapter
from .models import MatterEntityInfo
class MissingNode(HomeAssistantError):
@@ -45,6 +46,16 @@ def get_matter(hass: HomeAssistant) -> MatterAdapter:
return entries[0].runtime_data.adapter
def get_discovery_key(endpoint: MatterEndpoint, entity_info: MatterEntityInfo) -> str:
"""Return the key under which the adapter tracks a discovered entity."""
return (
f"{entity_info.platform}_{endpoint.node.node_id}_{endpoint.endpoint_id}_"
f"{entity_info.primary_attribute.cluster_id}_"
f"{entity_info.primary_attribute.attribute_id}_"
f"{entity_info.entity_description.key}"
)
def get_operational_instance_id(
server_info: ServerInfoMessage,
node: MatterNode,
@@ -67,20 +78,60 @@ def get_device_endpoint(endpoint: MatterEndpoint) -> MatterEndpoint:
return endpoint.node.get_compose_parent(endpoint.endpoint_id) or endpoint
def _get_device_id_for_device_endpoint(
server_info: ServerInfoMessage, device_endpoint: MatterEndpoint
) -> str:
"""Return HA device_id for the endpoint a device is derived from."""
operational_instance_id = get_operational_instance_id(
server_info, device_endpoint.node
)
if device_endpoint.is_bridged_device:
# Append endpoint ID if this endpoint is a bridged device
postfix = str(device_endpoint.endpoint_id)
else:
# this should be compatible with previous versions
postfix = "MatterNodeDevice"
return f"{operational_instance_id}-{postfix}"
def get_device_id(
server_info: ServerInfoMessage,
endpoint: MatterEndpoint,
) -> str:
"""Return HA device_id for the given MatterEndpoint."""
operational_instance_id = get_operational_instance_id(server_info, endpoint.node)
endpoint = get_device_endpoint(endpoint)
if endpoint.is_bridged_device:
# Append endpoint ID if this endpoint is a bridged device
postfix = str(endpoint.endpoint_id)
else:
# this should be compatible with previous versions
postfix = "MatterNodeDevice"
return f"{operational_instance_id}-{postfix}"
return _get_device_id_for_device_endpoint(
server_info, get_device_endpoint(endpoint)
)
def get_legacy_device_id(
server_info: ServerInfoMessage,
endpoint: MatterEndpoint,
) -> str:
"""Return the device_id matter-python-client <1.5.0 would have generated.
matter-python-client 1.5.0 changed `get_compose_parent()` to resolve to the top
of a composition instead of the closest parent, which can change the device_id
(and therefore entity unique_id) of a part nested below another part. Only used
to find entity registry entries that still use the pre-1.5.0 unique_id so they
can be migrated.
"""
closest_parent = endpoint.node.get_closest_compose_parent(endpoint.endpoint_id)
return _get_device_id_for_device_endpoint(server_info, closest_parent or endpoint)
def get_entity_unique_id(
device_id: str, endpoint: MatterEndpoint, entity_info: MatterEntityInfo
) -> str:
"""Return the unique_id for an entity discovered on a MatterEndpoint."""
primary_attribute = entity_info.primary_attribute
return (
f"{device_id}-"
f"{endpoint.endpoint_id}-"
f"{entity_info.entity_description.key}-"
f"{primary_attribute.cluster_id}-"
f"{primary_attribute.attribute_id}"
)
def get_node_device_identifier(
+9 -7
View File
@@ -191,7 +191,7 @@ class MatterLight(MatterEntity, LightEntity):
)
)
def _get_xy_color(self) -> tuple[float, float]:
def _get_xy_color(self) -> tuple[float, float] | None:
"""Get xy color from matter."""
x_color = self.get_matter_attribute_value(
@@ -201,8 +201,8 @@ class MatterLight(MatterEntity, LightEntity):
clusters.ColorControl.Attributes.CurrentY
)
assert x_color is not None
assert y_color is not None
if x_color is None or y_color is None:
return None
xy_color = convert_to_hass_xy((x_color, y_color))
LOGGER.debug(
@@ -213,7 +213,7 @@ class MatterLight(MatterEntity, LightEntity):
return xy_color
def _get_hs_color(self) -> tuple[float, float]:
def _get_hs_color(self) -> tuple[float, float] | None:
"""Get hs color from matter."""
hue = self.get_matter_attribute_value(
@@ -224,8 +224,8 @@ class MatterLight(MatterEntity, LightEntity):
clusters.ColorControl.Attributes.CurrentSaturation
)
assert hue is not None
assert saturation is not None
if hue is None or saturation is None:
return None
hs_color = convert_to_hass_hs((hue, saturation))
@@ -457,7 +457,9 @@ class MatterLight(MatterEntity, LightEntity):
def _check_transition_blocklist(self) -> None:
"""Check if this device is reported to have non working transitions."""
device_info = self._endpoint.device_info
if isinstance(device_info, clusters.BridgedDeviceBasicInformation):
if device_info is None or isinstance(
device_info, clusters.BridgedDeviceBasicInformation
):
return
if (
device_info.vendorID,
@@ -9,6 +9,6 @@
"documentation": "https://www.home-assistant.io/integrations/matter",
"integration_type": "hub",
"iot_class": "local_push",
"requirements": ["matter-python-client==1.4.0", "matter-ble-proxy==0.7.1"],
"requirements": ["matter-python-client==1.5.0", "matter-ble-proxy==0.7.1"],
"zeroconf": ["_matter._tcp.local.", "_matterc._udp.local."]
}
+9 -5
View File
@@ -151,7 +151,9 @@ class MatterRangeNumber(MatterEntity, NumberEntity):
# get the value from the primary attribute and convert
# it to the HA value if needed
value = self.get_matter_attribute_value(self._entity_info.primary_attribute)
if value_convert := self.entity_description.device_to_ha:
if value is not None and (
value_convert := self.entity_description.device_to_ha
):
value = value_convert(value)
self._attr_native_value = value
@@ -160,8 +162,9 @@ class MatterRangeNumber(MatterEntity, NumberEntity):
min_value = self.get_matter_attribute_value(
self.entity_description.min_attribute
)
min_convert = self.entity_description.format_min_value
self._attr_native_min_value = min_convert(min_value)
if min_value is not None:
min_convert = self.entity_description.format_min_value
self._attr_native_min_value = min_convert(min_value)
# min case 2: get the min from entity_description
elif self.entity_description.native_min_value is not None:
self._attr_native_min_value = self.entity_description.native_min_value
@@ -170,8 +173,9 @@ class MatterRangeNumber(MatterEntity, NumberEntity):
max_value = self.get_matter_attribute_value(
self.entity_description.max_attribute
)
max_convert = self.entity_description.format_max_value
self._attr_native_max_value = max_convert(max_value)
if max_value is not None:
max_convert = self.entity_description.format_max_value
self._attr_native_max_value = max_convert(max_value)
class MatterStartUpColorTemperatureNumber(MatterRangeNumber):
+7 -7
View File
@@ -145,13 +145,13 @@ class MatterMapSelectEntity(MatterAttributeSelectEntity):
"""Update from device."""
# the options can dynamically change based on the state of the device
available_values = cast(
list[int],
list[int] | None,
self.get_matter_attribute_value(self.entity_description.list_attribute),
)
# map available (int) values to string representation
self._attr_options = [
mapped_value
for value in available_values
for value in available_values or []
if (mapped_value := self.entity_description.device_to_ha(value))
]
# use base implementation from
@@ -293,15 +293,15 @@ class MatterListSelectEntity(MatterEntity, SelectEntity):
list_values_raw = self.get_matter_attribute_value(
self.entity_description.list_attribute
)
if TYPE_CHECKING:
assert list_values_raw is not None
# Accept both list[str] and list[int], convert to str
list_values = [str(v) for v in list_values_raw]
list_values = [str(v) for v in list_values_raw or []]
self._attr_options = list_values
current_option_idx: int = self.get_matter_attribute_value(
current_option_idx: int | None = self.get_matter_attribute_value(
self._entity_info.primary_attribute
)
if current_option_idx is None:
self._attr_current_option = None
return
try:
self._attr_current_option = list_values[current_option_idx]
except IndexError:
+10 -4
View File
@@ -469,13 +469,19 @@ class MatterListSensor(MatterSensor):
@override
def _update_from_device(self) -> None:
"""Update from device."""
self._attr_options = list_values = cast(
list[str],
self.get_matter_attribute_value(self.entity_description.list_attribute),
self._attr_options = list_values = (
cast(
list[str] | None,
self.get_matter_attribute_value(self.entity_description.list_attribute),
)
or []
)
current_value: int = self.get_matter_attribute_value(
current_value: int | None = self.get_matter_attribute_value(
self._entity_info.primary_attribute
)
if current_value is None:
self._attr_native_value = None
return
try:
self._attr_native_value = list_values[current_value]
except IndexError:
+1 -1
View File
@@ -1623,7 +1623,7 @@ matrix-nio==0.26.0
matter-ble-proxy==0.7.1
# homeassistant.components.matter
matter-python-client==1.4.0
matter-python-client==1.5.0
# homeassistant.components.maxcube
maxcube-api==0.4.3
@@ -487,7 +487,8 @@
},
"available": true,
"is_bridge": false,
"attribute_subscriptions": []
"attribute_subscriptions": [],
"endpoint_parents": null
}
],
"events": []
@@ -451,5 +451,6 @@
},
"available": true,
"is_bridge": false,
"attribute_subscriptions": []
"attribute_subscriptions": [],
"endpoint_parents": null
}
+41
View File
@@ -328,6 +328,47 @@ async def test_composed_bridged_device_endpoint_removed(
assert device_registry.async_get_device_by_identifier(identifier, entry_id) is None
async def test_migrate_unique_id_for_part_nested_below_another_part(
hass: HomeAssistant,
matter_client: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test the unique_id of a part nested below another part is migrated.
`get_compose_parent()` resolves to the top of a composition instead of the
closest parent, so a part nested below another part of a bridge (here,
endpoint 4 nested below endpoint 3, itself below the `BridgedNode` endpoint 2)
gets a `-2-4-` unique_id postfix instead of the `-MatterNodeDevice-4-` postfix
it got before. An existing entity registry entry using the old unique_id must
be renamed to the new one so it is not orphaned.
"""
node = create_node_from_fixture("mock_composed_bridge", {"3/29/3": [4]})
matter_client.get_nodes.return_value = [node]
config_entry = MockConfigEntry(
domain=DOMAIN, data={"url": "ws://localhost:5580/ws"}
)
config_entry.add_to_hass(hass)
legacy_entry = entity_registry.async_get_or_create(
"sensor",
DOMAIN,
"00000000000004D2-0000000000000063-MatterNodeDevice-4-TemperatureSensor-1026-0",
config_entry=config_entry,
suggested_object_id="nested_part_temperature",
)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
migrated_entry = entity_registry.async_get(legacy_entry.entity_id)
assert migrated_entry is not None
assert (
migrated_entry.unique_id
== "00000000000004D2-0000000000000063-2-4-TemperatureSensor-1026-0"
)
assert hass.states.get(legacy_entry.entity_id) is not None
@pytest.mark.usefixtures("matter_node")
@pytest.mark.parametrize("node_fixture", ["atios_knx_bridge"])
@pytest.mark.parametrize(
+471
View File
@@ -1,5 +1,6 @@
"""Test Matter entity behavior."""
import copy
from typing import Any
from unittest.mock import MagicMock
@@ -12,6 +13,9 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .common import (
_setup_integration_with_nodes,
create_node_from_fixture,
set_node_attribute,
set_node_attribute_and_notify,
setup_integration_with_node_fixture,
trigger_subscription_callback,
@@ -643,3 +647,470 @@ async def test_entity_removal_unsubscribes_events(
assert hass.states.get(entity_id) is None
assert all(unsubscribe.called for _, unsubscribe in entity_subscriptions)
async def _remove_attributes(
hass: HomeAssistant,
matter_client: MagicMock,
matter_node: MatterNode,
paths: list[str],
) -> None:
"""Remove attributes the way the server reports it.
Each attribute is first sent as a null value, then a node_updated without the
attribute follows.
"""
for path in paths:
endpoint, cluster, attribute = (int(part) for part in path.split("/"))
await set_node_attribute_and_notify(
hass,
matter_client,
matter_node,
endpoint=endpoint,
cluster_id=cluster,
attribute_id=attribute,
value=None,
)
node_data = copy.deepcopy(matter_node.node_data)
for path in paths:
del node_data.attributes[path]
matter_node.update(node_data)
await trigger_subscription_callback(
hass,
matter_client,
EventType.NODE_UPDATED,
matter_node,
node_id=matter_node.node_id,
)
@pytest.mark.parametrize(
("node_fixture", "entity_id", "removed_paths"),
[
(
"aqara_door_window_p2",
"number.aqara_door_and_window_sensor_p2_sensitivity",
["1/128/0", "1/128/1"],
),
(
"aqara_thermostat_w500",
"number.floor_heating_thermostat_occupied_setback",
["1/513/52", "1/513/53", "1/513/54"],
),
(
"mock_oven",
"number.mock_oven_temperature_setpoint",
["2/86/0", "2/86/1", "2/86/2"],
),
("mock_oven", "select.mock_oven_temperature_level", ["4/86/4", "4/86/5"]),
(
"silabs_laundrywasher",
"select.laundrywasher_spin_speed",
["1/83/0", "1/83/1"],
),
(
"silabs_laundrywasher",
"select.laundrywasher_number_of_rinses",
["1/83/2", "1/83/3"],
),
(
"mock_microwave_oven",
"select.mock_microwave_oven_power_level_w",
["1/95/6", "1/95/7"],
),
],
)
async def test_entity_removed_with_required_attribute(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
matter_client: MagicMock,
matter_node: MatterNode,
entity_id: str,
removed_paths: list[str],
) -> None:
"""Test an entity is removed when the device removes a required attribute."""
assert hass.states.get(entity_id) is not None
await _remove_attributes(hass, matter_client, matter_node, removed_paths)
assert entity_registry.async_get(entity_id) is None
assert hass.states.get(entity_id) is None
@pytest.mark.parametrize("node_fixture", ["silabs_laundrywasher"])
async def test_entity_added_again_with_required_attribute(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
matter_client: MagicMock,
matter_node: MatterNode,
) -> None:
"""Test an entity removed with a required attribute comes back with it."""
entity_id = "select.laundrywasher_spin_speed"
removed_paths = ["1/83/0", "1/83/1"]
old_values = {
path: matter_node.node_data.attributes[path] for path in removed_paths
}
await _remove_attributes(hass, matter_client, matter_node, removed_paths)
assert entity_registry.async_get(entity_id) is None
for path, value in old_values.items():
endpoint, cluster, attribute = (int(part) for part in path.split("/"))
matter_node.node_data.attributes[path] = value
set_node_attribute(matter_node, endpoint, cluster, attribute, value)
await trigger_subscription_callback(
hass,
matter_client,
EventType.NODE_UPDATED,
matter_node,
node_id=matter_node.node_id,
)
assert entity_registry.async_get(entity_id) is not None
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "Off"
@pytest.mark.parametrize(
("node_fixture", "entity_id", "path"),
[
# null when the current mode has no spin speed
("silabs_laundrywasher", "select.laundrywasher_spin_speed", "1/83/1"),
# null when the device presents no phases
("silabs_laundrywasher", "sensor.laundrywasher_current_phase", "1/96/0"),
("silabs_laundrywasher", "sensor.laundrywasher_current_phase", "1/96/1"),
],
)
async def test_null_list_index(
hass: HomeAssistant,
matter_client: MagicMock,
matter_node: MatterNode,
entity_id: str,
path: str,
) -> None:
"""Test a null list or list index leaves the entity state unknown."""
endpoint, cluster, attribute = (int(part) for part in path.split("/"))
await set_node_attribute_and_notify(
hass,
matter_client,
matter_node,
endpoint=endpoint,
cluster_id=cluster,
attribute_id=attribute,
value=None,
)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "unknown"
@pytest.mark.parametrize(
("node_fixture", "entity_id", "updates", "check_attribute"),
[
("silabs_fan", "fan.sl_fan", [("1/514/10", None)], "preset_mode"),
(
"extended_color_light",
"light.mock_extended_color_light",
[("1/768/0", None)],
"hs_color",
),
(
"extended_color_light",
"light.mock_extended_color_light",
[("1/768/8", 1), ("1/768/3", None)],
"xy_color",
),
],
)
async def test_null_optional_attribute(
hass: HomeAssistant,
matter_client: MagicMock,
matter_node: MatterNode,
entity_id: str,
updates: list[tuple[str, Any]],
check_attribute: str,
) -> None:
"""Test a null optional attribute leaves the derived state empty."""
for path, value in updates:
endpoint, cluster, attribute = (int(part) for part in path.split("/"))
await set_node_attribute_and_notify(
hass,
matter_client,
matter_node,
endpoint=endpoint,
cluster_id=cluster,
attribute_id=attribute,
value=value,
)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "on"
assert check_attribute in state.attributes
if check_attribute != "preset_mode":
assert state.attributes[check_attribute] is None
@pytest.mark.parametrize("node_fixture", ["silabs_laundrywasher"])
async def test_entities_removed_in_one_node_update(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
matter_client: MagicMock,
node_fixture: str,
) -> None:
"""Test all entities that lose a required attribute in one update are removed.
Like the client, the subscribers are called from the list that removing an
entity unsubscribes it from.
"""
subscribers: dict[str, list[Any]] = {}
def _subscribe_events(**kwargs: Any) -> Any:
key = (
f"{kwargs.get('event_filter')}/{kwargs.get('node_filter')}/"
f"{kwargs.get('attr_path_filter')}"
)
subscribers.setdefault(key, []).append(kwargs["callback"])
return lambda: subscribers[key].remove(kwargs["callback"])
matter_client.subscribe_events.side_effect = _subscribe_events
node = await setup_integration_with_node_fixture(hass, node_fixture, matter_client)
removed = {
"select.laundrywasher_spin_speed": ["1/83/0", "1/83/1"],
"select.laundrywasher_number_of_rinses": ["1/83/2", "1/83/3"],
}
node_data = copy.deepcopy(node.node_data)
for paths in removed.values():
for path in paths:
del node_data.attributes[path]
node.update(node_data)
for callback in subscribers[f"{EventType.NODE_UPDATED}/{node.node_id}/None"]:
callback(EventType.NODE_UPDATED, node)
await hass.async_block_till_done()
for entity_id in removed:
assert entity_registry.async_get(entity_id) is None
@pytest.mark.parametrize("node_fixture", ["silabs_laundrywasher"])
async def test_entity_kept_when_endpoint_leaves_node_data(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
matter_client: MagicMock,
matter_node: MatterNode,
) -> None:
"""Test entities of an endpoint missing from the node data are not removed.
The endpoint is removed with its device when endpoint_removed arrives.
"""
entity_id = "select.laundrywasher_spin_speed"
node_data = copy.deepcopy(matter_node.node_data)
node_data.attributes = {
path: value
for path, value in node_data.attributes.items()
if not path.startswith("1/")
}
matter_node.update(node_data)
await trigger_subscription_callback(
hass,
matter_client,
EventType.NODE_UPDATED,
matter_node,
node_id=matter_node.node_id,
)
assert entity_registry.async_get(entity_id) is not None
def _dispatch(
matter_client: MagicMock, event: EventType, data: Any, path: str | None
) -> None:
"""Call the matching subscribers without running the event loop."""
for sub in matter_client.subscribe_events.call_args_list:
kwargs = sub.kwargs
if kwargs.get("event_filter") != event:
continue
if path is not None and kwargs.get("attr_path_filter") != path:
continue
kwargs["callback"](event, data)
@pytest.mark.parametrize("node_fixture", ["silabs_laundrywasher"])
async def test_entity_kept_when_attribute_comes_back_in_same_batch(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
matter_client: MagicMock,
matter_node: MatterNode,
) -> None:
"""Test an entity is kept when a later update of the same batch restores it."""
entity_id = "select.laundrywasher_spin_speed"
full = copy.deepcopy(matter_node.node_data)
partial = copy.deepcopy(full)
for path in ("1/83/0", "1/83/1"):
del partial.attributes[path]
matter_node.update(partial)
_dispatch(matter_client, EventType.NODE_UPDATED, matter_node, None)
matter_node.update(full)
_dispatch(matter_client, EventType.NODE_UPDATED, matter_node, None)
await hass.async_block_till_done()
assert entity_registry.async_get(entity_id) is not None
@pytest.mark.parametrize("node_fixture", ["aqara_door_window_p2"])
async def test_entity_kept_when_feature_comes_back_in_same_batch(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
matter_client: MagicMock,
matter_node: MatterNode,
) -> None:
"""Test an entity is kept when its feature leaves and returns in one batch."""
entity_id = "number.aqara_door_and_window_sensor_p2_sensitivity"
path = "1/128/65532"
feature_map = matter_node.node_data.attributes[path]
for value in (0, feature_map):
set_node_attribute(matter_node, 1, 128, 65532, value)
_dispatch(matter_client, EventType.ATTRIBUTE_UPDATED, value, path)
await hass.async_block_till_done()
assert entity_registry.async_get(entity_id) is not None
set_node_attribute(matter_node, 1, 128, 65532, 0)
_dispatch(matter_client, EventType.ATTRIBUTE_UPDATED, 0, path)
await hass.async_block_till_done()
assert entity_registry.async_get(entity_id) is None
@pytest.mark.parametrize("node_fixture", ["aqara_door_window_p2"])
async def test_entity_removed_for_other_reason_in_same_batch(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
matter_client: MagicMock,
matter_node: MatterNode,
) -> None:
"""Test a returning feature does not keep an entity missing a required attribute."""
entity_id = "number.aqara_door_and_window_sensor_p2_sensitivity"
node_data = copy.deepcopy(matter_node.node_data)
del node_data.attributes["1/128/0"]
set_node_attribute(matter_node, 1, 128, 65532, 0)
_dispatch(matter_client, EventType.ATTRIBUTE_UPDATED, 0, "1/128/65532")
matter_node.update(node_data)
_dispatch(matter_client, EventType.NODE_UPDATED, matter_node, None)
await hass.async_block_till_done()
assert entity_registry.async_get(entity_id) is None
@pytest.mark.parametrize("node_fixture", ["silabs_fan"])
async def test_node_update_without_wind_setting(
hass: HomeAssistant,
matter_client: MagicMock,
matter_node: MatterNode,
) -> None:
"""Test a fan falls back to its fan mode preset without a wind setting."""
entity_id = "fan.sl_fan"
await set_node_attribute_and_notify(
hass,
matter_client,
matter_node,
endpoint=1,
cluster_id=514,
attribute_id=10,
value=2,
)
state = hass.states.get(entity_id)
assert state is not None
assert state.attributes["preset_mode"] == "natural_wind"
node_data = copy.deepcopy(matter_node.node_data)
del node_data.attributes["1/514/10"]
matter_node.update(node_data)
await trigger_subscription_callback(
hass,
matter_client,
EventType.NODE_UPDATED,
matter_node,
node_id=matter_node.node_id,
)
state = hass.states.get(entity_id)
assert state is not None
assert state.attributes["preset_mode"] == "low"
@pytest.mark.parametrize(
("node_fixture", "entity_id", "removed_path", "check_attribute"),
[
(
"extended_color_light",
"light.mock_extended_color_light",
"1/8/0",
"brightness",
),
(
"extended_color_light",
"light.mock_extended_color_light",
"1/768/0",
"hs_color",
),
],
)
async def test_node_update_without_optional_attribute(
hass: HomeAssistant,
matter_client: MagicMock,
matter_node: MatterNode,
entity_id: str,
removed_path: str,
check_attribute: str,
) -> None:
"""Test a node update without an optional attribute the entity reads.
The client resets the endpoint to the node update, so the attribute reads as
None even without a null value before it.
"""
node_data = copy.deepcopy(matter_node.node_data)
del node_data.attributes[removed_path]
matter_node.update(node_data)
await trigger_subscription_callback(
hass,
matter_client,
EventType.NODE_UPDATED,
matter_node,
node_id=matter_node.node_id,
)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "on"
assert state.attributes[check_attribute] is None
async def test_bridged_node_without_device_info(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
matter_client: MagicMock,
) -> None:
"""Test a Bridged Node without BridgedDeviceBasicInformation is set up."""
node = create_node_from_fixture("fritz_bridge")
node_data = copy.deepcopy(node.node_data)
node_data.attributes = {
path: value
for path, value in node_data.attributes.items()
if not path.startswith("42/57/")
}
await _setup_integration_with_nodes(hass, matter_client, [MatterNode(node_data)])
# the entities of endpoints 40 and 41 belong to the device of the Bridged Node (42)
for endpoint_id in (40, 41):
assert any(
entity.platform == "matter" and f"-42-{endpoint_id}-" in entity.unique_id
for entity in entity_registry.entities.values()
)