-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathZigbee-Tuya_Alarm
1980 lines (1768 loc) · 81.8 KB
/
Zigbee-Tuya_Alarm
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
/**
* Copyright 2020 Markus Liljergren (https://oh-lalabs.com)
*
* Version: v1.0.1.1123
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* NOTE: This is an auto-generated file and most comments have been removed!
*
*/
// BEGIN:getDefaultImports()
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
import java.security.MessageDigest
// END: getDefaultImports()
import hubitat.helper.HexUtils
metadata {
definition (name: "Zigbee - Tuya Alarm", namespace: "oh-lalabs.com", author: "Markus Liljergren", filename: "zigbee-tuya-alarm", importUrl: "https://raw.githubusercontent.com/markus-li/Hubitat/release/drivers/expanded/zigbee-tuya-alarm-expanded.groovy") {
// BEGIN:getDefaultMetadataCapabilitiesForZigbeeDevices()
capability "Sensor"
capability "PresenceSensor"
capability "Initialize"
capability "Refresh"
// END: getDefaultMetadataCapabilitiesForZigbeeDevices()
capability "Configuration"
capability "Sensor"
capability "Battery"
capability "Switch"
capability "Alarm"
capability "TemperatureMeasurement"
capability "RelativeHumidityMeasurement"
capability "PowerSource"
// BEGIN:getDefaultMetadataAttributes()
attribute "driver", "string"
// END: getDefaultMetadataAttributes()
// BEGIN:getMetadataAttributesForLastCheckin()
attribute "lastCheckin", "Date"
attribute "lastCheckinEpoch", "number"
attribute "notPresentCounter", "number"
attribute "restoredCounter", "number"
// END: getMetadataAttributesForLastCheckin()
attribute "absoluteHumidity", "number"
attribute "alarmLength", "number"
attribute "alarmType", "number"
attribute "alarmVolume", "string"
command "setAlarmType", [[name:"Type", type: "NUMBER", description: "1..18 = set alarm type, can be any number between 1 and 18"]]
command "setAlarmLength", [[name:"Length", type: "NUMBER", description: "0..180 = set alarm length in seconds. 0 = no audible alarm"]]
command "setAlarmVolume", [[name:"Volume", type: "ENUM", description: "set alarm volume", constraints: ["low", "medium", "high"]]]
// BEGIN:getCommandsForPresence()
command "resetRestoredCounter"
// END: getCommandsForPresence()
// BEGIN:getCommandsForZigbeePresence()
command "forceRecoveryMode", [[name:"Minutes*", type: "NUMBER", description: "Maximum minutes to run in Recovery Mode"]]
// END: getCommandsForZigbeePresence()
command "test"
fingerprint model:"TS0601", manufacturer:"_TZE200_d0yu2xgi", profileId:"0104", endpointId:"01", inClusters:"0000,0004,0005,EF00", outClusters:"0019,000A", application:"53"
fingerprint model:"0yu2xgi", manufacturer:"_TYST11_d0yu2xgi", profileId:"0104", endpointId:"01", inClusters:"0000,0003", outClusters:"0003,0019", application:"49"
}
preferences {
// BEGIN:getDefaultMetadataPreferences(includeCSS=True, includeRunReset=False)
input(name: "debugLogging", type: "bool", title: styling_getLogo() + styling_addTitleDiv("Enable debug logging"), description: "" + styling_getDefaultCSS(), defaultValue: false, submitOnChange: true, displayDuringSetup: false, required: false)
input(name: "infoLogging", type: "bool", title: styling_addTitleDiv("Enable info logging"), description: "", defaultValue: true, submitOnChange: true, displayDuringSetup: false, required: false)
// END: getDefaultMetadataPreferences(includeCSS=True, includeRunReset=False)
// BEGIN:getMetadataPreferencesForLastCheckin()
input(name: "lastCheckinEnable", type: "bool", title: styling_addTitleDiv("Enable Last Checkin Date"), description: styling_addDescriptionDiv("Records Date events if enabled"), defaultValue: true)
input(name: "lastCheckinEpochEnable", type: "bool", title: styling_addTitleDiv("Enable Last Checkin Epoch"), description: styling_addDescriptionDiv("Records Epoch events if enabled"), defaultValue: false)
input(name: "presenceEnable", type: "bool", title: styling_addTitleDiv("Enable Presence"), description: styling_addDescriptionDiv("Enables Presence to indicate if the device has sent data within the last 3 hours (REQUIRES at least one of the Checkin options to be enabled)"), defaultValue: true)
input(name: "presenceWarningEnable", type: "bool", title: styling_addTitleDiv("Enable Presence Warning"), description: styling_addDescriptionDiv("Enables Presence Warnings in the Logs (default: true)"), defaultValue: true)
// END: getMetadataPreferencesForLastCheckin()
// BEGIN:getMetadataPreferencesForRecoveryMode(defaultMode="Slow")
input(name: "recoveryMode", type: "enum", title: styling_addTitleDiv("Recovery Mode"), description: styling_addDescriptionDiv("Select Recovery mode type (default: Slow)<br/>NOTE: The \"Insane\" and \"Suicidal\" modes may destabilize your mesh if run on more than a few devices at once!"), options: ["Disabled", "Slow", "Normal", "Insane", "Suicidal"], defaultValue: "Slow")
// END: getMetadataPreferencesForRecoveryMode(defaultMode="Slow")
// BEGIN:getDefaultMetadataPreferencesForTHMonitorAlternative1()
input(name: "tempUnitDisplayed", type: "enum", title: styling_addTitleDiv("Displayed Temperature Unit"), description: "", defaultValue: "0", required: true, multiple: false, options:[["0":"System Default"], ["1":"Celsius"], ["2":"Fahrenheit"], ["3":"Kelvin"]])
input(name: "tempOffset", type: "decimal", title: styling_addTitleDiv("Temperature Offset"), description: styling_addDescriptionDiv("Adjust the temperature by this many degrees."), displayDuringSetup: true, required: false, range: "*..*")
input(name: "tempRes", type: "enum", title: styling_addTitleDiv("Temperature Resolution"), description: styling_addDescriptionDiv("Temperature sensor resolution (0..2 = maximum number of decimal places, default: 1)<br/>NOTE: If the 2nd decimal is a 0 (eg. 24.70) it will show without the last decimal (eg. 24.7)."), options: ["0", "1", "2"], defaultValue: "1", displayDuringSetup: true, required: false)
input(name: "humidityOffset", type: "decimal", title: styling_addTitleDiv("Humidity Offset"), description: styling_addDescriptionDiv("Adjust the humidity by this many percent."), displayDuringSetup: true, required: false, range: "*..*")
input(name: "humidityRes", type: "enum", title: styling_addTitleDiv("Humidity Resolution"), description: styling_addDescriptionDiv("Humidity sensor resolution (0..1 = maximum number of decimal places, default: 1)"), options: ["0", "1"], defaultValue: "1")
input(name: "reportAbsoluteHumidity", type: "bool", title: styling_addTitleDiv("Report Absolute Humidity"), description: styling_addDescriptionDiv("Also report Absolute Humidity. Default = Disabled"), defaultValue: false)
if(getDeviceDataByName('hasPressure') == "True") {
input(name: "pressureUnitConversion", type: "enum", title: styling_addTitleDiv("Displayed Pressure Unit"), description: styling_addDescriptionDiv("(default: kPa)"), options: ["mbar", "kPa", "inHg", "mmHg", "atm"], defaultValue: "kPa")
input(name: "pressureRes", type: "enum", title: styling_addTitleDiv("Humidity Resolution"), description: styling_addDescriptionDiv("Humidity sensor resolution (0..1 = maximum number of decimal places, default: default)"), options: ["default", "0", "1", "2"], defaultValue: "default")
input(name: "pressureOffset", type: "decimal", title: styling_addTitleDiv("Pressure Offset"), description: styling_addDescriptionDiv("Adjust the pressure value by this much."), displayDuringSetup: true, required: false, range: "*..*")
}
// END: getDefaultMetadataPreferencesForTHMonitorAlternative1()
}
}
// BEGIN:getDeviceInfoFunction()
def String getDeviceInfoByName(infoName) {
def Map deviceInfo = ['name': 'Zigbee - Tuya Alarm', 'namespace': 'oh-lalabs.com', 'author': 'Markus Liljergren', 'filename': 'zigbee-tuya-alarm', 'importUrl': 'https://raw.githubusercontent.com/markus-li/Hubitat/release/drivers/expanded/zigbee-tuya-alarm-expanded.groovy']
return(deviceInfo[infoName])
}
// END: getDeviceInfoFunction()
/* These functions are unique to each driver */
def ArrayList<String> refresh() {
logging("refresh() model='${getDeviceDataByName('model')}'", 10)
getDriverVersion()
configurePresence()
startCheckEventInterval()
setLogsOffTask(noLogWarning=true)
def ArrayList<String> cmd = []
cmd += zigbee.readAttribute(0x0000, 0x0005)
logging("refresh cmd: $cmd", 1)
sendZigbeeCommands(cmd)
/* refreshEvents() just sends all current states again, it's a hack for HubConnect */
refreshEvents()
}
def initialize() {
logging("initialize()", 100)
unschedule()
refresh()
configureDevice()
}
void installed() {
logging("installed()", 100)
refresh()
configureDevice()
}
void updated() {
logging("updated()", 100)
refresh()
configureDevice()
}
void configureDevice() {
logging('configureDevice()', 100)
Integer alarmLength = device.currentValue('alarmLength')
alarmLength = alarmLength != null ? alarmLength : 10
logging("Alarm Length Set: $alarmLength", 100)
setAlarmLength(alarmLength)
Integer alarmType = device.currentValue('alarmType')
alarmType = alarmType != null ? alarmType : 1
logging("Alarm Type Set: $alarmType", 100)
setAlarmType(alarmType)
String alarmVolume = device.currentValue('alarmVolume')
alarmVolume = alarmVolume != null ? alarmVolume : 'low'
logging("Alarm Volume Set: $alarmVolume", 100)
setAlarmVolume(alarmVolume)
sendTuyaCommand(0x00, "7001000101")
sendTuyaCommand(0x10, "")
}
void test() {
ArrayList<String> cmd = []
cmd += zigbeeWriteAttribute(CLUSTER_BASIC, 0xFFDE, 0x20, 0x13)
cmd += zigbeeSpecialCommand(0x11, 0x01, 0x0000, 0xF0)
cmd += zigbeeSpecialCommand(0x11, 0x01, 0xEF00, 0x03)
cmd += getTuyaCommand(0x10, "")
sendZigbeeCommands(cmd)
logging("Done with test()", 100)
}
ArrayList<String> zigbeeSpecialCommand(Integer frameControlField, Integer endpoint, Integer cluster, Integer command, Map additionalParams = [:], int delay = 2001) {
logging("zigbeeSpecialCommand()", 1)
String mfgCode = "0000"
if(additionalParams.containsKey("mfgCode")) {
mfgCode = "${integerToHexString(HexUtils.hexStringToInt(additionalParams.get("mfgCode")), 2, reverse=true)}"
log.error "Manufacturer code support is NOT implemented!"
}
Random rnd = new Random()
String commandArgs = "0x${device.deviceNetworkId} 1 $endpoint 0x${integerToHexString(cluster, 2)} " +
"{${integerToHexString(frameControlField, 1)}${HexUtils.integerToHexString(rnd.nextInt(255),1)}${integerToHexString(command, 1)}}"
ArrayList<String> cmd = ["he raw $commandArgs", "delay $delay"]
logging("zigbeeSpecialCommand cmd=$cmd", 1)
return cmd
}
void configure() {
configureDevice()
}
Integer getMINUTES_BETWEEN_EVENTS() {
return 140
}
ArrayList<String> parse(String description) {
// BEGIN:getGenericZigbeeParseHeader(loglevel=0)
//logging("PARSE START---------------------", 0)
//logging("Parsing: '${description}'", 0)
ArrayList<String> cmd = []
Map msgMap = null
if(description.indexOf('encoding: 4C') >= 0) {
msgMap = zigbee.parseDescriptionAsMap(description.replace('encoding: 4C', 'encoding: F2'))
msgMap = unpackStructInMap(msgMap)
} else if(description.indexOf('attrId: FF01, encoding: 42') >= 0) {
msgMap = zigbee.parseDescriptionAsMap(description.replace('encoding: 42', 'encoding: F2'))
msgMap["encoding"] = "41"
msgMap["value"] = parseXiaomiStruct(msgMap["value"], isFCC0=false, hasLength=true)
} else {
if(description.indexOf('encoding: 42') >= 0) {
List values = description.split("value: ")[1].split("(?<=\\G..)")
String fullValue = values.join()
Integer zeroIndex = values.indexOf("01")
if(zeroIndex > -1) {
//logging("zeroIndex: $zeroIndex, fullValue: $fullValue, string: ${values.take(zeroIndex).join()}", 0)
msgMap = zigbee.parseDescriptionAsMap(description.replace(fullValue, values.take(zeroIndex).join()))
values = values.drop(zeroIndex + 3)
msgMap["additionalAttrs"] = [
["encoding": "41",
"value": parseXiaomiStruct(values.join(), isFCC0=false, hasLength=true)]
]
} else {
msgMap = zigbee.parseDescriptionAsMap(description)
}
} else {
msgMap = zigbee.parseDescriptionAsMap(description)
}
if(msgMap.containsKey("encoding") && msgMap.containsKey("value") && msgMap["encoding"] != "41" && msgMap["encoding"] != "42") {
msgMap["valueParsed"] = zigbee_generic_decodeZigbeeData(msgMap["value"], msgMap["encoding"])
}
if(msgMap == [:] && description.indexOf("zone") == 0) {
msgMap["type"] = "zone"
java.util.regex.Matcher zoneMatcher = description =~ /.*zone.*status.*0x(?<status>([0-9a-fA-F][0-9a-fA-F])+).*extended.*status.*0x(?<statusExtended>([0-9a-fA-F][0-9a-fA-F])+).*/
if(zoneMatcher.matches()) {
msgMap["parsed"] = true
msgMap["status"] = zoneMatcher.group("status")
msgMap["statusInt"] = Integer.parseInt(msgMap["status"], 16)
msgMap["statusExtended"] = zoneMatcher.group("statusExtended")
msgMap["statusExtendedInt"] = Integer.parseInt(msgMap["statusExtended"], 16)
} else {
msgMap["parsed"] = false
}
}
}
//logging("msgMap: ${msgMap}", 0)
// END: getGenericZigbeeParseHeader(loglevel=0)
switch(msgMap["cluster"] + '_' + msgMap["attrId"]) {
case "0000_0001":
logging("Application ID Received", 1)
updateApplicationId(msgMap['value'])
break
case "0000_0004":
logging("Manufacturer Name Received - description:${description} | msgMap:${msgMap}", 1)
updateManufacturer(msgMap['value'])
break
case "0000_0005":
logging("Model Name Received - description:${description} | msgMap:${msgMap}", 1)
setCleanModelName(newModelToSet=msgMap["value"])
break
default:
switch(msgMap["clusterId"]) {
case "EF00":
//logging("Tuya Payload - description:${description} | msgMap:${msgMap}", 0)
parseTuyaPayload(msgMap)
break
case "8004":
updateDataFromSimpleDescriptorData(msgMap["data"])
break
case "000A":
case "0013":
case "0006":
case "8021":
case "8032":
//logging("General catchall - description:${description} | msgMap:${msgMap}", 0)
break
default:
logging("Unhandled Event IGNORE THIS - description:${description} | msgMap:${msgMap}", 100)
break
}
break
}
if(hasCorrectCheckinEvents(maximumMinutesBetweenEvents=140) == false) {
sendZigbeeCommands(zigbee.readAttribute(CLUSTER_BASIC, 0x0004))
}
sendlastCheckinEvent(minimumMinutesToRepeat=30)
// BEGIN:getGenericZigbeeParseFooter(loglevel=0)
//logging("PARSE END-----------------------", 0)
msgMap = null
return cmd
// END: getGenericZigbeeParseFooter(loglevel=0)
}
void sendOnOffEvent(boolean onOff) {
if(invertValve == null) invertValve = false
logging("sendOnOffEvent(onOff=$onOff)", 1)
if(onOff == invertValve) {
sendEvent(name:"valve", value: "closed", isStateChange: false, descriptionText: "Valve closed")
sendEvent(name:"switch", value: "off", isStateChange: false, descriptionText: "Valve closed")
} else {
sendEvent(name:"valve", value: "open", isStateChange: false, descriptionText: "Valve opened")
sendEvent(name:"switch", value: "on", isStateChange: false, descriptionText: "Valve opened")
}
}
void sendPowerEvent(Float power) {
Float variancePercent = 0.10
if(powerOffset != null) power = power + powerOffset
if(power < 0 ) power = 0
if(powerMinimum != null && power < powerMinimum) power = 0
Float oldPower = device.currentValue('power') == null ? null : device.currentValue('power')
if(oldPower == null) {
logging("Power: $power (oldPower: $oldPower)", 1)
} else {
logging("Power: $power (oldPower: $oldPower, lower: ${oldPower * (1-variancePercent)}, upper: ${oldPower * (1+variancePercent)})", 1)
}
if(oldPower == null || power < oldPower * (1-variancePercent) || power > oldPower * (1+variancePercent)) {
logging("Sending Power event: ${power}W (old Power: ${oldPower}W)", 1)
sendEvent(name:"power", value: power, unit: "W", isStateChange: true)
sendEvent(name:"powerWithUnit", value: "${power}W", isStateChange: true)
} else {
logging("SKIPPING Power event: ${power}W (old Power: ${oldPower}W)", 1)
}
}
void parseTuyaPayload(Map msgMap) {
/* This is lazy parsing of these packets, it's NOT complete, the data lengths and structure is part of the packet... We should use this information... */
switch(msgMap['command']) {
case '01':
case '02':
List data = msgMap['data']
String commandType = data[2] + data[3]
logging("Tuya Status: ${msgMap['data']}", 1)
logging("Tuya Command Type: $commandType", 1)
switch(commandType) {
case '6801':
boolean active = data[-1] == '01'
String activeAsString = active ? 'both' : 'off'
logging("Alarm status: ${activeAsString}", 100)
sendEvent(name:"alarm", value: activeAsString, isStateChange: false)
sendEvent(name:"switch", value: active ? 'on' : 'off', isStateChange: false)
break
case '6702':
Integer length = HexUtils.hexStringToInt(data[-1])
logging("Alarm length: ${length}", 100)
sendEvent(name:"alarmLength", value: length, isStateChange: false)
break
case '6604':
Integer type = HexUtils.hexStringToInt(data[-1]) + 1
logging("Alarm type: ${type}", 100)
sendEvent(name:"alarmType", value: type, isStateChange: false)
break
case '7404':
Integer volume = HexUtils.hexStringToInt(data[-1])
volume = volume > 2 ? 2 : volume
List volumeTypes = ['high', 'medium', 'low']
logging("Alarm volume: ${volumeTypes[volume]}", 100)
sendEvent(name:"alarmVolume", value: volumeTypes[volume], isStateChange: false)
break
case '6902':
// Integer temperature = HexUtils.hexStringToInt(data.takeRight(4).join('')) * 10
// logging("Raw Temperature: ${temperature}", 1)
// zigbee_sensor_parseSendTemperatureEvent(temperature)
try{ Integer temperature = HexUtils.hexStringToInt(data.takeRight(4).join('')) * 10
logging("Raw Temperature: ${temperature}", 1)
zigbee_sensor_parseSendTemperatureEvent(temperature) }
catch(Exception e) {
}
break
case '6A02':
Integer humidity = HexUtils.hexStringToInt(data.takeRight(2).join('')) * 100
logging("Raw Humidity: ${humidity}", 1)
zigbee_sensor_parseSendHumidityEvent(humidity, 1.1)
break
case '6504':
Integer type = HexUtils.hexStringToInt(data[-1])
logging("Power type: ${type}", 100)
logging("Tuya Power Status: ${msgMap['data']}", 100)
sendEvent(name:"powerSource", value: type == 0 || type == 1 ? 'battery' : 'dc', isStateChange: false)
break
case '6B02':
break
case '6C02':
break
case '6D02':
break
case '6E02':
break
case '7001':
if(HexUtils.hexStringToInt(data[-1]) != 1) {
logging("The device was not set to using Celsius internally! Fixing that now...", 100)
sendTuyaCommand(0x00, "7001000101")
} else {
logging("Device reported that it is using Celsius internally. This is how it should be even when using Fahrenheit in HE!", 100)
}
break
case '7101':
logging("7101 Tuya Status: ${msgMap['data']}", 100)
break
case '7201':
logging("7201 Tuya Status: ${msgMap['data']}", 100)
break
case '7304':
logging("7304 Tuya Status: ${msgMap['data']}", 100)
break
default:
logging("UNKNOWN Tuya Status: ${msgMap['data']}", 100)
logging("UNKNOWN Tuya Command Type: $commandType", 100)
}
break
case '0B':
if(msgMap['data'] != ['00', '00']) {
logging("Tuya 0B: ${msgMap} ", 100)
}
break
default:
logging("Tuya Unknown Command: ${msgMap}", 100)
}
}
/**
* --------- WRITE ATTRIBUTE METHODS ---------
*/
void on() {
logging("on()", 1)
sendTuyaCommand(0x00, "6801000101")
}
void off() {
logging("off()", 1)
sendTuyaCommand(0x00, "6801000100")
}
void siren() {
on()
}
void strobe() {
on()
}
void both() {
on()
}
void setAlarmType(BigDecimal type) {
type = type > 180 ? 180 : type < 1 ? 1 : type
logging("setAlarmType(type=$type)", 100)
sendTuyaCommand(0x00, "66040001${HexUtils.integerToHexString(type.intValue()-1,1)}")
}
void setAlarmVolume(String volume) {
switch(volume) {
case "high":
sendTuyaCommand(0x00, "7404000100")
break
case "medium":
sendTuyaCommand(0x00, "7404000101")
break
default:
sendTuyaCommand(0x00, "7404000102")
break
}
}
void setAlarmLength(BigDecimal length) {
length = length > 255 ? 255 : length < 0 ? 0 : length
logging("setAlarmLength(length=$length)", 100)
sendTuyaCommand(0x00, "670200040000${HexUtils.integerToHexString(length.intValue(),2)}")
}
void sendTuyaCommand(Integer command, String payload) {
Random rnd = new Random()
def String fullPayload = "00${HexUtils.integerToHexString(rnd.nextInt(255),1)}" + payload
sendZigbeeCommands(zigbeeCommand(0x01, 0xEF00, command, 101, fullPayload))
logging("Payload sent: $fullPayload", 100)
}
def ArrayList<String> getTuyaCommand(Integer command, String payload) {
Random rnd = new Random()
String fullPayload = "00${HexUtils.integerToHexString(rnd.nextInt(255),1)}" + payload
return zigbeeCommand(0x01, 0xEF00, command, 101, fullPayload)
}
/**
* --------- READ ATTRIBUTE METHODS ---------
*/
/**
* -----------------------------------------------------------------------------
* Everything below here are LIBRARY includes and should NOT be edited manually!
* -----------------------------------------------------------------------------
* --- Nothings to edit here, move along! --------------------------------------
* -----------------------------------------------------------------------------
*/
// BEGIN:getDefaultFunctions()
private String getDriverVersion() {
comment = "Works with the Tuya Alarm."
if(comment != "") state.comment = comment
String version = "v1.0.1.1123"
logging("getDriverVersion() = ${version}", 100)
sendEvent(name: "driver", value: version)
updateDataValue('driver', version)
return version
}
// END: getDefaultFunctions()
// BEGIN:getLoggingFunction()
private boolean logging(message, level) {
boolean didLogging = false
Integer logLevelLocal = 0
if (infoLogging == null || infoLogging == true) {
logLevelLocal = 100
}
if (debugLogging == true) {
logLevelLocal = 1
}
if (logLevelLocal != 0){
switch (logLevelLocal) {
case 1:
if (level >= 1 && level < 99) {
log.debug "$message"
didLogging = true
} else if (level == 100) {
log.info "$message"
didLogging = true
}
break
case 100:
if (level == 100 ) {
log.info "$message"
didLogging = true
}
break
}
}
return didLogging
}
// END: getLoggingFunction()
// BEGIN:getHelperFunctions('zigbee-generic')
private getCLUSTER_BASIC() { 0x0000 }
private getCLUSTER_POWER() { 0x0001 }
private getCLUSTER_WINDOW_COVERING() { 0x0102 }
private getCLUSTER_WINDOW_POSITION() { 0x000d }
private getCLUSTER_ON_OFF() { 0x0006 }
private getBASIC_ATTR_POWER_SOURCE() { 0x0007 }
private getPOWER_ATTR_BATTERY_PERCENTAGE_REMAINING() { 0x0021 }
private getPOSITION_ATTR_VALUE() { 0x0055 }
private getCOMMAND_OPEN() { 0x00 }
private getCOMMAND_CLOSE() { 0x01 }
private getCOMMAND_PAUSE() { 0x02 }
private getENCODING_SIZE() { 0x39 }
void updateNeededSettings() {
}
void refreshEvents() {
}
ArrayList<String> zigbeeCommand(Integer cluster, Integer command, Map additionalParams, int delay = 201, String... payload) {
ArrayList<String> cmd = zigbee.command(cluster, command, additionalParams, delay, payload)
cmd[0] = cmd[0].replace('0xnull', '0x01')
return cmd
}
def ArrayList<String> zigbeeCommand(Integer cluster, Integer command, int delay = 202, String... payload) {
def ArrayList<String> cmd = zigbee.command(cluster, command, [:], delay, payload)
cmd[0] = cmd[0].replace('0xnull', '0x01')
return cmd
}
ArrayList<String> zigbeeCommand(Integer endpoint, Integer cluster, Integer command, int delay = 203, String... payload) {
zigbeeCommand(endpoint, cluster, command, [:], delay, payload)
}
ArrayList<String> zigbeeCommand(Integer endpoint, Integer cluster, Integer command, Map additionalParams, int delay = 204, String... payload) {
String mfgCode = ""
if(additionalParams.containsKey("mfgCode")) {
mfgCode = " {${HexUtils.integerToHexString(HexUtils.hexStringToInt(additionalParams.get("mfgCode")), 2)}}"
}
String finalPayload = payload != null && payload != [] ? payload[0] : ""
String cmdArgs = "0x${device.deviceNetworkId} 0x${HexUtils.integerToHexString(endpoint, 1)} 0x${HexUtils.integerToHexString(cluster, 2)} " +
"0x${HexUtils.integerToHexString(command, 1)} " +
"{$finalPayload}" +
"$mfgCode"
ArrayList<String> cmd = ["he cmd $cmdArgs", "delay $delay"]
return cmd
}
ArrayList<String> zigbeeWriteAttribute(Integer cluster, Integer attributeId, Integer dataType, Integer value, Map additionalParams = [:], int delay = 199) {
ArrayList<String> cmd = zigbee.writeAttribute(cluster, attributeId, dataType, value, additionalParams, delay)
cmd[0] = cmd[0].replace('0xnull', '0x01')
return cmd
}
ArrayList<String> zigbeeWriteAttribute(Integer endpoint, Integer cluster, Integer attributeId, Integer dataType, Integer value, Map additionalParams = [:], int delay = 198) {
logging("zigbeeWriteAttribute()", 1)
String mfgCode = ""
if(additionalParams.containsKey("mfgCode")) {
mfgCode = " {${HexUtils.integerToHexString(HexUtils.hexStringToInt(additionalParams.get("mfgCode")), 2)}}"
}
String wattrArgs = "0x${device.deviceNetworkId} $endpoint 0x${HexUtils.integerToHexString(cluster, 2)} " +
"0x${HexUtils.integerToHexString(attributeId, 2)} " +
"0x${HexUtils.integerToHexString(dataType, 1)} " +
"{${HexUtils.integerToHexString(value, 1)}}" +
"$mfgCode"
ArrayList<String> cmd = ["he wattr $wattrArgs", "delay $delay"]
logging("zigbeeWriteAttribute cmd=$cmd", 1)
return cmd
}
ArrayList<String> zigbeeReadAttribute(Integer cluster, Integer attributeId, Map additionalParams = [:], int delay = 205) {
ArrayList<String> cmd = zigbee.readAttribute(cluster, attributeId, additionalParams, delay)
cmd[0] = cmd[0].replace('0xnull', '0x01')
return cmd
}
ArrayList<String> zigbeeReadAttribute(Integer endpoint, Integer cluster, Integer attributeId, int delay = 206) {
ArrayList<String> cmd = ["he rattr 0x${device.deviceNetworkId} ${endpoint} 0x${HexUtils.integerToHexString(cluster, 2)} 0x${HexUtils.integerToHexString(attributeId, 2)} {}", "delay $delay"]
return cmd
}
ArrayList<String> zigbeeWriteLongAttribute(Integer cluster, Integer attributeId, Integer dataType, Long value, Map additionalParams = [:], int delay = 207) {
return zigbeeWriteLongAttribute(1, cluster, attributeId, dataType, value, additionalParams, delay)
}
ArrayList<String> zigbeeWriteLongAttribute(Integer endpoint, Integer cluster, Integer attributeId, Integer dataType, Long value, Map additionalParams = [:], int delay = 208) {
logging("zigbeeWriteLongAttribute()", 1)
String mfgCode = ""
if(additionalParams.containsKey("mfgCode")) {
mfgCode = " {${HexUtils.integerToHexString(HexUtils.hexStringToInt(additionalParams.get("mfgCode")), 2)}}"
}
String wattrArgs = "0x${device.deviceNetworkId} $endpoint 0x${HexUtils.integerToHexString(cluster, 2)} " +
"0x${HexUtils.integerToHexString(attributeId, 2)} " +
"0x${HexUtils.integerToHexString(dataType, 1)} " +
"{${Long.toHexString(value)}}" +
"$mfgCode"
ArrayList<String> cmd = ["he wattr $wattrArgs", "delay $delay"]
logging("zigbeeWriteLongAttribute cmd=$cmd", 1)
return cmd
}
void sendZigbeeCommand(String cmd) {
logging("sendZigbeeCommand(cmd=$cmd)", 1)
sendZigbeeCommands([cmd])
}
void sendZigbeeCommands(ArrayList<String> cmd) {
logging("sendZigbeeCommands(cmd=$cmd)", 1)
hubitat.device.HubMultiAction allActions = new hubitat.device.HubMultiAction()
cmd.each {
allActions.add(new hubitat.device.HubAction(it, hubitat.device.Protocol.ZIGBEE))
}
sendHubCommand(allActions)
}
String setCleanModelName(String newModelToSet=null, List<String> acceptedModels=null) {
String model = newModelToSet != null ? newModelToSet : getDeviceDataByName('model')
model = model == null ? "null" : model
String newModel = model.replaceAll("[^A-Za-z0-9.\\-_ ]", "")
boolean found = false
if(acceptedModels != null) {
acceptedModels.each {
if(found == false && newModel.startsWith(it) == true) {
newModel = it
found = true
}
}
}
logging("dirty model = $model, clean model=$newModel", 1)
updateDataValue('model', newModel)
return newModel
}
void resetBatteryReplacedDate(boolean forced=true) {
if(forced == true || device.currentValue('batteryLastReplaced') == null) {
sendEvent(name: "batteryLastReplaced", value: new Date().format('yyyy-MM-dd HH:mm:ss'))
}
}
void parseAndSendBatteryStatus(BigDecimal vCurrent) {
BigDecimal vMin = vMinSetting == null ? 2.5 : vMinSetting
BigDecimal vMax = vMaxSetting == null ? 3.0 : vMaxSetting
BigDecimal bat = 0
if(vMax - vMin > 0) {
bat = ((vCurrent - vMin) / (vMax - vMin)) * 100.0
if (batt == -999) bat = 100
} else {
bat = 100
}
bat = bat.setScale(0, BigDecimal.ROUND_HALF_UP)
bat = bat > 100 ? 100 : bat
vCurrent = vCurrent.setScale(3, BigDecimal.ROUND_HALF_UP)
logging("Battery event: $bat% (V = $vCurrent)", 1)
sendEvent(name:"battery", value: bat, unit: "%", isStateChange: false)
}
Map unpackStructInMap(Map msgMap, String originalEncoding="4C") {
msgMap['encoding'] = originalEncoding
List<String> values = msgMap['value'].split("(?<=\\G..)")
logging("unpackStructInMap() values=$values", 1)
Integer numElements = Integer.parseInt(values.take(2).reverse().join(), 16)
values = values.drop(2)
List r = []
Integer cType = null
List ret = null
while(values != []) {
cType = Integer.parseInt(values.take(1)[0], 16)
values = values.drop(1)
ret = zigbee_generic_convertStructValueToList(values, cType)
r += ret[0]
values = ret[1]
}
if(r.size() != numElements) throw new Exception("The STRUCT specifies $numElements elements, found ${r.size()}!")
msgMap['value'] = r
return msgMap
}
Map parseXiaomiStruct(String xiaomiStruct, boolean isFCC0=false, boolean hasLength=false) {
Map tags = [
'01': 'battery',
'03': 'deviceTemperature',
'04': 'unknown1',
'05': 'RSSI_dB',
'06': 'LQI',
'07': 'unknown2',
'08': 'unknown3',
'09': 'unknown4',
'0A': 'routerid',
'0B': 'unknown5',
'0C': 'unknown6',
'6429': 'temperature',
'6410': 'openClose',
'6420': 'curtainPosition',
'6521': 'humidity',
'6510': 'switch2',
'66': 'pressure',
'6E': 'unknown10',
'6F': 'unknown11',
'95': 'consumption',
'96': 'voltage',
'98': 'power',
'9721': 'gestureCounter1',
'9739': 'consumption',
'9821': 'gestureCounter2',
'9839': 'power',
'99': 'gestureCounter3',
'9A21': 'gestureCounter4',
'9A20': 'unknown7',
'9A25': 'accelerometerXYZ',
'9B': 'unknown9',
]
if(isFCC0 == true) {
tags['05'] = 'numBoots'
tags['6410'] = 'onOff'
tags['95'] = 'current'
}
List<String> values = xiaomiStruct.split("(?<=\\G..)")
if(hasLength == true) values = values.drop(1)
Map r = [:]
r["raw"] = [:]
String cTag = null
String cTypeStr = null
Integer cType = null
String cKey = null
List ret = null
while(values != []) {
cTag = values.take(1)[0]
values = values.drop(1)
cTypeStr = values.take(1)[0]
cType = Integer.parseInt(cTypeStr, 16)
values = values.drop(1)
if(tags.containsKey(cTag+cTypeStr)) {
cKey = tags[cTag+cTypeStr]
} else if(tags.containsKey(cTag)) {
cKey = tags[cTag]
} else {
cKey = "unknown${cTag}${cTypeStr}"
log.warn("PLEASE REPORT TO DEV - The Xiaomi Struct used an unrecognized tag: 0x$cTag (type: 0x$cTypeStr) (struct: $xiaomiStruct)")
}
ret = zigbee_generic_convertStructValue(r, values, cType, cKey, cTag)
r = ret[0]
values = ret[1]
}
return r
}
Map parseAttributeStruct(List data, boolean hasLength=false) {
Map tags = [
'0000': 'ZCLVersion',
'0001': 'applicationVersion',
'0002': 'stackVersion',
'0003': 'HWVersion',
'0004': 'manufacturerName',
'0005': 'dateCode',
'0006': 'modelIdentifier',
'0007': 'powerSource',
'0010': 'locationDescription',
'0011': 'physicalEnvironment',
'0012': 'deviceEnabled',
'0013': 'alarmMask',
'0014': 'disableLocalConfig',
'4000': 'SWBuildID',
]
List<String> values = data
if(hasLength == true) values = values.drop(1)
Map r = [:]
r["raw"] = [:]
String cTag = null
String cTypeStr = null
Integer cType = null
String cKey = null
List ret = null
while(values != []) {
cTag = values.take(2).reverse().join()
values = values.drop(2)
values = values.drop(1)
cTypeStr = values.take(1)[0]
cType = Integer.parseInt(cTypeStr, 16)
values = values.drop(1)
if(tags.containsKey(cTag+cTypeStr)) {
cKey = tags[cTag+cTypeStr]
} else if(tags.containsKey(cTag)) {
cKey = tags[cTag]
} else {
throw new Exception("The Xiaomi Struct used an unrecognized tag: 0x$cTag (type: 0x$cTypeStr)")
}
ret = zigbee_generic_convertStructValue(r, values, cType, cKey, cTag)
r = ret[0]
values = ret[1]
}
return r
}
def zigbee_generic_decodeZigbeeData(String value, String cTypeStr, boolean reverseBytes=true) {
List values = value.split("(?<=\\G..)")
values = reverseBytes == true ? values.reverse() : values
Integer cType = Integer.parseInt(cTypeStr, 16)
Map rMap = [:]
rMap['raw'] = [:]
List ret = zigbee_generic_convertStructValue(rMap, values, cType, "NA", "NA")
return ret[0]["NA"]
}
List zigbee_generic_convertStructValueToList(List values, Integer cType) {
Map rMap = [:]
rMap['raw'] = [:]
List ret = zigbee_generic_convertStructValue(rMap, values, cType, "NA", "NA")
return [ret[0]["NA"], ret[1]]
}
List zigbee_generic_convertStructValue(Map r, List values, Integer cType, String cKey, String cTag) {
String cTypeStr = cType != null ? integerToHexString(cType, 1) : null
switch(cType) {
case 0x10:
r["raw"][cKey] = values.take(1)[0]
r[cKey] = Integer.parseInt(r["raw"][cKey], 16) != 0
values = values.drop(1)
break
case 0x18:
case 0x20:
r["raw"][cKey] = values.take(1)[0]
r[cKey] = Integer.parseInt(r["raw"][cKey], 16)
values = values.drop(1)
break
case 0x19:
case 0x21:
r["raw"][cKey] = values.take(2).reverse().join()
r[cKey] = Integer.parseInt(r["raw"][cKey], 16)
values = values.drop(2)
break
case 0x1A:
case 0x22:
r["raw"][cKey] = values.take(3).reverse().join()
r[cKey] = Integer.parseInt(r["raw"][cKey], 16)
values = values.drop(3)
break
case 0x1B:
case 0x23:
r["raw"][cKey] = values.take(4).reverse().join()
r[cKey] = Long.parseLong(r["raw"][cKey], 16)
values = values.drop(4)
break
case 0x1C:
case 0x24:
r["raw"][cKey] = values.take(5).reverse().join()
r[cKey] = Long.parseLong(r["raw"][cKey], 16)
values = values.drop(5)
break
case 0x1D:
case 0x25:
r["raw"][cKey] = values.take(6).reverse().join()
r[cKey] = Long.parseLong(r["raw"][cKey], 16)
values = values.drop(6)
break
case 0x1E:
case 0x26:
r["raw"][cKey] = values.take(7).reverse().join()
r[cKey] = Long.parseLong(r["raw"][cKey], 16)
values = values.drop(7)
break
case 0x1F:
case 0x27:
r["raw"][cKey] = values.take(8).reverse().join()
r[cKey] = new BigInteger(r["raw"][cKey], 16)
values = values.drop(8)
break
case 0x28:
r["raw"][cKey] = values.take(1).reverse().join()
r[cKey] = convertToSignedInt8(Integer.parseInt(r["raw"][cKey], 16))
values = values.drop(1)
break
case 0x29:
r["raw"][cKey] = values.take(2).reverse().join()
r[cKey] = (Integer) (short) Integer.parseInt(r["raw"][cKey], 16)
values = values.drop(2)
break
case 0x2B:
r["raw"][cKey] = values.take(4).reverse().join()
r[cKey] = (Integer) Long.parseLong(r["raw"][cKey], 16)
values = values.drop(4)
break
case 0x30:
r["raw"][cKey] = values.take(1)[0]
r[cKey] = Integer.parseInt(r["raw"][cKey], 16)
values = values.drop(1)
break
case 0x31:
r["raw"][cKey] = values.take(2).reverse().join()
r[cKey] = Integer.parseInt(r["raw"][cKey], 16)
values = values.drop(2)
break
case 0x39:
r["raw"][cKey] = values.take(4).reverse().join()
r[cKey] = parseSingleHexToFloat(r["raw"][cKey])
values = values.drop(4)