ZHA device channel refactoring (#31971)

* Add ZHA core typing helper.
* Add aux_channels to ZHA rule matching.
* Add match rule claim_channels() method.
* Expose underlying zigpy device.
* Not sure we need this one.
* Move "base" channels.
* Framework for channel discovery.
* Make DEVICE_CLASS and REMOTE_DEVICE_TYPE default dicts.
* Remove attribute reporting configuration registry.
* Refactor channels.
- Refactor zha events
- Use compound IDs and unique_ids
- Refactor signal dispatching on attribute updates

* Use unique id compatible with entities unique ids.
* Refactor ZHA Entity registry.
Let match rule to check for the match.

* Refactor discovery to use new channels.
* Cleanup ZDO channel.
Remove unused zha store call.

* Handle channel configuration and initialization.
* Refactor ZHA Device to use new channels.
* Refactor ZHA Gateway to use new discovery framework.
Use hass.data for entity info intermediate store.

* Don't keep entities in hass.data.
* ZHA gateway new discovery framework.
* Refactor ZHA platform loading.
* Don't update ZHA entities, when restoring from zigpy.
* ZHA entity discover tests.
* Add AnalogInput sensor.
* Remove 0xFC02 based entity from Keen smart vents.
* Clean up IAS channels.
* Refactor entity restoration.
* Fix lumi.router entities name.
* Rename EndpointsChannel to ChannelPool.
* Make Channels.pools a list.
* Fix cover test.
* Fix FakeDevice class.
* Fix device actions.
* Fix channels typing.
* Revert update_before_add=False
* Refactor channel class matching.
* Use a helper function for adding entities.
* Make Pylint happy.
* Rebase cleanup.
* Update coverage for ZHA device type overrides.
* Use cluster_id for single output cluster registry.
* Remove ZHA typing from coverage.
* Fix tests.
* Address comments.
* Address comments.
This commit is contained in:
Alexei Chetroi authored and GitHub committed 2020-02-21 18:06:57 -05:00
1 parent 36db302cc8
commit 3385893b77
40 files changed
+1918 -1325

No files matched your search

+1
View File
@@ -63,6 +63,7 @@ class FakeDevice:
def __init__(self, app, ieee, manufacturer, model, node_desc=None):
"""Init fake device."""
self._application = app
self.application = app
self.ieee = zigpy.types.EUI64.convert(ieee)
self.nwk = 0xB79C
self.zdo = Mock()
+41 -3
View File
@@ -9,6 +9,7 @@ import zigpy.group
import zigpy.types
import homeassistant.components.zha.core.const as zha_const
import homeassistant.components.zha.core.device as zha_core_device
import homeassistant.components.zha.core.registries as zha_regs
from homeassistant.setup import async_setup_component
@@ -63,7 +64,7 @@ async def config_entry_fixture(hass):
@pytest.fixture
def setup_zha(hass, config_entry, zigpy_app_controller, zigpy_radio):
"""Set up ZHA component."""
zha_config = {zha_const.DOMAIN: {zha_const.CONF_ENABLE_QUIRKS: False}}
zha_config = {zha_const.CONF_ENABLE_QUIRKS: False}
radio_details = {
zha_const.ZHA_GW_RADIO: mock.MagicMock(return_value=zigpy_radio),
@@ -71,9 +72,12 @@ def setup_zha(hass, config_entry, zigpy_app_controller, zigpy_radio):
zha_const.ZHA_GW_RADIO_DESCRIPTION: "mock radio",
}
async def _setup():
async def _setup(config=None):
config = config or {}
with mock.patch.dict(zha_regs.RADIO_TYPES, {"MockRadio": radio_details}):
status = await async_setup_component(hass, zha_const.DOMAIN, zha_config)
status = await async_setup_component(
hass, zha_const.DOMAIN, {zha_const.DOMAIN: {**zha_config, **config}}
)
assert status is True
await hass.async_block_till_done()
@@ -153,6 +157,7 @@ def zha_device_restored(hass, zigpy_app_controller, setup_zha):
zigpy_app_controller.devices[zigpy_dev.ieee] = zigpy_dev
await setup_zha()
zha_gateway = hass.data[zha_const.DATA_ZHA][zha_const.DATA_ZHA_GATEWAY]
await zha_gateway.async_load_devices()
return zha_gateway.get_device(zigpy_dev.ieee)
return _zha_device
@@ -162,3 +167,36 @@ def zha_device_restored(hass, zigpy_app_controller, setup_zha):
def zha_device_joined_restored(request):
"""Join or restore ZHA device."""
return request.getfixturevalue(request.param)
@pytest.fixture
def zha_device_mock(hass, zigpy_device_mock):
"""Return a zha Device factory."""
def _zha_device(
endpoints=None,
ieee="00:11:22:33:44:55:66:77",
manufacturer="mock manufacturer",
model="mock model",
node_desc=b"\x02@\x807\x10\x7fd\x00\x00*d\x00\x00",
):
if endpoints is None:
endpoints = {
1: {
"in_clusters": [0, 1, 8, 768],
"out_clusters": [0x19],
"device_type": 0x0105,
},
2: {
"in_clusters": [0],
"out_clusters": [6, 8, 0x19, 768],
"device_type": 0x0810,
},
}
zigpy_device = zigpy_device_mock(
endpoints, ieee, manufacturer, model, node_desc
)
zha_device = zha_core_device.ZHADevice(hass, zigpy_device, mock.MagicMock())
return zha_device
return _zha_device
+222 -11
View File
@@ -1,9 +1,14 @@
"""Test ZHA Core channels."""
import asyncio
from unittest import mock
import asynctest
import pytest
import zigpy.types as t
import homeassistant.components.zha.core.channels as channels
import homeassistant.components.zha.core.device as zha_device
import homeassistant.components.zha.core.channels as zha_channels
import homeassistant.components.zha.core.channels.base as base_channels
import homeassistant.components.zha.core.const as zha_const
import homeassistant.components.zha.core.registries as registries
from .common import get_zha_gateway
@@ -28,6 +33,15 @@ async def zha_gateway(hass, setup_zha):
return get_zha_gateway(hass)
@pytest.fixture
def channel_pool():
"""Endpoint Channels fixture."""
ch_pool_mock = mock.MagicMock(spec_set=zha_channels.ChannelPool)
type(ch_pool_mock).skip_configuration = mock.PropertyMock(return_value=False)
ch_pool_mock.id = 1
return ch_pool_mock
@pytest.mark.parametrize(
"cluster_id, bind_count, attrs",
[
@@ -72,7 +86,7 @@ async def zha_gateway(hass, setup_zha):
],
)
async def test_in_channel_config(
cluster_id, bind_count, attrs, hass, zigpy_device_mock, zha_gateway
cluster_id, bind_count, attrs, channel_pool, zigpy_device_mock, zha_gateway
):
"""Test ZHA core channel configuration for input clusters."""
zigpy_dev = zigpy_device_mock(
@@ -81,13 +95,12 @@ async def test_in_channel_config(
"test manufacturer",
"test model",
)
zha_dev = zha_device.ZHADevice(hass, zigpy_dev, zha_gateway)
cluster = zigpy_dev.endpoints[1].in_clusters[cluster_id]
channel_class = registries.ZIGBEE_CHANNEL_REGISTRY.get(
cluster_id, channels.AttributeListeningChannel
cluster_id, base_channels.AttributeListeningChannel
)
channel = channel_class(cluster, zha_dev)
channel = channel_class(cluster, channel_pool)
await channel.async_configure()
@@ -130,7 +143,7 @@ async def test_in_channel_config(
],
)
async def test_out_channel_config(
cluster_id, bind_count, zha_gateway, hass, zigpy_device_mock
cluster_id, bind_count, channel_pool, zigpy_device_mock, zha_gateway
):
"""Test ZHA core channel configuration for output clusters."""
zigpy_dev = zigpy_device_mock(
@@ -139,14 +152,13 @@ async def test_out_channel_config(
"test manufacturer",
"test model",
)
zha_dev = zha_device.ZHADevice(hass, zigpy_dev, zha_gateway)
cluster = zigpy_dev.endpoints[1].out_clusters[cluster_id]
cluster.bind_only = True
channel_class = registries.ZIGBEE_CHANNEL_REGISTRY.get(
cluster_id, channels.AttributeListeningChannel
cluster_id, base_channels.AttributeListeningChannel
)
channel = channel_class(cluster, zha_dev)
channel = channel_class(cluster, channel_pool)
await channel.async_configure()
@@ -159,4 +171,203 @@ def test_channel_registry():
for (cluster_id, channel) in registries.ZIGBEE_CHANNEL_REGISTRY.items():
assert isinstance(cluster_id, int)
assert 0 <= cluster_id <= 0xFFFF
assert issubclass(channel, channels.ZigbeeChannel)
assert issubclass(channel, base_channels.ZigbeeChannel)
def test_epch_unclaimed_channels(channel):
"""Test unclaimed channels."""
ch_1 = channel(zha_const.CHANNEL_ON_OFF, 6)
ch_2 = channel(zha_const.CHANNEL_LEVEL, 8)
ch_3 = channel(zha_const.CHANNEL_COLOR, 768)
ep_channels = zha_channels.ChannelPool(
mock.MagicMock(spec_set=zha_channels.Channels), mock.sentinel.ep
)
all_channels = {ch_1.id: ch_1, ch_2.id: ch_2, ch_3.id: ch_3}
with mock.patch.dict(ep_channels.all_channels, all_channels, clear=True):
available = ep_channels.unclaimed_channels()
assert ch_1 in available
assert ch_2 in available
assert ch_3 in available
ep_channels.claimed_channels[ch_2.id] = ch_2
available = ep_channels.unclaimed_channels()
assert ch_1 in available
assert ch_2 not in available
assert ch_3 in available
ep_channels.claimed_channels[ch_1.id] = ch_1
available = ep_channels.unclaimed_channels()
assert ch_1 not in available
assert ch_2 not in available
assert ch_3 in available
ep_channels.claimed_channels[ch_3.id] = ch_3
available = ep_channels.unclaimed_channels()
assert ch_1 not in available
assert ch_2 not in available
assert ch_3 not in available
def test_epch_claim_channels(channel):
"""Test channel claiming."""
ch_1 = channel(zha_const.CHANNEL_ON_OFF, 6)
ch_2 = channel(zha_const.CHANNEL_LEVEL, 8)
ch_3 = channel(zha_const.CHANNEL_COLOR, 768)
ep_channels = zha_channels.ChannelPool(
mock.MagicMock(spec_set=zha_channels.Channels), mock.sentinel.ep
)
all_channels = {ch_1.id: ch_1, ch_2.id: ch_2, ch_3.id: ch_3}
with mock.patch.dict(ep_channels.all_channels, all_channels, clear=True):
assert ch_1.id not in ep_channels.claimed_channels
assert ch_2.id not in ep_channels.claimed_channels
assert ch_3.id not in ep_channels.claimed_channels
ep_channels.claim_channels([ch_2])
assert ch_1.id not in ep_channels.claimed_channels
assert ch_2.id in ep_channels.claimed_channels
assert ep_channels.claimed_channels[ch_2.id] is ch_2
assert ch_3.id not in ep_channels.claimed_channels
ep_channels.claim_channels([ch_3, ch_1])
assert ch_1.id in ep_channels.claimed_channels
assert ep_channels.claimed_channels[ch_1.id] is ch_1
assert ch_2.id in ep_channels.claimed_channels
assert ep_channels.claimed_channels[ch_2.id] is ch_2
assert ch_3.id in ep_channels.claimed_channels
assert ep_channels.claimed_channels[ch_3.id] is ch_3
assert "1:0x0300" in ep_channels.claimed_channels
@mock.patch("homeassistant.components.zha.core.channels.ChannelPool.add_relay_channels")
@mock.patch(
"homeassistant.components.zha.core.discovery.PROBE.discover_entities",
mock.MagicMock(),
)
def test_ep_channels_all_channels(m1, zha_device_mock):
"""Test EndpointChannels adding all channels."""
zha_device = zha_device_mock(
{
1: {"in_clusters": [0, 1, 6, 8], "out_clusters": [], "device_type": 0x0000},
2: {
"in_clusters": [0, 1, 6, 8, 768],
"out_clusters": [],
"device_type": 0x0000,
},
}
)
channels = zha_channels.Channels(zha_device)
ep_channels = zha_channels.ChannelPool.new(channels, 1)
assert "1:0x0000" in ep_channels.all_channels
assert "1:0x0001" in ep_channels.all_channels
assert "1:0x0006" in ep_channels.all_channels
assert "1:0x0008" in ep_channels.all_channels
assert "1:0x0300" not in ep_channels.all_channels
assert "2:0x0000" not in ep_channels.all_channels
assert "2:0x0001" not in ep_channels.all_channels
assert "2:0x0006" not in ep_channels.all_channels
assert "2:0x0008" not in ep_channels.all_channels
assert "2:0x0300" not in ep_channels.all_channels
channels = zha_channels.Channels(zha_device)
ep_channels = zha_channels.ChannelPool.new(channels, 2)
assert "1:0x0000" not in ep_channels.all_channels
assert "1:0x0001" not in ep_channels.all_channels
assert "1:0x0006" not in ep_channels.all_channels
assert "1:0x0008" not in ep_channels.all_channels
assert "1:0x0300" not in ep_channels.all_channels
assert "2:0x0000" in ep_channels.all_channels
assert "2:0x0001" in ep_channels.all_channels
assert "2:0x0006" in ep_channels.all_channels
assert "2:0x0008" in ep_channels.all_channels
assert "2:0x0300" in ep_channels.all_channels
@mock.patch("homeassistant.components.zha.core.channels.ChannelPool.add_relay_channels")
@mock.patch(
"homeassistant.components.zha.core.discovery.PROBE.discover_entities",
mock.MagicMock(),
)
def test_channel_power_config(m1, zha_device_mock):
"""Test that channels only get a single power channel."""
in_clusters = [0, 1, 6, 8]
zha_device = zha_device_mock(
{
1: {"in_clusters": in_clusters, "out_clusters": [], "device_type": 0x0000},
2: {
"in_clusters": [*in_clusters, 768],
"out_clusters": [],
"device_type": 0x0000,
},
}
)
channels = zha_channels.Channels.new(zha_device)
pools = {pool.id: pool for pool in channels.pools}
assert "1:0x0000" in pools[1].all_channels
assert "1:0x0001" in pools[1].all_channels
assert "1:0x0006" in pools[1].all_channels
assert "1:0x0008" in pools[1].all_channels
assert "1:0x0300" not in pools[1].all_channels
assert "2:0x0000" in pools[2].all_channels
assert "2:0x0001" not in pools[2].all_channels
assert "2:0x0006" in pools[2].all_channels
assert "2:0x0008" in pools[2].all_channels
assert "2:0x0300" in pools[2].all_channels
zha_device = zha_device_mock(
{
1: {"in_clusters": [], "out_clusters": [], "device_type": 0x0000},
2: {"in_clusters": in_clusters, "out_clusters": [], "device_type": 0x0000},
}
)
channels = zha_channels.Channels.new(zha_device)
pools = {pool.id: pool for pool in channels.pools}
assert "1:0x0001" not in pools[1].all_channels
assert "2:0x0001" in pools[2].all_channels
zha_device = zha_device_mock(
{2: {"in_clusters": in_clusters, "out_clusters": [], "device_type": 0x0000}}
)
channels = zha_channels.Channels.new(zha_device)
pools = {pool.id: pool for pool in channels.pools}
assert "2:0x0001" in pools[2].all_channels
async def test_ep_channels_configure(channel):
"""Test unclaimed channels."""
ch_1 = channel(zha_const.CHANNEL_ON_OFF, 6)
ch_2 = channel(zha_const.CHANNEL_LEVEL, 8)
ch_3 = channel(zha_const.CHANNEL_COLOR, 768)
ch_3.async_configure = asynctest.CoroutineMock(side_effect=asyncio.TimeoutError)
ch_3.async_initialize = asynctest.CoroutineMock(side_effect=asyncio.TimeoutError)
ch_4 = channel(zha_const.CHANNEL_ON_OFF, 6)
ch_5 = channel(zha_const.CHANNEL_LEVEL, 8)
ch_5.async_configure = asynctest.CoroutineMock(side_effect=asyncio.TimeoutError)
ch_5.async_initialize = asynctest.CoroutineMock(side_effect=asyncio.TimeoutError)
channels = mock.MagicMock(spec_set=zha_channels.Channels)
type(channels).semaphore = mock.PropertyMock(return_value=asyncio.Semaphore(3))
ep_channels = zha_channels.ChannelPool(channels, mock.sentinel.ep)
claimed = {ch_1.id: ch_1, ch_2.id: ch_2, ch_3.id: ch_3}
relay = {ch_4.id: ch_4, ch_5.id: ch_5}
with mock.patch.dict(ep_channels.claimed_channels, claimed, clear=True):
with mock.patch.dict(ep_channels.relay_channels, relay, clear=True):
await ep_channels.async_configure()
await ep_channels.async_initialize(mock.sentinel.from_cache)
for ch in [*claimed.values(), *relay.values()]:
assert ch.async_initialize.call_count == 1
assert ch.async_initialize.await_count == 1
assert ch.async_initialize.call_args[0][0] is mock.sentinel.from_cache
assert ch.async_configure.call_count == 1
assert ch.async_configure.await_count == 1
assert ch_3.warning.call_count == 2
assert ch_5.warning.call_count == 2
+1 -1
View File
@@ -45,7 +45,7 @@ async def test_cover(m1, hass, zha_device_joined_restored, zigpy_cover_device):
return 100
with patch(
"homeassistant.components.zha.core.channels.ZigbeeChannel.get_attribute_value",
"homeassistant.components.zha.core.channels.base.ZigbeeChannel.get_attribute_value",
new=MagicMock(side_effect=get_chan_attr),
) as get_attr_mock:
# load up cover domain
+2 -3
View File
@@ -11,7 +11,6 @@ from homeassistant.components.device_automation import (
_async_get_device_automations as async_get_device_automations,
)
from homeassistant.components.zha import DOMAIN
from homeassistant.components.zha.core.const import CHANNEL_EVENT_RELAY
from homeassistant.helpers.device_registry import async_get_registry
from homeassistant.setup import async_setup_component
@@ -104,8 +103,8 @@ async def test_action(hass, device_ias):
await hass.async_block_till_done()
calls = async_mock_service(hass, DOMAIN, "warning_device_warn")
channel = {ch.name: ch for ch in zha_device.all_channels}[CHANNEL_EVENT_RELAY]
channel.zha_send_event(channel.cluster, COMMAND_SINGLE, [])
channel = zha_device.channels.pools[0].relay_channels["1:0x0006"]
channel.zha_send_event(COMMAND_SINGLE, [])
await hass.async_block_till_done()
assert len(calls) == 1
+2 -3
View File
@@ -3,7 +3,6 @@ import pytest
import zigpy.zcl.clusters.general as general
import homeassistant.components.automation as automation
from homeassistant.components.zha.core.const import CHANNEL_EVENT_RELAY
from homeassistant.helpers.device_registry import async_get_registry
from homeassistant.setup import async_setup_component
@@ -173,8 +172,8 @@ async def test_if_fires_on_event(hass, mock_devices, calls):
await hass.async_block_till_done()
channel = {ch.name: ch for ch in zha_device.all_channels}[CHANNEL_EVENT_RELAY]
channel.zha_send_event(channel.cluster, COMMAND_SINGLE, [])
channel = zha_device.channels.pools[0].relay_channels["1:0x0006"]
channel.zha_send_event(COMMAND_SINGLE, [])
await hass.async_block_till_done()
assert len(calls) == 1
+323 -34
View File
@@ -4,10 +4,24 @@ import re
from unittest import mock
import pytest
import zigpy.quirks
import zigpy.zcl.clusters.closures
import zigpy.zcl.clusters.general
import zigpy.zcl.clusters.security
import homeassistant.components.zha.binary_sensor
import homeassistant.components.zha.core.channels as zha_channels
import homeassistant.components.zha.core.channels.base as base_channels
import homeassistant.components.zha.core.const as zha_const
import homeassistant.components.zha.core.discovery as disc
import homeassistant.components.zha.core.gateway as core_zha_gw
import homeassistant.components.zha.core.registries as zha_regs
import homeassistant.components.zha.cover
import homeassistant.components.zha.device_tracker
import homeassistant.components.zha.fan
import homeassistant.components.zha.light
import homeassistant.components.zha.lock
import homeassistant.components.zha.sensor
import homeassistant.components.zha.switch
import homeassistant.helpers.entity_registry
from .common import get_zha_gateway
@@ -16,12 +30,34 @@ from .zha_devices_list import DEVICES
NO_TAIL_ID = re.compile("_\\d$")
@pytest.fixture
def channels_mock(zha_device_mock):
"""Channels mock factory."""
def _mock(
endpoints,
ieee="00:11:22:33:44:55:66:77",
manufacturer="mock manufacturer",
model="mock model",
node_desc=b"\x02@\x807\x10\x7fd\x00\x00*d\x00\x00",
):
zha_dev = zha_device_mock(endpoints, ieee, manufacturer, model, node_desc)
channels = zha_channels.Channels.new(zha_dev)
return channels
return _mock
@pytest.mark.parametrize("device", DEVICES)
async def test_devices(
device, hass, zigpy_device_mock, monkeypatch, zha_device_joined_restored
):
"""Test device discovery."""
entity_registry = await homeassistant.helpers.entity_registry.async_get_registry(
hass
)
zigpy_device = zigpy_device_mock(
device["endpoints"],
"00:11:22:33:44:55:66:77",
@@ -30,45 +66,298 @@ async def test_devices(
node_descriptor=device["node_descriptor"],
)
_dispatch = mock.MagicMock(wraps=disc.async_dispatch_discovery_info)
monkeypatch.setattr(core_zha_gw, "async_dispatch_discovery_info", _dispatch)
entity_registry = await homeassistant.helpers.entity_registry.async_get_registry(
hass
orig_new_entity = zha_channels.ChannelPool.async_new_entity
_dispatch = mock.MagicMock(wraps=orig_new_entity)
try:
zha_channels.ChannelPool.async_new_entity = lambda *a, **kw: _dispatch(*a, **kw)
zha_dev = await zha_device_joined_restored(zigpy_device)
await hass.async_block_till_done()
finally:
zha_channels.ChannelPool.async_new_entity = orig_new_entity
entity_ids = hass.states.async_entity_ids()
await hass.async_block_till_done()
zha_entity_ids = {
ent for ent in entity_ids if ent.split(".")[0] in zha_const.COMPONENTS
}
event_channels = {
ch.id for pool in zha_dev.channels.pools for ch in pool.relay_channels.values()
}
entity_map = device["entity_map"]
assert zha_entity_ids == set(
[
e["entity_id"]
for e in entity_map.values()
if not e.get("default_match", False)
]
)
assert event_channels == set(device["event_channels"])
for call in _dispatch.call_args_list:
_, component, entity_cls, unique_id, channels = call[0]
key = (component, unique_id)
entity_id = entity_registry.async_get_entity_id(component, "zha", unique_id)
assert key in entity_map
assert entity_id is not None
no_tail_id = NO_TAIL_ID.sub("", entity_map[key]["entity_id"])
assert entity_id.startswith(no_tail_id)
assert set([ch.name for ch in channels]) == set(entity_map[key]["channels"])
assert entity_cls.__name__ == entity_map[key]["entity_class"]
@mock.patch(
"homeassistant.components.zha.core.discovery.ProbeEndpoint.discover_by_device_type"
)
@mock.patch(
"homeassistant.components.zha.core.discovery.ProbeEndpoint.discover_by_cluster_id"
)
def test_discover_entities(m1, m2):
"""Test discover endpoint class method."""
ep_channels = mock.MagicMock()
disc.PROBE.discover_entities(ep_channels)
assert m1.call_count == 1
assert m1.call_args[0][0] is ep_channels
assert m2.call_count == 1
assert m2.call_args[0][0] is ep_channels
@pytest.mark.parametrize(
"device_type, component, hit",
[
(0x0100, zha_const.LIGHT, True),
(0x0108, zha_const.SWITCH, True),
(0x0051, zha_const.SWITCH, True),
(0xFFFF, None, False),
],
)
def test_discover_by_device_type(device_type, component, hit):
"""Test entity discovery by device type."""
ep_channels = mock.MagicMock(spec_set=zha_channels.ChannelPool)
ep_mock = mock.PropertyMock()
ep_mock.return_value.profile_id = 0x0104
ep_mock.return_value.device_type = device_type
type(ep_channels).endpoint = ep_mock
get_entity_mock = mock.MagicMock(
return_value=(mock.sentinel.entity_cls, mock.sentinel.claimed)
)
with mock.patch(
"homeassistant.components.zha.core.registries.ZHA_ENTITIES.get_entity",
get_entity_mock,
):
disc.PROBE.discover_by_device_type(ep_channels)
if hit:
assert get_entity_mock.call_count == 1
assert ep_channels.claim_channels.call_count == 1
assert ep_channels.claim_channels.call_args[0][0] is mock.sentinel.claimed
assert ep_channels.async_new_entity.call_count == 1
assert ep_channels.async_new_entity.call_args[0][0] == component
assert ep_channels.async_new_entity.call_args[0][1] == mock.sentinel.entity_cls
def test_discover_by_device_type_override():
"""Test entity discovery by device type overriding."""
ep_channels = mock.MagicMock(spec_set=zha_channels.ChannelPool)
ep_mock = mock.PropertyMock()
ep_mock.return_value.profile_id = 0x0104
ep_mock.return_value.device_type = 0x0100
type(ep_channels).endpoint = ep_mock
overrides = {ep_channels.unique_id: {"type": zha_const.SWITCH}}
get_entity_mock = mock.MagicMock(
return_value=(mock.sentinel.entity_cls, mock.sentinel.claimed)
)
with mock.patch(
"homeassistant.components.zha.core.registries.ZHA_ENTITIES.get_entity",
get_entity_mock,
):
with mock.patch.dict(disc.PROBE._device_configs, overrides, clear=True):
disc.PROBE.discover_by_device_type(ep_channels)
assert get_entity_mock.call_count == 1
assert ep_channels.claim_channels.call_count == 1
assert ep_channels.claim_channels.call_args[0][0] is mock.sentinel.claimed
assert ep_channels.async_new_entity.call_count == 1
assert ep_channels.async_new_entity.call_args[0][0] == zha_const.SWITCH
assert (
ep_channels.async_new_entity.call_args[0][1] == mock.sentinel.entity_cls
)
def test_discover_probe_single_cluster():
"""Test entity discovery by single cluster."""
ep_channels = mock.MagicMock(spec_set=zha_channels.ChannelPool)
ep_mock = mock.PropertyMock()
ep_mock.return_value.profile_id = 0x0104
ep_mock.return_value.device_type = 0x0100
type(ep_channels).endpoint = ep_mock
get_entity_mock = mock.MagicMock(
return_value=(mock.sentinel.entity_cls, mock.sentinel.claimed)
)
channel_mock = mock.MagicMock(spec_set=base_channels.ZigbeeChannel)
with mock.patch(
"homeassistant.components.zha.core.registries.ZHA_ENTITIES.get_entity",
get_entity_mock,
):
disc.PROBE.probe_single_cluster(zha_const.SWITCH, channel_mock, ep_channels)
assert get_entity_mock.call_count == 1
assert ep_channels.claim_channels.call_count == 1
assert ep_channels.claim_channels.call_args[0][0] is mock.sentinel.claimed
assert ep_channels.async_new_entity.call_count == 1
assert ep_channels.async_new_entity.call_args[0][0] == zha_const.SWITCH
assert ep_channels.async_new_entity.call_args[0][1] == mock.sentinel.entity_cls
assert ep_channels.async_new_entity.call_args[0][3] == mock.sentinel.claimed
@pytest.mark.parametrize("device_info", DEVICES)
async def test_discover_endpoint(device_info, channels_mock, hass):
"""Test device discovery."""
with mock.patch(
"homeassistant.components.zha.core.discovery._async_create_cluster_channel",
wraps=disc._async_create_cluster_channel,
"homeassistant.components.zha.core.channels.Channels.async_new_entity"
) as new_ent:
channels = channels_mock(
device_info["endpoints"],
manufacturer=device_info["manufacturer"],
model=device_info["model"],
node_desc=device_info["node_descriptor"],
)
assert device_info["event_channels"] == sorted(
[ch.id for pool in channels.pools for ch in pool.relay_channels.values()]
)
assert new_ent.call_count == len(
[
device_info
for device_info in device_info["entity_map"].values()
if not device_info.get("default_match", False)
]
)
for call_args in new_ent.call_args_list:
comp, ent_cls, unique_id, channels = call_args[0]
map_id = (comp, unique_id)
assert map_id in device_info["entity_map"]
entity_info = device_info["entity_map"][map_id]
assert set([ch.name for ch in channels]) == set(entity_info["channels"])
assert ent_cls.__name__ == entity_info["entity_class"]
def _ch_mock(cluster):
"""Return mock of a channel with a cluster."""
channel = mock.MagicMock()
type(channel).cluster = mock.PropertyMock(return_value=cluster(mock.MagicMock()))
return channel
@mock.patch(
"homeassistant.components.zha.core.discovery.ProbeEndpoint"
".handle_on_off_output_cluster_exception",
new=mock.MagicMock(),
)
@mock.patch(
"homeassistant.components.zha.core.discovery.ProbeEndpoint.probe_single_cluster"
)
def _test_single_input_cluster_device_class(probe_mock):
"""Test SINGLE_INPUT_CLUSTER_DEVICE_CLASS matching by cluster id or class."""
door_ch = _ch_mock(zigpy.zcl.clusters.closures.DoorLock)
cover_ch = _ch_mock(zigpy.zcl.clusters.closures.WindowCovering)
multistate_ch = _ch_mock(zigpy.zcl.clusters.general.MultistateInput)
class QuirkedIAS(zigpy.quirks.CustomCluster, zigpy.zcl.clusters.security.IasZone):
pass
ias_ch = _ch_mock(QuirkedIAS)
class _Analog(zigpy.quirks.CustomCluster, zigpy.zcl.clusters.general.AnalogInput):
pass
analog_ch = _ch_mock(_Analog)
ch_pool = mock.MagicMock(spec_set=zha_channels.ChannelPool)
ch_pool.unclaimed_channels.return_value = [
door_ch,
cover_ch,
multistate_ch,
ias_ch,
analog_ch,
]
disc.ProbeEndpoint().discover_by_cluster_id(ch_pool)
assert probe_mock.call_count == len(ch_pool.unclaimed_channels())
probes = (
(zha_const.LOCK, door_ch),
(zha_const.COVER, cover_ch),
(zha_const.SENSOR, multistate_ch),
(zha_const.BINARY_SENSOR, ias_ch),
(zha_const.SENSOR, analog_ch),
)
for call, details in zip(probe_mock.call_args_list, probes):
component, ch = details
assert call[0][0] == component
assert call[0][1] == ch
def test_single_input_cluster_device_class():
"""Test SINGLE_INPUT_CLUSTER_DEVICE_CLASS matching by cluster id or class."""
_test_single_input_cluster_device_class()
def test_single_input_cluster_device_class_by_cluster_class():
"""Test SINGLE_INPUT_CLUSTER_DEVICE_CLASS matching by cluster id or class."""
mock_reg = {
zigpy.zcl.clusters.closures.DoorLock.cluster_id: zha_const.LOCK,
zigpy.zcl.clusters.closures.WindowCovering.cluster_id: zha_const.COVER,
zigpy.zcl.clusters.general.AnalogInput: zha_const.SENSOR,
zigpy.zcl.clusters.general.MultistateInput: zha_const.SENSOR,
zigpy.zcl.clusters.security.IasZone: zha_const.BINARY_SENSOR,
}
with mock.patch.dict(
zha_regs.SINGLE_INPUT_CLUSTER_DEVICE_CLASS, mock_reg, clear=True
):
await zha_device_joined_restored(zigpy_device)
await hass.async_block_till_done()
_test_single_input_cluster_device_class()
entity_ids = hass.states.async_entity_ids()
await hass.async_block_till_done()
zha_entities = {
ent for ent in entity_ids if ent.split(".")[0] in zha_const.COMPONENTS
}
zha_gateway = get_zha_gateway(hass)
zha_dev = zha_gateway.get_device(zigpy_device.ieee)
event_channels = { # pylint: disable=protected-access
ch.id for ch in zha_dev._relay_channels.values()
}
@pytest.mark.parametrize(
"override, entity_id",
[
(None, "light.manufacturer_model_77665544_level_light_color_on_off"),
("switch", "switch.manufacturer_model_77665544_on_off"),
],
)
async def test_device_override(hass, zigpy_device_mock, setup_zha, override, entity_id):
"""Test device discovery override."""
assert zha_entities == set(device["entities"])
assert event_channels == set(device["event_channels"])
zigpy_device = zigpy_device_mock(
{
1: {
"device_type": 258,
"endpoint_id": 1,
"in_clusters": [0, 3, 4, 5, 6, 8, 768, 2821, 64513],
"out_clusters": [25],
"profile_id": 260,
}
},
"00:11:22:33:44:55:66:77",
"manufacturer",
"model",
)
entity_map = device["entity_map"]
for calls in _dispatch.call_args_list:
discovery_info = calls[0][2]
unique_id = discovery_info["unique_id"]
channels = discovery_info["channels"]
component = discovery_info["component"]
key = (component, unique_id)
entity_id = entity_registry.async_get_entity_id(component, "zha", unique_id)
if override is not None:
override = {"device_config": {"00:11:22:33:44:55:66:77-1": {"type": override}}}
assert key in entity_map
assert entity_id is not None
no_tail_id = NO_TAIL_ID.sub("", entity_map[key]["entity_id"])
assert entity_id.startswith(no_tail_id)
assert set([ch.name for ch in channels]) == set(entity_map[key]["channels"])
await setup_zha(override)
assert hass.states.get(entity_id) is None
zha_gateway = get_zha_gateway(hass)
await zha_gateway.async_device_initialized(zigpy_device)
await hass.async_block_till_done()
assert hass.states.get(entity_id) is not None
+59 -6
View File
@@ -55,8 +55,20 @@ def channels(channel):
# manufacturer matching
(registries.MatchRule(manufacturers="no match"), False),
(registries.MatchRule(manufacturers=MANUFACTURER), True),
(
registries.MatchRule(manufacturers="no match", aux_channels="aux_channel"),
False,
),
(
registries.MatchRule(
manufacturers=MANUFACTURER, aux_channels="aux_channel"
),
True,
),
(registries.MatchRule(models=MODEL), True),
(registries.MatchRule(models="no match"), False),
(registries.MatchRule(models=MODEL, aux_channels="aux_channel"), True),
(registries.MatchRule(models="no match", aux_channels="aux_channel"), False),
# match everything
(
registries.MatchRule(
@@ -113,10 +125,9 @@ def channels(channel):
),
],
)
def test_registry_matching(rule, matched, zha_device, channels):
def test_registry_matching(rule, matched, channels):
"""Test strict rule matching."""
reg = registries.ZHAEntityRegistry()
assert reg._strict_matched(zha_device, channels, rule) is matched
assert rule.strict_matched(MANUFACTURER, MODEL, channels) is matched
@pytest.mark.parametrize(
@@ -197,7 +208,49 @@ def test_registry_matching(rule, matched, zha_device, channels):
),
],
)
def test_registry_loose_matching(rule, matched, zha_device, channels):
def test_registry_loose_matching(rule, matched, channels):
"""Test loose rule matching."""
reg = registries.ZHAEntityRegistry()
assert reg._loose_matched(zha_device, channels, rule) is matched
assert rule.loose_matched(MANUFACTURER, MODEL, channels) is matched
def test_match_rule_claim_channels_color(channel):
"""Test channel claiming."""
ch_color = channel("color", 0x300)
ch_level = channel("level", 8)
ch_onoff = channel("on_off", 6)
rule = registries.MatchRule(channel_names="on_off", aux_channels={"color", "level"})
claimed = rule.claim_channels([ch_color, ch_level, ch_onoff])
assert {"color", "level", "on_off"} == set([ch.name for ch in claimed])
@pytest.mark.parametrize(
"rule, match",
[
(registries.MatchRule(channel_names={"level"}), {"level"}),
(registries.MatchRule(channel_names={"level", "no match"}), {"level"}),
(registries.MatchRule(channel_names={"on_off"}), {"on_off"}),
(registries.MatchRule(generic_ids="channel_0x0000"), {"basic"}),
(
registries.MatchRule(channel_names="level", generic_ids="channel_0x0000"),
{"basic", "level"},
),
(registries.MatchRule(channel_names={"level", "power"}), {"level", "power"}),
(
registries.MatchRule(
channel_names={"level", "on_off"}, aux_channels={"basic", "power"}
),
{"basic", "level", "on_off", "power"},
),
(registries.MatchRule(channel_names={"color"}), set()),
],
)
def test_match_rule_claim_channels(rule, match, channel, channels):
"""Test channel claiming."""
ch_basic = channel("basic", 0)
channels.append(ch_basic)
ch_power = channel("power", 1)
channels.append(ch_power)
claimed = rule.claim_channels(channels)
assert match == set([ch.name for ch in claimed])
+36 -33
View File
@@ -523,7 +523,7 @@ DEVICES = [
"channels": ["ias_zone"],
"entity_class": "IASZone",
"entity_id": "binary_sensor.heiman_co_v16_77665544_ias_zone",
},
}
},
"event_channels": [],
"manufacturer": "Heiman",
@@ -547,7 +547,7 @@ DEVICES = [
"channels": ["ias_zone"],
"entity_class": "IASZone",
"entity_id": "binary_sensor.heiman_warningdevice_77665544_ias_zone",
},
}
},
"event_channels": [],
"manufacturer": "Heiman",
@@ -1036,7 +1036,6 @@ DEVICES = [
}
},
"entities": [
"binary_sensor.keen_home_inc_sv02_610_mp_1_3_77665544_manufacturer_specific",
"light.keen_home_inc_sv02_610_mp_1_3_77665544_level_on_off",
"sensor.keen_home_inc_sv02_610_mp_1_3_77665544_power",
"sensor.keen_home_inc_sv02_610_mp_1_3_77665544_pressure",
@@ -1063,12 +1062,6 @@ DEVICES = [
"entity_class": "Pressure",
"entity_id": "sensor.keen_home_inc_sv02_610_mp_1_3_77665544_pressure",
},
("binary_sensor", "00:11:22:33:44:55:66:77-1-64514"): {
"channels": ["manufacturer_specific"],
"entity_class": "BinarySensor",
"entity_id": "binary_sensor.keen_home_inc_sv02_610_mp_1_3_77665544_manufacturer_specific",
"default_match": True,
},
},
"event_channels": [],
"manufacturer": "Keen Home Inc",
@@ -1101,7 +1094,6 @@ DEVICES = [
}
},
"entities": [
"binary_sensor.keen_home_inc_sv02_612_mp_1_2_77665544_manufacturer_specific",
"light.keen_home_inc_sv02_612_mp_1_2_77665544_level_on_off",
"sensor.keen_home_inc_sv02_612_mp_1_2_77665544_power",
"sensor.keen_home_inc_sv02_612_mp_1_2_77665544_pressure",
@@ -1128,12 +1120,6 @@ DEVICES = [
"entity_class": "Pressure",
"entity_id": "sensor.keen_home_inc_sv02_612_mp_1_2_77665544_pressure",
},
("binary_sensor", "00:11:22:33:44:55:66:77-1-64514"): {
"channels": ["manufacturer_specific"],
"entity_class": "BinarySensor",
"entity_id": "binary_sensor.keen_home_inc_sv02_612_mp_1_2_77665544_manufacturer_specific",
"default_match": True,
},
},
"event_channels": [],
"manufacturer": "Keen Home Inc",
@@ -1166,7 +1152,6 @@ DEVICES = [
}
},
"entities": [
"binary_sensor.keen_home_inc_sv02_612_mp_1_3_77665544_manufacturer_specific",
"light.keen_home_inc_sv02_612_mp_1_3_77665544_level_on_off",
"sensor.keen_home_inc_sv02_612_mp_1_3_77665544_power",
"sensor.keen_home_inc_sv02_612_mp_1_3_77665544_pressure",
@@ -1193,12 +1178,6 @@ DEVICES = [
"entity_class": "Pressure",
"entity_id": "sensor.keen_home_inc_sv02_612_mp_1_3_77665544_pressure",
},
("binary_sensor", "00:11:22:33:44:55:66:77-1-64514"): {
"channels": ["manufacturer_specific"],
"entity_class": "BinarySensor",
"entity_id": "binary_sensor.keen_home_inc_sv02_612_mp_1_3_77665544_manufacturer_specific",
"default_match": True,
},
},
"event_channels": [],
"manufacturer": "Keen Home Inc",
@@ -1784,13 +1763,21 @@ DEVICES = [
"profile_id": 260,
}
},
"entities": ["light.lumi_lumi_router_77665544_on_off_on_off"],
"entities": [
"binary_sensor.lumi_lumi_router_77665544_on_off",
"light.lumi_lumi_router_77665544_on_off",
],
"entity_map": {
("binary_sensor", "00:11:22:33:44:55:66:77-8-6"): {
"channels": ["on_off", "on_off"],
"entity_class": "Opening",
"entity_id": "binary_sensor.lumi_lumi_router_77665544_on_off",
},
("light", "00:11:22:33:44:55:66:77-8"): {
"channels": ["on_off", "on_off"],
"entity_class": "Light",
"entity_id": "light.lumi_lumi_router_77665544_on_off_on_off",
}
"entity_id": "light.lumi_lumi_router_77665544_on_off",
},
},
"event_channels": ["8:0x0006"],
"manufacturer": "LUMI",
@@ -1808,13 +1795,21 @@ DEVICES = [
"profile_id": 260,
}
},
"entities": ["light.lumi_lumi_router_77665544_on_off_on_off"],
"entities": [
"binary_sensor.lumi_lumi_router_77665544_on_off",
"light.lumi_lumi_router_77665544_on_off",
],
"entity_map": {
("binary_sensor", "00:11:22:33:44:55:66:77-8-6"): {
"channels": ["on_off", "on_off"],
"entity_class": "Opening",
"entity_id": "binary_sensor.lumi_lumi_router_77665544_on_off",
},
("light", "00:11:22:33:44:55:66:77-8"): {
"channels": ["on_off", "on_off"],
"entity_class": "Light",
"entity_id": "light.lumi_lumi_router_77665544_on_off_on_off",
}
"entity_id": "light.lumi_lumi_router_77665544_on_off",
},
},
"event_channels": ["8:0x0006"],
"manufacturer": "LUMI",
@@ -1832,13 +1827,21 @@ DEVICES = [
"profile_id": 260,
}
},
"entities": ["light.lumi_lumi_router_77665544_on_off_on_off"],
"entities": [
"binary_sensor.lumi_lumi_router_77665544_on_off",
"light.lumi_lumi_router_77665544_on_off",
],
"entity_map": {
("binary_sensor", "00:11:22:33:44:55:66:77-8-6"): {
"channels": ["on_off", "on_off"],
"entity_class": "Opening",
"entity_id": "binary_sensor.lumi_lumi_router_77665544_on_off",
},
("light", "00:11:22:33:44:55:66:77-8"): {
"channels": ["on_off", "on_off"],
"entity_class": "Light",
"entity_id": "light.lumi_lumi_router_77665544_on_off_on_off",
}
"entity_id": "light.lumi_lumi_router_77665544_on_off",
},
},
"event_channels": ["8:0x0006"],
"manufacturer": "LUMI",
@@ -1862,7 +1865,7 @@ DEVICES = [
"channels": ["illuminance"],
"entity_class": "Illuminance",
"entity_id": "sensor.lumi_lumi_sen_ill_mgl01_77665544_illuminance",
},
}
},
"event_channels": [],
"manufacturer": "LUMI",