Raise HomeAssistantError for ZHA action / WS API failures (#177672)

This commit is contained in:
TheJulianJES
2026-11-23 17:20:29 -05:00
committed by GitHub
parent 808bd4703a
commit 01ddf2a6da
5 changed files with 618 additions and 104 deletions
+94 -49
View File
@@ -25,7 +25,8 @@ from zha.application.platforms.siren import (
StrobeLevel,
WarningMode,
)
from zha.zigbee.device import ZigbeeDevice
from zha.zigbee.device import BaseDevice, ZigbeeDevice
from zha.zigbee.group import Group
from zigpy.types.named import EUI64, KeyData
from zigpy.typing import (
UNDEFINED as ZIGPY_UNDEFINED,
@@ -50,7 +51,12 @@ from .const import (
ZHAService,
ZHAServiceArgument,
)
from .helpers import IEEE_SCHEMA, SERVICE_PERMIT_PARAMS, get_zha_data
from .helpers import (
IEEE_SCHEMA,
SERVICE_PERMIT_PARAMS,
convert_zha_error_to_ha_error,
get_zha_data,
)
_LOGGER = logging.getLogger(__name__)
@@ -188,12 +194,21 @@ def _get_gateway(service: ServiceCall) -> Gateway:
return gateway_proxy.gateway
def _get_device(zha_gateway: Gateway, ieee: EUI64) -> BaseDevice:
"""Return the device, raising a user-facing error if it is unknown."""
if (zha_device := zha_gateway.get_device(ieee)) is None:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="device_not_found",
translation_placeholders={"ieee": str(ieee)},
)
return zha_device
def _get_zigbee_device(zha_gateway: Gateway, ieee: EUI64) -> ZigbeeDevice:
"""Return the Zigbee device, raising if it is missing or not a Zigbee device."""
zha_device = zha_gateway.get_device(ieee)
if zha_device is None:
raise ValueError(f"Device with IEEE {ieee!s} not found")
zha_device = _get_device(zha_gateway, ieee)
if not isinstance(zha_device, ZigbeeDevice):
raise ServiceValidationError(
translation_domain=DOMAIN,
@@ -204,6 +219,31 @@ def _get_zigbee_device(zha_gateway: Gateway, ieee: EUI64) -> ZigbeeDevice:
return zha_device
def _get_warning_device(zha_gateway: Gateway, ieee: EUI64) -> BaseSiren:
"""Return the IAS warning device entity of a device, raising if it has none."""
zha_device = _get_device(zha_gateway, ieee)
try:
return zha_device.get_entity(Platform.SIREN, pick_first=True)
except LookupError as err:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="no_warning_device",
translation_placeholders={"ieee": str(ieee)},
) from err
def _get_group(zha_gateway: Gateway, group_id: int) -> Group:
"""Return the group, raising a user-facing error if it is unknown."""
if (group := zha_gateway.get_group(group_id)) is None:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="group_not_found",
translation_placeholders={"group_id": str(group_id)},
)
return group
async def _permit(service: ServiceCall) -> None:
"""Allow devices to join this network."""
application_controller = _get_gateway(service).application_controller
@@ -215,24 +255,27 @@ async def _permit(service: ServiceCall) -> None:
src_ieee = service.data[ZHAServiceArgument.SOURCE_IEEE]
link_key = service.data[ZHAServiceArgument.INSTALL_CODE]
_LOGGER.info("Allowing join for %s device with link key", src_ieee)
await application_controller.permit_with_link_key(
time_s=duration, node=src_ieee, link_key=link_key
)
async with convert_zha_error_to_ha_error():
await application_controller.permit_with_link_key(
time_s=duration, node=src_ieee, link_key=link_key
)
return
if ZHAServiceArgument.QR_CODE in service.data:
src_ieee, link_key = service.data[ZHAServiceArgument.QR_CODE]
_LOGGER.info("Allowing join for %s device with link key", src_ieee)
await application_controller.permit_with_link_key(
time_s=duration, node=src_ieee, link_key=link_key
)
async with convert_zha_error_to_ha_error():
await application_controller.permit_with_link_key(
time_s=duration, node=src_ieee, link_key=link_key
)
return
if ieee:
_LOGGER.info("Permitting joins for %ss on %s device", duration, ieee)
else:
_LOGGER.info("Permitting joins for %ss", duration)
await application_controller.permit(time_s=duration, node=ieee)
async with convert_zha_error_to_ha_error():
await application_controller.permit(time_s=duration, node=ieee)
async def _remove(service: ServiceCall) -> None:
@@ -240,7 +283,8 @@ async def _remove(service: ServiceCall) -> None:
zha_gateway = _get_gateway(service)
ieee: EUI64 = service.data[ZHAServiceArgument.IEEE]
_LOGGER.info("Removing node %s", ieee)
await zha_gateway.async_remove_device(ieee)
async with convert_zha_error_to_ha_error():
await zha_gateway.async_remove_device(ieee)
async def _set_zigbee_cluster_attributes(service: ServiceCall) -> None:
@@ -256,14 +300,15 @@ async def _set_zigbee_cluster_attributes(service: ServiceCall) -> None:
ZHAServiceArgument.MANUFACTURER, ZIGPY_UNDEFINED
)
zha_device = _get_zigbee_device(zha_gateway, ieee)
response = await zha_device.write_zigbee_attribute(
endpoint_id,
cluster_id,
attribute,
value,
cluster_type=cluster_type,
manufacturer=manufacturer,
)
async with convert_zha_error_to_ha_error():
response = await zha_device.write_zigbee_attribute(
endpoint_id,
cluster_id,
attribute,
value,
cluster_type=cluster_type,
manufacturer=manufacturer,
)
_LOGGER.debug(
(
@@ -305,16 +350,17 @@ async def _issue_zigbee_cluster_command(service: ServiceCall) -> None:
if cluster_id >= MFG_CLUSTER_ID_START and manufacturer is None:
manufacturer = zha_device.manufacturer_code
await zha_device.issue_cluster_command(
endpoint_id,
cluster_id,
command,
command_type,
args,
params,
cluster_type=cluster_type,
manufacturer=manufacturer,
)
async with convert_zha_error_to_ha_error():
await zha_device.issue_cluster_command(
endpoint_id,
cluster_id,
command,
command_type,
args,
params,
cluster_type=cluster_type,
manufacturer=manufacturer,
)
_LOGGER.debug(
(
"Issued command for: %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s]"
@@ -349,12 +395,11 @@ async def _issue_zigbee_group_command(service: ServiceCall) -> None:
manufacturer: int | ZigpyUndefinedType = service.data.get(
ZHAServiceArgument.MANUFACTURER, ZIGPY_UNDEFINED
)
group = zha_gateway.get_group(group_id)
group = _get_group(zha_gateway, group_id)
if cluster_id >= MFG_CLUSTER_ID_START and manufacturer is None:
_LOGGER.error("Missing manufacturer attribute for cluster: %d", cluster_id)
response = None
if group is not None:
cluster = group.endpoint[cluster_id]
cluster = group.endpoint[cluster_id]
async with convert_zha_error_to_ha_error():
response = await cluster.command(
command, *args, manufacturer=manufacturer, expect_reply=True
)
@@ -381,10 +426,10 @@ async def _warning_device_squawk(service: ServiceCall) -> None:
strobe: int = service.data[ZHAServiceArgument.STROBE]
level: int = service.data[ZHAServiceArgument.LEVEL]
device = zha_gateway.get_device(ieee)
siren: BaseSiren = device.get_entity(Platform.SIREN, pick_first=True)
siren = _get_warning_device(zha_gateway, ieee)
await siren.async_squawk(mode=mode, strobe=strobe, squawk_level=level)
async with convert_zha_error_to_ha_error():
await siren.async_squawk(mode=mode, strobe=strobe, squawk_level=level)
async def _warning_device_warn(service: ServiceCall) -> None:
@@ -398,17 +443,17 @@ async def _warning_device_warn(service: ServiceCall) -> None:
duty_mode: int = service.data[ZHAServiceArgument.DUTY_CYCLE]
intensity: int = service.data[ZHAServiceArgument.INTENSITY]
device = zha_gateway.get_device(ieee)
siren: BaseSiren = device.get_entity(Platform.SIREN, pick_first=True)
siren = _get_warning_device(zha_gateway, ieee)
await siren.async_turn_on(
tone=mode,
volume_level=level,
duration=duration,
strobe=strobe,
strobe_duty_cycle=duty_mode,
strobe_intensity=intensity,
)
async with convert_zha_error_to_ha_error():
await siren.async_turn_on(
tone=mode,
volume_level=level,
duration=duration,
strobe=strobe,
strobe_duty_cycle=duty_mode,
strobe_intensity=intensity,
)
LOCK_CODE_SLOT_SCHEMA: VolDictType = {
@@ -2394,9 +2394,18 @@
}
},
"exceptions": {
"device_not_found": {
"message": "Device {ieee} was not found."
},
"group_not_found": {
"message": "Group {group_id} was not found."
},
"no_gateway": {
"message": "ZHA is not loaded, so this action cannot be performed."
},
"no_warning_device": {
"message": "Device {ieee} is not an IAS warning device, so this action cannot be performed."
},
"not_zigbee_device": {
"message": "Device {ieee} is not a Zigbee device, so this action cannot be performed."
}
+76 -31
View File
@@ -24,7 +24,7 @@ from zha.application.const import (
from zha.application.gateway import Gateway
from zha.application.helpers import async_is_bindable_target, get_matched_clusters
from zha.exceptions import ZHAException
from zha.zigbee.device import ZigbeeDevice
from zha.zigbee.device import BaseDevice, ZigbeeDevice
from zha.zigbee.group import GroupMemberReference
import zigpy.backups
from zigpy.config import CONF_DEVICE
@@ -73,6 +73,7 @@ from .helpers import (
ZHAGatewayProxy,
async_cluster_exists,
cluster_command_schema_to_vol_schema,
convert_zha_error_to_ha_error,
get_config_entry,
get_zha_gateway,
get_zha_gateway_proxy,
@@ -198,23 +199,25 @@ async def websocket_permit_devices(
zha_gateway_proxy.async_enable_debug_mode()
src_ieee: EUI64
link_key: KeyData
application_controller = zha_gateway_proxy.gateway.application_controller
if ATTR_SOURCE_IEEE in msg:
src_ieee = msg[ATTR_SOURCE_IEEE]
link_key = msg[ATTR_INSTALL_CODE]
_LOGGER.debug("Allowing join for %s device with link key", src_ieee)
await zha_gateway_proxy.gateway.application_controller.permit_with_link_key(
time_s=duration, node=src_ieee, link_key=link_key
)
async with convert_zha_error_to_ha_error():
await application_controller.permit_with_link_key(
time_s=duration, node=src_ieee, link_key=link_key
)
elif ATTR_QR_CODE in msg:
src_ieee, link_key = msg[ATTR_QR_CODE]
_LOGGER.debug("Allowing join for %s device with link key", src_ieee)
await zha_gateway_proxy.gateway.application_controller.permit_with_link_key(
time_s=duration, node=src_ieee, link_key=link_key
)
async with convert_zha_error_to_ha_error():
await application_controller.permit_with_link_key(
time_s=duration, node=src_ieee, link_key=link_key
)
else:
await zha_gateway_proxy.gateway.application_controller.permit(
time_s=duration, node=ieee
)
async with convert_zha_error_to_ha_error():
await application_controller.permit(time_s=duration, node=ieee)
connection.send_result(msg[ID])
@@ -724,7 +727,11 @@ async def websocket_read_zigbee_cluster_attributes(
cluster_type: str = msg[ATTR_CLUSTER_TYPE]
attribute: int = msg[ATTR_ATTRIBUTE]
manufacturer: int | ZigpyUndefinedType = msg.get(ATTR_MANUFACTURER, ZIGPY_UNDEFINED)
zha_device = zha_gateway.get_device(ieee)
if (
zha_device := _async_get_device(zha_gateway, connection, msg[ID], ieee)
) is None:
return
success = {}
failure = {}
# Green Power devices have no clusters
@@ -732,9 +739,13 @@ async def websocket_read_zigbee_cluster_attributes(
cluster = zha_device.async_get_cluster(
endpoint_id, cluster_id, cluster_type=cluster_type
)
success, failure = await cluster.read_attributes(
[attribute], allow_cache=False, only_cache=False, manufacturer=manufacturer
)
async with convert_zha_error_to_ha_error():
success, failure = await cluster.read_attributes(
[attribute],
allow_cache=False,
only_cache=False,
manufacturer=manufacturer,
)
_LOGGER.debug(
(
"Read attribute for: %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s]"
@@ -772,8 +783,11 @@ async def websocket_get_bindable_devices(
"""Directly bind devices."""
zha_gateway_proxy = get_zha_gateway_proxy(hass)
source_ieee: EUI64 = msg[ATTR_IEEE]
source_device = zha_gateway_proxy.device_proxies.get(source_ieee)
assert source_device is not None
if (source_device := zha_gateway_proxy.device_proxies.get(source_ieee)) is None:
connection.send_error(
msg[ID], websocket_api.ERR_NOT_FOUND, "ZHA Device not found"
)
return
devices = [
device.zha_device_info
@@ -808,8 +822,21 @@ async def websocket_bind_devices(
zha_gateway = get_zha_gateway(hass)
source_ieee: EUI64 = msg[ATTR_SOURCE_IEEE]
target_ieee: EUI64 = msg[ATTR_TARGET_IEEE]
if (
source_device := _async_get_zigbee_device(
zha_gateway, connection, msg[ID], source_ieee
)
) is None:
return
if (
target_device := _async_get_device(
zha_gateway, connection, msg[ID], target_ieee
)
) is None:
return
await async_binding_operation(
zha_gateway, source_ieee, target_ieee, zdo_types.ZDOCmd.Bind_req
source_device, target_device, zdo_types.ZDOCmd.Bind_req
)
_LOGGER.info(
"Devices bound: %s: [%s] %s: [%s]",
@@ -837,8 +864,21 @@ async def websocket_unbind_devices(
zha_gateway = get_zha_gateway(hass)
source_ieee: EUI64 = msg[ATTR_SOURCE_IEEE]
target_ieee: EUI64 = msg[ATTR_TARGET_IEEE]
if (
source_device := _async_get_zigbee_device(
zha_gateway, connection, msg[ID], source_ieee
)
) is None:
return
if (
target_device := _async_get_device(
zha_gateway, connection, msg[ID], target_ieee
)
) is None:
return
await async_binding_operation(
zha_gateway, source_ieee, target_ieee, zdo_types.ZDOCmd.Unbind_req
source_device, target_device, zdo_types.ZDOCmd.Unbind_req
)
_LOGGER.info(
"Devices un-bound: %s: [%s] %s: [%s]",
@@ -912,16 +952,26 @@ async def websocket_unbind_group(
connection.send_result(msg[ID])
@callback
def _async_get_device(
zha_gateway: Gateway, connection: ActiveConnection, msg_id: int, ieee: EUI64
) -> BaseDevice | None:
"""Return the device, or send an error if it is missing."""
if (zha_device := zha_gateway.get_device(ieee)) is None:
connection.send_error(
msg_id, websocket_api.ERR_NOT_FOUND, "ZHA Device not found"
)
return None
return zha_device
@callback
def _async_get_zigbee_device(
zha_gateway: Gateway, connection: ActiveConnection, msg_id: int, ieee: EUI64
) -> ZigbeeDevice | None:
"""Return the Zigbee device, or send an error if it is missing or not Zigbee."""
zha_device = zha_gateway.get_device(ieee)
if zha_device is None:
connection.send_error(
msg_id, websocket_api.ERR_NOT_FOUND, "ZHA Device not found"
)
if (zha_device := _async_get_device(zha_gateway, connection, msg_id, ieee)) is None:
return None
if not isinstance(zha_device, ZigbeeDevice):
@@ -936,17 +986,12 @@ def _async_get_zigbee_device(
async def async_binding_operation(
zha_gateway: Gateway,
source_ieee: EUI64,
target_ieee: EUI64,
source_device: ZigbeeDevice,
target_device: BaseDevice,
operation: zdo_types.ZDOCmd,
) -> None:
"""Create or remove a direct zigbee binding between 2 devices."""
source_device = zha_gateway.get_zigbee_device(source_ieee)
target_device = zha_gateway.get_device(target_ieee)
assert target_device
target_ieee = target_device.ieee
clusters_to_bind = await get_matched_clusters(source_device, target_device)
zdo = source_device.device.zdo
+286 -20
View File
@@ -1,22 +1,35 @@
"""Tests for the ZHA services."""
from collections.abc import Callable, Coroutine
from typing import TYPE_CHECKING, Any
from unittest.mock import AsyncMock, _Call, call, patch
import pytest
from zha.zigbee.device import BaseDevice
from zigpy.device import GreenPowerDevice as ZigpyGreenPowerDevice, ZigbeeDevice
import zigpy.exceptions
from zigpy.profiles import zha
from zigpy.typing import UNDEFINED as ZIGPY_UNDEFINED
from zigpy.zcl.clusters import general
from zigpy.zcl.clusters import general, security
from zigpy.zgp.types import ApplicationID, SrcID
from homeassistant.components.zha.const import DOMAIN, ZHAService
from homeassistant.components.zha.helpers import get_zha_gateway
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.setup import async_setup_component
from .conftest import SIG_EP_INPUT, SIG_EP_OUTPUT, SIG_EP_PROFILE, SIG_EP_TYPE
from .conftest import (
FIXTURE_GRP_ID,
SIG_EP_INPUT,
SIG_EP_OUTPUT,
SIG_EP_PROFILE,
SIG_EP_TYPE,
)
if TYPE_CHECKING:
from zigpy.application import ControllerApplication
IEEE_SWITCH_DEVICE = "01:2d:6f:00:0a:90:69:e7"
SET_ATTRIBUTE_DATA = {"endpoint_id": 1, "cluster_id": 6, "attribute": 0, "value": 1}
@@ -29,6 +42,24 @@ CLUSTER_COMMAND_DATA = {
}
def _add_switch_device(
hass: HomeAssistant, zigpy_device_mock: Callable[..., ZigbeeDevice]
) -> BaseDevice:
"""Add an on/off switch device to the gateway and return the ZHA device."""
zigpy_device = zigpy_device_mock(
{
1: {
SIG_EP_INPUT: [general.Basic.cluster_id, general.OnOff.cluster_id],
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: zha.DeviceType.ON_OFF_SWITCH,
SIG_EP_PROFILE: zha.PROFILE_ID,
}
},
ieee=IEEE_SWITCH_DEVICE,
)
return get_zha_gateway(hass).get_or_create_device(zigpy_device)
async def test_services_registered_without_gateway(hass: HomeAssistant) -> None:
"""Test the actions are registered during component setup."""
assert await async_setup_component(hass, DOMAIN, {})
@@ -135,20 +166,7 @@ async def test_cluster_service(
) -> None:
"""Test the cluster actions are forwarded to the device."""
await setup_zha()
gateway = get_zha_gateway(hass)
zigpy_device = zigpy_device_mock(
{
1: {
SIG_EP_INPUT: [general.Basic.cluster_id, general.OnOff.cluster_id],
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: zha.DeviceType.ON_OFF_SWITCH,
SIG_EP_PROFILE: zha.PROFILE_ID,
}
},
ieee=IEEE_SWITCH_DEVICE,
)
zha_device = gateway.get_or_create_device(zigpy_device)
zha_device = _add_switch_device(hass, zigpy_device_mock)
with patch.object(zha_device, method, AsyncMock()) as method_mock:
await hass.services.async_call(
@@ -171,22 +189,28 @@ async def test_cluster_service(
CLUSTER_COMMAND_DATA,
id="issue_zigbee_cluster_command",
),
pytest.param(ZHAService.WARNING_DEVICE_SQUAWK, {}, id="warning_device_squawk"),
pytest.param(ZHAService.WARNING_DEVICE_WARN, {}, id="warning_device_warn"),
],
)
async def test_cluster_service_unknown_device_raises(
async def test_service_unknown_device_raises(
hass: HomeAssistant,
setup_zha: Callable[..., Coroutine[None]],
service: str,
data: dict,
) -> None:
"""Test the cluster actions reject an unknown device."""
"""Test the device actions reject an unknown device."""
await setup_zha()
with pytest.raises(ValueError, match=f"Device with IEEE {IEEE_SWITCH_DEVICE}"):
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN, service, {"ieee": IEEE_SWITCH_DEVICE, **data}, blocking=True
)
assert err.value.translation_domain == DOMAIN
assert err.value.translation_key == "device_not_found"
assert err.value.translation_placeholders == {"ieee": IEEE_SWITCH_DEVICE}
@pytest.mark.parametrize(
("service", "data"),
@@ -229,3 +253,245 @@ async def test_cluster_service_green_power_device_raises(
assert err.value.translation_domain == DOMAIN
assert err.value.translation_key == "not_zigbee_device"
assert err.value.translation_placeholders == {"ieee": str(zigpy_gpd.ieee)}
@pytest.mark.parametrize(
("side_effect", "message"),
[
pytest.param(
zigpy.exceptions.DeliveryError(
"Failed to deliver packet: <TXStatus.MAC_CHANNEL_ACCESS_FAILURE: 225>",
225,
),
(
"Failed to send request: Failed to deliver packet: "
"<TXStatus.MAC_CHANNEL_ACCESS_FAILURE: 225>"
),
id="delivery_error",
),
pytest.param(
TimeoutError(),
"Failed to send request: device did not respond",
id="timeout",
),
],
)
@pytest.mark.parametrize(
("service", "data", "method"),
[
pytest.param(
ZHAService.SET_ZIGBEE_CLUSTER_ATTRIBUTE,
SET_ATTRIBUTE_DATA,
"write_zigbee_attribute",
id="set_zigbee_cluster_attribute",
),
pytest.param(
ZHAService.ISSUE_ZIGBEE_CLUSTER_COMMAND,
CLUSTER_COMMAND_DATA,
"issue_cluster_command",
id="issue_zigbee_cluster_command",
),
],
)
async def test_cluster_service_radio_failure(
hass: HomeAssistant,
setup_zha: Callable[..., Coroutine[None]],
zigpy_device_mock: Callable[..., ZigbeeDevice],
service: str,
data: dict,
method: str,
side_effect: Exception,
message: str,
) -> None:
"""Test a radio failure in a cluster action raises a readable error."""
await setup_zha()
zha_device = _add_switch_device(hass, zigpy_device_mock)
with (
patch.object(zha_device, method, AsyncMock(side_effect=side_effect)),
pytest.raises(HomeAssistantError) as err,
):
await hass.services.async_call(
DOMAIN, service, {"ieee": IEEE_SWITCH_DEVICE, **data}, blocking=True
)
assert str(err.value) == message
@pytest.mark.parametrize(
("data", "method"),
[
pytest.param({}, "permit", id="permit"),
pytest.param(
{"qr_code": "000D6FFFFED4163B|52797BF4A5084DAA8E1712B61741CA024051"},
"permit_with_link_key",
id="permit_with_link_key",
),
],
)
async def test_permit_radio_failure(
hass: HomeAssistant,
setup_zha: Callable[..., Coroutine[None]],
zigpy_app_controller: ControllerApplication,
data: dict[str, Any],
method: str,
) -> None:
"""Test a radio failure when permitting joins raises a readable error."""
await setup_zha()
getattr(zigpy_app_controller, method).side_effect = zigpy.exceptions.DeliveryError(
"Failed to deliver packet", 225
)
with pytest.raises(HomeAssistantError) as err:
await hass.services.async_call(DOMAIN, ZHAService.PERMIT, data, blocking=True)
assert str(err.value) == "Failed to send request: Failed to deliver packet"
async def test_remove_radio_failure(
hass: HomeAssistant,
setup_zha: Callable[..., Coroutine[None]],
zigpy_device_mock: Callable[..., ZigbeeDevice],
zigpy_app_controller: ControllerApplication,
) -> None:
"""Test a radio failure when removing a device raises a readable error."""
await setup_zha()
_add_switch_device(hass, zigpy_device_mock)
zigpy_app_controller.remove = AsyncMock(
side_effect=zigpy.exceptions.DeliveryError("Failed to deliver packet", 225)
)
with pytest.raises(HomeAssistantError) as err:
await hass.services.async_call(
DOMAIN, ZHAService.REMOVE, {"ieee": IEEE_SWITCH_DEVICE}, blocking=True
)
assert str(err.value) == "Failed to send request: Failed to deliver packet"
@pytest.mark.parametrize(
"service", [ZHAService.WARNING_DEVICE_SQUAWK, ZHAService.WARNING_DEVICE_WARN]
)
async def test_warning_device_service_without_siren_raises(
hass: HomeAssistant,
setup_zha: Callable[..., Coroutine[None]],
zigpy_device_mock: Callable[..., ZigbeeDevice],
service: str,
) -> None:
"""Test the warning device actions reject a device without a siren."""
await setup_zha()
_add_switch_device(hass, zigpy_device_mock)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN, service, {"ieee": IEEE_SWITCH_DEVICE}, blocking=True
)
assert err.value.translation_domain == DOMAIN
assert err.value.translation_key == "no_warning_device"
assert err.value.translation_placeholders == {"ieee": IEEE_SWITCH_DEVICE}
@pytest.mark.parametrize(
("service", "method"),
[
pytest.param(
ZHAService.WARNING_DEVICE_SQUAWK, "async_squawk", id="warning_device_squawk"
),
pytest.param(
ZHAService.WARNING_DEVICE_WARN, "async_turn_on", id="warning_device_warn"
),
],
)
async def test_warning_device_service_radio_failure(
hass: HomeAssistant,
setup_zha: Callable[..., Coroutine[None]],
zigpy_device_mock: Callable[..., ZigbeeDevice],
service: str,
method: str,
) -> None:
"""Test a radio failure in a warning device action raises a readable error."""
await setup_zha()
gateway = get_zha_gateway(hass)
zigpy_device = zigpy_device_mock(
{
1: {
SIG_EP_INPUT: [general.Basic.cluster_id, security.IasWd.cluster_id],
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: zha.DeviceType.IAS_WARNING_DEVICE,
SIG_EP_PROFILE: zha.PROFILE_ID,
}
},
ieee=IEEE_SWITCH_DEVICE,
)
zha_device = gateway.get_or_create_device(zigpy_device)
await gateway.async_device_initialized(zigpy_device)
await hass.async_block_till_done(wait_background_tasks=True)
siren = zha_device.get_entity(Platform.SIREN, pick_first=True)
with (
patch.object(
siren,
method,
AsyncMock(
side_effect=zigpy.exceptions.DeliveryError(
"Failed to deliver packet", 225
)
),
),
pytest.raises(HomeAssistantError) as err,
):
await hass.services.async_call(
DOMAIN, service, {"ieee": IEEE_SWITCH_DEVICE}, blocking=True
)
assert str(err.value) == "Failed to send request: Failed to deliver packet"
async def test_group_command_unknown_group_raises(
hass: HomeAssistant, setup_zha: Callable[..., Coroutine[None]]
) -> None:
"""Test the group command action rejects an unknown group."""
await setup_zha()
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
ZHAService.ISSUE_ZIGBEE_GROUP_COMMAND,
{"group": 0x1234, "cluster_id": 6, "command": 0},
blocking=True,
)
assert err.value.translation_domain == DOMAIN
assert err.value.translation_key == "group_not_found"
assert err.value.translation_placeholders == {"group_id": str(0x1234)}
async def test_group_command_radio_failure(
hass: HomeAssistant, setup_zha: Callable[..., Coroutine[None]]
) -> None:
"""Test a radio failure in the group command action raises a readable error."""
await setup_zha()
group = get_zha_gateway(hass).get_group(FIXTURE_GRP_ID)
assert group is not None
with (
patch.object(
group.endpoint[general.OnOff.cluster_id],
"command",
AsyncMock(
side_effect=zigpy.exceptions.DeliveryError(
"Failed to deliver packet", 225
)
),
),
pytest.raises(HomeAssistantError) as err,
):
await hass.services.async_call(
DOMAIN,
ZHAService.ISSUE_ZIGBEE_GROUP_COMMAND,
{"group": FIXTURE_GRP_ID, "cluster_id": 6, "command": 0},
blocking=True,
)
assert str(err.value) == "Failed to send request: Failed to deliver packet"
+153 -4
View File
@@ -35,6 +35,7 @@ from zha.zigbee.device import (
import zigpy.backups
from zigpy.const import SIG_EP_INPUT, SIG_EP_OUTPUT, SIG_EP_PROFILE, SIG_EP_TYPE
from zigpy.device import GreenPowerDevice as ZigpyGreenPowerDevice
import zigpy.exceptions
import zigpy.profiles.zha
import zigpy.types
from zigpy.types.named import EUI64
@@ -46,6 +47,7 @@ from zigpy.zgp.types import ApplicationID, SrcID
from zigpy.zgp.util import synthetic_ieee
from homeassistant.components.websocket_api import (
ERR_HOME_ASSISTANT_ERROR,
ERR_INVALID_FORMAT,
ERR_NOT_FOUND,
ERR_NOT_SUPPORTED,
@@ -86,6 +88,7 @@ from .data import BASE_CUSTOM_CONFIGURATION, CONFIG_WITH_ALARM_OPTIONS
IEEE_SWITCH_DEVICE = "01:2d:6f:00:0a:90:69:e7"
IEEE_GROUPABLE_DEVICE = "01:2d:6f:00:0a:90:69:e8"
IEEE_UNKNOWN_DEVICE = "28:6d:97:00:01:04:11:8c"
GREEN_POWER_SRC_ID = SrcID(0x12345678)
IEEE_GREEN_POWER_DEVICE = str(synthetic_ieee(GREEN_POWER_SRC_ID))
@@ -661,6 +664,75 @@ async def test_read_zigbee_cluster_attribute(
assert read_mock.call_count == read_calls
async def test_read_zigbee_cluster_attribute_device_not_found(
zha_client: MockHAClientWebSocket,
) -> None:
"""Test reading a cluster attribute of an unknown device."""
await zha_client.send_json(
{
ID: 5,
TYPE: "zha/devices/clusters/attributes/value",
ATTR_IEEE: IEEE_UNKNOWN_DEVICE,
ATTR_ENDPOINT_ID: 1,
ATTR_CLUSTER_ID: general.OnOff.cluster_id,
ATTR_CLUSTER_TYPE: CLUSTER_TYPE_IN,
ATTR_ATTRIBUTE: 0,
}
)
msg = await zha_client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == ERR_NOT_FOUND
async def test_read_zigbee_cluster_attribute_radio_failure(
hass: HomeAssistant, zha_client: MockHAClientWebSocket
) -> None:
"""Test a failed cluster attribute read is reported as a readable error."""
cluster = (
get_zha_gateway(hass)
.get_device(EUI64.convert(IEEE_SWITCH_DEVICE))
.async_get_cluster(1, general.OnOff.cluster_id)
)
with patch.object(
cluster,
"read_attributes",
AsyncMock(
side_effect=zigpy.exceptions.DeliveryError("Failed to deliver packet", 225)
),
):
await zha_client.send_json(
{
ID: 5,
TYPE: "zha/devices/clusters/attributes/value",
ATTR_IEEE: IEEE_SWITCH_DEVICE,
ATTR_ENDPOINT_ID: 1,
ATTR_CLUSTER_ID: general.OnOff.cluster_id,
ATTR_CLUSTER_TYPE: CLUSTER_TYPE_IN,
ATTR_ATTRIBUTE: 0,
}
)
msg = await zha_client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == ERR_HOME_ASSISTANT_ERROR
assert msg["error"]["message"] == "Failed to send request: Failed to deliver packet"
async def test_get_bindable_devices_device_not_found(
zha_client: MockHAClientWebSocket,
) -> None:
"""Test listing the bindable devices of an unknown device."""
await zha_client.send_json(
{ID: 5, TYPE: "zha/devices/bindable", ATTR_IEEE: IEEE_UNKNOWN_DEVICE}
)
msg = await zha_client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == ERR_NOT_FOUND
async def test_get_zha_config_with_green_power_device(
hass: HomeAssistant, zha_client: MockHAClientWebSocket
) -> None:
@@ -1139,6 +1211,29 @@ async def test_ws_permit_ha12(
assert app_controller.permit_with_link_key.call_count == 0
async def test_ws_permit_radio_failure(
app_controller: ControllerApplication, zha_client: MockHAClientWebSocket
) -> None:
"""Test a failed permit is reported as a readable error."""
app_controller.permit.side_effect = zigpy.exceptions.DeliveryError(
"Failed to deliver packet", 225
)
await zha_client.send_json({ID: 14, TYPE: f"{DOMAIN}/devices/{ZHAService.PERMIT}"})
msg_type = None
while msg_type != TYPE_RESULT:
# There will be logging events coming over the websocket
# as well so we want to ignore those
msg = await zha_client.receive_json()
msg_type = msg["type"]
assert msg["id"] == 14
assert not msg["success"]
assert msg["error"]["code"] == ERR_HOME_ASSISTANT_ERROR
assert msg["error"]["message"] == "Failed to send request: Failed to deliver packet"
async def test_ws_permit_overlapping_restores_log_levels(
zha_client: MockHAClientWebSocket, caplog: pytest.LogCaptureFixture
) -> None:
@@ -1344,6 +1439,7 @@ async def test_websocket_change_channel(
)
async def test_websocket_bind_unbind_devices(
operation: tuple[str, zdo_types.ZDOCmd],
hass: HomeAssistant,
app_controller: ControllerApplication,
zha_client,
) -> None:
@@ -1367,16 +1463,69 @@ async def test_websocket_bind_unbind_devices(
assert msg["id"] == 27
assert msg["type"] == TYPE_RESULT
assert msg["success"]
gateway = get_zha_gateway(hass)
assert binding_operation_mock.mock_calls == [
call(
ANY,
EUI64.convert(IEEE_SWITCH_DEVICE),
EUI64.convert(IEEE_GROUPABLE_DEVICE),
gateway.get_device(EUI64.convert(IEEE_SWITCH_DEVICE)),
gateway.get_device(EUI64.convert(IEEE_GROUPABLE_DEVICE)),
req,
)
]
@pytest.mark.parametrize("command_type", ["bind", "unbind"])
@pytest.mark.parametrize(
("source_ieee", "target_ieee", "error_code"),
[
pytest.param(
IEEE_UNKNOWN_DEVICE,
IEEE_GROUPABLE_DEVICE,
ERR_NOT_FOUND,
id="missing_source",
),
pytest.param(
IEEE_SWITCH_DEVICE, IEEE_UNKNOWN_DEVICE, ERR_NOT_FOUND, id="missing_target"
),
pytest.param(
IEEE_GREEN_POWER_DEVICE,
IEEE_GROUPABLE_DEVICE,
ERR_NOT_SUPPORTED,
id="green_power_source",
),
],
)
async def test_websocket_bind_unbind_devices_invalid_device(
command_type: str,
source_ieee: str,
target_ieee: str,
error_code: str,
hass: HomeAssistant,
zha_client: MockHAClientWebSocket,
) -> None:
"""Test binding devices fails for a missing device or a Green Power source."""
await _async_add_green_power_device(hass)
with patch(
"homeassistant.components.zha.websocket_api.async_binding_operation",
autospec=True,
) as binding_operation_mock:
await zha_client.send_json(
{
ID: 27,
TYPE: f"zha/devices/{command_type}",
ATTR_SOURCE_IEEE: source_ieee,
ATTR_TARGET_IEEE: target_ieee,
}
)
msg = await zha_client.receive_json()
assert msg["id"] == 27
assert msg["type"] == TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == error_code
assert binding_operation_mock.call_count == 0
@pytest.mark.parametrize(
("command_type", "method"),
[
@@ -1425,7 +1574,7 @@ async def test_websocket_bind_unbind_group(
@pytest.mark.parametrize(
("source_ieee", "error_code"),
[
pytest.param("28:6d:97:00:01:04:11:8c", ERR_NOT_FOUND, id="missing"),
pytest.param(IEEE_UNKNOWN_DEVICE, ERR_NOT_FOUND, id="missing"),
pytest.param(IEEE_GREEN_POWER_DEVICE, ERR_NOT_SUPPORTED, id="green_power"),
],
)