-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathtest_cluster_handlers.py
1440 lines (1234 loc) · 50.8 KB
/
test_cluster_handlers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Test ZHA Core cluster_handlers."""
# pylint:disable=redefined-outer-name,too-many-lines
import logging
import math
from typing import TYPE_CHECKING, Any
from unittest import mock
from unittest.mock import AsyncMock, MagicMock, call, patch
import pytest
from zhaquirks.centralite.cl_3130 import CentraLite3130
from zhaquirks.xiaomi.aqara.sensor_switch_aq3 import BUTTON_DEVICE_TYPE, SwitchAQ3
from zigpy.device import Device as ZigpyDevice
from zigpy.endpoint import Endpoint as ZigpyEndpoint
import zigpy.profiles.zha
from zigpy.quirks import _DEVICE_REGISTRY
import zigpy.types as t
from zigpy.zcl import foundation
import zigpy.zcl.clusters
from zigpy.zcl.clusters import CLUSTERS_BY_ID
from zigpy.zcl.clusters.general import (
Basic,
Identify,
LevelControl,
MultistateInput,
OnOff,
Ota,
PollControl,
PowerConfiguration,
)
from zigpy.zcl.clusters.homeautomation import Diagnostic
from zigpy.zcl.clusters.measurement import TemperatureMeasurement
import zigpy.zdo.types as zdo_t
from tests.common import (
SIG_EP_INPUT,
SIG_EP_OUTPUT,
SIG_EP_PROFILE,
SIG_EP_TYPE,
create_mock_zigpy_device,
join_zigpy_device,
make_zcl_header,
send_attributes_report,
)
from zha.application.const import ATTR_QUIRK_ID
from zha.application.gateway import Gateway
from zha.exceptions import ZHAException
from zha.zigbee.cluster_handlers import (
AttrReportConfig,
ClientClusterHandler,
ClusterHandler,
ClusterHandlerStatus,
parse_and_log_command,
retry_request,
)
from zha.zigbee.cluster_handlers.const import (
CLUSTER_HANDLER_COLOR,
CLUSTER_HANDLER_LEVEL,
CLUSTER_HANDLER_ON_OFF,
)
from zha.zigbee.cluster_handlers.general import PollControlClusterHandler
from zha.zigbee.cluster_handlers.lighting import ColorClusterHandler
from zha.zigbee.cluster_handlers.lightlink import LightLinkClusterHandler
from zha.zigbee.cluster_handlers.registries import (
CLIENT_CLUSTER_HANDLER_REGISTRY,
CLUSTER_HANDLER_REGISTRY,
)
from zha.zigbee.device import Device
from zha.zigbee.endpoint import Endpoint
@pytest.fixture
def ieee():
"""IEEE fixture."""
return t.EUI64.deserialize(b"ieeeaddr")[0]
@pytest.fixture
def nwk():
"""NWK fixture."""
return t.NWK(0xBEEF)
@pytest.fixture
def zigpy_coordinator_device(zha_gateway: Gateway) -> ZigpyDevice:
"""Coordinator device fixture."""
coordinator = create_mock_zigpy_device(
zha_gateway,
{
1: {
SIG_EP_INPUT: [0x1000],
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: 0x1234,
SIG_EP_PROFILE: 0x0104,
}
},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
nwk=0x0000,
)
coordinator.add_to_group = AsyncMock(return_value=[0])
return coordinator
@pytest.fixture
def endpoint(zigpy_coordinator_device: ZigpyDevice) -> Endpoint:
"""Endpoint cluster_handlers fixture."""
endpoint_mock = mock.MagicMock(spec_set=Endpoint)
endpoint_mock.zigpy_endpoint.device.application.get_device.return_value = (
zigpy_coordinator_device
)
endpoint_mock.device.skip_configuration = False
endpoint_mock.id = 1
return endpoint_mock
@pytest.fixture
def poll_control_ch(
endpoint: Endpoint,
zha_gateway: Gateway,
) -> PollControlClusterHandler:
"""Poll control cluster_handler fixture."""
cluster_id = zigpy.zcl.clusters.general.PollControl.cluster_id
zigpy_dev = create_mock_zigpy_device(
zha_gateway,
{
1: {
SIG_EP_INPUT: [cluster_id],
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: 0x1234,
SIG_EP_PROFILE: 0x0104,
}
},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
)
cluster = zigpy_dev.endpoints[1].in_clusters[cluster_id]
cluster_handler_class: type[PollControlClusterHandler] | None = (
CLUSTER_HANDLER_REGISTRY.get(cluster_id).get(None)
)
assert cluster_handler_class is not None
return cluster_handler_class(cluster, endpoint)
@pytest.fixture
async def poll_control_device(zha_gateway: Gateway) -> Device:
"""Poll control device fixture."""
cluster_id = zigpy.zcl.clusters.general.PollControl.cluster_id
zigpy_dev = create_mock_zigpy_device(
zha_gateway,
{
1: {
SIG_EP_INPUT: [cluster_id],
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: 0x1234,
SIG_EP_PROFILE: 0x0104,
}
},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
)
zha_device = await join_zigpy_device(zha_gateway, zigpy_dev)
return zha_device
@pytest.mark.parametrize(
("cluster_id", "bind_count", "attrs"),
[
(zigpy.zcl.clusters.general.Basic.cluster_id, 0, {}),
(
zigpy.zcl.clusters.general.PowerConfiguration.cluster_id,
1,
{"battery_voltage", "battery_percentage_remaining"},
),
(
zigpy.zcl.clusters.general.DeviceTemperature.cluster_id,
1,
{"current_temperature"},
),
(zigpy.zcl.clusters.general.Identify.cluster_id, 0, {}),
(zigpy.zcl.clusters.general.Groups.cluster_id, 0, {}),
(zigpy.zcl.clusters.general.Scenes.cluster_id, 1, {}),
(zigpy.zcl.clusters.general.OnOff.cluster_id, 1, {"on_off"}),
(zigpy.zcl.clusters.general.OnOffConfiguration.cluster_id, 1, {}),
(zigpy.zcl.clusters.general.LevelControl.cluster_id, 1, {"current_level"}),
(zigpy.zcl.clusters.general.Alarms.cluster_id, 1, {}),
(zigpy.zcl.clusters.general.AnalogInput.cluster_id, 1, {"present_value"}),
(zigpy.zcl.clusters.general.AnalogOutput.cluster_id, 1, {"present_value"}),
(zigpy.zcl.clusters.general.AnalogValue.cluster_id, 1, {"present_value"}),
(zigpy.zcl.clusters.general.AnalogOutput.cluster_id, 1, {"present_value"}),
(zigpy.zcl.clusters.general.BinaryOutput.cluster_id, 1, {"present_value"}),
(zigpy.zcl.clusters.general.BinaryValue.cluster_id, 1, {"present_value"}),
(zigpy.zcl.clusters.general.MultistateInput.cluster_id, 1, {"present_value"}),
(zigpy.zcl.clusters.general.MultistateOutput.cluster_id, 1, {"present_value"}),
(zigpy.zcl.clusters.general.MultistateValue.cluster_id, 1, {"present_value"}),
(zigpy.zcl.clusters.general.Commissioning.cluster_id, 1, {}),
(zigpy.zcl.clusters.general.Partition.cluster_id, 1, {}),
(zigpy.zcl.clusters.general.Ota.cluster_id, 0, {}),
(zigpy.zcl.clusters.general.PowerProfile.cluster_id, 1, {}),
(zigpy.zcl.clusters.general.ApplianceControl.cluster_id, 1, {}),
(zigpy.zcl.clusters.general.PollControl.cluster_id, 1, {}),
(zigpy.zcl.clusters.general.GreenPowerProxy.cluster_id, 0, {}),
(zigpy.zcl.clusters.closures.DoorLock.cluster_id, 1, {"lock_state"}),
(
zigpy.zcl.clusters.hvac.Thermostat.cluster_id,
1,
{
"local_temperature",
"occupied_cooling_setpoint",
"occupied_heating_setpoint",
"unoccupied_cooling_setpoint",
"unoccupied_heating_setpoint",
"running_mode",
"running_state",
"system_mode",
"occupancy",
"pi_cooling_demand",
"pi_heating_demand",
},
),
(zigpy.zcl.clusters.hvac.Fan.cluster_id, 1, {"fan_mode"}),
(
zigpy.zcl.clusters.lighting.Color.cluster_id,
1,
{
"current_x",
"current_y",
"color_temperature",
},
),
(
zigpy.zcl.clusters.measurement.IlluminanceMeasurement.cluster_id,
1,
{"measured_value"},
),
(
zigpy.zcl.clusters.measurement.IlluminanceLevelSensing.cluster_id,
1,
{"level_status"},
),
(
zigpy.zcl.clusters.measurement.TemperatureMeasurement.cluster_id,
1,
{"measured_value"},
),
(
zigpy.zcl.clusters.measurement.PressureMeasurement.cluster_id,
1,
{"measured_value"},
),
(
zigpy.zcl.clusters.measurement.FlowMeasurement.cluster_id,
1,
{"measured_value"},
),
(
zigpy.zcl.clusters.measurement.RelativeHumidity.cluster_id,
1,
{"measured_value"},
),
(zigpy.zcl.clusters.measurement.OccupancySensing.cluster_id, 1, {"occupancy"}),
(
zigpy.zcl.clusters.smartenergy.Metering.cluster_id,
1,
{
"instantaneous_demand",
"current_summ_delivered",
"current_tier1_summ_delivered",
"current_tier2_summ_delivered",
"current_tier3_summ_delivered",
"current_tier4_summ_delivered",
"current_tier5_summ_delivered",
"current_tier6_summ_delivered",
"current_summ_received",
"status",
},
),
(
zigpy.zcl.clusters.homeautomation.ElectricalMeasurement.cluster_id,
1,
{
"active_power",
"active_power_max",
"apparent_power",
"rms_current",
"rms_current_max",
"rms_voltage",
"rms_voltage_max",
},
),
],
)
async def test_in_cluster_handler_config(
cluster_id,
bind_count,
attrs,
endpoint: Endpoint,
zha_gateway: Gateway, # pylint: disable=unused-argument
) -> None:
"""Test ZHA core cluster handler configuration for input clusters."""
zigpy_dev = create_mock_zigpy_device(
zha_gateway,
{1: {SIG_EP_INPUT: [cluster_id], SIG_EP_OUTPUT: [], SIG_EP_TYPE: 0x1234}},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
)
cluster = zigpy_dev.endpoints[1].in_clusters[cluster_id]
cluster_handler_class: type[ClusterHandler] | None = CLUSTER_HANDLER_REGISTRY.get(
cluster_id, {None, ClusterHandler}
).get(None)
assert cluster_handler_class is not None
cluster_handler = cluster_handler_class(cluster, endpoint)
assert cluster_handler.status == ClusterHandlerStatus.CREATED
if TYPE_CHECKING:
# Workaround for https://github.com/python/mypy/issues/9005
assert cluster_handler.status != ClusterHandlerStatus.CREATED
await cluster_handler.async_configure()
assert cluster_handler.status == ClusterHandlerStatus.CONFIGURED
assert cluster.bind.call_count == bind_count
assert cluster.configure_reporting.call_count == 0
assert cluster.configure_reporting_multiple.call_count == math.ceil(len(attrs) / 3)
reported_attrs = {
a
for a in attrs
for attr in cluster.configure_reporting_multiple.call_args_list
for attrs in attr[0][0]
}
assert set(attrs) == reported_attrs
async def test_cluster_handler_bind_error(
endpoint: Endpoint,
zha_gateway: Gateway, # pylint: disable=unused-argument
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test ZHA core cluster handler bind error."""
zigpy_dev = create_mock_zigpy_device(
zha_gateway,
{1: {SIG_EP_INPUT: [OnOff.cluster_id], SIG_EP_OUTPUT: [], SIG_EP_TYPE: 0x1234}},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
)
cluster: zigpy.zcl.Cluster = zigpy_dev.endpoints[1].in_clusters[OnOff.cluster_id]
cluster.bind.side_effect = zigpy.exceptions.ZigbeeException
cluster_handler_class: type[ClusterHandler] | None = CLUSTER_HANDLER_REGISTRY.get(
OnOff.cluster_id, {None, ClusterHandler}
).get(None)
assert cluster_handler_class is not None
cluster_handler = cluster_handler_class(cluster, endpoint)
await cluster_handler.async_configure()
assert cluster.bind.await_count == 1
assert cluster.configure_reporting.await_count == 0
assert f"Failed to bind '{cluster.ep_attribute}' cluster:" in caplog.text
async def test_cluster_handler_configure_reporting_error(
endpoint: Endpoint,
zha_gateway: Gateway, # pylint: disable=unused-argument
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test ZHA core cluster handler configure reporting error."""
zigpy_dev = create_mock_zigpy_device(
zha_gateway,
{1: {SIG_EP_INPUT: [OnOff.cluster_id], SIG_EP_OUTPUT: [], SIG_EP_TYPE: 0x1234}},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
)
cluster: zigpy.zcl.Cluster = zigpy_dev.endpoints[1].in_clusters[OnOff.cluster_id]
cluster.configure_reporting_multiple.side_effect = zigpy.exceptions.ZigbeeException
cluster_handler_class: type[ClusterHandler] | None = CLUSTER_HANDLER_REGISTRY.get(
OnOff.cluster_id, {None, ClusterHandler}
).get(None)
assert cluster_handler_class is not None
cluster_handler = cluster_handler_class(cluster, endpoint)
await cluster_handler.async_configure()
assert cluster.bind.await_count == 1
assert cluster.configure_reporting_multiple.await_count == 1
assert f"failed to set reporting on '{cluster.ep_attribute}' cluster" in caplog.text
async def test_write_attributes_safe_key_error(
endpoint: Endpoint,
zha_gateway: Gateway, # pylint: disable=unused-argument
) -> None:
"""Test ZHA core cluster handler write attributes safe key error."""
zigpy_dev = create_mock_zigpy_device(
zha_gateway,
{1: {SIG_EP_INPUT: [OnOff.cluster_id], SIG_EP_OUTPUT: [], SIG_EP_TYPE: 0x1234}},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
)
cluster: zigpy.zcl.Cluster = zigpy_dev.endpoints[1].in_clusters[OnOff.cluster_id]
cluster.write_attributes = AsyncMock(
return_value=[
foundation.WriteAttributesResponse.deserialize(b"\x01\x00\x00")[0]
]
)
cluster_handler_class: type[ClusterHandler] | None = CLUSTER_HANDLER_REGISTRY.get(
OnOff.cluster_id, {None, ClusterHandler}
).get(None)
assert cluster_handler_class is not None
cluster_handler = cluster_handler_class(cluster, endpoint)
with pytest.raises(ZHAException, match="Failed to write attribute on_off=bar"):
await cluster_handler.write_attributes_safe(
{OnOff.AttributeDefs.on_off.name: "bar"}
)
async def test_get_attributes_error(
endpoint: Endpoint,
zha_gateway: Gateway, # pylint: disable=unused-argument
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test ZHA core cluster handler get attributes timeout error."""
zigpy_dev = create_mock_zigpy_device(
zha_gateway,
{1: {SIG_EP_INPUT: [OnOff.cluster_id], SIG_EP_OUTPUT: [], SIG_EP_TYPE: 0x1234}},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
)
cluster: zigpy.zcl.Cluster = zigpy_dev.endpoints[1].in_clusters[OnOff.cluster_id]
cluster.read_attributes.side_effect = zigpy.exceptions.ZigbeeException
cluster_handler_class: type[ClusterHandler] | None = CLUSTER_HANDLER_REGISTRY.get(
OnOff.cluster_id, {None, ClusterHandler}
).get(None)
assert cluster_handler_class is not None
cluster_handler = cluster_handler_class(cluster, endpoint)
await cluster_handler.get_attributes(["foo"])
assert (
f"failed to get attributes '['foo']' on '{OnOff.ep_attribute}' cluster"
in caplog.text
)
async def test_get_attributes_error_raises(
endpoint: Endpoint,
zha_gateway: Gateway, # pylint: disable=unused-argument
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test ZHA core cluster handler get attributes timeout error."""
zigpy_dev = create_mock_zigpy_device(
zha_gateway,
{1: {SIG_EP_INPUT: [OnOff.cluster_id], SIG_EP_OUTPUT: [], SIG_EP_TYPE: 0x1234}},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
)
cluster: zigpy.zcl.Cluster = zigpy_dev.endpoints[1].in_clusters[OnOff.cluster_id]
cluster.read_attributes.side_effect = zigpy.exceptions.ZigbeeException
cluster_handler_class: type[ClusterHandler] | None = CLUSTER_HANDLER_REGISTRY.get(
OnOff.cluster_id, {None, ClusterHandler}
).get(None)
assert cluster_handler_class is not None
cluster_handler = cluster_handler_class(cluster, endpoint)
with pytest.raises(zigpy.exceptions.ZigbeeException):
await cluster_handler._get_attributes(True, ["foo"])
assert (
f"failed to get attributes '['foo']' on '{OnOff.ep_attribute}' cluster"
in caplog.text
)
@pytest.mark.parametrize(
("cluster_id", "bind_count"),
[
(0x0000, 0),
(0x0001, 1),
(0x0002, 1),
(0x0003, 0),
(0x0004, 0),
(0x0005, 1),
(0x0006, 1),
(0x0007, 1),
(0x0008, 1),
(0x0009, 1),
(0x0015, 1),
(0x0016, 1),
(0x0019, 0),
(0x001A, 1),
(0x001B, 1),
(0x0020, 1),
(0x0021, 0),
(0x0101, 1),
(0x0202, 1),
(0x0300, 1),
(0x0400, 1),
(0x0402, 1),
(0x0403, 1),
(0x0405, 1),
(0x0406, 1),
(0x0702, 1),
(0x0B04, 1),
],
)
async def test_out_cluster_handler_config(
cluster_id: int,
bind_count: int,
endpoint: Endpoint,
zha_gateway: Gateway, # pylint: disable=unused-argument
) -> None:
"""Test ZHA core cluster handler configuration for output clusters."""
zigpy_dev = create_mock_zigpy_device(
zha_gateway,
{1: {SIG_EP_OUTPUT: [cluster_id], SIG_EP_INPUT: [], SIG_EP_TYPE: 0x1234}},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
)
cluster = zigpy_dev.endpoints[1].out_clusters[cluster_id]
cluster.bind_only = True
cluster_handler_class: type[ClusterHandler] | None = CLUSTER_HANDLER_REGISTRY.get(
cluster_id, {None: ClusterHandler}
).get(None)
assert cluster_handler_class is not None
cluster_handler = cluster_handler_class(cluster, endpoint)
await cluster_handler.async_configure()
assert cluster.bind.call_count == bind_count
assert cluster.configure_reporting.call_count == 0
def test_cluster_handler_registry() -> None:
"""Test ZIGBEE cluster handler Registry."""
# get all quirk ID from zigpy quirks registry
all_quirk_ids = {}
for cluster_id in CLUSTERS_BY_ID:
all_quirk_ids[cluster_id] = {None}
for manufacturer in _DEVICE_REGISTRY.registry.values():
for model_quirk_list in manufacturer.values():
for quirk in model_quirk_list:
quirk_id = getattr(quirk, ATTR_QUIRK_ID, None)
device_description: dict[str, dict[str, Any]] = getattr(
quirk, "replacement", None
) or getattr(quirk, "signature", None)
for endpoint in device_description["endpoints"].values():
cluster_ids = set()
if "input_clusters" in endpoint:
cluster_ids.update(endpoint["input_clusters"])
if "output_clusters" in endpoint:
cluster_ids.update(endpoint["output_clusters"])
for cluster_id in cluster_ids:
if not isinstance(cluster_id, int):
cluster_id = cluster_id.cluster_id
if cluster_id not in all_quirk_ids:
all_quirk_ids[cluster_id] = {None}
all_quirk_ids[cluster_id].add(quirk_id)
for (
cluster_id,
cluster_handler_classes,
) in CLUSTER_HANDLER_REGISTRY.items():
assert isinstance(cluster_id, int)
assert 0 <= cluster_id <= 0xFFFF
assert cluster_id in all_quirk_ids
assert isinstance(cluster_handler_classes, dict)
for quirk_id, cluster_handler in cluster_handler_classes.items():
assert quirk_id is None or isinstance(quirk_id, str)
assert issubclass(cluster_handler, ClusterHandler)
assert quirk_id in all_quirk_ids[cluster_id]
def test_epch_unclaimed_cluster_handlers(cluster_handler) -> None:
"""Test unclaimed cluster handlers."""
ch_1 = cluster_handler(CLUSTER_HANDLER_ON_OFF, 6)
ch_2 = cluster_handler(CLUSTER_HANDLER_LEVEL, 8)
ch_3 = cluster_handler(CLUSTER_HANDLER_COLOR, 768)
mock_dev = mock.MagicMock(spec=Device)
mock_dev.unique_id = "00:11:22:33:44:55:66:77"
ep_cluster_handlers = Endpoint(mock.MagicMock(spec_set=ZigpyEndpoint), mock_dev)
all_cluster_handlers = {ch_1.id: ch_1, ch_2.id: ch_2, ch_3.id: ch_3}
with mock.patch.dict(
ep_cluster_handlers.all_cluster_handlers, all_cluster_handlers, clear=True
):
available = ep_cluster_handlers.unclaimed_cluster_handlers()
assert ch_1 in available
assert ch_2 in available
assert ch_3 in available
ep_cluster_handlers.claimed_cluster_handlers[ch_2.id] = ch_2
available = ep_cluster_handlers.unclaimed_cluster_handlers()
assert ch_1 in available
assert ch_2 not in available
assert ch_3 in available
ep_cluster_handlers.claimed_cluster_handlers[ch_1.id] = ch_1
available = ep_cluster_handlers.unclaimed_cluster_handlers()
assert ch_1 not in available
assert ch_2 not in available
assert ch_3 in available
ep_cluster_handlers.claimed_cluster_handlers[ch_3.id] = ch_3
available = ep_cluster_handlers.unclaimed_cluster_handlers()
assert ch_1 not in available
assert ch_2 not in available
assert ch_3 not in available
def test_epch_claim_cluster_handlers(cluster_handler) -> None:
"""Test cluster handler claiming."""
ch_1 = cluster_handler(CLUSTER_HANDLER_ON_OFF, 6)
ch_2 = cluster_handler(CLUSTER_HANDLER_LEVEL, 8)
ch_3 = cluster_handler(CLUSTER_HANDLER_COLOR, 768)
mock_dev = mock.MagicMock(spec=Device)
mock_dev.unique_id = "00:11:22:33:44:55:66:77"
ep_cluster_handlers = Endpoint(mock.MagicMock(spec_set=ZigpyEndpoint), mock_dev)
all_cluster_handlers = {ch_1.id: ch_1, ch_2.id: ch_2, ch_3.id: ch_3}
with mock.patch.dict(
ep_cluster_handlers.all_cluster_handlers, all_cluster_handlers, clear=True
):
assert ch_1.id not in ep_cluster_handlers.claimed_cluster_handlers
assert ch_2.id not in ep_cluster_handlers.claimed_cluster_handlers
assert ch_3.id not in ep_cluster_handlers.claimed_cluster_handlers
ep_cluster_handlers.claim_cluster_handlers([ch_2])
assert ch_1.id not in ep_cluster_handlers.claimed_cluster_handlers
assert ch_2.id in ep_cluster_handlers.claimed_cluster_handlers
assert ep_cluster_handlers.claimed_cluster_handlers[ch_2.id] is ch_2
assert ch_3.id not in ep_cluster_handlers.claimed_cluster_handlers
ep_cluster_handlers.claim_cluster_handlers([ch_3, ch_1])
assert ch_1.id in ep_cluster_handlers.claimed_cluster_handlers
assert ep_cluster_handlers.claimed_cluster_handlers[ch_1.id] is ch_1
assert ch_2.id in ep_cluster_handlers.claimed_cluster_handlers
assert ep_cluster_handlers.claimed_cluster_handlers[ch_2.id] is ch_2
assert ch_3.id in ep_cluster_handlers.claimed_cluster_handlers
assert ep_cluster_handlers.claimed_cluster_handlers[ch_3.id] is ch_3
assert "1:0x0300" in ep_cluster_handlers.claimed_cluster_handlers
@mock.patch("zha.zigbee.endpoint.Endpoint.add_client_cluster_handlers")
@mock.patch(
"zha.application.discovery.ENDPOINT_PROBE.discover_entities",
mock.MagicMock(),
)
async def test_ep_cluster_handlers_all_cluster_handlers(
m1, # pylint: disable=unused-argument
zha_gateway: Gateway,
) -> None:
"""Test Endpointcluster_handlers adding all cluster_handlers."""
zha_device = await join_zigpy_device(
zha_gateway,
create_mock_zigpy_device(
zha_gateway,
{
1: {
SIG_EP_INPUT: [0, 1, 6, 8],
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: zigpy.profiles.zha.DeviceType.ON_OFF_SWITCH,
SIG_EP_PROFILE: 0x0104,
},
2: {
SIG_EP_INPUT: [0, 1, 6, 8, 768],
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: 0x0000,
SIG_EP_PROFILE: 0x0104,
},
},
),
)
assert "1:0x0000" in zha_device._endpoints[1].all_cluster_handlers
assert "1:0x0001" in zha_device._endpoints[1].all_cluster_handlers
assert "1:0x0006" in zha_device._endpoints[1].all_cluster_handlers
assert "1:0x0008" in zha_device._endpoints[1].all_cluster_handlers
assert "1:0x0300" not in zha_device._endpoints[1].all_cluster_handlers
assert "2:0x0000" not in zha_device._endpoints[1].all_cluster_handlers
assert "2:0x0001" not in zha_device._endpoints[1].all_cluster_handlers
assert "2:0x0006" not in zha_device._endpoints[1].all_cluster_handlers
assert "2:0x0008" not in zha_device._endpoints[1].all_cluster_handlers
assert "2:0x0300" not in zha_device._endpoints[1].all_cluster_handlers
assert "1:0x0000" not in zha_device._endpoints[2].all_cluster_handlers
assert "1:0x0001" not in zha_device._endpoints[2].all_cluster_handlers
assert "1:0x0006" not in zha_device._endpoints[2].all_cluster_handlers
assert "1:0x0008" not in zha_device._endpoints[2].all_cluster_handlers
assert "1:0x0300" not in zha_device._endpoints[2].all_cluster_handlers
assert "2:0x0000" in zha_device._endpoints[2].all_cluster_handlers
assert "2:0x0001" in zha_device._endpoints[2].all_cluster_handlers
assert "2:0x0006" in zha_device._endpoints[2].all_cluster_handlers
assert "2:0x0008" in zha_device._endpoints[2].all_cluster_handlers
assert "2:0x0300" in zha_device._endpoints[2].all_cluster_handlers
@mock.patch("zha.zigbee.endpoint.Endpoint.add_client_cluster_handlers")
@mock.patch(
"zha.application.discovery.ENDPOINT_PROBE.discover_entities",
mock.MagicMock(),
)
async def test_cluster_handler_power_config(
m1, # pylint: disable=unused-argument
zha_gateway: Gateway,
) -> None:
"""Test that cluster_handlers only get a single power cluster_handler."""
in_clusters = [0, 1, 6, 8]
zha_device: Device = await join_zigpy_device(
zha_gateway,
create_mock_zigpy_device(
zha_gateway,
endpoints={
1: {
SIG_EP_INPUT: in_clusters,
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: 0x0000,
SIG_EP_PROFILE: 0x0104,
},
2: {
SIG_EP_INPUT: [*in_clusters, 768],
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: 0x0000,
SIG_EP_PROFILE: 0x0104,
},
},
ieee="01:2d:6f:00:0a:90:69:e8",
),
)
assert "1:0x0000" in zha_device._endpoints[1].all_cluster_handlers
assert "1:0x0001" in zha_device._endpoints[1].all_cluster_handlers
assert "1:0x0006" in zha_device._endpoints[1].all_cluster_handlers
assert "1:0x0008" in zha_device._endpoints[1].all_cluster_handlers
assert "1:0x0300" not in zha_device._endpoints[1].all_cluster_handlers
assert "2:0x0000" in zha_device._endpoints[2].all_cluster_handlers
assert "2:0x0001" in zha_device._endpoints[2].all_cluster_handlers
assert "2:0x0006" in zha_device._endpoints[2].all_cluster_handlers
assert "2:0x0008" in zha_device._endpoints[2].all_cluster_handlers
assert "2:0x0300" in zha_device._endpoints[2].all_cluster_handlers
zha_device = await join_zigpy_device(
zha_gateway,
create_mock_zigpy_device(
zha_gateway,
endpoints={
1: {
SIG_EP_INPUT: [],
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: 0x0000,
SIG_EP_PROFILE: 0x0104,
},
2: {
SIG_EP_INPUT: in_clusters,
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: 0x0000,
SIG_EP_PROFILE: 0x0104,
},
},
ieee="02:2d:6f:00:0a:90:69:e8",
),
)
assert "1:0x0001" not in zha_device._endpoints[1].all_cluster_handlers
assert "2:0x0001" in zha_device._endpoints[2].all_cluster_handlers
zha_device = await join_zigpy_device(
zha_gateway,
create_mock_zigpy_device(
zha_gateway,
endpoints={
2: {
SIG_EP_INPUT: in_clusters,
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: 0x0000,
SIG_EP_PROFILE: 0x0104,
}
},
ieee="03:2d:6f:00:0a:90:69:e8",
),
)
assert "2:0x0001" in zha_device._endpoints[2].all_cluster_handlers
async def test_ep_cluster_handlers_configure(cluster_handler) -> None:
"""Test unclaimed cluster handlers."""
ch_1 = cluster_handler(CLUSTER_HANDLER_ON_OFF, 6)
ch_2 = cluster_handler(CLUSTER_HANDLER_LEVEL, 8)
ch_3 = cluster_handler(CLUSTER_HANDLER_COLOR, 768)
ch_3.async_configure = AsyncMock(side_effect=TimeoutError)
ch_3.async_initialize = AsyncMock(side_effect=TimeoutError)
ch_4 = cluster_handler(CLUSTER_HANDLER_ON_OFF, 6)
ch_5 = cluster_handler(CLUSTER_HANDLER_LEVEL, 8)
ch_5.async_configure = AsyncMock(side_effect=TimeoutError)
ch_5.async_initialize = AsyncMock(side_effect=TimeoutError)
endpoint_mock = mock.MagicMock(spec_set=ZigpyEndpoint)
type(endpoint_mock).in_clusters = mock.PropertyMock(return_value={})
type(endpoint_mock).out_clusters = mock.PropertyMock(return_value={})
type(endpoint_mock).profile_id = mock.PropertyMock(
return_value=zigpy.profiles.zha.PROFILE_ID
)
type(endpoint_mock).device_type = mock.PropertyMock(
return_value=zigpy.profiles.zha.DeviceType.COLOR_DIMMABLE_LIGHT
)
zha_dev = mock.MagicMock(spec=Device)
zha_dev.unique_id = "00:11:22:33:44:55:66:77"
type(zha_dev).quirk_id = mock.PropertyMock(return_value=None)
endpoint = Endpoint.new(endpoint_mock, zha_dev)
claimed = {ch_1.id: ch_1, ch_2.id: ch_2, ch_3.id: ch_3}
client_handlers = {ch_4.id: ch_4, ch_5.id: ch_5}
with (
mock.patch.dict(endpoint.claimed_cluster_handlers, claimed, clear=True),
mock.patch.dict(endpoint.client_cluster_handlers, client_handlers, clear=True),
):
await endpoint.async_configure()
await endpoint.async_initialize(mock.sentinel.from_cache)
for ch in [*claimed.values(), *client_handlers.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.debug.call_count == 2
assert ch_5.debug.call_count == 2
async def test_poll_control_configure(
poll_control_ch: PollControlClusterHandler,
) -> None:
"""Test poll control cluster_handler configuration."""
await poll_control_ch.async_configure()
assert poll_control_ch.cluster.write_attributes.call_count == 1
assert poll_control_ch.cluster.write_attributes.call_args[0][0] == {
"checkin_interval": poll_control_ch.CHECKIN_INTERVAL
}
async def test_poll_control_checkin_response(
poll_control_ch: PollControlClusterHandler,
) -> None:
"""Test poll control cluster_handler checkin response."""
rsp_mock = AsyncMock()
set_interval_mock = AsyncMock()
fast_poll_mock = AsyncMock()
cluster = poll_control_ch.cluster
patch_1 = mock.patch.object(cluster, "checkin_response", rsp_mock)
patch_2 = mock.patch.object(cluster, "set_long_poll_interval", set_interval_mock)
patch_3 = mock.patch.object(cluster, "fast_poll_stop", fast_poll_mock)
with patch_1, patch_2, patch_3:
await poll_control_ch.check_in_response(33)
assert rsp_mock.call_count == 1
assert set_interval_mock.call_count == 1
assert fast_poll_mock.call_count == 1
await poll_control_ch.check_in_response(33)
assert cluster.endpoint.request.call_count == 3
assert cluster.endpoint.request.await_count == 3
assert cluster.endpoint.request.mock_calls[0].kwargs["sequence"] == 33
assert cluster.endpoint.request.mock_calls[0].kwargs["cluster"] == 0x0020
assert cluster.endpoint.request.mock_calls[1].kwargs["cluster"] == 0x0020
async def test_poll_control_cluster_command(poll_control_device: Device) -> None:
"""Test poll control cluster_handler response to cluster command."""
checkin_mock = AsyncMock()
poll_control_ch = poll_control_device._endpoints[1].all_cluster_handlers["1:0x0020"]
cluster = poll_control_ch.cluster
# events = async_capture_events("zha_event")
poll_control_ch.emit_zha_event = MagicMock(wraps=poll_control_ch.emit_zha_event)
with mock.patch.object(poll_control_ch, "check_in_response", checkin_mock):
tsn = 22
hdr = make_zcl_header(0, global_command=False, tsn=tsn)
cluster.handle_message(
hdr, [mock.sentinel.args, mock.sentinel.args2, mock.sentinel.args3]
)
await poll_control_device.gateway.async_block_till_done()
assert checkin_mock.call_count == 1
assert checkin_mock.await_count == 1
assert checkin_mock.mock_calls == [call(tsn)]
assert poll_control_ch.emit_zha_event.call_count == 1
assert poll_control_ch.emit_zha_event.call_args_list[0] == mock.call(
"checkin", [mock.sentinel.args, mock.sentinel.args2, mock.sentinel.args3]
)
async def test_poll_control_ignore_list(poll_control_device: Device) -> None:
"""Test poll control cluster_handler ignore list."""
set_long_poll_mock = AsyncMock()
poll_control_ch = poll_control_device._endpoints[1].all_cluster_handlers["1:0x0020"]
cluster = poll_control_ch.cluster
with mock.patch.object(cluster, "set_long_poll_interval", set_long_poll_mock):
await poll_control_ch.check_in_response(33)
assert set_long_poll_mock.call_count == 1
set_long_poll_mock.reset_mock()
poll_control_ch.skip_manufacturer_id(4151)
with mock.patch.object(cluster, "set_long_poll_interval", set_long_poll_mock):
await poll_control_ch.check_in_response(33)
assert set_long_poll_mock.call_count == 0
async def test_poll_control_ikea(poll_control_device: Device) -> None:
"""Test poll control cluster_handler ignore list for ikea."""
set_long_poll_mock = AsyncMock()
poll_control_ch = poll_control_device._endpoints[1].all_cluster_handlers["1:0x0020"]
cluster = poll_control_ch.cluster
delattr(poll_control_device, "manufacturer_code")
poll_control_device.device.node_desc.manufacturer_code = 4476
with mock.patch.object(cluster, "set_long_poll_interval", set_long_poll_mock):
await poll_control_ch.check_in_response(33)
assert set_long_poll_mock.call_count == 0
@pytest.fixture
def zigpy_zll_device(zha_gateway: Gateway) -> ZigpyDevice:
"""ZLL device fixture."""
return create_mock_zigpy_device(
zha_gateway,
{
1: {
SIG_EP_INPUT: [0x1000],
SIG_EP_OUTPUT: [],
SIG_EP_TYPE: 0x1234,
SIG_EP_PROFILE: zigpy.profiles.zll.PROFILE_ID,
}
},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
)
async def test_zll_device_groups(
zigpy_zll_device: ZigpyDevice,
endpoint: Endpoint,
zigpy_coordinator_device: ZigpyDevice,
) -> None:
"""Test adding coordinator to ZLL groups."""
cluster = zigpy_zll_device.endpoints[1].lightlink
cluster_handler = LightLinkClusterHandler(cluster, endpoint)
get_group_identifiers_rsp = zigpy.zcl.clusters.lightlink.LightLink.commands_by_name[
"get_group_identifiers_rsp"
].schema
with patch.object(
cluster,
"get_group_identifiers",
AsyncMock(
return_value=get_group_identifiers_rsp(
total=0, start_index=0, group_info_records=[]
)