/
Tuya Zigbee Light Sensor.groovy
3256 lines (2996 loc) · 145 KB
/
Tuya Zigbee Light Sensor.groovy
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 Zigbee Light Sensor - Driver for Hubitat Elevation
*
* https://community.hubitat.com/t/dynamic-capabilities-commands-and-attributes-for-drivers/98342
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*
* This driver is inspired by @w35l3y work on Tuya device driver (Edge project).
* For a big portions of code all credits go to Jonathan Bradshaw.
*
* ver. 2.0.0 2023-05-08 kkossev - Initial test version (VINDSTYRKA driver)
* ver. 2.0.1 2023-05-27 kkossev - another test version (Aqara TVOC Air Monitor driver)
* ver. 2.0.2 2023-05-29 kkossev - Just another test version (Aqara E1 thermostat driver) (not ready yet!); added 'Advanced Options'; Xiaomi cluster decoding; added temperatureScale and tVocUnit'preferences; temperature rounding bug fix
* ver. 2.0.3 2023-06-10 kkossev - Tuya Zigbee Fingerbot
* ver. 2.0.4 2023-06-29 kkossev - Tuya Zigbee Switch; Tuya Zigbee Button Dimmer; Tuya Zigbee Dimmer; Tuya Zigbee Light Sensor;
* ver. 2.0.5 2023-07-02 kkossev - Tuya Zigbee Button Dimmer: added Debounce option; added VoltageToPercent option for battery; added reverseButton option; healthStatus bug fix; added Zigbee Groups' command; added switch moode (dimmer/scene) for TS004F
* ver. 2.0.6 2023-07-09 kkossev - Tuya Zigbee Light Sensor: added min/max reporting time; illuminance threshold; added lastRx checkInTime, batteryTime, battCtr; added illuminanceCoeff; checkDriverVersion() bug fix;
*
* TODO: implement Configure device only
* TODO: implement LOAD ALL DEFAUTS
* TODO: add timeout for auto-clearing of the Info event
* TODO: add pingSuccess and pingFailure in health stats
* TODO: add clearStatistics toggle in Preferences
* TODO: skip threshold checking on maxReportingTime
* TODO: measure PTT for on/off commands
* TODO: calculate and store the average ping RTT
* TODO: Fingerbot: add the fingerprint
* TODO: Fingerbot: add Momentary capability
* TODO: Fingerbot: touch button (on top) enable/disable option
* TODO: aqaraModel is no saved
* TODO: Aqara devices: store NWK in states for
* TODO: Aqara TVOC: implement battery level/percentage for
* TODO: implement Get Device Info command
* TODO: continue the work on the 'device' capability (this project main goal!)
* TODO: state timesamps in human readable form
* TODO: process the min/max reporting times preferences for temperature and humidity;
* TODO: parse the details of the configuration respose - cluster, min, max, delta ...
* TODO: battery min/max voltage preferences
*/
static String version() { "2.0.6" }
static String timeStamp() {"2023/07/09 10:21 PM"}
@Field static final Boolean _DEBUG = false
import groovy.transform.Field
import hubitat.device.HubMultiAction
import hubitat.device.Protocol
import hubitat.helper.HexUtils
import hubitat.zigbee.zcl.DataType
import java.util.concurrent.ConcurrentHashMap
/*
* To switch between driver types :
* 1. Copy this code
* 2. From HE 'Drivers Code' select 'New Driver'
* 3. Paste the copied code
* 4. Comment out the previous device type and un-comment the new device type in the lines defining the:
* deviceType
* DEVICE_TYPE
* name (in the metadata definition section)
* 5. Save
*/
//deviceType = "Device"
//@Field static final String DEVICE_TYPE = "Device"
//deviceType = "AirQuality"
//@Field static final String DEVICE_TYPE = "AirQuality"
//deviceType = "Fingerbot"
//@Field static final String DEVICE_TYPE = "Fingerbot"
//deviceType = "Thermostat"
//@Field static final String DEVICE_TYPE = "Thermostat"
//deviceType = "Switch"
//@Field static final String DEVICE_TYPE = "Switch"
//deviceType = "Dimmer"
//@Field static final String DEVICE_TYPE = "Dimmer"
//deviceType = "Bulb"
//@Field static final String DEVICE_TYPE = "ButtonDimmer"
//deviceType = "ButtonDimmer"
@Field static final String DEVICE_TYPE = "LightSensor"
deviceType = "LightSensor"
//@Field static final String DEVICE_TYPE = "Bulb"
//deviceType = "Relay"
//@Field static final String DEVICE_TYPE = "Relay"
//deviceType = "Plug"
//@Field static final String DEVICE_TYPE = "Plug"
//deviceType = "MotionSensor"
//@Field static final String DEVICE_TYPE = "MotionSensor"
//deviceType = "THSensor"
//@Field static final String DEVICE_TYPE = "THSensor"
@Field static final Boolean _THREE_STATE = true
metadata {
definition (
//name: 'Tuya Zigbee Device',
//name: 'VINDSTYRKA Air Quality Monitor',
//name: 'Aqara TVOC Air Quality Monitor',
//name: 'Tuya Zigbee Fingerbot',
//name: 'Aqara E1 Thermostat',
//name: 'Tuya Zigbee Switch',
//name: 'Tuya Zigbee Dimmer',
//name: 'Tuya Zigbee Button Dimmer',
name: 'Tuya Zigbee Light Sensor',
//name: 'Tuya Zigbee Bulb',
//name: 'Tuya Zigbee Relay',
//name: 'Tuya Zigbee Plug V2',
//importUrl: 'https://raw.githubusercontent.com/kkossev/Hubitat/development/Drivers/Tuya%20Zigbee%20Device%20Driver/Tuya%20Zigbee%20Device.groovy',
//importUrl: 'https://raw.githubusercontent.com/kkossev/Hubitat/development/Drivers/Tuya%20Device%20Driver/VINDSTYRKA%20Air%20Quality%20Monitor.groovy',
//importUrl: 'https://raw.githubusercontent.com/kkossev/Hubitat/development/Drivers/Aqara%20TVOC%20Air%20Quality%20Monitor/Aqara%20TVOC%20Air%20Quality%20Monitor.groovy',
//importUrl: 'https://raw.githubusercontent.com/kkossev/Hubitat/development/Drivers/Tuya%20Zigbee%20Fingerbot/Tuya%20Zigbee%20Fingerbot.groovy',
//importUrl: 'https://raw.githubusercontent.com/kkossev/Hubitat/development/Drivers/Aqara%20E1%20Thermostat/Aqara%20E1%20Thermostat.groovy',
//importUrl: 'https://raw.githubusercontent.com/kkossev/Hubitat/development/Drivers/Tuya%20Zigbee%20Plug/Tuya%20Zigbee%20Plug%20V2.groovy',
//importUrl: 'https://raw.githubusercontent.com/kkossev/Hubitat/development/Drivers/Tuya%20Zigbee%20Switch/Tuya%20Zigbee%20Switch.groovy',
//importUrl: 'https://raw.githubusercontent.com/kkossev/Hubitat/development/Drivers/Tuya%20Zigbee%20Dimmer/Tuya%20Zigbee%20Dimmer.groovy',
//importUrl: 'https://raw.githubusercontent.com/kkossev/Hubitat/development/Drivers/Tuya%20TS004F/Tuya%20Zigbee%20Button%20Dimmer.groovy',
importUrl: 'https://raw.githubusercontent.com/kkossev/Hubitat/development/Drivers/Tuya%20Zigbee%20Light%20Sensor/Tuya%20Zigbee%20Light%20Sensor.groovy',
namespace: 'kkossev', author: 'Krassimir Kossev', singleThreaded: true )
{
if (_DEBUG) {
command 'test', [[name: "test", type: "STRING", description: "test", defaultValue : ""]]
command 'parseTest', [[name: "parseTest", type: "STRING", description: "parseTest", defaultValue : ""]]
command "tuyaTest", [
[name:"dpCommand", type: "STRING", description: "Tuya DP Command", constraints: ["STRING"]],
[name:"dpValue", type: "STRING", description: "Tuya DP value", constraints: ["STRING"]],
[name:"dpType", type: "ENUM", constraints: ["DP_TYPE_VALUE", "DP_TYPE_BOOL", "DP_TYPE_ENUM"], description: "DP data type"]
]
}
// common capabilities for all device types
capability 'Configuration'
capability 'Refresh'
capability 'Health Check'
// common attributes for all device types
attribute 'healthStatus', 'enum', ['unknown', 'offline', 'online']
attribute "rtt", "number"
attribute "Info", "string"
// common commands for all device types
// removed from version 2.0.6 //command "initialize", [[name: "Manually initialize the device after switching drivers. \n\r ***** Will load device default values! *****"]] // do NOT declare Initialize capability!
command "configure", [[name:"normally it is not needed to configure anything", type: "ENUM", constraints: ["--- select ---"]+ConfigureOpts.keySet() as List<String>]]
// deviceType specific capabilities, commands and attributes
if (deviceType in ["Device"]) {
if (_DEBUG) {
command "getAllProperties", [[name: "Get All Properties"]]
}
}
if (_DEBUG || (deviceType in ["Dimmer", "ButtonDimmer", "Switch", "Valve"])) {
command "zigbeeGroups", [
[name:"command", type: "ENUM", constraints: ZigbeeGroupsOpts.options.values() as List<String>],
[name:"value", type: "STRING", description: "Tuya DP value", constraints: ["STRING"]]
]
}
if (deviceType in ["Device", "THSensor", "MotionSensor", "LightSensor", "AirQuality", "Thermostat"]) {
capability "Sensor"
}
if (deviceType in ["Device", "Switch", "Relay", "Plug", "Outlet", "Thermostat", "Fingerbot", "Dimmer", "Bulb"]) {
capability "Actuator"
}
if (deviceType in ["Device", "THSensor", "LightSensor", "MotionSensor", "AirQuality", "Thermostat", "Fingerbot", "ButtonDimmer"]) {
capability "Battery"
attribute "batteryVoltage", "number"
}
if (deviceType in ["Thermostat"]) {
capability "ThermostatHeatingSetpoint"
}
if (deviceType in ["Plug", "Outlet"]) {
capability "Outlet"
}
if (deviceType in ["Device", "Switch", "Plug", "Outlet", "Dimmer", "Fingerbot"]) {
capability "Switch"
if (_THREE_STATE == true) {
attribute "switch", "enum", SwitchThreeStateOpts.options.values() as List<String>
}
}
if (deviceType in ["Dimmer", "ButtonDimmer"]) {
capability "SwitchLevel"
//command "switchLevelCommand"
//attribute "switchAttribute", "number"
}
if (deviceType in ["Button", "ButtonDimmer"]) {
capability "PushableButton"
capability "DoubleTapableButton"
capability "HoldableButton"
capability "ReleasableButton"
}
if (deviceType in ["ButtonDimmer"]) {
attribute "switchMode", "enum", SwitchModeOpts.options.values() as List<String> // ["dimmer", "scene"]
command "switchMode", [[name: "mode*", type: "ENUM", constraints: ["--- select ---"] + SwitchModeOpts.options.values() as List<String>, description: "Select device mode"]]
}
if (deviceType in ["Device", "THSensor", "AirQuality", "Thermostat"]) {
capability "TemperatureMeasurement"
}
if (deviceType in ["Device", "THSensor", "AirQuality"]) {
capability "RelativeHumidityMeasurement"
}
if (deviceType in ["Device", "LightSensor"]) {
capability "IlluminanceMeasurement"
}
if (deviceType in ["AirQuality"]) {
capability "AirQuality" // Attributes: airQualityIndex - NUMBER, range:0..500
attribute "pm25", "number"
attribute "airQualityLevel", "enum", ["Good","Moderate","Unhealthy for Sensitive Groups","Unhealthy","Very Unhealthy","Hazardous"] // https://www.airnow.gov/aqi/aqi-basics/
}
if (deviceType in ["Fingerbot"]) {
attribute "fingerbotMode", "enum", FingerbotModeOpts.options.values() as List<String>
attribute "direction", "enum", FingerbotDirectionOpts.options.values() as List<String>
attribute "pushTime", "number"
attribute "dnPosition", "number"
attribute "upPosition", "number"
}
// trap for Hubitat F2 bug
fingerprint profileId:"0104", endpointId:"F2", inClusters:"", outClusters:"", model:"unknown", manufacturer:"unknown", deviceJoinName: "Zigbee device affected by Hubitat F2 bug"
if (deviceType in ["AirQuality"]) {
fingerprint profileId:"0104", endpointId:"01", inClusters:"0000,0003,0004,0402,0405,FC57,FC7C,042A,FC7E", outClusters:"0003,0019,0020,0202", model:"VINDSTYRKA", manufacturer:"IKEA of Sweden", deviceJoinName: "VINDSTYRKA Air Quality Monitor E2112"
fingerprint profileId:"0104", endpointId:"01", inClusters:"0000,0003,0500,0001", outClusters:"0019", model:"lumi.airmonitor.acn01", manufacturer:"LUMI", deviceJoinName: "Aqara TVOC Air Quality Monitor"
}
if (deviceType in ["Thermostat"]) {
fingerprint profileId:"0104", endpointId:"01", inClusters:"0000,0001,0003,FCC0,000A,0201", outClusters:"0003,FCC0,0201", model:"lumi.airrtc.agl001", manufacturer:"LUMI", deviceJoinName: "Aqara E1 Thermostat" // model: 'SRTS-A01'
}
if (deviceType in ["LightSensor"]) {
fingerprint profileId:"0104", endpointId:"01", inClusters:"0000,0400,0001,0500", outClusters:"0019,000A", model:"TS0222", manufacturer:"_TYZB01_4mdqxxnn", deviceJoinName: "Tuya Illuminance Sensor TS0222"
fingerprint profileId:"0104", endpointId:"01", inClusters:"0004,0005,EF00,0000", outClusters:"0019,000A", model:"TS0601", manufacturer:"_TZE200_khx7nnka", deviceJoinName: "Tuya Illuminance Sensor TS0601"
fingerprint profileId:"0104", endpointId:"01", inClusters:"0004,0005,EF00,0000", outClusters:"0019,000A", model:"TS0601", manufacturer:"_TZE200_yi4jtqq1", deviceJoinName: "Tuya Illuminance Sensor TS0601"
}
if (deviceType in ["ButtonDimmer"]) {
fingerprint profileId:"0104", endpointId:"01", inClusters:"0000,0001,0003,0004,0006,1000", outClusters:"0019,000A,0003,0004,0005,0006,0008,1000", model:"TS004F", manufacturer:"_TZ3000_xxxxxxxx", deviceJoinName: "Tuya Scene Switch TS004F"
fingerprint profileId:"0104", endpointId:"01", inClusters:"0001,0003,0004,0006,1000,0000", outClusters:"0003,0004,0005,0006,0008,1000,0019,000A", model:"TS004F", manufacturer:"_TZ3000_xxxxxxxx", deviceJoinName: "Tuya Smart Knob TS004F" //KK
fingerprint profileId:"0104", endpointId:"01", inClusters:"0000,0001,0003,0004,0006,1000,E001", outClusters:"0019,000A,0003,0004,0006,0008,1000", model: "TS004F", manufacturer: "_TZ3000_xxxxxxxx", deviceJoinName: "MOES Smart Button (ZT-SY-SR-MS)" // MOES ZigBee IP55 Waterproof Smart Button Scene Switch & Wireless Remote Dimmer (ZT-SY-SR-MS)
fingerprint profileId:"0104", endpointId:"01", inClusters:"0000,0001,0006", outClusters:"0019,000A", model:"TS0044", manufacturer:"_TZ3000_xxxxxxxx", deviceJoinName: "Zemismart Wireless Scene Switch"
fingerprint profileId:"0104", endpointId:"01", inClusters:"0000,000A,0001,0006", outClusters: "0019", model: "TS0044", manufacturer: "_TZ3000_xxxxxxxx", deviceJoinName: "Zemismart 4 Button Remote (ESW-0ZAA-EU)" // needs debouncing
fingerprint profileId:"0104", endpointId:"01", inClusters:"0001,0006,E000,0000", outClusters: "0019,000A", model: "TS0044", manufacturer: "_TZ3000_xxxxxxxx", deviceJoinName: "Moes 4 button controller" // https://community.hubitat.com/t/release-tuya-scene-switch-ts004f-driver/92823/75?u=kkossev
}
}
preferences {
input name: 'txtEnable', type: 'bool', title: '<b>Enable descriptionText logging</b>', defaultValue: true, description: \
'<i>Enables command logging.</i>'
input name: 'logEnable', type: 'bool', title: '<b>Enable debug logging</b>', defaultValue: true, description: \
'<i>Turns on debug logging for 24 hours.</i>'
if (deviceType in ["AirQuality"]) {
if (isVINDSTIRKA()) {
input name: 'airQualityIndexCheckInterval', type: 'enum', title: '<b>Air Quality Index check interval</b>', options: AirQualityIndexCheckIntervalOpts.options, defaultValue: AirQualityIndexCheckIntervalOpts.defaultValue, required: true, description: \
'<i>Changes how often the hub retreives the Air Quality Index.</i>'
}
else if (isAqaraTRV()) {
input name: 'temperatureScale', type: 'enum', title: '<b>Temperaure Scale on the Screen</b>', options: TemperatureScaleOpts.options, defaultValue: TemperatureScaleOpts.defaultValue, required: true, description: \
'<i>Changes the temperature scale (Celsius, Fahrenheit) on the screen.</i>'
input name: 'tVocUnut', type: 'enum', title: '<b>tVOC unit on the Screen</b>', options: TvocUnitOpts.options, defaultValue: TvocUnitOpts.defaultValue, required: true, description: \
'<i>Changes the tVOC unit (mg/m³, ppb) on the screen.</i>'
}
}
if (deviceType in ["Fingerbot"]) {
input name: 'fingerbotMode', type: 'enum', title: '<b>Fingerbot Mode</b>', options: FingerbotModeOpts.options, defaultValue: FingerbotModeOpts.defaultValue, required: true, description: \
'<i>Push or Switch.</i>'
input name: 'direction', type: 'enum', title: '<b>Fingerbot Direction</b>', options: FingerbotDirectionOpts.options, defaultValue: FingerbotDirectionOpts.defaultValue, required: true, description: \
'<i>Finger movement direction.</i>'
input name: 'pushTime', type: 'number', title: '<b>Push Time</b>', description: '<i>The time that the finger will stay in down position in Push mode, seconds</i>', required: true, range: "0..255", defaultValue: 0
input name: 'upPosition', type: 'number', title: '<b>Up Postition</b>', description: '<i>Finger up position, (0..50), percent</i>', required: true, range: "0..50", defaultValue: 0
input name: 'dnPosition', type: 'number', title: '<b>Down Postition</b>', description: '<i>Finger down position (51..100), percent</i>', required: true, range: "51..100", defaultValue: 100
}
if (advancedOptions == true || advancedOptions == false) { // groovy ...
if (device.hasCapability("IlluminanceMeasurement")) {
input name: "minReportingTime", type: "number", title: "<b>Minimum time between reports</b>", description: "<i>Minimum reporting interval, seconds (1..300)</i>", range: "1..300", defaultValue: DEFAULT_MIN_REPORTING_TIME
input name: "maxReportingTime", type: "number", title: "<b>Maximum time between reports</b>", description: "<i>Maximum reporting interval, seconds (120..10000)</i>", range: "120..10000", defaultValue: DEFAULT_MAX_REPORTING_TIME
}
if (device.hasCapability("IlluminanceMeasurement")) {
input name: "illuminanceThreshold", type: "number", title: "<b>Illuminance Reporting Threshold</b>", description: "<i>Illuminance reporting threshold, range (1..255)<br>Bigger values will result in less frequent reporting</i>", range: "1..255", defaultValue: DEFAULT_ILLUMINANCE_THRESHOLD
input name: "illuminanceCoeff", type: "decimal", title: "<b>Illuminance Correction Coefficient</b>", description: "<i>Illuminance correction coefficient, range (0.10..10.00)</i>", range: "0.10..10.00", defaultValue: 1.00
}
}
input name: 'advancedOptions', type: 'bool', title: '<b>Advanced Options</b>', description: "<i>These advanced options should be already automatically set in an optimal way for your device...</i>", defaultValue: false
if (advancedOptions == true || advancedOptions == true) {
input name: 'healthCheckMethod', type: 'enum', title: '<b>Healthcheck Method</b>', options: HealthcheckMethodOpts.options, defaultValue: HealthcheckMethodOpts.defaultValue, required: true, description: \
'<i>Method to check device online/offline status.</i>'
//if (healthCheckMethod != null && safeToInt(healthCheckMethod.value) != 0) {
input name: 'healthCheckInterval', type: 'enum', title: '<b>Healthcheck Interval</b>', options: HealthcheckIntervalOpts.options, defaultValue: HealthcheckIntervalOpts.defaultValue, required: true, description: \
'<i>How often the hub will check the device health.<br>3 consecutive failures will result in status "offline"</i>'
//}
if (device.hasCapability("Battery")) {
input name: 'voltageToPercent', type: 'bool', title: '<b>Battery Voltage to Percentage</b>', defaultValue: false, description: '<i>Convert battery voltage to battery Percentage remaining.</i>'
}
if ((deviceType in ["Switch", "Plug", "Dimmer"]) && _THREE_STATE == true) {
input name: 'threeStateEnable', type: 'bool', title: '<b>Enable three-states events</b>', description: '<i>What\'s wrong with the three-state concept?</i>', defaultValue: false
}
if (deviceType in ["Button", "ButtonDimmer"]) {
input name: "reverseButton", type: "bool", title: "<b>Reverse button order</b>", defaultValue: true, description: '<i>Switches button order </i>'
input name: 'debounce', type: 'enum', title: '<b>Debouncing</b>', options: DebounceOpts.options, defaultValue: DebounceOpts.defaultValue, required: true, description: '<i>Debouncing options.</i>'
}
}
}
}
@Field static final Integer DIGITAL_TIMER = 1000 // command was sent by this driver
@Field static final Integer REFRESH_TIMER = 5000 // refresh time in miliseconds
@Field static final Integer DEBOUNCING_TIMER = 300 // ignore switch events
@Field static final Integer COMMAND_TIMEOUT = 10 // timeout time in seconds
@Field static final Integer MAX_PING_MILISECONDS = 10000 // rtt more than 10 seconds will be ignored
@Field static final String UNKNOWN = "UNKNOWN"
@Field static final Integer DEFAULT_MIN_REPORTING_TIME = 10 // send the report event no more often than 10 seconds by default
@Field static final Integer DEFAULT_MAX_REPORTING_TIME = 3600
@Field static final Integer PRESENCE_COUNT_THRESHOLD = 3 // missing 3 checks will set the device healthStatus to offline
@Field static final int DELAY_MS = 200 // Delay in between zigbee commands
@Field static final Integer DEFAULT_ILLUMINANCE_THRESHOLD = 5
@Field static final Map HealthcheckMethodOpts = [ // used by healthCheckMethod
defaultValue: 1,
options : [0: 'Disabled', 1: 'Activity check', 2: 'Periodic polling']
]
@Field static final Map HealthcheckIntervalOpts = [ // used by healthCheckInterval
defaultValue: 240,
options : [10: 'Every 10 Mins', 30: 'Every 30 Mins', 60: 'Every 1 Hour', 240: 'Every 4 Hours', 720: 'Every 12 Hours']
]
@Field static final Map TemperatureScaleOpts = [ // bit 7
defaultValue: 0,
options : [0: 'Celsius', 1: 'Fahrenheit']
]
@Field static final Map TvocUnitOpts = [ // bit 0
defaultValue: 1,
options : [0: 'mg/m³', 1: 'ppb']
]
@Field static final Map FingerbotModeOpts = [
defaultValue: 0,
options : [0: 'push', 1: 'switch']
]
@Field static final Map FingerbotDirectionOpts = [
defaultValue: 0,
options : [0: 'normal', 1: 'reverse']
]
@Field static final Map SwitchThreeStateOpts = [
defaultValue: 0,
options : [0: 'off', 1: 'on', 2: 'switching_off', 3: 'switching_on', 4: 'switch_failure']
]
@Field static final Map DebounceOpts = [
defaultValue: 1000,
options : [0: 'disabled', 800: '0.8 seconds', 1000: '1.0 seconds', 1200: '1.2 seconds', 1500: '1.5 seconds', 2000: '2.0 seconds',]
]
@Field static final Map ZigbeeGroupsOptsDebug = [
defaultValue: 0,
options : [99: '--- select ---', 0: 'Add group', 1: 'View group', 2: 'Get group membership', 3: 'Remove group', 4: 'Remove all groups', 5: 'Add group if identifying']
]
@Field static final Map ZigbeeGroupsOpts = [
defaultValue: 0,
options : [99: '--- select ---', 0: 'Add group', 2: 'Get group membership', 3: 'Remove group', 4: 'Remove all groups']
]
/*
@Field static final Map ConfigureOpts = [
defaultValue: 0,
options : [0: 'LOAD ALL DEFAULTS', 1: 'Configure the device only', 2: 'Delete All Preferences', 3: 'Delete All Current States', 4:'Delete All Scheduled Jobs',\
5:'Delete All State Variables', 6:'Delete All Child Devices']
]
*/
@Field static final Map SwitchModeOpts = [
defaultValue: 1,
options : [0: 'dimmer', 1: 'scene']
]
def isChattyDeviceReport(description) {return false /*(description?.contains("cluster: FC7E")) */}
def isVINDSTIRKA() { (device?.getDataValue('model') ?: 'n/a') in ['VINDSTYRKA'] }
def isAqaraTVOC() { (device?.getDataValue('model') ?: 'n/a') in ['lumi.airmonitor.acn01'] }
def isAqaraTRV() { (device?.getDataValue('model') ?: 'n/a') in ['lumi.airrtc.agl001'] }
def isAqaraFP1() { (device?.getDataValue('model') ?: 'n/a') in ['lumi.motion.ac01'] }
def isFingerbot() { (device?.getDataValue('manufacturer') ?: 'n/a') in ['_TZ3210_dse8ogfy'] }
/**
* Parse Zigbee message
* @param description Zigbee message in hex format
*/
void parse(final String description) {
checkDriverVersion()
if (!isChattyDeviceReport(description)) { logDebug "parse: ${description}" }
if (state.stats != null) state.stats['rxCtr'] = (state.stats['rxCtr'] ?: 0) + 1 else state.stats=[:]
unschedule('deviceCommandTimeout')
setHealthStatusOnline()
final Map descMap = zigbee.parseDescriptionAsMap(description)
if (descMap.profileId == '0000') {
parseZdoClusters(descMap)
return
}
if (descMap.isClusterSpecific == false) {
parseGeneralCommandResponse(descMap)
return
}
if (!isChattyDeviceReport(description)) {logDebug "descMap = ${descMap}"}
//
final String clusterName = clusterLookup(descMap.clusterInt)
final String attribute = descMap.attrId ? " attribute 0x${descMap.attrId} (value ${descMap.value})" : ''
//if (settings.logEnable) { log.trace "zigbee received ${clusterName} message" + attribute }
switch (descMap.clusterInt as Integer) {
case zigbee.BASIC_CLUSTER: // 0x0000
parseBasicCluster(descMap)
descMap.remove('additionalAttrs')?.each { final Map map -> parseBasicCluster(descMap + map) }
break
case zigbee.POWER_CONFIGURATION_CLUSTER: // 0x0001
parsePowerCluster(descMap)
descMap.remove('additionalAttrs')?.each { final Map map -> parsePowerCluster(descMap + map) }
break
case zigbee.GROUPS_CLUSTER:
parseGroupsCluster(descMap)
descMap.remove('additionalAttrs')?.each {final Map map -> parseGroupsCluster(descMap + map) }
break
case zigbee.ON_OFF_CLUSTER: // 0x0006
parseOnOffCluster(descMap)
descMap.remove('additionalAttrs')?.each { final Map map -> parseOnOffCluster(descMap + map) }
break
case zigbee.LEVEL_CONTROL_CLUSTER: // 0x0008
parseLevelControlCluster(descMap)
descMap.remove('additionalAttrs')?.each { final Map map -> parseLevelControlCluster(descMap + map) }
break
case 0x000C : // Aqara TVOC Air Monitor
parseAirQualityIndexCluster(descMap)
break
case 0x0201 : // Aqara E1 TRV
parseThermostatCluster(descMap)
descMap.remove('additionalAttrs')?.each { final Map map -> parseThermostatCluster(descMap + map) }
break
case zigbee.ILLUMINANCE_MEASUREMENT_CLUSTER : //0x0400
parseIlluminanceCluster(descMap)
descMap.remove('additionalAttrs')?.each { final Map map -> parseIlluminanceCluster(descMap + map) }
//log.warn "${clusterName} (${(descMap.clusterInt as Integer)}) parser not implemented yet!"
break
case zigbee.TEMPERATURE_MEASUREMENT_CLUSTER : //0x0402
parseTemperatureCluster(descMap)
break
case zigbee.RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER : //0x0405
parseHumidityCluster(descMap)
break
case 0x042A : // pm2.5
parsePm25Cluster(descMap)
break
case zigbee.ELECTRICAL_MEASUREMENT_CLUSTER:
parseElectricalMeasureCluster(descMap)
descMap.remove('additionalAttrs')?.each { final Map map -> parseElectricalMeasureCluster(descMap + map) }
break
case zigbee.METERING_CLUSTER:
parseMeteringCluster(descMap)
descMap.remove('additionalAttrs')?.each { final Map map -> parseMeteringCluster(descMap + map) }
break
case 0xEF00 : // Tuya famous cluster
parseTuyaCluster(descMap)
descMap.remove('additionalAttrs')?.each { final Map map -> parseTuyaCluster(descMap + map) }
break
case 0xfc7e : // tVOC 'Sensirion VOC index' https://sensirion.com/media/documents/02232963/6294E043/Info_Note_VOC_Index.pdf
parseAirQualityIndexCluster(descMap)
break
case XIAOMI_CLUSTER_ID : // 0xFCC0 Xiaomi cluster
parseXiaomiCluster(descMap)
descMap.remove('additionalAttrs')?.each { final Map m -> parseXiaomiCluster(descMap + m) }
break
default:
if (settings.logEnable) {
logWarn "zigbee received unknown message cluster: ${descMap}"
}
break
}
}
/**
* ZDO (Zigbee Data Object) Clusters Parsing
* @param descMap Zigbee message in parsed map format
*/
void parseZdoClusters(final Map descMap) {
final Integer clusterId = descMap.clusterInt as Integer
final String clusterName = ZdoClusterEnum[clusterId] ?: "UNKNOWN_CLUSTER (0x${descMap.clusterId})"
final String statusHex = ((List)descMap.data)[1]
final Integer statusCode = hexStrToUnsignedInt(statusHex)
final String statusName = ZigbeeStatusEnum[statusCode] ?: "0x${statusHex}"
if (statusCode > 0x00) {
logWarn "zigbee received device object ${clusterName} error: ${statusName}"
}
else {
logDebug "zigbee received device object ${clusterName} success: ${descMap.data}"
}
}
/**
* Zigbee General Command Parsing
* @param descMap Zigbee message in parsed map format
*/
void parseGeneralCommandResponse(final Map descMap) {
final int commandId = hexStrToUnsignedInt(descMap.command)
switch (commandId) {
case 0x01: // read attribute response
parseReadAttributeResponse(descMap)
break
case 0x04: // write attribute response
parseWriteAttributeResponse(descMap)
break
case 0x07: // configure reporting response
parseConfigureResponse(descMap)
break
case 0x09: // read reporting configuration response
parseReadReportingConfigResponse(descMap)
break
case 0x0B: // default command response
parseDefaultCommandResponse(descMap)
break
default:
final String commandName = ZigbeeGeneralCommandEnum[commandId] ?: "UNKNOWN_COMMAND (0x${descMap.command})"
final String clusterName = clusterLookup(descMap.clusterInt)
final String status = descMap.data in List ? ((List)descMap.data).last() : descMap.data
final int statusCode = hexStrToUnsignedInt(status)
final String statusName = ZigbeeStatusEnum[statusCode] ?: "0x${status}"
if (statusCode > 0x00) {
log.warn "zigbee ${commandName} ${clusterName} error: ${statusName}"
} else if (settings.logEnable) {
log.trace "zigbee ${commandName} ${clusterName}: ${descMap.data}"
}
break
}
}
/**
* Zigbee Read Attribute Response Parsing
* @param descMap Zigbee message in parsed map format
*/
void parseReadAttributeResponse(final Map descMap) {
final List<String> data = descMap.data as List<String>
final String attribute = data[1] + data[0]
final int statusCode = hexStrToUnsignedInt(data[2])
final String status = ZigbeeStatusEnum[statusCode] ?: "0x${data}"
if (statusCode > 0x00) {
logWarn "zigbee read ${clusterLookup(descMap.clusterInt)} attribute 0x${attribute} error: ${status}"
}
else {
logDebug "zigbee read ${clusterLookup(descMap.clusterInt)} attribute 0x${attribute} response: ${status} ${data}"
}
}
/**
* Zigbee Write Attribute Response Parsing
* @param descMap Zigbee message in parsed map format
*/
void parseWriteAttributeResponse(final Map descMap) {
final String data = descMap.data in List ? ((List)descMap.data).first() : descMap.data
final int statusCode = hexStrToUnsignedInt(data)
final String statusName = ZigbeeStatusEnum[statusCode] ?: "0x${data}"
if (statusCode > 0x00) {
logWarn "zigbee response write ${clusterLookup(descMap.clusterInt)} attribute error: ${statusName}"
}
else {
logDebug "zigbee response write ${clusterLookup(descMap.clusterInt)} attribute response: ${statusName}"
}
}
/**
* Zigbee Configure Reporting Response Parsing
* @param descMap Zigbee message in parsed map format
*/
void parseConfigureResponse(final Map descMap) {
// TODO - parse the details of the configuration respose - cluster, min, max, delta ...
final String status = ((List)descMap.data).first()
final int statusCode = hexStrToUnsignedInt(status)
if (statusCode == 0x00 && settings.enableReporting != false) {
state.reportingEnabled = true
}
final String statusName = ZigbeeStatusEnum[statusCode] ?: "0x${status}"
if (statusCode > 0x00) {
log.warn "zigbee configure reporting error: ${statusName} ${descMap.data}"
} else {
logDebug "zigbee configure reporting response: ${statusName} ${descMap.data}"
}
}
/**
* Zigbee Default Command Response Parsing
* @param descMap Zigbee message in parsed map format
*/
void parseDefaultCommandResponse(final Map descMap) {
final List<String> data = descMap.data as List<String>
final String commandId = data[0]
final int statusCode = hexStrToUnsignedInt(data[1])
final String status = ZigbeeStatusEnum[statusCode] ?: "0x${data[1]}"
if (statusCode > 0x00) {
logWarn "zigbee ${clusterLookup(descMap.clusterInt)} command 0x${commandId} error: ${status}"
} else {
logDebug "zigbee ${clusterLookup(descMap.clusterInt)} command 0x${commandId} response: ${status}"
}
}
// Zigbee Attribute IDs
@Field static final int AC_CURRENT_DIVISOR_ID = 0x0603
@Field static final int AC_CURRENT_MULTIPLIER_ID = 0x0602
@Field static final int AC_FREQUENCY_ID = 0x0300
@Field static final int AC_POWER_DIVISOR_ID = 0x0605
@Field static final int AC_POWER_MULTIPLIER_ID = 0x0604
@Field static final int AC_VOLTAGE_DIVISOR_ID = 0x0601
@Field static final int AC_VOLTAGE_MULTIPLIER_ID = 0x0600
@Field static final int ACTIVE_POWER_ID = 0x050B
@Field static final int ATTRIBUTE_READING_INFO_SET = 0x0000
@Field static final int FIRMWARE_VERSION_ID = 0x4000
@Field static final int PING_ATTR_ID = 0x01
@Field static final int POWER_ON_OFF_ID = 0x0000
@Field static final int POWER_RESTORE_ID = 0x4003
@Field static final int RMS_CURRENT_ID = 0x0508
@Field static final int RMS_VOLTAGE_ID = 0x0505
@Field static final Map<Integer, String> ZigbeeStatusEnum = [
0x00: 'Success',
0x01: 'Failure',
0x02: 'Not Authorized',
0x80: 'Malformed Command',
0x81: 'Unsupported COMMAND',
0x85: 'Invalid Field',
0x86: 'Unsupported Attribute',
0x87: 'Invalid Value',
0x88: 'Read Only',
0x89: 'Insufficient Space',
0x8A: 'Duplicate Exists',
0x8B: 'Not Found',
0x8C: 'Unreportable Attribute',
0x8D: 'Invalid Data Type',
0x8E: 'Invalid Selector',
0x94: 'Time out',
0x9A: 'Notification Pending',
0xC3: 'Unsupported Cluster'
]
@Field static final Map<Integer, String> ZdoClusterEnum = [
0x0013: 'Device announce',
0x8004: 'Simple Descriptor Response',
0x8005: 'Active Endpoints Response',
0x801D: 'Extended Simple Descriptor Response',
0x801E: 'Extended Active Endpoint Response',
0x8021: 'Bind Response',
0x8022: 'Unbind Response',
0x8023: 'Bind Register Response',
]
@Field static final Map<Integer, String> ZigbeeGeneralCommandEnum = [
0x00: 'Read Attributes',
0x01: 'Read Attributes Response',
0x02: 'Write Attributes',
0x03: 'Write Attributes Undivided',
0x04: 'Write Attributes Response',
0x05: 'Write Attributes No Response',
0x06: 'Configure Reporting',
0x07: 'Configure Reporting Response',
0x08: 'Read Reporting Configuration',
0x09: 'Read Reporting Configuration Response',
0x0A: 'Report Attributes',
0x0B: 'Default Response',
0x0C: 'Discover Attributes',
0x0D: 'Discover Attributes Response',
0x0E: 'Read Attributes Structured',
0x0F: 'Write Attributes Structured',
0x10: 'Write Attributes Structured Response',
0x11: 'Discover Commands Received',
0x12: 'Discover Commands Received Response',
0x13: 'Discover Commands Generated',
0x14: 'Discover Commands Generated Response',
0x15: 'Discover Attributes Extended',
0x16: 'Discover Attributes Extended Response'
]
/*
* -----------------------------------------------------------------------------
* Xiaomi cluster 0xFCC0 parser.
* -----------------------------------------------------------------------------
*/
@Field static final int XIAOMI_CLUSTER_ID = 0xFCC0
// Zigbee Attributes
@Field static final int DIRECTION_MODE_ATTR_ID = 0x0144
@Field static final int MODEL_ATTR_ID = 0x05
@Field static final int PRESENCE_ACTIONS_ATTR_ID = 0x0143
@Field static final int PRESENCE_ATTR_ID = 0x0142
@Field static final int REGION_EVENT_ATTR_ID = 0x0151
@Field static final int RESET_PRESENCE_ATTR_ID = 0x0157
@Field static final int SENSITIVITY_LEVEL_ATTR_ID = 0x010C
@Field static final int SET_EDGE_REGION_ATTR_ID = 0x0156
@Field static final int SET_EXIT_REGION_ATTR_ID = 0x0153
@Field static final int SET_INTERFERENCE_ATTR_ID = 0x0154
@Field static final int SET_REGION_ATTR_ID = 0x0150
@Field static final int TRIGGER_DISTANCE_ATTR_ID = 0x0146
@Field static final int XIAOMI_RAW_ATTR_ID = 0xFFF2
@Field static final int XIAOMI_SPECIAL_REPORT_ID = 0x00F7
@Field static final Map MFG_CODE = [ mfgCode: 0x115F ]
// Xiaomi Tags
@Field static final int DIRECTION_MODE_TAG_ID = 0x67
@Field static final int SENSITIVITY_LEVEL_TAG_ID = 0x66
@Field static final int SWBUILD_TAG_ID = 0x08
@Field static final int TRIGGER_DISTANCE_TAG_ID = 0x69
@Field static final int PRESENCE_ACTIONS_TAG_ID = 0x66
@Field static final int PRESENCE_TAG_ID = 0x65
void parseXiaomiCluster(final Map descMap) {
if (settings.logEnable) {
log.trace "zigbee received xiaomi cluster attribute 0x${descMap.attrId} (value ${descMap.value})"
}
switch (descMap.attrInt as Integer) {
case 0x00FC: // FP1
log.info "unknown attribute - resetting?"
break
case PRESENCE_ATTR_ID: // FP1
final Integer value = hexStrToUnsignedInt(descMap.value)
parseXiaomiClusterPresence(value)
break
case PRESENCE_ACTIONS_ATTR_ID: // FP1
final Integer value = hexStrToUnsignedInt(descMap.value)
parseXiaomiClusterPresenceAction(value)
break
case REGION_EVENT_ATTR_ID: // FP1
// Region events can be sent fast and furious so buffer them
final Integer regionId = HexUtils.hexStringToInt(descMap.value[0..1])
final Integer value = HexUtils.hexStringToInt(descMap.value[2..3])
if (settings.logEnable) {
log.debug "xiaomi: region ${regionId} action is ${value}"
}
if (device.currentValue("region${regionId}") != null) {
RegionUpdateBuffer.get(device.id).put(regionId, value)
runInMillis(REGION_UPDATE_DELAY_MS, 'updateRegions')
}
break
case SENSITIVITY_LEVEL_ATTR_ID: // FP1
final Integer value = hexStrToUnsignedInt(descMap.value)
log.info "sensitivity level is '${SensitivityLevelOpts.options[value]}' (0x${descMap.value})"
device.updateSetting('sensitivityLevel', [value: value.toString(), type: 'enum'])
break
case TRIGGER_DISTANCE_ATTR_ID: // FP1
final Integer value = hexStrToUnsignedInt(descMap.value)
log.info "approach distance is '${ApproachDistanceOpts.options[value]}' (0x${descMap.value})"
device.updateSetting('approachDistance', [value: value.toString(), type: 'enum'])
break
case DIRECTION_MODE_ATTR_ID: // FP1
final Integer value = hexStrToUnsignedInt(descMap.value)
log.info "monitoring direction mode is '${DirectionModeOpts.options[value]}' (0x${descMap.value})"
device.updateSetting('directionMode', [value: value.toString(), type: 'enum'])
break
case XIAOMI_SPECIAL_REPORT_ID: // sent every 5 minutes
final Map<Integer, Integer> tags = decodeXiaomiTags(descMap.value)
parseXiaomiClusterTags(tags)
break
case XIAOMI_RAW_ATTR_ID: // FP1
final byte[] rawData = HexUtils.hexStringToByteArray(descMap.value)
if (rawData.size() == 24 && settings.enableDistanceDirection) {
final int degrees = rawData[19]
final int distanceCm = (rawData[17] << 8) | (rawData[18] & 0x00ff)
if (settings.logEnable) {
log.debug "location ${degrees}°, ${distanceCm}cm"
}
runIn(1, 'updateLocation', [ data: [ degrees: degrees, distanceCm: distanceCm ] ])
}
break
case 0x0271: // result['system_mode'] = {1: 'heat', 0: 'off'}[value];
final Integer value = hexStrToUnsignedInt(descMap.value)
logInfo "system_mode raw = ${value}"
break;
case 0x0272: // result['preset'] = {2: 'away', 1: 'auto', 0: 'manual'}[value];
final Integer value = hexStrToUnsignedInt(descMap.value)
logInfo "preset raw = ${value}"
break;
case 0x0273: // result['window_detection'] = {1: 'ON', 0: 'OFF'}[value];
final Integer value = hexStrToUnsignedInt(descMap.value)
logInfo "window_detection raw = ${value}"
break;
case 0x0274: // result['valve_detection'] = {1: 'ON', 0: 'OFF'}[value];
final Integer value = hexStrToUnsignedInt(descMap.value)
logInfo "valve_detection raw = ${value}"
break;
case 0x0275: // result['valve_alarm'] = {1: true, 0: false}[value];
final Integer value = hexStrToUnsignedInt(descMap.value)
logInfo "valve_alarm raw = ${value}"
break;
case 0x0277: // result['child_lock'] = {1: 'LOCK', 0: 'UNLOCK'}[value];
final Integer value = hexStrToUnsignedInt(descMap.value)
logInfo "child_lock raw = ${value}"
break;
case 0x0279: // result['away_preset_temperature'] = (value / 100).toFixed(1);
final Integer value = hexStrToUnsignedInt(descMap.value)
logInfo "away_preset_temperature raw = ${value}"
break;
case 0x027a: // result['window_open'] = {1: true, 0: false}[value];
final Integer value = hexStrToUnsignedInt(descMap.value)
logInfo "window_open raw = ${value}"
break;
case 0x027b: // result['calibrated'] = {1: true, 0: false}[value];
final Integer value = hexStrToUnsignedInt(descMap.value)
logInfo "calibrated raw = ${value}"
break;
case 0x0276: // unknown
case 0x027c: // unknown
case 0x027d: // unknown
case 0x0280: // unknown
case 0xfff2: // unknown
case 0x00ff: // unknown
case 0x00f7: // unknown
case 0xfff2: // unknown
try {
final Integer value = hexStrToUnsignedInt(descMap.value)
logDebug "Aqara E1 TRV unknown attribute ${descMap.attrInt} value raw = ${value}"
}
catch (e) {
logWarn "exception caught while processing Aqara E1 TRV unknown attribute ${descMap.attrInt} descMap.value = ${descMap.value}"
}
break;
case 0x027e: // result['sensor'] = {1: 'external', 0: 'internal'}[value];
final Integer value = hexStrToUnsignedInt(descMap.value)
logInfo "sensor raw = ${value}"
break;
case 0x040a: // E1 battery
final Integer value = hexStrToUnsignedInt(descMap.value)
logInfo "battery raw = ${value}"
break
case 0x00FF:
// unknown
break
default:
log.warn "zigbee received unknown xiaomi cluster 0xFCC0 attribute 0x${descMap.attrId} (value ${descMap.value})"
break
}
}
void parseXiaomiClusterTags(final Map<Integer, Object> tags) {
tags.each { final Integer tag, final Object value ->
switch (tag) {
case 0x01: // battery voltage
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} battery voltage is ${value/1000}V (raw=${value})"
break
case 0x03:
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} device temperature is ${value}°"
break
case 0x05:
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} RSSI is ${value}"
break
case 0x06:
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} LQI is ${value}"
break
case 0x08: // SWBUILD_TAG_ID:
final String swBuild = '0.0.0_' + (value & 0xFF).toString().padLeft(4, '0')
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} swBuild is ${swBuild} (raw ${value})"
device.updateDataValue(aqaraVersion, swBuild)
break
case 0x0a:
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} <b>Parent NWK is ${value}</b>"
break
case 0x0b:
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} light level is ${value}"
break
case 0x64:
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} temperature is ${value/100} (raw ${value})" // Aqara TVOC
// TODO - also smoke gas/density if UINT !
break
case 0x65:
if (isAqaraFP1()) { logDebug "xiaomi decode PRESENCE_TAG_ID tag: 0x${intToHexStr(tag, 1)}=${value}" }
else { logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} humidity is ${value/100} (raw ${value})" } // Aqara TVOC
break
case 0x66:
if (isAqaraFP1()) { logDebug "xiaomi decode SENSITIVITY_LEVEL_TAG_ID tag: 0x${intToHexStr(tag, 1)}=${value}" }
else if (isAqaraTVOC()) { logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} airQualityIndex is ${value}" } // Aqara TVOC level (in ppb)
else { logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} presure is ${value}" }
break
case 0x67:
if (isAqaraFP1()) { logDebug "xiaomi decode DIRECTION_MODE_TAG_ID tag: 0x${intToHexStr(tag, 1)}=${value}" }
else { logDebug "xiaomi decode unknown tag: 0x${intToHexStr(tag, 1)}=${value}" } // Aqara TVOC:
// air quality (as 6 - #stars) ['excellent', 'good', 'moderate', 'poor', 'unhealthy'][val - 1]
break
case 0x69:
if (isAqaraFP1()) { logDebug "xiaomi decode TRIGGER_DISTANCE_TAG_ID tag: 0x${intToHexStr(tag, 1)}=${value}" }
else { logDebug "xiaomi decode unknown tag: 0x${intToHexStr(tag, 1)}=${value}" }
break
case 0x6a:
if (isAqaraFP1()) { logDebug "xiaomi decode FP1 unknown tag: 0x${intToHexStr(tag, 1)}=${value}" }
else { logDebug "xiaomi decode MOTION SENSITIVITY tag: 0x${intToHexStr(tag, 1)}=${value}" }
break
case 0x6b:
if (isAqaraFP1()) { logDebug "xiaomi decode FP1 unknown tag: 0x${intToHexStr(tag, 1)}=${value}" }
else { logDebug "xiaomi decode MOTION LED tag: 0x${intToHexStr(tag, 1)}=${value}" }
break
case 0x95:
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} energy is ${value}"
break
case 0x96:
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} voltage is ${value}"
break
case 0x97:
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} current is ${value}"
break
case 0x98:
logDebug "xiaomi decode tag: 0x${intToHexStr(tag, 1)} power is ${value}"
break
case 0x9b:
logDebug "xiaomi decode CONSUMER CONNECTED tag: 0x${intToHexStr(tag, 1)}=${value}"
break
default:
logDebug "xiaomi decode unknown tag: 0x${intToHexStr(tag, 1)}=${value}"
}
}
}
/**
* Reads a specified number of little-endian bytes from a given
* ByteArrayInputStream and returns a BigInteger.
*/
private static BigInteger readBigIntegerBytes(final ByteArrayInputStream stream, final int length) {
final byte[] byteArr = new byte[length]
stream.read(byteArr, 0, length)
BigInteger bigInt = BigInteger.ZERO
for (int i = byteArr.length - 1; i >= 0; i--) {
bigInt |= (BigInteger.valueOf((byteArr[i] & 0xFF) << (8 * i)))
}
return bigInt
}
/**
* Decodes a Xiaomi Zigbee cluster attribute payload in hexadecimal format and
* returns a map of decoded tag number and value pairs where the value is either a
* BigInteger for fixed values or a String for variable length.
*/
private static Map<Integer, Object> decodeXiaomiTags(final String hexString) {
final Map<Integer, Object> results = [:]
final byte[] bytes = HexUtils.hexStringToByteArray(hexString)
new ByteArrayInputStream(bytes).withCloseable { final stream ->
while (stream.available() > 2) {
int tag = stream.read()
int dataType = stream.read()
Object value
if (DataType.isDiscrete(dataType)) {
int length = stream.read()
byte[] byteArr = new byte[length]
stream.read(byteArr, 0, length)
value = new String(byteArr)
} else {
int length = DataType.getLength(dataType)
value = readBigIntegerBytes(stream, length)
}
results[tag] = value
}
}
return results
}
/*
* -----------------------------------------------------------------------------
* Standard clusters reporting handlers
* -----------------------------------------------------------------------------
*/
@Field static final Map powerSourceOpts = [ defaultValue: 0, options: [0: 'unknown', 1: 'mains', 2: 'mains', 3: 'battery', 4: 'dc', 5: 'emergency mains', 6: 'emergency mains']]
/**
* Zigbee Basic Cluster Parsing 0x0000
* @param descMap Zigbee message in parsed map format
*/
void parseBasicCluster(final Map descMap) {
def now = new Date().getTime()
state.lastRx["checkInTime"] = now
switch (descMap.attrInt as Integer) {
case PING_ATTR_ID: // 0x01 - Using 0x01 read as a simple ping/pong mechanism
logDebug "Tuya check-in message (attribute ${descMap.attrId} reported: ${descMap.value})"
if (state.lastTx == null) state.lastTx = [:]
def timeRunning = now.toInteger() - (state.lastTx["pingTime"] ?: '0').toInteger()
if (timeRunning > 0 && timeRunning < MAX_PING_MILISECONDS) {
sendRttEvent()
}
break
case 0x0004:
logDebug "received device manufacturer ${descMap?.value}"
break
case 0x0007:
def powerSourceReported = powerSourceOpts.options[descMap?.value as int]
logDebug "received Power source <b>${powerSourceReported}</b> (${descMap?.value})"
//powerSourceEvent( powerSourceReported )
break
case 0xFFDF:
logDebug "Tuya check-in (Cluster Revision=${descMap?.value})"
break
case 0xFFE2:
logDebug "Tuya check-in (AppVersion=${descMap?.value})"
break
case [0xFFE0, 0xFFE1, 0xFFE3, 0xFFE4] :
logDebug "Tuya unknown attribute ${descMap?.attrId} value=${descMap?.value}"
break
case 0xFFFE:
logDebug "Tuya attributeReportingStatus (attribute FFFE) value=${descMap?.value}"
break