-
Notifications
You must be signed in to change notification settings - Fork 727
/
Copy path__init__.py
1543 lines (1299 loc) · 52.1 KB
/
__init__.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
"""Tuya devices."""
import dataclasses
import datetime
import enum
import logging
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from zigpy.quirks import CustomCluster, CustomDevice
import zigpy.types as t
from zigpy.zcl import foundation
from zigpy.zcl.clusters.closures import WindowCovering
from zigpy.zcl.clusters.general import LevelControl, OnOff, PowerConfiguration
from zigpy.zcl.clusters.homeautomation import ElectricalMeasurement
from zigpy.zcl.clusters.hvac import Thermostat, UserInterface
from zigpy.zcl.clusters.smartenergy import Metering
from zhaquirks import Bus, EventableCluster, LocalDataCluster
from zhaquirks.const import (
DOUBLE_PRESS,
LEFT,
LONG_PRESS,
RIGHT,
SHORT_PRESS,
ZHA_SEND_EVENT,
)
# ---------------------------------------------------------
# Tuya Custom Cluster ID
# ---------------------------------------------------------
TUYA_CLUSTER_ID = 0xEF00
TUYA_CLUSTER_E000_ID = 0xE000
TUYA_CLUSTER_E001_ID = 0xE001
# ---------------------------------------------------------
# Tuya Cluster Commands
# ---------------------------------------------------------
TUYA_SET_DATA = 0x00
TUYA_GET_DATA = 0x01
TUYA_SET_DATA_RESPONSE = 0x02
TUYA_SEND_DATA = 0x04
TUYA_ACTIVE_STATUS_RPT = 0x06
TUYA_SET_TIME = 0x24
# TODO: To be checked
TUYA_MCU_VERSION_REQ = 0x10
TUYA_MCU_VERSION_RSP = 0x11
#
TUYA_LEVEL_COMMAND = 514
COVER_EVENT = "cover_event"
LEVEL_EVENT = "level_event"
TUYA_MCU_COMMAND = "tuya_mcu_command"
# Rotating for remotes
STOP = "stop" # To constans
# ---------------------------------------------------------
# Value for dp_type
# ---------------------------------------------------------
# ID Name Description
# ---------------------------------------------------------
# 0x00 DP_TYPE_RAW ?
# 0x01 DP_TYPE_BOOL ?
# 0x02 DP_TYPE_VALUE 4 byte unsigned integer
# 0x03 DP_TYPE_STRING variable length string
# 0x04 DP_TYPE_ENUM 1 byte enum
# 0x05 DP_TYPE_FAULT 1 byte bitmap (didn't test yet)
TUYA_DP_TYPE_RAW = 0x0000
TUYA_DP_TYPE_BOOL = 0x0100
TUYA_DP_TYPE_VALUE = 0x0200
TUYA_DP_TYPE_STRING = 0x0300
TUYA_DP_TYPE_ENUM = 0x0400
TUYA_DP_TYPE_FAULT = 0x0500
# ---------------------------------------------------------
# Value for dp_identifier (These are device specific)
# ---------------------------------------------------------
# ID Name Type Description
# ---------------------------------------------------------
# 0x01 control enum open, stop, close, continue
# 0x02 percent_control value 0-100% control
# 0x03 percent_state value Report from motor about current percentage
# 0x04 control_back enum Configures motor direction (untested)
# 0x05 work_state enum Motor Direction Setting
# 0x06 situation_set enum Configures if 100% equals to fully closed or fully open (untested)
# 0x07 fault bitmap Anything but 0 means something went wrong (untested)
TUYA_DP_ID_CONTROL = 0x01
TUYA_DP_ID_PERCENT_CONTROL = 0x02
TUYA_DP_ID_PERCENT_STATE = 0x03
TUYA_DP_ID_DIRECTION_CHANGE = 0x05
TUYA_DP_ID_COVER_INVERTED = 0x06
# ---------------------------------------------------------
# Window Cover Server Commands
# ---------------------------------------------------------
WINDOW_COVER_COMMAND_UPOPEN = 0x0000
WINDOW_COVER_COMMAND_DOWNCLOSE = 0x0001
WINDOW_COVER_COMMAND_STOP = 0x0002
WINDOW_COVER_COMMAND_LIFTPERCENT = 0x0005
WINDOW_COVER_COMMAND_CUSTOM = 0x0006
# ---------------------------------------------------------
# TUYA Cover Custom Values
# ---------------------------------------------------------
COVER_EVENT = "cover_event"
ATTR_COVER_POSITION = 0x0008
ATTR_COVER_DIRECTION = 0x8001
ATTR_COVER_INVERTED = 0x8002
# ---------------------------------------------------------
# TUYA Switch Custom Values
# ---------------------------------------------------------
SWITCH_EVENT = "switch_event"
ATTR_ON_OFF = 0x0000
ATTR_COVER_POSITION = 0x0008
TUYA_CMD_BASE = 0x0100
# ---------------------------------------------------------
# DP Value meanings in Status Report
# ---------------------------------------------------------
# Type ID IntDP Description
# ---------------------------------------------------------
# 0x04 0x01 1025 Confirm opening/closing/stopping (triggered from Zigbee)
# 0x02 0x02 514 Started moving to position (triggered from Zigbee)
# 0x04 0x07 1031 Started moving (triggered by transmitter order pulling on curtain)
# 0x02 0x03 515 Arrived at position
# 0x01 0x05 261 Returned by configuration set; ignore
# 0x02 0x69 617 Not sure what this is
# 0x04 0x05 1029 Changed the Motor Direction
# 0x04 0x65 1125 Change of tilt/lift mode 1 = lift 0=tilt
# ---------------------------------------------------------
_LOGGER = logging.getLogger(__name__)
class TuyaTimePayload(t.LVList, item_type=t.uint8_t, length_type=t.uint16_t_be):
"""Tuya set time payload definition."""
class TuyaDPType(t.enum8):
"""DataPoint Type."""
RAW = 0x00
BOOL = 0x01
VALUE = 0x02
STRING = 0x03
ENUM = 0x04
BITMAP = 0x05
class TuyaData(t.Struct):
"""Tuya Data type."""
dp_type: TuyaDPType
function: t.uint8_t
raw: t.LVBytes
@property
def payload(
self,
) -> Union[
t.int32s_be,
t.Bool,
t.CharacterString,
t.enum8,
t.bitmap8,
t.bitmap16,
t.bitmap32,
t.LVBytes,
]:
"""Payload accordingly to data point type."""
if self.dp_type == TuyaDPType.VALUE:
return t.int32s_be.deserialize(self.raw)[0]
elif self.dp_type == TuyaDPType.BOOL:
return t.Bool.deserialize(self.raw)[0]
elif self.dp_type == TuyaDPType.STRING:
return t.CharacterString(self.raw.decode("utf8"))
elif self.dp_type == TuyaDPType.ENUM:
return t.enum8.deserialize(self.raw)[0]
elif self.dp_type == TuyaDPType.BITMAP:
bitmaps = {1: t.bitmap8, 2: t.bitmap16, 4: t.bitmap32}
try:
return bitmaps[len(self.raw)].deserialize(self.raw)[0]
except KeyError as exc:
raise ValueError(f"Wrong bitmap length: {len(self.raw)}") from exc
elif self.dp_type == TuyaDPType.RAW:
return self.raw
else:
raise ValueError(f"Unknown {self.dp_type} datapoint type")
@payload.setter
def payload(self, value):
"""Set payload accordingly to data point type."""
if self.dp_type == TuyaDPType.VALUE:
self.raw = t.int32s_be(value).serialize()
elif self.dp_type == TuyaDPType.BOOL:
self.raw = t.Bool(value).serialize()
elif self.dp_type == TuyaDPType.STRING:
self.raw = value.encode("utf8")
elif self.dp_type == TuyaDPType.ENUM:
self.raw = t.enum8(value).serialize()
elif self.dp_type == TuyaDPType.BITMAP:
if not isinstance(value, (t.bitmap8, t.bitmap16, t.bitmap32)):
value = t.bitmap8(value)
self.raw = value.serialize()[::-1]
elif self.dp_type == TuyaDPType.RAW:
self.raw = value.serialize()
else:
raise ValueError(f"Unknown {self.dp_type} datapoint type")
def __new__(cls, *args, **kwargs):
"""Disable copy constrctor."""
return super().__new__(cls)
def __init__(self, value=None, function=0, *args, **kwargs):
"""Convert from a zigpy typed value to a tuya data payload."""
self.function = function
if value is None:
return
elif isinstance(value, (t.bitmap8, t.bitmap16, t.bitmap32)):
self.dp_type = TuyaDPType.BITMAP
elif isinstance(value, (bool, t.Bool)):
self.dp_type = TuyaDPType.BOOL
elif isinstance(value, enum.Enum):
self.dp_type = TuyaDPType.ENUM
elif isinstance(value, int):
self.dp_type = TuyaDPType.VALUE
elif isinstance(value, str):
self.dp_type = TuyaDPType.STRING
else:
self.dp_type = TuyaDPType.RAW
self.payload = value
class Data(t.List, item_type=t.uint8_t):
"""list of uint8_t."""
def __init__(self, value=None):
"""Convert from a zigpy typed value to a tuya data payload."""
if value is None:
super().__init__()
return
if type(value) is list or type(value) is bytes:
super().__init__(value)
return
# serialized in little-endian by zigpy
super().__init__(value.serialize())
# we want big-endian, with length prepended
self.append(len(self))
self.reverse()
def __int__(self):
"""Convert from a tuya data payload to an int typed value."""
# first uint8_t is the length of the remaining data
# tuya data is in big endian whereas ztypes use little endian
ints = {
1: t.int8s,
2: t.int16s,
3: t.int24s,
4: t.int32s,
5: t.int40s,
6: t.int48s,
7: t.int56s,
8: t.int64s,
}
return ints[self[0]].deserialize(bytes(reversed(self[1:])))[0]
def __iter__(self):
"""Convert from a tuya data payload to a list typed value."""
return iter(reversed(self[1:]))
def serialize(self) -> bytes:
"""Overload serialize to avoid prior implicit conversion to list."""
assert self._item_type is not None
return b"".join([self._item_type(i).serialize() for i in self[:]])
class TuyaDatapointData(t.Struct):
"""Tuya Datapoint and Data."""
dp: t.uint8_t
data: TuyaData
class TuyaCommand(t.Struct):
"""Tuya manufacturer cluster command."""
status: t.uint8_t
tsn: t.uint8_t
datapoints: t.List[TuyaDatapointData]
class NoManufacturerCluster(CustomCluster):
"""Forces the NO manufacturer id in command."""
async def command(
self,
command_id: Union[foundation.GeneralCommand, int, t.uint8_t],
*args,
manufacturer: Optional[Union[int, t.uint16_t]] = None,
expect_reply: bool = True,
tsn: Optional[Union[int, t.uint8_t]] = None,
**kwargs: Any,
):
"""Override the default Cluster command."""
self.debug("Setting the NO manufacturer id in command: %s", command_id)
return await super().command(
command_id,
*args,
manufacturer=foundation.ZCLHeader.NO_MANUFACTURER_ID,
expect_reply=expect_reply,
tsn=tsn,
**kwargs,
)
class TuyaManufCluster(CustomCluster):
"""Tuya manufacturer specific cluster."""
name = "Tuya Manufacturer Specicific"
cluster_id = TUYA_CLUSTER_ID
ep_attribute = "tuya_manufacturer"
set_time_offset = 0
set_time_local_offset = None
class Command(t.Struct):
"""Tuya manufacturer cluster command."""
status: t.uint8_t
tsn: t.uint8_t
command_id: t.uint16_t
function: t.uint8_t
data: Data
class MCUVersionRsp(t.Struct):
"""Tuya MCU version response Zcl payload."""
tsn: t.uint16_t
version: t.uint8_t
""" Time sync command (It's transparent between MCU and server)
Time request device -> server
payloadSize = 0
Set time, server -> device
payloadSize, should be always 8
payload[0-3] - UTC timestamp (big endian)
payload[4-7] - Local timestamp (big endian)
Zigbee payload is very similar to the UART payload which is described here: https://developer.tuya.com/en/docs/iot/device-development/access-mode-mcu/zigbee-general-solution/tuya-zigbee-module-uart-communication-protocol/tuya-zigbee-module-uart-communication-protocol?id=K9ear5khsqoty#title-10-Time%20synchronization
Some devices need the timestamp in seconds from 1/1/1970 and others in seconds from 1/1/2000.
Also, there is devices which uses both timestamps variants (probably bug). Use set_time_local_offset var in this cases.
NOTE: You need to wait for time request before setting it. You can't set time without request."""
server_commands = {
0x0000: foundation.ZCLCommandDef(
"set_data", {"param": Command}, False, is_manufacturer_specific=True
),
0x0010: foundation.ZCLCommandDef(
"mcu_version_req",
{"param": t.uint16_t},
False,
is_manufacturer_specific=True,
),
0x0024: foundation.ZCLCommandDef(
"set_time", {"param": TuyaTimePayload}, False, is_manufacturer_specific=True
),
}
client_commands = {
0x0001: foundation.ZCLCommandDef(
"get_data", {"param": Command}, True, is_manufacturer_specific=True
),
0x0002: foundation.ZCLCommandDef(
"set_data_response", {"param": Command}, True, is_manufacturer_specific=True
),
0x0006: foundation.ZCLCommandDef(
"active_status_report",
{"param": Command},
True,
is_manufacturer_specific=True,
),
0x0011: foundation.ZCLCommandDef(
"mcu_version_rsp",
{"param": MCUVersionRsp},
True,
is_manufacturer_specific=True,
),
0x0024: foundation.ZCLCommandDef(
"set_time_request", {"param": t.data16}, True, is_manufacturer_specific=True
),
}
def __init__(self, *args, **kwargs):
"""Init."""
super().__init__(*args, **kwargs)
self.endpoint.device.command_bus = Bus()
self.endpoint.device.command_bus.add_listener(self) # listen MCU commands
def tuya_mcu_command(self, command: Command):
"""Tuya MCU command listener. Only endpoint:1 must listen to MCU commands."""
self.create_catching_task(
self.command(TUYA_SET_DATA, command, expect_reply=True)
)
def handle_cluster_request(
self,
hdr: foundation.ZCLHeader,
args: Tuple,
*,
dst_addressing: Optional[
Union[t.Addressing.Group, t.Addressing.IEEE, t.Addressing.NWK]
] = None,
) -> None:
"""Handle time request."""
if hdr.command_id != 0x0024 or self.set_time_offset == 0:
return super().handle_cluster_request(
hdr, args, dst_addressing=dst_addressing
)
# Send default response because the MCU expects it
if not hdr.frame_control.disable_default_response:
self.send_default_rsp(hdr, status=foundation.Status.SUCCESS)
_LOGGER.debug(
"[0x%04x:%s:0x%04x] Got set time request (command 0x%04x)",
self.endpoint.device.nwk,
self.endpoint.endpoint_id,
self.cluster_id,
hdr.command_id,
)
payload = TuyaTimePayload()
utc_timestamp = int(
(
datetime.datetime.utcnow()
- datetime.datetime(self.set_time_offset, 1, 1)
).total_seconds()
)
local_timestamp = int(
(
datetime.datetime.now()
- datetime.datetime(
self.set_time_local_offset or self.set_time_offset, 1, 1
)
).total_seconds()
)
payload.extend(utc_timestamp.to_bytes(4, "big", signed=False))
payload.extend(local_timestamp.to_bytes(4, "big", signed=False))
self.create_catching_task(
super().command(TUYA_SET_TIME, payload, expect_reply=False)
)
class TuyaManufClusterAttributes(TuyaManufCluster):
"""Manufacturer specific cluster for Tuya converting attributes <-> commands."""
def handle_cluster_request(
self,
hdr: foundation.ZCLHeader,
args: Tuple,
*,
dst_addressing: Optional[
Union[t.Addressing.Group, t.Addressing.IEEE, t.Addressing.NWK]
] = None,
) -> None:
"""Handle cluster request."""
if hdr.command_id not in (0x0001, 0x0002):
return super().handle_cluster_request(
hdr, args, dst_addressing=dst_addressing
)
# Send default response because the MCU expects it
if not hdr.frame_control.disable_default_response:
self.send_default_rsp(hdr, status=foundation.Status.SUCCESS)
tuya_cmd = args[0].command_id
tuya_data = args[0].data
_LOGGER.debug(
"[0x%04x:%s:0x%04x] Received value %s "
"for attribute 0x%04x (command 0x%04x)",
self.endpoint.device.nwk,
self.endpoint.endpoint_id,
self.cluster_id,
repr(tuya_data[1:]),
tuya_cmd,
hdr.command_id,
)
if tuya_cmd not in self.attributes:
return
ztype = self.attributes[tuya_cmd].type
zvalue = ztype(tuya_data)
self._update_attribute(tuya_cmd, zvalue)
def read_attributes(
self, attributes, allow_cache=False, only_cache=False, manufacturer=None
):
"""Ignore remote reads as the "get_data" command doesn't seem to do anything."""
return super().read_attributes(
attributes, allow_cache=True, only_cache=True, manufacturer=manufacturer
)
async def write_attributes(self, attributes, manufacturer=None):
"""Defer attributes writing to the set_data tuya command."""
records = self._write_attr_records(attributes)
for record in records:
cmd_payload = TuyaManufCluster.Command()
cmd_payload.status = 0
cmd_payload.tsn = self.endpoint.device.application.get_sequence()
cmd_payload.command_id = record.attrid
cmd_payload.function = 0
cmd_payload.data = record.value.value
await super().command(
TUYA_SET_DATA,
cmd_payload,
manufacturer=manufacturer,
expect_reply=False,
tsn=cmd_payload.tsn,
)
return [[foundation.WriteAttributesStatusRecord(foundation.Status.SUCCESS)]]
class TuyaOnOff(CustomCluster, OnOff):
"""Tuya On/Off cluster for On/Off device."""
def __init__(self, *args, **kwargs):
"""Init."""
super().__init__(*args, **kwargs)
self.endpoint.device.switch_bus.add_listener(self)
def switch_event(self, channel, state):
"""Switch event."""
_LOGGER.debug(
"%s - Received switch event message, channel: %d, state: %d",
self.endpoint.device.ieee,
channel,
state,
)
# update status only if event == endpoint
if self.endpoint.endpoint_id == channel:
self._update_attribute(ATTR_ON_OFF, state)
async def command(
self,
command_id: Union[foundation.GeneralCommand, int, t.uint8_t],
*args,
manufacturer: Optional[Union[int, t.uint16_t]] = None,
expect_reply: bool = True,
tsn: Optional[Union[int, t.uint8_t]] = None,
):
"""Override the default Cluster command."""
if command_id in (0x0000, 0x0001):
cmd_payload = TuyaManufCluster.Command()
cmd_payload.status = 0
# cmd_payload.tsn = tsn if tsn else self.endpoint.device.application.get_sequence()
cmd_payload.tsn = 0
cmd_payload.command_id = TUYA_CMD_BASE + self.endpoint.endpoint_id
cmd_payload.function = 0
cmd_payload.data = [1, command_id]
self.endpoint.device.command_bus.listener_event(
TUYA_MCU_COMMAND,
cmd_payload,
)
return foundation.GENERAL_COMMANDS[
foundation.GeneralCommand.Default_Response
].schema(command_id=command_id, status=foundation.Status.SUCCESS)
return foundation.GENERAL_COMMANDS[
foundation.GeneralCommand.Default_Response
].schema(command_id=command_id, status=foundation.Status.UNSUP_CLUSTER_COMMAND)
class TuyaManufacturerClusterOnOff(TuyaManufCluster):
"""Manufacturer Specific Cluster of On/Off device."""
def handle_cluster_request(
self,
hdr: foundation.ZCLHeader,
args: Tuple[TuyaManufCluster.Command],
*,
dst_addressing: Optional[
Union[t.Addressing.Group, t.Addressing.IEEE, t.Addressing.NWK]
] = None,
) -> None:
"""Handle cluster request."""
if hdr.command_id in (0x0002, 0x0001):
# Send default response because the MCU expects it
if not hdr.frame_control.disable_default_response:
self.send_default_rsp(hdr, status=foundation.Status.SUCCESS)
tuya_payload = args[0]
self.endpoint.device.switch_bus.listener_event(
SWITCH_EVENT,
tuya_payload.command_id - TUYA_CMD_BASE,
tuya_payload.data[1],
)
elif hdr.command_id == TUYA_SET_TIME:
"""Time event call super"""
_LOGGER.debug("TUYA_SET_TIME --> hdr: %s, args: %s", hdr, args)
super().handle_cluster_request(hdr, args, dst_addressing=dst_addressing)
else:
_LOGGER.warning("Unsupported command: %s", hdr)
class TuyaSwitch(CustomDevice):
"""Tuya switch device."""
def __init__(self, *args, **kwargs):
"""Init device."""
self.switch_bus = Bus()
super().__init__(*args, **kwargs)
class TuyaDimmerSwitch(TuyaSwitch):
"""Tuya dimmer switch device."""
def __init__(self, *args, **kwargs):
"""Init device."""
self.dimmer_bus = Bus()
super().__init__(*args, **kwargs)
class TuyaThermostatCluster(LocalDataCluster, Thermostat):
"""Thermostat cluster for Tuya thermostats."""
_CONSTANT_ATTRIBUTES = {0x001B: Thermostat.ControlSequenceOfOperation.Heating_Only}
def __init__(self, *args, **kwargs):
"""Init."""
super().__init__(*args, **kwargs)
self.endpoint.device.thermostat_bus.add_listener(self)
def temperature_change(self, attr, value):
"""Local or target temperature change from device."""
self._update_attribute(self.attributes_by_name[attr].id, value)
def state_change(self, value):
"""State update from device."""
if value == 0:
mode = self.RunningMode.Off
state = self.RunningState.Idle
else:
mode = self.RunningMode.Heat
state = self.RunningState.Heat_State_On
self._update_attribute(self.attributes_by_name["running_mode"].id, mode)
self._update_attribute(self.attributes_by_name["running_state"].id, state)
# pylint: disable=R0201
def map_attribute(self, attribute, value):
"""Map standardized attribute value to dict of manufacturer values."""
return {}
async def write_attributes(self, attributes, manufacturer=None):
"""Implement writeable attributes."""
records = self._write_attr_records(attributes)
if not records:
return [[foundation.WriteAttributesStatusRecord(foundation.Status.SUCCESS)]]
manufacturer_attrs = {}
for record in records:
attr_name = self.attributes[record.attrid].name
new_attrs = self.map_attribute(attr_name, record.value.value)
_LOGGER.debug(
"[0x%04x:%s:0x%04x] Mapping standard %s (0x%04x) "
"with value %s to custom %s",
self.endpoint.device.nwk,
self.endpoint.endpoint_id,
self.cluster_id,
attr_name,
record.attrid,
repr(record.value.value),
repr(new_attrs),
)
manufacturer_attrs.update(new_attrs)
if not manufacturer_attrs:
return [
[
foundation.WriteAttributesStatusRecord(
foundation.Status.FAILURE, r.attrid
)
for r in records
]
]
await self.endpoint.tuya_manufacturer.write_attributes(
manufacturer_attrs, manufacturer=manufacturer
)
return [[foundation.WriteAttributesStatusRecord(foundation.Status.SUCCESS)]]
# pylint: disable=W0236
async def command(
self,
command_id: Union[foundation.GeneralCommand, int, t.uint8_t],
*args,
manufacturer: Optional[Union[int, t.uint16_t]] = None,
expect_reply: bool = True,
tsn: Optional[Union[int, t.uint8_t]] = None,
):
"""Implement thermostat commands."""
if command_id != 0x0000:
return foundation.GENERAL_COMMANDS[
foundation.GeneralCommand.Default_Response
].schema(
command_id=command_id, status=foundation.Status.UNSUP_CLUSTER_COMMAND
)
mode, offset = args
if mode not in (self.SetpointMode.Heat, self.SetpointMode.Both):
return foundation.GENERAL_COMMANDS[
foundation.GeneralCommand.Default_Response
].schema(command_id=command_id, status=foundation.Status.INVALID_VALUE)
attrid = self.attributes_by_name["occupied_heating_setpoint"].id
success, _ = await self.read_attributes((attrid,), manufacturer=manufacturer)
try:
current = success[attrid]
except KeyError:
return foundation.GENERAL_COMMANDS[
foundation.GeneralCommand.Default_Response
].schema(command_id=command_id, status=foundation.Status.FAILURE)
# offset is given in decidegrees, see Zigbee cluster specification
(res,) = await self.write_attributes(
{"occupied_heating_setpoint": current + offset * 10},
manufacturer=manufacturer,
)
return foundation.GENERAL_COMMANDS[
foundation.GeneralCommand.Default_Response
].schema(command_id=command_id, status=res[0].status)
class TuyaUserInterfaceCluster(LocalDataCluster, UserInterface):
"""HVAC User interface cluster for tuya thermostats."""
def __init__(self, *args, **kwargs):
"""Init."""
super().__init__(*args, **kwargs)
self.endpoint.device.ui_bus.add_listener(self)
def child_lock_change(self, mode):
"""Change of child lock setting."""
if mode == 0:
lockout = self.KeypadLockout.No_lockout
else:
lockout = self.KeypadLockout.Level_1_lockout
self._update_attribute(self.attributes_by_name["keypad_lockout"].id, lockout)
def map_attribute(self, attribute, value):
"""Map standardized attribute value to dict of manufacturer values."""
return {}
async def write_attributes(self, attributes, manufacturer=None):
"""Defer the keypad_lockout attribute to child_lock."""
records = self._write_attr_records(attributes)
manufacturer_attrs = {}
for record in records:
if record.attrid == self.attributes_by_name["keypad_lockout"].id:
lock = 0 if record.value.value == self.KeypadLockout.No_lockout else 1
new_attrs = {self._CHILD_LOCK_ATTR: lock}
else:
attr_name = self.attributes[record.attrid].name
new_attrs = self.map_attribute(attr_name, record.value.value)
_LOGGER.debug(
"[0x%04x:%s:0x%04x] Mapping standard %s (0x%04x) "
"with value %s to custom %s",
self.endpoint.device.nwk,
self.endpoint.endpoint_id,
self.cluster_id,
attr_name,
record.attrid,
repr(record.value.value),
repr(new_attrs),
)
manufacturer_attrs.update(new_attrs)
if not manufacturer_attrs:
return [
[
foundation.WriteAttributesStatusRecord(
foundation.Status.FAILURE, r.attrid
)
for r in records
]
]
await self.endpoint.tuya_manufacturer.write_attributes(
manufacturer_attrs, manufacturer=manufacturer
)
return [[foundation.WriteAttributesStatusRecord(foundation.Status.SUCCESS)]]
class TuyaLocalCluster(LocalDataCluster):
"""Tuya virtual clusters.
Prevents attribute reads and writes. Attribute writes could be converted
to DataPoint updates.
"""
def update_attribute(self, attr_name: str, value: Any) -> None:
"""Update attribute by attribute name."""
try:
attr = self.attributes_by_name[attr_name]
except KeyError:
self.debug("no such attribute: %s", attr_name)
return
return self._update_attribute(attr.id, value)
class TuyaPowerConfigurationCluster(PowerConfiguration, TuyaLocalCluster):
"""PowerConfiguration cluster for battery-operated thermostats."""
def __init__(self, *args, **kwargs):
"""Init."""
super().__init__(*args, **kwargs)
self.endpoint.device.battery_bus.add_listener(self)
def battery_change(self, value):
"""Change of reported battery percentage remaining."""
self.update_attribute("battery_percentage_remaining", value * 2)
class TuyaPowerConfigurationCluster2AAA(PowerConfiguration, TuyaLocalCluster):
"""PowerConfiguration cluster for devices with 2 AAA."""
BATTERY_SIZES = 0x0031
BATTERY_QUANTITY = 0x0033
BATTERY_RATED_VOLTAGE = 0x0034
_CONSTANT_ATTRIBUTES = {
BATTERY_SIZES: 4,
BATTERY_QUANTITY: 2,
BATTERY_RATED_VOLTAGE: 15,
}
class TuyaPowerConfigurationCluster2AA(TuyaPowerConfigurationCluster):
"""PowerConfiguration cluster for devices with 2 AA."""
BATTERY_SIZES = 0x0031
BATTERY_RATED_VOLTAGE = 0x0034
BATTERY_QUANTITY = 0x0033
_CONSTANT_ATTRIBUTES = {
BATTERY_SIZES: 3,
BATTERY_RATED_VOLTAGE: 15,
BATTERY_QUANTITY: 2,
}
class TuyaPowerConfigurationCluster3AA(TuyaPowerConfigurationCluster):
"""PowerConfiguration cluster for devices with 3 AA."""
BATTERY_SIZES = 0x0031
BATTERY_RATED_VOLTAGE = 0x0034
BATTERY_QUANTITY = 0x0033
_CONSTANT_ATTRIBUTES = {
BATTERY_SIZES: 3,
BATTERY_RATED_VOLTAGE: 15,
BATTERY_QUANTITY: 3,
}
class TuyaThermostat(CustomDevice):
"""Generic Tuya thermostat device."""
def __init__(self, *args, **kwargs):
"""Init device."""
self.thermostat_bus = Bus()
self.ui_bus = Bus()
self.battery_bus = Bus()
super().__init__(*args, **kwargs)
# Tuya Zigbee OnOff Cluster Attribute Implementation
class SwitchBackLight(t.enum8):
"""Tuya switch back light mode enum."""
Mode_0 = 0x00
Mode_1 = 0x01
Mode_2 = 0x02
class SwitchMode(t.enum8):
"""Tuya switch mode enum."""
Command = 0x00
Event = 0x01
class PowerOnState(t.enum8):
"""Tuya power on state enum."""
Off = 0x00
On = 0x01
LastState = 0x02
class TuyaZBOnOffAttributeCluster(CustomCluster, OnOff):
"""Tuya Zigbee On Off cluster with extra attributes."""
attributes = OnOff.attributes.copy()
attributes.update({0x8000: ("child_lock", t.Bool)})
attributes.update({0x8001: ("backlight_mode", SwitchBackLight)})
attributes.update({0x8002: ("power_on_state", PowerOnState)})
attributes.update({0x8004: ("switch_mode", SwitchMode)})
class TuyaSmartRemoteOnOffCluster(OnOff, EventableCluster):
"""TuyaSmartRemoteOnOffCluster: fire events corresponding to press type."""
rotate_type = {
0x00: RIGHT,
0x01: LEFT,
0x02: STOP,
}
press_type = {
0x00: SHORT_PRESS,
0x01: DOUBLE_PRESS,
0x02: LONG_PRESS,
}
name = "TS004X_cluster"
ep_attribute = "TS004X_cluster"
attributes = OnOff.attributes.copy()
attributes.update({0x8001: ("backlight_mode", SwitchBackLight)})
attributes.update({0x8002: ("power_on_state", PowerOnState)})
attributes.update({0x8004: ("switch_mode", SwitchMode)})
def __init__(self, *args, **kwargs):
"""Init."""
self.last_tsn = -1
super().__init__(*args, **kwargs)
server_commands = OnOff.server_commands.copy()
server_commands.update(
{
0xFC: foundation.ZCLCommandDef(
"rotate_type",
{"rotate_type": t.uint8_t},
False,
is_manufacturer_specific=True,
),
0xFD: foundation.ZCLCommandDef(
"press_type",
{"press_type": t.uint8_t},
False,
is_manufacturer_specific=True,
),
}
)
def handle_cluster_request(
self,
hdr: foundation.ZCLHeader,
args: List[Any],
*,
dst_addressing: Optional[
Union[t.Addressing.Group, t.Addressing.IEEE, t.Addressing.NWK]
] = None,
):
"""Handle press_types command."""
# normally if default response sent, TS004x wouldn't send such repeated zclframe (with same sequence number),
# but for stability reasons (e. g. the case the response doesn't arrive the device), we can simply ignore it
if hdr.tsn == self.last_tsn:
_LOGGER.debug("TS004X: ignoring duplicate frame")
return
# save last sequence number
self.last_tsn = hdr.tsn
# send default response (as soon as possible), so avoid repeated zclframe from device
if not hdr.frame_control.disable_default_response:
self.debug("TS004X: send default response")
self.send_default_rsp(hdr, status=foundation.Status.SUCCESS)
# handle command
if hdr.command_id == 0xFC: