-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMatter_Advanced_Bridge.groovy
3029 lines (2790 loc) · 155 KB
/
Matter_Advanced_Bridge.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
/* groovylint-disable CompileStatic, CouldBeSwitchStatement, DuplicateListLiteral, DuplicateMapLiteral, DuplicateNumberLiteral, DuplicateStringLiteral, ImplicitClosureParameter, ImplicitReturnStatement, InsecureRandom, LineLength, MethodCount, MethodParameterTypeRequired, MethodSize, NglParseError, NoDef, NoDouble, PublicMethodsBeforeNonPublicMethods, StaticMethodsBeforeInstanceMethods, UnnecessaryGetter, UnnecessaryObjectReferences, UnnecessarySetter */
/**
* Matter Advanced Bridge - Device Driver for Hubitat Elevation
*
* https://community.hubitat.com/t/dynamic-capabilities-commands-and-attributes-for-drivers/98342
* https://community.hubitat.com/t/project-zemismart-m1-matter-bridge-for-tuya-zigbee-devices-matter/127009
*
* 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.
*
* Thanks to Hubitat for publishing the sample Matter driver https://github.com/hubitat/HubitatPublic/blob/master/examples/drivers/thirdRealityMatterNightLight.groovy
*
* The full revisions history is available at https://github.com/kkossev/Hubitat---Matter-Advanced-Bridge/wiki/Matter-Advanced-Bridge-%E2%80%90-revisions-history
* The full TODO list is available at https://github.com/kkossev/Hubitat---Matter-Advanced-Bridge/wiki/Matter-Advanced-Bridge-%E2%80%90-TODO-list
*
* ver. 1.0.0 2024-03-16 kkossev - public release version.
* ver. 1.0.1 2024-04-13 kkossev - tests; resetStats bug fix;
* ver. 1.1.0 2024-07-20 kkossev - merged pull request from dds82 (added Matter_Generic_Component_Door_Lock); added Identify command; reduced battery attribute subscriptions;
* ver. 1.1.1 2024-07-23 kkossev - added Switch capability to the Matter Door Lock component driver.
* ver. 1.1.2 2024-07-31 kkossev - skipped General Diagnostics cluster 0x0033 discovery - Aqara M3 firmware 4.1.7_0013 returns error reading attribute 0x0000
* ver. 1.1.3 2024-08-09 kkossev - fixed sendSubsribeList() typo;
* ver. 1.2.0 2024-10-03 kkossev - [2.3.9.186] platform: cleanSubscribe; decoded events for child devices w/o the attribute defined are sent anyway; added Matter Thermostats.
* ver. 1.2.1 2024-10-05 kkossev - thermostatSetpoint attribute is also updated; Matter Events basic decoding (buttons and Locks are still NOT working!); thermostat driver automatic assignment bug fix;
* checking both 'maxHeatSetpointLimit' and 'absMaxHeatSetpointLimit' when setting the thermostatSetpoint; thermostatOperatingState is updated (digital); thermostat on() and of() commands bug fix;
* ver. 1.2.2 2024-10-11 kkossev - added 'Matter Generic Component SwitchBot Button' by @ymerj
* ver. 1.3.0 2024-10-10 kkossev - adding 'Matter Generic Component Air Purifier' (W.I.P.) : cluster 005B 'AirQuality'
* ver. 1.3.1 2024-11-12 kkossev - bugfix: nullpointer exception in discoverAllStateMachine()
* ver. 1.4.0 2024-12-26 kkossev - HE Platform 2.4.0.x compatibility update
* ver. 1.4.1 2025-01-12 kkossev - (dev.branch) restored the commands descriptions;
*
* TODO: add cluster 042A 'PM2.5ConcentrationMeasurement'
*
* TODO: add cluster 0071 'HEPAFilterMonitoring'
* TODO: add cluster 0202 'Window Covering'
* TODO: Matter events subscription - buttons and locks
* TODO: bugfix: Curtain driver exception @UncleAlias #4
*
*/
/* groovylint-disable-next-line NglParseError */
#include kkossev.matterLib
#include kkossev.matterUtilitiesLib
#include kkossev.matterStateMachinesLib
static String version() { '1.4.1' }
static String timeStamp() { '2025/01/12 10:56 PM' }
@Field static final Boolean _DEBUG = false
@Field static final String DRIVER_NAME = 'Matter Advanced Bridge'
@Field static final String COMM_LINK = 'https://community.hubitat.com/t/release-matter-advanced-bridge-limited-device-support/135252'
@Field static final String GITHUB_LINK = 'https://github.com/kkossev/Hubitat---Matter-Advanced-Bridge/wiki'
@Field static final String IMPORT_URL = 'https://raw.githubusercontent.com/kkossev/Hubitat---Matter-Advanced-Bridge/main/Matter_Advanced_Bridge.groovy'
@Field static final Boolean DEFAULT_LOG_ENABLE = false
@Field static final Boolean DO_NOT_TRACE_FFFX = true // don't trace the FFFx global attributes
@Field static final Boolean MINIMIZE_STATE_VARIABLES_DEFAULT = true // minimize the state variables
@Field static final String DEVICE_TYPE = 'MATTER_BRIDGE'
@Field static final Boolean STATE_CACHING = false // enable/disable state caching
@Field static final Integer CACHING_TIMER = 60 // state caching time in seconds
@Field static final Integer DIGITAL_TIMER = 3000 // command was sent by this driver
@Field static final Integer REFRESH_TIMER = 6000 // refresh time in miliseconds
@Field static final Integer INFO_AUTO_CLEAR_PERIOD = 60 // automatically clear the Info attribute after 60 seconds
@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 Integer PRESENCE_COUNT_THRESHOLD = 2 // missing 3 checks will set the device healthStatus to offline
@Field static final String UNKNOWN = 'UNKNOWN'
@Field static final Integer SHORT_TIMEOUT = 7
@Field static final Integer LONG_TIMEOUT = 15
import com.hubitat.app.ChildDeviceWrapper
import com.hubitat.app.DeviceWrapper
import com.hubitat.app.exception.UnknownDeviceTypeException
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.transform.Field
import groovy.transform.CompileStatic
import hubitat.helper.HexUtils
import java.util.concurrent.ConcurrentHashMap
import hubitat.matter.DataType
metadata {
definition(name: DRIVER_NAME, namespace: 'kkossev', author: 'Krassimir Kossev', importUrl: IMPORT_URL, singleThreaded: true ) {
capability 'Actuator'
capability 'Sensor'
capability 'Initialize'
capability 'Refresh'
capability 'Health Check'
attribute 'healthStatus', 'enum', ['unknown', 'offline', 'online']
attribute 'rtt', 'number'
attribute 'Status', 'string'
attribute 'productName', 'string'
attribute 'nodeLabel', 'string'
attribute 'softwareVersionString', 'string'
attribute 'rebootCount', 'number'
attribute 'upTime', 'number'
attribute 'totalOperationalHours', 'number'
attribute 'deviceCount', 'number'
attribute 'endpointsCount', 'number'
attribute 'initializeCtr', 'number'
attribute 'reachable', 'string'
attribute 'state', 'enum', [
'not configured',
'error',
'authenticating',
'authenticated',
'connected',
'disconnected',
'ready'
]
command '_DiscoverAll', [[name:'Discover all bridged devices!' , type:ENUM, description: 'Type', constraints: ['All', 'BasicInfo', 'PartsList', 'ChildDevices', 'Subscribe']]]
command 'reSubscribe', [[name: 're-subscribe to the Matter controller events']]
command 'loadAllDefaults', [[name: 'panic button: Clear all States and scheduled jobs']]
command 'identify' // works with Nuki Lock!
if (_DEBUG) {
command 'getInfo', [
[name:'infoType', type: 'ENUM', description: 'Bridge Info Type', constraints: ['Basic', 'Extended']], // if the parameter name is 'type' - shows a drop-down list of the available drivers!
[name:'endpoint', type: 'STRING', description: 'Endpoint', constraints: ['STRING']]
]
command 'test', [[name: 'test', type: 'STRING', description: 'test', defaultValue : '']]
}
// do not expose the known Matter Bridges fingerprints for now ... Let the stock driver be assigned automatically.
// fingerprint endpointId:"01", inClusters:"0003,001D", outClusters:"001E", model:"Aqara Hub E1", manufacturer:"Aqara", controllerType:"MAT"
}
preferences {
input name: "helpInfo", type: "hidden", title: fmtHelpInfo("Community Link")
input name:'txtEnable', type: 'bool', title: '<b>Enable descriptionText logging</b>', defaultValue: true
input name:'logEnable', type: 'bool', title: '<b>Enable debug logging</b>', defaultValue: DEFAULT_LOG_ENABLE
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 (device && 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>'
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>'
input name: 'traceEnable', type: 'bool', title: '<b>Enable trace logging</b>', defaultValue: false, description: '<i>Turns on detailed extra trace logging for 30 minutes.</i>'
input name: 'minimizeStateVariables', type: 'bool', title: '<b>Minimize State Variables</b>', defaultValue: MINIMIZE_STATE_VARIABLES_DEFAULT, description: '<i>Minimize the state variables size.</i>'
}
}
}
@Field static final Map HealthcheckMethodOpts = [ // used by healthCheckMethod
defaultValue: 2,
options : [0: 'Disabled', 1: 'Activity check', 2: 'Periodic polling']
]
@Field static final Map HealthcheckIntervalOpts = [ // used by healthCheckInterval
defaultValue: 15,
options : [1: 'Every minute (not recommended!)', 15: 'Every 15 Mins', 30: 'Every 30 Mins', 60: 'Every 1 Hour', 240: 'Every 4 Hours', 720: 'Every 12 Hours']
]
@Field static final Map StartUpOnOffEnumOpts = [0: 'Off', 1: 'On', 2: 'Toggle']
@Field static final Map<Integer, Map> SupportedMatterClusters = [
// On/Off Cluster
0x0006 : [attributes: 'OnOffClusterAttributes', commands: 'OnOffClusterCommands', parser: 'parseOnOffCluster',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]]]
],
// Level Control Cluster
0x0008 : [attributes: 'LevelControlClusterAttributes', commands: 'LevelControlClusterCommands', parser: 'parseLevelControlCluster',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]]]
],
0x002F : [parser: 'parsePowerSource', attributes: 'PowerSourceClusterAttributes',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]], // Status
// [0x0001: [min: 0, max: 0xFFFF, delta: 0]], // Order
// [0x0002: [min: 0, max: 0xFFFF, delta: 0]], // Description
[0x000B: [min: 0, max: 0xFFFF, delta: 0]], // BatVoltage (11)
[0x000C: [min: 0, max: 0xFFFF, delta: 0]], // BatPercentRemaining (12)
// [0x000E: [min: 0, max: 0xFFFF, delta: 0]], // BatChargeLevel (14)
// [0x000F: [min: 0, max: 0xFFFF, delta: 0]] // BatReplacementNeeded (15)
]
],
/*
0x0039 : [attributes: 'BridgedDeviceBasicAttributes', commands: 'BridgedDeviceBasicCommands', parser: 'parseBridgedDeviceBasic', // BridgedDeviceBasic
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]]]
],
*/
0x003B : [parser: 'parseSwitch', attributes: 'SwitchClusterAttributes', events: 'SwitchClusterEvents', // Switch
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]], // NumberOfPositions
[0x0001: [min: 0, max: 0xFFFF, delta: 0]], // CurrentPosition
[0x0002: [min: 0, max: 0xFFFF, delta: 0]]] // MultiPressMax
],
// Descriptor Cluster
/*
0x001D : [attributes: 'DescriptorClusterAttributes', parser: 'parseDescriptorCluster', // decimal(29) manually subscribe to the Bridge device ep=0 0x001D 0x0003
subscriptions : [[0x0003: [min: 0, max: 0xFFFF, delta: 0]]] // PartsList
],
*/
// Contact Sensor Cluster
0x0045 : [attributes: 'BooleanStateClusterAttributes', parser: 'parseContactSensor',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]]]
],
// Air Quality Cluster
0x005B : [attributes: 'AirQualityClusterAttributes', parser: 'parseAirQuality',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]]]
],
// DoorLock Cluster
0x0101 : [attributes: 'DoorLockClusterAttributes', commands: 'DoorLockClusterCommands', parser: 'parseDoorLock',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]]] // LockState
],
// WindowCovering
0x0102 : [attributes: 'WindowCoveringClusterAttributes', commands: 'WindowCoveringClusterCommands', parser: 'parseWindowCovering',
subscriptions : [[0x000A: [min: 0, max: 0xFFFF, delta: 0]], // OperationalStatus
[0x000B: [min: 0, max: 0xFFFF, delta: 0]], // TargetPositionLiftPercent100ths
[0x000E: [min: 0, max: 0xFFFF, delta: 0]]] // CurrentPositionLiftPercent100ths
],
// Thermostat
0x0201 : [attributes: 'ThermostatClusterAttributes', commands: 'ThermostatClusterCommands', parser: 'parseThermostat',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]], // LocalTemperature +Aqara
[0x0003: [min: 0, max: 0xFFFF, delta: 0]], // AbsMinHeatSetpointLimit +Aqaea
[0x0004: [min: 0, max: 0xFFFF, delta: 0]], // AbsMaxHeatSetpointLimit +Aqara
[0x0010: [min: 0, max: 0xFFFF, delta: 0]], // LocalTemperatureCalibration
[0x0012: [min: 0, max: 0xFFFF, delta: 0]], // OccupiedHeatingSetpoint +Aqara
[0x0015: [min: 0, max: 0xFFFF, delta: 0]], // MinHeatSetpointLimit +Aqara
[0x0016: [min: 0, max: 0xFFFF, delta: 0]], // MaxHeatSetpointLimit +Aqara
[0x001A: [min: 0, max: 0xFFFF, delta: 0]], // RemoteSensing
[0x001B: [min: 0, max: 0xFFFF, delta: 0]], // ControlSequenceOfOperation +Aqara
[0x001C: [min: 0, max: 0xFFFF, delta: 0]], // SystemMode +Aqara
[0x001D: [min: 0, max: 0xFFFF, delta: 0]], // AlarmMask
[0x001E: [min: 0, max: 0xFFFF, delta: 0]], // ThermostatRunningMode
[0x0029: [min: 0, max: 0xFFFF, delta: 0]]] // ThermostatRunningState
],
// ColorControl Cluster
0x0300 : [attributes: 'ColorControlClusterAttributes', commands: 'ColorControlClusterCommands', parser: 'parseColorControl',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]], // CurrentHue
[0x0001: [min: 0, max: 0xFFFF, delta: 0]], // CurrentSaturation
[0x0007: [min: 0, max: 0xFFFF, delta: 0]], // ColorTemperatureMireds
[0x0008: [min: 0, max: 0xFFFF, delta: 0]]] // ColorMode
],
// IlluminanceMeasurement Cluster
0x0400 : [attributes: 'IlluminanceMeasurementClusterAttributes', parser: 'parseIlluminanceMeasurement',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]]]
],
// TemperatureMeasurement Cluster
0x0402 : [attributes: 'TemperatureMeasurementClusterAttributes', parser: 'parseTemperatureMeasurement',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]]]
],
// HumidityMeasurement Cluster
0x0405 : [attributes: 'RelativeHumidityMeasurementClusterAttributes', parser: 'parseHumidityMeasurement',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]]]
],
// OccupancySensing (motion) Cluster
0x0406 : [attributes: 'OccupancySensingClusterAttributes', parser: 'parseOccupancySensing',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]]]
],
// PM25ConcentrationMeasurement Cluster
0x042A : [attributes: 'ConcentrationMeasurementClustersAttributes', parser: 'parseConcentrationMeasurement',
subscriptions : [[0x0000: [min: 0, max: 0xFFFF, delta: 0]]]
],
]
@Field static final Map<Integer, String> ParsedMatterClusters = [
0x0006 : 'parseOnOffCluster',
0x0008 : 'parseLevelControlCluster',
0x001D : 'parseDescriptorCluster',
0x0028 : 'parseBasicInformationCluster',
0x002F : 'parsePowerSource',
0x0033 : 'parseGeneralDiagnostics',
0x0039 : 'parseBridgedDeviceBasic',
0x003B : 'parseSwitch',
0x0045 : 'parseContactSensor',
0x005B : 'parseAirQuality',
0x0101 : 'parseDoorLock',
0x0102 : 'parseWindowCovering',
0x0201 : 'parseThermostat',
0x0300 : 'parseColorControl',
0x0400 : 'parseIlluminanceMeasurement',
0x0402 : 'parseTemperatureMeasurement',
0x0405 : 'parseHumidityMeasurement',
0x0406 : 'parseOccupancySensing',
0x042A : 'parseConcentrationMeasurement'
]
// Json Parsing Cache
@Field static final Map<String, Map> jsonCache = new ConcurrentHashMap<>()
// Track for dimming operations
@Field static final Map<String, Integer> levelChanges = new ConcurrentHashMap<>()
// Json Parser
@Field static final JsonSlurper jsonParser = new JsonSlurper()
// Random number generator
@Field static final Random random = new Random()
//parsers
void parse(final String description) {
checkDriverVersion()
checkSubscriptionStatus()
unschedule('deviceCommandTimeout')
setHealthStatusOnline()
Map descMap
try {
descMap = myParseDescriptionAsMap(description)
} catch (e) {
logWarn "parse: exception ${e} <br> Failed to parse description: ${description}"
return
}
if (descMap == null) {
logWarn "parse: descMap is null description:${description}"
return
}
updateStateStats(descMap)
checkStateMachineConfirmation(descMap)
if (isDeviceDisabled(descMap)) {
if (traceEnable) { logWarn "parse: device is disabled: ${descMap}" }
return
}
if (!(((descMap.attrId in ['FFF8', 'FFF9', 'FFFA', 'FFFC', 'FFFD', '00FE']) && DO_NOT_TRACE_FFFX) || state['states']['isDiscovery'] == true)) {
logDebug "parse: descMap:${descMap} description:${description}"
}
parseGlobalElements(descMap)
//return
gatherAttributesValuesInfo(descMap)
String parserFunc = ParsedMatterClusters[HexUtils.hexStringToInt(descMap.cluster)]
if (parserFunc) {
if (_DEBUG) {
this."${parserFunc}"(descMap)
}
else {
try {
this."${parserFunc}"(descMap)
} catch (e) {
logWarn "parserFunc: exception ${e} <br> Failed to parse description: ${description}"
}
}
} else {
logWarn "parserFunc: NOT PROCESSED: ${descMap} description:${description}"
}
}
Map myParseDescriptionAsMap(description) {
Map descMap
try {
descMap = matter.parseDescriptionAsMap(description)
//log.trace "myParseDescriptionAsMap: descMap:${descMap} description:${description}"
} catch (e) {
logWarn "parse: exception ${e} <br> Failed to parse description: ${description}"
return null
}
if (descMap == null) {
logWarn "parse: descMap is null description:${description}"
return null
}
// parse: descMap:[endpoint:00, cluster:0028, attrId:0000, value:01, clusterInt:40, attrInt:0] description:read attr - endpoint: 00, cluster: 0028, attrId: 0000, value: 0401
if (descMap.value != null && descMap.attrId != null && descMap.value in ['1518', '1618', '1818']
&& ( descMap.attrId in ['FFF8', 'FFF9','FFFA', 'FFFB', 'FFFC', 'FFFD', 'FFFE', 'FFFF']
|| descMap.cluster == '001D')
) {
descMap.value = []
if (settings?.traceEnable) { log.warn "myParseDescriptionAsMap: descMap:${descMap} description:${description}" }
}
//descMap.value = JvmDescMap.decodedValue.toString()
return descMap
}
boolean isDeviceDisabled(final Map descMap) {
if (descMap.endpoint == '00') {
return false
}
// get device dni
String dni = "${device.id}-${descMap.endpoint}"
ChildDeviceWrapper dw = getChildDevice(dni)
if (dw == null) {
return false
}
if (dw?.disabled == true) {
if (traceEnable) { logWarn "isDeviceDisabled: device:${dw} is disabled" }
return true
}
return false
}
void checkStateMachineConfirmation(final Map descMap) {
if (state['stateMachines'] == null || state['stateMachines']['toBeConfirmed'] == null) {
return
}
List toBeConfirmedList = state['stateMachines']['toBeConfirmed']
//logTrace "checkStateMachineConfirmation: toBeConfirmedList:${toBeConfirmedList} (endpoint:${descMap.endpoint} clusterInt:${descMap.clusterInt} attrInt:${descMap.attrInt})"
if (toBeConfirmedList == null || toBeConfirmedList.size() == 0) {
return
}
// toBeConfirmedList first element is endpoint, second is clusterInt, third is attrInt
if (HexUtils.hexStringToInt(descMap.endpoint) == toBeConfirmedList[0] && descMap.clusterInt == toBeConfirmedList[1] && descMap.attrInt == toBeConfirmedList[2]) {
logDebug "checkStateMachineConfirmation: endpoint:${descMap.endpoint} cluster:${descMap.cluster} attrId:${descMap.attrId} - <b>CONFIRMED!</b>"
state['stateMachines']['Confirmation'] = true
}
}
String getClusterName(final String cluster) { return MatterClusters[HexUtils.hexStringToInt(cluster)] ?: UNKNOWN }
String getAttributeName(final Map descMap) { return (descMap.attrId != null) ? getAttributeName(descMap.cluster, descMap.attrId) : UNKNOWN }
String getAttributeName(final String cluster, String attrId) { return getAttributesMapByClusterId(cluster)?.get(HexUtils.hexStringToInt(attrId)) ?: GlobalElementsAttributes[HexUtils.hexStringToInt(attrId)] ?: UNKNOWN }
String getFingerprintName(final Map descMap) { return descMap.endpoint == '00' ? 'bridgeDescriptor' : "fingerprint${descMap.endpoint}" }
String getFingerprintName(final Integer endpoint) { return getFingerprintName([endpoint: HexUtils.integerToHexString(endpoint, 1)]) }
String getStateClusterName(final Map descMap) {
String clusterMapName = ''
if (descMap.cluster == '001D') {
clusterMapName = getAttributeName(descMap)
}
else {
clusterMapName = descMap.cluster + '_' + descMap.attrId
}
}
@CompileStatic
String getDeviceDisplayName(final Integer endpoint) { return getDeviceDisplayName(HexUtils.integerToHexString(endpoint, 1)) }
/**
* Returns the device label based on the provided endpoint.
* If a child device exists, the label is retrieved from the child device display name.
* If no child device exists yet, the label is constructed by combining the endpoint with the vendor name, product name, and custom label.
* If the vendor name or product name is available, they are included in parentheses.
*
* @param endpoint The endpoint of the device.
* @return The device display label.
*/
String getDeviceDisplayName(final String endpoint) {
// if a child device exists, use its endpoint to get the ${device.displayName}
if (getChildDevice("${device.id}-${endpoint}") != null) {
return getChildDevice("${device.id}-${endpoint}")?.displayName
}
String label = "Bridge#${device.id} Device#${endpoint} "
String fingerprintName = getFingerprintName([endpoint: endpoint])
String vendorName = state[fingerprintName]?.VendorName ?: ''
String productName = state[fingerprintName]?.ProductName ?: ''
String customLabel = state[fingerprintName]?.Label ?: ''
if (vendorName || productName) {
label += "(${vendorName} ${productName}) "
}
label += customLabel
return label
}
// credits: @jvm33
// Matter payloads need hex parameters of greater than 2 characters to be pair-reversed.
// This function takes a list of parameters and pair-reverses those longer than 2 characters.
// Alternatively, it can take a string and pair-revers that.
// Thus, e.g., ["0123", "456789", "10"] becomes "230189674510" and "123456" becomes "563412"
@CompileStatic
private String byteReverseParameters(String oneString) { byteReverseParameters([] << oneString) }
@CompileStatic
private String byteReverseParameters(List<String> parameters) {
StringBuilder rStr = new StringBuilder(64)
for (hexString in parameters) {
if (hexString.length() % 2) throw new Exception("In method byteReverseParameters, trying to reverse a hex string that is not an even number of characters in length. Error in Hex String: ${hexString}, All method parameters were ${parameters}.")
for(Integer i = hexString.length() -1 ; i > 0 ; i -= 2) {
rStr << hexString[i-1..i]
}
}
return rStr
}
// 7.13. Global Elements - used for self-description of the server
//@CompileStatic
void parseGlobalElements(final Map descMap) {
//logTrace "parseGlobalElements: descMap:${descMap}"
switch (descMap.attrId) {
case '00FE' : // FabricIndex fabric-idx
case 'FFF8' : // GeneratedCommandList list[command-id]
case 'FFF9' : // AcceptedCommandList list[command-id]
case 'FFFA' : // EventList list[eventid]
case 'FFFC' : // FeatureMap map32
case 'FFFD' : // ClusterRevision uint16
case 'FFFB' : // AttributeList list[attribid]
String fingerprintName = getFingerprintName(descMap)
String attributeName = getStateClusterName(descMap)
String action = 'stored in'
if (state[fingerprintName] == null) {
state[fingerprintName] = [:]
}
if (state[fingerprintName][attributeName] == null) {
state[fingerprintName][attributeName] = [:]
action = 'created in'
}
state[fingerprintName][attributeName] = descMap.value
logTrace "parseGlobalElements: cluster: <b>${getClusterName(descMap.cluster)}</b> (0x${descMap.cluster}) attr: <b>${attributeName}</b> (0x${descMap.attrId}) value:${descMap.value} <b>-> ${action}</b> [$fingerprintName][$attributeName]"
//logTrace "parseGlobalElements: state[${fingerprintName}][${attributeName}] = ${state[fingerprintName][attributeName]}"
break
default :
break // not a global element
}
}
void gatherAttributesValuesInfo(final Map descMap) {
if (descMap == null || descMap?.attrId == null) {
return
}
Integer attrInt = descMap.attrInt as Integer
String attrName = getAttributeName(descMap)
Integer tempIntValue
String tmpStr
if (state.states['isInfo'] == true) {
logTrace "gatherAttributesValuesInfo: <b>isInfo:${state.states['isInfo']}</b> state.states['cluster'] = ${state.states['cluster']} "
if (state.states['cluster'] == descMap.cluster) {
if (descMap.value != null && descMap.value != '') {
tmpStr = "[${descMap.attrId}] ${attrName}"
if (state.tmp?.contains(tmpStr)) {
logDebug "gatherAttributesValuesInfo: tmpStr:${tmpStr} is already in the state.tmp"
return
}
try {
tempIntValue = HexUtils.hexStringToInt(descMap.value)
if (tempIntValue >= 10) {
tmpStr += ' = 0x' + descMap.value + ' (' + tempIntValue + ')'
} else {
tmpStr += ' = ' + descMap.value
}
} catch (e) {
tmpStr += ' = ' + descMap.value
}
state.tmp = (state.tmp ?: '') + "${tmpStr} " + '<br>'
}
}
}
else if ((state.states['isPing'] ?: false) == true && descMap.cluster == '0028' && descMap.attrId == '0000') {
Long now = new Date().getTime()
Integer timeRunning = now.toInteger() - (state.lastTx['pingTime'] ?: '0').toInteger()
if (timeRunning > 0 && timeRunning < MAX_PING_MILISECONDS) {
state.stats['pingsOK'] = (state.stats['pingsOK'] ?: 0) + 1
if (timeRunning < safeToInt((state.stats['pingsMin'] ?: '999'))) { state.stats['pingsMin'] = timeRunning }
if (timeRunning > safeToInt((state.stats['pingsMax'] ?: '0'))) { state.stats['pingsMax'] = timeRunning }
state.stats['pingsAvg'] = approxRollingAverage(safeToDouble(state.stats['pingsAvg']), safeToDouble(timeRunning)) as int
sendRttEvent()
} else {
logWarn "unexpected ping timeRunning=${timeRunning} "
}
state.states['isPing'] = false
}
else {
logTrace "gatherAttributesValuesInfo: isInfo:${state.states['isInfo']} descMap:${descMap}"
}
}
//@CompileStatic
void parseGeneralDiagnostics(final Map descMap) {
//logTrace "parseGeneralDiagnostics: descMap:${descMap}"
Integer value
switch (descMap.attrId) {
case '0001' : // RebootCount - a best-effort count of the number of times the Node has rebooted
value = HexUtils.hexStringToInt(descMap.value)
sendMatterEvent([name: 'rebootCount', value: value, descriptionText: "${getDeviceDisplayName(descMap.endpoint)} RebootCount is ${value}"])
break
case '0002' : // UpTime - a best-effort assessment of the length of time, in seconds,since the Node’s last reboot
value = HexUtils.hexStringToInt(descMap.value)
sendMatterEvent([name: 'upTime', value:value, descriptionText: "${getDeviceDisplayName(descMap.endpoint)} UpTime is ${value} seconds"])
break
case '0003' : // TotalOperationalHours - a best-effort attempt at tracking the length of time, in hours, that the Node has been operational
value = HexUtils.hexStringToInt(descMap.value)
sendMatterEvent([name: 'totalOperationalHours', value: value, descriptionText: "${getDeviceDisplayName(descMap.endpoint)} TotalOperationalHours is ${value} hours"])
break
default :
if (descMap.attrId != '0000') { if (traceEnable) { logInfo "parse: parseGeneralDiagnostics: ${attrName} = ${descMap.value}" } }
break
}
}
void parsePowerSource(final Map descMap) {
logTrace "parsePowerSource: descMap:${descMap}"
String attrName = getAttributeName(descMap)
Integer value
String descriptionText = ''
Map eventMap = [:]
String eventName = attrName[0].toLowerCase() + attrName[1..-1] // change the attribute name first letter to lower case
switch (attrName) {
case ['BatTimeRemaining', 'BatChargeLevel', 'BatReplacementNeeded', 'BatReplaceability', 'BatReplacementDescription', 'BatQuantity'] :
descriptionText = "${getDeviceDisplayName(descMap?.endpoint)} Power source ${attrName} is ${descMap.value}"
eventMap = [name: eventName, value: descMap.value, descriptionText: descriptionText]
break
case 'BatPercentRemaining' : // BatteryPercentageRemaining 0x000C
value = HexUtils.hexStringToInt(descMap.value)
descriptionText = "${getDeviceDisplayName(descMap?.endpoint)} Battery percentage remaining is ${value / 2}% (raw:${descMap.value})"
eventMap = [name: 'battery', value: value / 2, descriptionText: descriptionText]
break
case 'BatVoltage' : // BatteryVoltage 0x000B
value = HexUtils.hexStringToInt(descMap.value)
descriptionText = "${getDeviceDisplayName(descMap?.endpoint)} Battery voltage is ${value / 1000}V (raw:${descMap.value})"
eventMap = [name: 'batteryVoltage', value: value / 1000, descriptionText: descriptionText]
break
case 'Status' : // PowerSourceStatus 0x0000
String statusDesc = PowerSourceClusterStatus[HexUtils.hexStringToInt(descMap.value)] ?: UNKNOWN
statusDesc = statusDesc[0].toLowerCase() + statusDesc[1..-1] // change the powerSourceStatus attribute value first letter to lower case
descriptionText = "${getDeviceDisplayName(descMap?.endpoint)} Power source status is ${statusDesc} (raw:${descMap.value})"
eventMap = [name: 'powerSourceStatus', value: statusDesc, descriptionText: descriptionText]
break
case 'Order' : // PowerSourceOrder 0x0001
descriptionText = "${getDeviceDisplayName(descMap?.endpoint)} Power source order is ${descMap.value}"
eventMap = [name: 'powerSourceOrder', value: descMap.value, descriptionText: descriptionText]
break
case 'Description' : // PowerSourceDescription 0x0002
descriptionText = "${getDeviceDisplayName(descMap?.endpoint)} Power source description is ${descMap.value}"
eventMap = [name: 'powerSourceDescription', value: descMap.value, descriptionText: descriptionText]
break
default :
logInfo "Power source ${attrName} is ${descMap.value} (unprocessed)"
break
}
if (eventMap != [:]) {
eventMap.type = 'physical'
eventMap.isStateChange = true
sendMatterEvent(eventMap, descMap, true) // bridge events
}
}
void parseBasicInformationCluster(final Map descMap) { // 0x0028 BasicInformation (the Bridge)
Map eventMap = [:]
String attrName = getAttributeName(descMap)
String fingerprintName = getFingerprintName(descMap)
if (state[fingerprintName] == null) { state[fingerprintName] = [:] }
String eventName = attrName[0].toLowerCase() + attrName[1..-1] // change the attribute name first letter to lower case
if (attrName in ['ProductName', 'NodeLabel', 'SoftwareVersionString', 'Reachable']) {
if (descMap.value != null && descMap.value != '') {
state[fingerprintName][attrName] = descMap.value
eventMap = [name: eventName, value:descMap.value, descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} ${eventName} is: ${descMap.value}"]
if (logEnable) { logInfo "parseBasicInformationCluster: ${attrName} = ${descMap.value}" }
}
}
if (eventMap != [:]) {
eventMap.type = 'physical'; eventMap.isStateChange = true
sendMatterEvent(eventMap, descMap) // bridge events
}
}
void parseBridgedDeviceBasic(final Map descMap) { // 0x0039 BridgedDeviceBasic (the child devices)
Map eventMap = [:]
String attrName = getAttributeName(descMap)
String fingerprintName = getFingerprintName(descMap)
if (state[fingerprintName] == null) { state[fingerprintName] = [:] }
String eventName = attrName[0].toLowerCase() + attrName[1..-1] // change the attribute name first letter to lower case
if (attrName in ['VendorName', 'ProductName', 'NodeLabel', 'SoftwareVersionString', 'Reachable']) {
if (descMap.value != null && descMap.value != '') {
state[fingerprintName][attrName] = descMap.value
eventMap = [name: eventName, value:descMap.value, descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} ${eventName} is: ${descMap.value}"]
if (logEnable) { logInfo "parseBridgedDeviceBasic: ${attrName} = ${descMap.value}" }
}
}
if (eventMap != [:]) {
eventMap.type = 'physical'; eventMap.isStateChange = true
sendMatterEvent(eventMap, descMap) // child events
}
}
void parseDescriptorCluster(final Map descMap) { // 0x001D Descriptor
logTrace "parseDescriptorCluster: descMap:${descMap}"
String attrName = getAttributeName(descMap) //= DescriptorClusterAttributes[descMap.attrInt as int] ?: GlobalElementsAttributes[descMap.attrInt as int] ?: UNKNOWN
String endpointId = descMap.endpoint
String fingerprintName = getFingerprintName(descMap) /*"fingerprint${endpointId}"
/*
[0000] DeviceTypeList = [16, 1818]
[0001] ServerList = [03, 1D, 1F, 28, 29, 2A, 2B, 2C, 2E, 30, 31, 32, 33, 34, 37, 39, 3C, 3E, 3F, 40]
[0002] ClientList = [03, 1F, 29, 39]
[0003] PartsList = [01, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 10, 11]
*/
switch (descMap.attrId) {
case ['0000', '0001', '0002', '0003'] :
state[fingerprintName][attrName] = descMap.value
logTrace "parse: Descriptor (${descMap.cluster}): ${attrName} = <b>-> updated state[$fingerprintName][$attrName]</b> to ${descMap.value}"
if (endpointId == '00' && descMap.cluster == '001D') {
if (attrName == 'PartsList') {
List partsList = descMap.value as List
int partsListCount = partsList.size() // the number of the elements in the partsList
int oldCount = device.currentValue('endpointsCount') ?: 0 as int
String descriptionText = "${getDeviceDisplayName(descMap?.endpoint)} Bridge partsListCount is: ${partsListCount}"
sendMatterEvent([name: 'endpointsCount', value: partsListCount, descriptionText: descriptionText], descMap)
if (partsListCount != oldCount) {
logWarn "THE NUMBER OF THE BRIDGED DEVICES CHANGED FROM ${oldCount} TO ${partsListCount} !!!"
}
}
}
break
default :
logTrace "parseDescriptorCluster: Descriptor: ${attrName} = ${descMap.value}"
break
}
}
void parseOnOffCluster(final Map descMap) {
logTrace "parseOnOffCluster: descMap:${descMap}"
if (descMap.cluster != '0006') { logWarn "parseOnOffCluster: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"; return }
Integer value
switch (descMap.attrId) {
case '0000' : // Switch
String switchState = descMap.value == '01' ? 'on' : 'off'
sendMatterEvent([
name: 'switch',
value: switchState,
descriptionText: "${getDeviceDisplayName(descMap.endpoint)} switch is ${switchState}"
], descMap, true)
break
case '4000' : // GlobalSceneControl
if (logEnable) { logInfo "parse: Switch: GlobalSceneControl = ${descMap.value}" }
if (state.onOff == null) { state.onOff = [:] } ; state.onOff['GlobalSceneControl'] = descMap.value
break
case '4001' : // OnTime
if (logEnable) { logInfo "parse: Switch: OnTime = ${descMap.value}" }
if (state.onOff == null) { state.onOff = [:] } ; state.onOff['OnTime'] = descMap.value
break
case '4002' : // OffWaitTime
if (logEnable) { logInfo "parse: Switch: OffWaitTime = ${descMap.value}" }
if (state.onOff == null) { state.onOff = [:] } ; state.onOff['OffWaitTime'] = descMap.value
break
case '4003' : // StartUpOnOff
value = descMap.value as int
String startUpOnOffText = "parse: Switch: StartUpOnOff = ${descMap.value} (${StartUpOnOffEnumOpts[value] ?: UNKNOWN})"
if (logEnable) { logInfo "${startUpOnOffText}" }
if (state.onOff == null) { state.onOff = [:] } ; state.onOff['StartUpOnOff'] = descMap.value
break
case ['FFF8', 'FFF9', 'FFFA', 'FFFB', 'FFFC', 'FFFD', '00FE'] :
logTrace "parse: Switch: ${attrName} = ${descMap.value}"
break
default :
logWarn "parseOnOffCluster: unexpected attrId:${descMap.attrId} (raw:${descMap.value})"
}
}
void parseLevelControlCluster(final Map descMap) {
logTrace "parseLevelControlCluster: descMap:${descMap}"
if (descMap.cluster != '0008') { logWarn "parseLevelControlCluster: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"; return }
Integer value
switch (descMap.attrId) {
case '0000' : // CurrentLevel
value = hex254ToInt100(descMap.value)
sendMatterEvent([
name: 'level',
value: value, //.toString(),
descriptionText: "${getDeviceDisplayName(descMap.endpoint)} level is ${value}"
], descMap, true)
break
default :
Map eventMap = [:]
String attrName = getAttributeName(descMap)
String fingerprintName = getFingerprintName(descMap)
if (state[fingerprintName] == null) { state[fingerprintName] = [:] }
String eventName = attrName[0].toLowerCase() + attrName[1..-1] // change the attribute name first letter to lower case
if (attrName in ['CurrentLevel', 'RemainingTime', 'MinLevel', 'MaxLevel', 'OnOffTransitionTime', 'OnLevel', 'OnTransitionTime', 'OffTransitionTime', 'Options', 'StartUpCurrentLevel', 'Reachable']) {
eventMap = [name: eventName, value:descMap.value, descriptionText: "${eventName} is: ${descMap.value}"]
if (logEnable) { logInfo "parseLevelControlCluster: ${attrName} = ${descMap.value}" }
}
else {
logWarn "parseLevelControlCluster: unsupported LevelControl: attribute ${descMap.attrId} ${attrName} = ${descMap.value}"
}
if (eventMap != [:]) {
eventMap.type = 'physical'; eventMap.isStateChange = true
sendMatterEvent(eventMap, descMap, true) // child events
}
}
}
// Method for parsing occupancy sensing
void parseOccupancySensing(final Map descMap) {
if (descMap.cluster != '0406') {
logWarn "parseOccupancySensing: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"
return
}
String motionAttr = descMap.value == '01' ? 'active' : 'inactive'
if (descMap.attrId == '0000') { // Occupancy
sendMatterEvent([
name: 'motion',
value: motionAttr,
descriptionText: "${getDeviceDisplayName(descMap.endpoint)} motion is ${motionAttr}"
], descMap, true)
} else {
logTrace "parseOccupancySensing: ${(OccupancySensingClusterAttributes[descMap.attrInt] ?: GlobalElementsAttributes[descMap.attrInt] ?: UNKNOWN)} = ${descMap.value}"
}
}
String getEventName(final Map descMap) {
return (descMap.evtId != null) ? getEventName(descMap.cluster, descMap.evtId) : 'NONE'
}
String getEventName(final String cluster, String evtId) {
return getEventsMapByClusterId(cluster)?.get(HexUtils.hexStringToInt(evtId)) ?: UNKNOWN
}
// Method for parsing 003B Switch cluster attributes and events
void parseSwitch(final Map descMap) {
if (descMap.cluster != '003B') { logWarn "parseSwitch: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"; return }
Map eventMap = [:]
String attrName = getAttributeName(descMap)
String evtName = getEventName(descMap) // switch event - added 2024/10/04
String fingerprintName = getFingerprintName(descMap)
logDebug "parseSwitch: fingerprintName:${fingerprintName} attrName:${attrName} evtName:${evtName}"
if (state[fingerprintName] == null) { state[fingerprintName] = [:] }
String eventName = attrName[0].toLowerCase() + attrName[1..-1] // change the attribute name first letter to lower case
if (descMap.evtId != null) { // event
eventName = evtName[0].toLowerCase() + evtName[1..-1] // change the event name first letter to lower case
eventMap = [name: eventName, value:descMap.value, descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} EVENT ${eventName} : ${descMap.value}"]
if (logEnable) { logDebug "parseSwitch: EVENT ${eventName} : ${descMap.value}" }
}
else { // attribute
if (attrName in SwitchClusterAttributes.values().toList()) {
String valueFormatted = descMap.value
eventMap = [name: eventName, value:valueFormatted, descriptionText: "${eventName} : ${valueFormatted}"]
if (logEnable) { logInfo "parseSwitch: ${attrName} is ${valueFormatted}" }
}
else {
logWarn "parseSwitch: unsupported: ${attrName} = ${descMap.value}"
}
}
if (eventMap != [:]) {
eventMap.type = 'physical'; eventMap.isStateChange = true
sendMatterEvent(eventMap, descMap, true) // child events
}
}
// Method for parsing contact sensor
void parseContactSensor(final Map descMap) {
if (descMap.cluster != '0045') { logWarn "parseContactSensor: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"; return }
String contactAttr = descMap.value == '01' ? 'closed' : 'open'
if (descMap.attrId == '0000') { // Contact
sendMatterEvent([
name: 'contact',
value: contactAttr,
descriptionText: "${getDeviceDisplayName(descMap.endpoint)} contact is ${contactAttr} (raw:${descMap.value})"
], descMap, true)
} else {
logTrace "parseContactSensor: ${(BooleanStateClusterAttributes[descMap.attrInt] ?: GlobalElementsAttributes[descMap.attrInt] ?: UNKNOWN)} = ${descMap.value}"
}
}
// Method for parsing illuminance measurement
void parseIlluminanceMeasurement(final Map descMap) { // 0400
if (descMap.cluster != '0400') { logWarn "parseIlluminanceMeasurement: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"; return }
if (descMap.attrId == '0000') { // Illuminance
Integer valueInt = HexUtils.hexStringToInt(descMap.value)
Integer valueLux = Math.pow( 10, (valueInt -1) / 10000) as Integer
if (valueLux < 0 || valueLux > 100000) {
logWarn "parseIlluminanceMeasurement: valueInt:${valueInt} is out of range"
return
}
sendMatterEvent([
name: 'illuminance',
value: valueLux as int,
unit: 'lx',
descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} illuminance is ${valueLux} lux"
], descMap, true)
} else {
logTrace "parseIlluminanceMeasurement: ${(IlluminanceMeasurementClusterAttributes[descMap.attrInt] ?: GlobalElementsAttributes[descMap.attrInt] ?: UNKNOWN)} = ${descMap.value}"
}
}
// Method for parsing temperature measurement
void parseTemperatureMeasurement(final Map descMap) { // 0402
if (descMap.cluster != '0402') { logWarn "parseTemperatureMeasurement: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"; return }
if (descMap.attrId == '0000') { // Temperature
Double valueInt = HexUtils.hexStringToInt(descMap.value) / 100.0
String unit
//log.debug "parseTemperatureMeasurement: location.temperatureScale:${location.temperatureScale}"
if (valueInt < -100 || valueInt > 300) {
logWarn "parseTemperatureMeasurement: valueInt:${valueInt} is out of range"
return
}
if (location.temperatureScale == 'F') {
valueInt = (valueInt * 1.8) + 32
unit = "\u00B0" + 'F'
}
else {
unit = "\u00B0" + 'C'
}
sendMatterEvent([
name: 'temperature',
value: valueInt.round(1) as double,
descriptionText: "${getDeviceDisplayName(descMap.endpoint)} temperature is ${valueInt.round(2)} ${unit}",
unit: unit
], descMap, true)
} else {
logTrace "parseTemperatureMeasurement: ${(TemperatureMeasurementClusterAttributes[descMap.attrInt] ?: GlobalElementsAttributes[descMap.attrInt] ?: UNKNOWN)} = ${descMap.value}"
logTrace "parseTemperatureMeasurement: ${getAttributeName(descMap)} = ${descMap.value}"
}
}
// Method for parsing humidity measurement
void parseHumidityMeasurement(final Map descMap) { // 0405
if (descMap.cluster != '0405') {
logWarn "parseHumidityMeasurement: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"
return
}
if (descMap.attrId == '0000') { // Humidity
Double valueInt = HexUtils.hexStringToInt(descMap.value) / 100.0
if (valueInt <= 0 || valueInt > 100) {
logWarn "parseHumidityMeasurement: valueInt:${valueInt} is out of range"
return
}
sendMatterEvent([
name: 'humidity',
value: valueInt.round(0) as int,
descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} humidity is ${valueInt.round(1)} %"
], descMap, true)
} else {
logTrace "parseHumidityMeasurement: ${(RelativeHumidityMeasurementClusterAttributes[descMap.attrInt] ?: GlobalElementsAttributes[descMap.attrInt] ?: UNKNOWN)} = ${descMap.value}"
}
}
void parseDoorLock(final Map descMap) { // 0101
if (descMap.cluster != '0101') { logWarn "parseDoorLock: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"; return }
if (descMap.attrId == '0000') { // LockState
String lockState = descMap.value == '01' ? 'locked' : 'unlocked'
sendMatterEvent([
name: 'lock',
value: lockState,
descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} lock is ${lockState}"
], descMap)
} else {
logTrace "parseDoorLock: <b>UNPROCESSED</b> ${(DoorLockClusterAttributes[descMap.attrInt] ?: GlobalElementsAttributes[descMap.attrInt] ?: UNKNOWN)} = ${descMap.value}"
// added in version 1.1.0 - send the unprocessed attributes to the child driver for further processing
sendMatterEvent([
name: 'unprocessed',
value: descMap.toString(),
descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} <b>unprocessed</b> cluster ${descMap.cluster} attribute ${descMap.attrId} <i>(to be re-processed in the child driver!)</i>"
], descMap, ignoreDuplicates = false)
}
}
void parseAirQuality(final Map descMap) { // 005B
if (descMap.cluster != '005B') { logWarn "parseAirQuality: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"; return }
logTrace "parseAirQuality: <b>UNPROCESSED</b> ${(AirQualityClusterAttributes[descMap.attrInt] ?: GlobalElementsAttributes[descMap.attrInt] ?: UNKNOWN)} = ${descMap.value}"
// send the unprocessed attributes to the child driver for further processing
sendMatterEvent([
name: 'unprocessed',
value: descMap.toString(),
descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} <b>unprocessed</b> cluster ${descMap.cluster} attribute ${descMap.attrId} <i>(to be re-processed in the child driver!)</i>"
], descMap, ignoreDuplicates = false)
}
// to be used in multiple clusters !
void parseConcentrationMeasurement(final Map descMap) { // 042A
if (descMap.cluster != '042A') { logWarn "parseConcentrationMeasurement: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"; return }
logTrace "parseConcentrationMeasurement: <b>UNPROCESSED</b> ${(ConcentrationMeasurementClustersAttributes[descMap.attrInt] ?: GlobalElementsAttributes[descMap.attrInt] ?: UNKNOWN)} = ${descMap.value}"
// send the unprocessed attributes to the child driver for further processing
sendMatterEvent([
name: 'unprocessed',
value: descMap.toString(),
descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} <b>unprocessed</b> cluster ${descMap.cluster} attribute ${descMap.attrId} <i>(to be re-processed in the child driver!)</i>"
], descMap, ignoreDuplicates = false)
}
void parseWindowCovering(final Map descMap) { // 0102
if (descMap.cluster != '0102') { logWarn "parseWindowCovering: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"; return }
if (descMap.attrId == '000B') { // TargetPositionLiftPercent100ths
Integer valueInt = (HexUtils.hexStringToInt(descMap.value) / 100) as int
sendMatterEvent([
name: 'targetPosition',
value: valueInt,
descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} <b>targetPosition</b> is reported as ${valueInt} <i>(to be re-processed in the child driver!)</i>"
], descMap, ignoreDuplicates = false)
} else if (descMap.attrId == '000E') { // CurrentPositionLiftPercent100ths
Integer valueInt = (HexUtils.hexStringToInt(descMap.value) / 100) as int
sendMatterEvent([
name: 'position',
value: valueInt,
descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} <b>position</b> is is reported as ${valueInt} <i>(to be re-processed in the child driver!)</i>"
], descMap, ignoreDuplicates = false)
} else if (descMap.attrId == '000A') { // OperationalStatus
sendMatterEvent([
name: 'operationalStatus',
value: descMap.value,
descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} operationalStatus is ${descMap.value}"
], descMap, ignoreDuplicates = false)
}
else {
logTrace "parseWindowCovering: ${(WindowCoveringClusterAttributes[descMap.attrInt] ?: GlobalElementsAttributes[descMap.attrInt] ?: UNKNOWN)} = ${descMap.value}"
}
}
void parseColorControl(final Map descMap) { // 0300
if (descMap.cluster != '0300') { logWarn "parseColorControl: unexpected cluster:${descMap.cluster} (attrId:${descMap.attrId})"; return }
ChildDeviceWrapper dw = getDw(descMap)
switch (descMap.attrId) {
case '0000' : // CurrentHue
Integer valueInt = (HexUtils.hexStringToInt(descMap.value) / 2.54) as int
logTrace "parseColorControl: hue = ${valueInt}"
sendMatterEvent([
name: 'hue',
value: valueInt,
descriptionText: "${getDeviceDisplayName(descMap?.endpoint)} hue is ${valueInt}"
], descMap, true)
if (dw?.currentValue('colorMode') != 'CT') {
sendColorNameEvent(descMap, hue=valueInt, saturation=null) // added 02/19/2024
}
break
case '0001' : // CurrentSaturation
Integer valueInt = (HexUtils.hexStringToInt(descMap.value) / 2.54) as int
logTrace "parseColorControl: CurrentSaturation = ${valueInt} (raw=0x${descMap.value})"
sendMatterEvent([
name: 'saturation',