forked from vurvantsev/HubitatCustom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Advanced Universal Z-Wave Plus Dimmer Driver.groovy
1919 lines (1637 loc) · 84 KB
/
Advanced Universal Z-Wave Plus Dimmer Driver.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
import java.util.concurrent.*;
import groovy.transform.Field
@Field static String driverVersion = "0.0.3"
@Field static Boolean deleteAndResetStateData = false
@Field static defaultParseMap = [
0x20:2, // Basic Set
0x25:2, // Switch Binary
0x26:3, // Switch MultiLevel
0x31:11,// Sensor MultiLevel
0x32:5, // Meter
0x5B:1, // Central Scene
0x60:4, // MultiChannel
0x62:1, // Door Lock
0x63:1, // User Code
0x6C:1, // Supervision
0x71:8, // Notification
0x80:1, // Battery
0x86:3, // Version
0x98:1, // Security
0x9B:2 // Configuration
]
@Field static endPointMap = [
[manufacturer:798, deviceId:1, deviceType:14, ep:[
1:[driver:"Generic Component Fan Control"],
2:[driver:"Generic Component Dimmer"]
]]
]
metadata {
definition (name: "[Beta] Advanced Zwave Plus Metering Dimmer",namespace: "jvm", author: "jvm") {
// capability "Configuration" // Does the same as Initialize, so don't show the separate control!
capability "Initialize"
capability "Refresh"
// For switches and dimmers!
capability "Switch"
capability "SwitchLevel"
// Does anybody really use the "Change Level" controls? If so, uncomment it!
// capability "ChangeLevel"
// These are generally harmless to keep in, even for non-metering devices, so generally leave uncommented
capability "EnergyMeter"
capability "PowerMeter"
capability "VoltageMeasurement"
command "meterRefresh"
// Central Scene functions. Include the "commands" if you want to generate central scene actions from the web interface. If they are not included, central scene will still be generated from the device.
capability "PushableButton"
command "push", ["NUMBER"]
capability "HoldableButton"
command "hold", ["NUMBER"]
capability "ReleasableButton"
command "release", ["NUMBER"]
capability "DoubleTapableButton"
command "doubleTap", ["NUMBER"]
// capability "Battery"
// command "batteryGet"
// capability "Lock"
// capability "Lock Codes"
// command "lockrefresh"
command "getAllParameterValues"
// command "getSupportedNotifications"
// capability "Sensor"
// capability "MotionSensor"
// capability "ContactSensor"
// capability "RelativeHumidityMeasurement"
// capability "SmokeDetector"
// capability "TamperAlert"
// capability "TemperatureMeasurement"
// capability "WaterSensor"
/** The "ResetDriverStateData" command deletes all state data stored by the driver.
This is for debugging purposes. In production code, it can be removed.
*/
// command "test"
command "ResetDriverStateData"
command "getFirmwareVersion"
/**
setParameter is a generalized function for setting parameters.
*/
command "setParameter",[
[name:"parameterNumber",type:"NUMBER", description:"Parameter Number", constraints:["NUMBER"]],
[name:"size",type:"NUMBER", description:"Parameter Size", constraints:["NUMBER"]],
[name:"value",type:"NUMBER", description:"Parameter Value", constraints:["NUMBER"]]
]
// fingerprint inClusters:"0x5E,0x25,0x85,0x8E,0x59,0x55,0x86,0x72,0x5A,0x73,0x70,0x5B,0x6C,0x9F,0x7A", deviceJoinName: "ZWave Plus CentralScene Dimmer" //US
}
preferences
{
input name: "advancedEnable", type: "bool", title: "Enable Advanced Configuration", defaultValue: true
if (advancedEnable)
{
input name: "logEnable", type: "bool", title: "Enable debug logging", defaultValue: false
input name: "txtEnable", type: "bool", title: "Enable text logging", defaultValue: true
// input name: "confirmSend", type: "bool", title: "Always confirm new value after sending to device (reduces performance)", defaultValue: false
state.parameterInputs?.each { input it.value }
}
}
}
void ResetDriverStateData()
{
state.clear()
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////// Utilities for storing data in a global Hash Map shared across driver instances ////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// The following ConcurrentHashMap is used to store data with a device key consisting of manufacturer/ device ID / device type / firmware main / firmware sub
@Field static ConcurrentHashMap<String, Map> deviceSpecificData = new ConcurrentHashMap<String, Map>()
/**
getDeviceMapForProduct returns the main Map data structure containing all the data gathered for the particular Product and firmware version. The data may have been gathered by any of the drivers!
*/
synchronized Map getDeviceMapForProduct()
{
String manufacturer = hubitat.helper.HexUtils.integerToHexString( device.getDataValue("manufacturer").toInteger(), 2)
String deviceType = hubitat.helper.HexUtils.integerToHexString( device.getDataValue("deviceType").toInteger(), 2)
String deviceID = hubitat.helper.HexUtils.integerToHexString( device.getDataValue("deviceId").toInteger(), 2)
Map deviceFirmware = getFirmwareVersion()
Integer firmwareMain = deviceFirmware.main as Integer
Integer firmwareSub = deviceFirmware.sub as Integer
String key = "${manufacturer}:${deviceType}:${deviceID}:${firmwareMain}:${firmwareSub}"
return deviceSpecificData.get(key, [:])
}
synchronized Map getDeviceMapByNetworkID()
{
String netID = device.getDeviceNetworkId()
return deviceSpecificData.get(netID, [:])
}
/*
//////////////////////////////////////////////////////////////////////
////// Get Device's Database Information Version ///////
//////////////////////////////////////////////////////////////////////
The function getDeviceDataFromDatabase() accesses the Z-Wave device database at www.opensmarthouse.org to
retrieve a database record that contains a detailed description of the device.
Since the database records are firmware-dependent, This function
should be called AFTER retrieving the device's firmware version using getFirmwareVersionFromDevice().
*/
synchronized Map getInputControlsForDevice()
{
Map inputControls = getDeviceMapForProduct().get("inputControls", [:])
if (inputControls?.size() > 0)
{
// if (logEnable) log.debug "Already have input controls for device ${device.displayName}."
if (state.parameterInputs.is(null)) state.parameterInputs = inputControls
return inputControls
} else if (state.parameterInputs) {
if (logEnable) log.debug "Loading Input Controls from saved state data."
state.parameterInputs.each{ k, v -> inputControls.put( k as Integer, v) }
return inputControls
} else {
if (logEnable) log.debug "Retrieving input control date from opensmarthouse.org for device ${device.displayName}."
try {
List parameterData = getOpenSmartHouseData()
inputControls = createInputControls(allParameterData)
getDeviceMapForProduct().put("inputControls", inputControls)
} catch (Exception ex) {
log.warn "Device ${device.displayName}: An Error occurred when attempting to get input controls. Error: ${ex}."
} finally {
state.parameterInputs = inputControls
return inputControls
}
}
}
List getOpenSmartHouseData()
{
if (txtEnable) log.info "Getting data from OpenSmartHouse for device ${device.displayName}."
String manufacturer = hubitat.helper.HexUtils.integerToHexString( device.getDataValue("manufacturer").toInteger(), 2)
String deviceType = hubitat.helper.HexUtils.integerToHexString( device.getDataValue("deviceType").toInteger(), 2)
String deviceID = hubitat.helper.HexUtils.integerToHexString( device.getDataValue("deviceId").toInteger(), 2)
String DeviceInfoURI = "http://www.opensmarthouse.org/dmxConnect/api/zwavedatabase/device/list.php?filter=manufacturer:0x${manufacturer}%20${deviceType}:${deviceID}"
def mydevice
Map deviceFirmwareVersion = getFirmwareVersion()
httpGet([uri:DeviceInfoURI])
{
resp ->
mydevice = resp.data.devices.find
{ element ->
Minimum_Version = element.version_min.split("\\.")
Maximum_Version = element.version_max.split("\\.")
Integer minMainVersion = Minimum_Version[0].toInteger()
Integer minSubVersion = Minimum_Version[1].toInteger()
Integer maxMainVersion = Maximum_Version[0].toInteger()
Integer maxSubVersion = Maximum_Version[1].toInteger()
if(logEnable) log.debug "Device firmware version in getDeviceDataFromDatabase httpGet is ${deviceFirmwareVersion}"
Boolean aboveMinimumVersion = (deviceFirmwareVersion.main > minMainVersion) || ((deviceFirmwareVersion.main == minMainVersion) && (deviceFirmwareVersion.sub >= minSubVersion))
Boolean belowMaximumVersion = (deviceFirmwareVersion.main < maxMainVersion) || ((deviceFirmwareVersion.main == maxMainVersion) && (deviceFirmwareVersion.sub <= maxSubVersion))
aboveMinimumVersion && belowMaximumVersion
}
}
if (! mydevice.id)
{
log.warn "Device ${device.displayName}: No database entry found for manufacturer: ${manufacturer}, deviceType: ${deviceType}, deviceID: ${deviceID}"
return null
}
String queryByDatabaseID= "http://www.opensmarthouse.org/dmxConnect/api/zwavedatabase/device/read.php?device_id=${mydevice.id}"
httpGet([uri:queryByDatabaseID]) { resp->
allParameterData = getDeviceMapForProduct().get("opensmarthouse", resp.data).parameters
}
return allParameterData
}
Map createInputControls(data)
{
Map inputControls = [:]
if (logEnable) log.debug "Device ${device.displayName}: Creating Input Controls"
data.each
{
// log.debug "Creating input control for parameter data: ${it}"
if (it.bitmask.toInteger())
{
if (!(inputControls?.get(it.param_id)))
{
log.warn "Device ${device.displayName}: Parameter ${it.param_id} is a bitmap field. This is poorly supported. Treating as an integer - rely on your user manual for proper values!"
Map newInput = [name: "configParam${"${it.param_id}".padLeft(3, "0")}", type:"integer", title: "(${it.param_id}) ${it.label} - bitmap", description: it.description, size:it.size, defaultValue: it.default]
inputControls.put(it.param_id, newInput)
}
/*
if (!(inputControls?.get(it.param_id)))
{
Map newInput = [name: "configParam${"${it.param_id}".padLeft(3, "0")}", title: "(${it.param_id}) Choose Multiple", type:"enum", multiple: true, size:it.size, options: [:]]
newInput.options.put(it.bitmask.toInteger(), "${it.description}")
inputControls.put(it.param_id, newInput)
} else { // add to the existing bitmap control
Map Options = inputControls[it.param_id].options
Options.put(it.bitmask.toInteger(), "${it.label} - ${it.options[1]?.label}")
Options = Options.sort()
if (logEnable) log.debug "Sorted bitmap Options: ${Options}"
inputControls[it.param_id].options = Options
}
*/
} else {
Map newInput = [name: "configParam${"${it.param_id}".padLeft(3, "0")}", title: "(${it.param_id}) ${it.label}", description: it.description, size:it.size, required: true , defaultValue: it.default]
def deviceOptions = [:]
it.options.each { deviceOptions.put(it.value, it.label) }
// Set input type. Should be one of: bool, date, decimal, email, enum, number, password, time, text. See: https://docs.hubitat.com/index.php?title=Device_Preferences
if (deviceOptions)
{
newInput.type = "enum"
newInput.options = deviceOptions
} else {
newInput.type = "integer"
}
inputControls[it.param_id] = newInput
}
}
return inputControls
}
//////////////////////////////////////////////////////////////////////
////// Initialization, update, and uninstall sequence ///////
//////////////////////////////////////////////////////////////////////
void refresh()
{
if (txtEnable) "Refreshing device ${device.displayName} status .."
sendToDevice(secure(zwave.basicV1.basicGet()))
if (getZwaveClassVersionMap().containsKey(0x32)) { meterRefresh() }
}
void installed() { initialize() }
void configure() { initialize() }
Integer getMajorVersion(String semVer)
{
def a = semVer?.split("\\.")
if (a.is( null ) ) {
return -1
} else {
return a[0] as Integer
}
}
void initialize()
{
log.info "Initializing device ${device.displayName}."
if (state.driverVersionNum == "0.0.2") state.remove("parameterInputs")
if (deleteAndResetStateData) state.clear()
if (state.driverVersionNum.is( null) || (getMajorVersion(state.driverVersionNum) != getMajorVersion(driverVersion)))
{
log.info "Driver main version number updated for device ${device.displayName}, resetting all state data."
state.clear()
state.driverVersionNum = driverVersion
} else if (state.driverVersionNum != driverVersion) {
state.driverVersionNum = driverVersion
}
state.firmwareVersion = getFirmwareVersion()
if (txtEnable) log.info "Device ${device.displayName} has firmware version: " + state.firmwareVersion
state.ZwaveClassVersions = getZwaveClassVersionMap()
state.parameterInputs = getInputControlsForDevice()
def opensmarthouseData = getDeviceMapForProduct()?.get("opensmarthouse")
if (opensmarthouseData)
{
String inclusionInstructions = opensmarthouseData?.get("inclusion")
String exclusionInstructions = opensmarthouseData?.get("exclusion")
state.inclusion = "To include, set Hubitat in Z-Wave Include mode, then: ${inclusionInstructions}"
state.exclusion = "To exclude, set Hubitat in Z-Wave Exclude mode, then: ${exclusionInstructions}"
state.device = "${opensmarthouseData.manufacturer?.label}: ${opensmarthouseData?.label}, ${opensmarthouseData?.description}."
}
getAllParameterValues()
setIsDigitalEvent( false )
getCentralSceneInfo()
if (getZwaveClassVersionMap().containsKey(0x32))
{
state.metersSupported = getSupportedMeters()
}
refresh()
log.info "Completed initializing device ${device.displayName}."
}
/** Miscellaneous state and device data cleanup tool used during debugging and development
*/
void cleanup()
{
device.removeDataValue("firmwareVersion")
device.removeDataValue("hardwareVersion")
device.removeDataValue("protocolVersion")
device.removeDataValue("zwaveAssociationG1")
device.removeDataValue("zwNodeInfo")
}
void logsOff(){
log.warn "Device ${device.displayName}: debug logging disabled..."
device.updateSetting("logEnable",[value:"false",type:"bool"])
}
////////////////////////////////////////////////////////////////////////
///////////// Parameter Updating and Management /////////////
////////////////////////////////////////////////////////////////////////
// Need to use ConcurrentHashMap to process received parameters to ensure there isn't a conflict in the update!
@Field static ConcurrentHashMap<String, Map> allParameterDataStorage = new ConcurrentHashMap<String, Map>()
Map getPendingChangeMap()
{
String key = "${device.getDeviceNetworkId()}:pendingChanges"
allParameterDataStorage.get(key, [:])
}
Map getCurrentParameterValueMap()
{
String key = "${device.getDeviceNetworkId()}:currentValues"
if (!allParameterDataStorage.containsKey(key)) {
Map parameterValues = [:]
if (state.parameterValues) {
state.parameterValues.each{ k, v -> parameterValues.put(k as Integer, v as Integer)}
}
allParameterDataStorage.put(key, parameterValues)
}
return allParameterDataStorage.get(key)
}
void updated()
{
if (txtEnable) log.info "Device ${device.displayName}: Updating changed parameters (if any) . . ."
if (logEnable) runIn(1800,logsOff)
Map parameterValueMap = getCurrentParameterValueMap()
Map pendingChangeMap = getPendingChangeMap()
if (logEnable) log.debug "Device ${device.displayName}: Updating paramameter values. Last retrieved values are: " + parameterValueMap
// state.parameterValues = parameterValueMap
// Collect the settings values from the input controls
Map settingValueMap = [:]
getInputControlsForDevice().each { PKey , PData ->
Integer newValue = 0
// if the setting returne an array, then its a bitmap control, and add together the values.
if (settings[PData.name] instanceof ArrayList)
{
settings[PData.name].each{ newValue += it as Integer }
} else {
newValue = settings[PData.name] as Integer
}
settingValueMap.put(PKey as Integer, newValue)
}
if (logEnable) log.debug "Device ${device.displayName}: Updating paramameter values. Settings control values are: " + settingValueMap
// Find what change
settingValueMap.each {k, v ->
if (parameterValueMap?.get(k as Integer).is( null) )
{
if (logEnable) log.debug "Device ${device.displayName}: parameterValueMap ${k} is null." + pendingChangeMap
pendingChangeMap.put(k as Integer, v as Integer)
} else {
Boolean changedValue = (v as Integer) != (parameterValueMap.get(k as Integer) as Integer)
if (changedValue) pendingChangeMap.put(k as Integer, v as Integer)
}
}
if (logEnable) log.debug "Device ${device.displayName}: Pending changes are: " + pendingChangeMap
if (logEnable) log.debug "Device ${device.displayName}: Pending changes in ConcurrentHashMap are: " + getPendingChangeMap()
state.pendingChanges = pendingChangeMap
processPendingChanges()
}
void processPendingChanges()
{
// Hubitat state storage seems to convert integer keys to strings. Convert them back!
Map parameterValueMap = getCurrentParameterValueMap()
Map pendingChangeMap = getPendingChangeMap()
Map parameterSizeMap = state.parameterInputs?.collectEntries{k, v -> [(k as Integer):(v.size as Short)]}
if (logEnable) log.debug "Device ${device.displayName}: Processing pending parameter changes. Pending Change Data is: " + pendingChangeMap
if (parameterValueMap.is( null))
{
log.warn "Device ${device.displayName}: Error: tried to process parameter data, but missing state.parameterValues map!"
return
}
pendingChangeMap?.each{ k, v ->
Short PSize = parameterSizeMap?.get(k as Integer)
if (logEnable) log.debug "Device ${device.displayName}: Parameters for setParameter are: parameterNumber: ${k as Short}, size: ${PSize}, value: ${v}."
setParameter((k as Short), (PSize as Short), (v as BigInteger) )
}
}
//////////////////////////////////////////////////////////////////////
/////// Set, Get, and Process Parameter Values ////////
//////////////////////////////////////////////////////////////////////
void getParameterValue(parameterNumber)
{
sendToDevice(secure(zwave.configurationV1.configurationGet(parameterNumber: parameterNumber as Integer)))
}
void getAllParameterValues()
{
List<hubitat.zwave.Command> cmds=[]
getInputControlsForDevice().each{k, v ->
cmds << secure(zwave.configurationV1.configurationGet(parameterNumber: k as Integer))
}
if (cmds) {
if (txtEnable) log.info "Device ${device.displayName}: Sending commands to get all parameter values."
sendToDevice(cmds)
} else {
if (txtEnable) log.info "Device ${device.displayName}: No parameter values to retrieve."
}
}
void setParameter(Short parameterNumber = null, Short size = null, BigInteger value = null){
if (parameterNumber.is( null ) || size.is( null ) || value.is( null ) ) {
log.warn "Device ${device.displayName}: Can't set parameter ${parameterNumber}, Incomplete parameter list supplied... syntax: setParameter(parameterNumber,size,value), received: setParameter(${parameterNumber}, ${size}, ${value})."
} else {
List<hubitat.zwave.Command> cmds = []
cmds << secure(zwave.configurationV1.configurationSet(scaledConfigurationValue: value, parameterNumber: parameterNumber, size: size))
cmds << secure(zwave.configurationV1.configurationGet(parameterNumber: parameterNumber))
sendToDevice(cmds)
}
}
void zwaveEvent(hubitat.zwave.commands.configurationv1.ConfigurationReport cmd) { processConfigurationReport(cmd) }
void zwaveEvent(hubitat.zwave.commands.configurationv2.ConfigurationReport cmd) { processConfigurationReport(cmd) }
void processConfigurationReport(cmd) {
Map parameterValueMap = getCurrentParameterValueMap()
Map pendingChangeMap = getPendingChangeMap()
Map parameterInputs = getInputControlsForDevice()
parameterValueMap.put(cmd.parameterNumber as Integer, cmd.scaledConfigurationValue)
pendingChangeMap.remove(cmd.parameterNumber as Integer)
state.parameterValues = parameterValueMap
state.pendingChanges = pendingChangeMap
if (parameterInputs.get(cmd.parameterNumber as Integer)?.multiple as Boolean)
{
log.warn "Device ${device.displayName}: Code incomplete - Parameter ${cmd.parameterNumber} is a bitmap type which is not fully processed!"
} else {
device.updateSetting("configParam${"${cmd.parameterNumber as Integer}".padLeft(3,"0")}" ,[value: (cmd.parameterNumber as Integer)])
}
}
//////////////////////////////////////////////////////////////////////
////// Handle Supervision request ///////
//////////////////////////////////////////////////////////////////////
void zwaveEvent(hubitat.zwave.commands.supervisionv1.SupervisionGet cmd) {
if (logEnable) log.debug "Device ${device.displayName}: Supervision get: ${cmd}"
Map parseMap = state.ZwaveClassVersions?.collectEntries{k, v -> [(k as Integer) : (v as Integer)]}
// Map parseMap = getCommandClassVersions()
hubitat.zwave.Command encapsulatedCommand = cmd.encapsulatedCommand(parseMap)
if (encapsulatedCommand) {
zwaveEvent(encapsulatedCommand)
}
sendToDevice(secure((new hubitat.zwave.commands.supervisionv1.SupervisionReport(sessionID: cmd.sessionID, reserved: 0, moreStatusUpdates: false, status: 0xFF, duration: 0))))
}
//////////////////////////////////////////////////////////////////////
////// Get Device Firmware Version ///////
//////////////////////////////////////////////////////////////////////
@Field static Semaphore firmwareMutex = new Semaphore(1)
@Field static ConcurrentHashMap<String, Map> firmwareStore = new ConcurrentHashMap<String, Map>()
synchronized Map getFirmwareVersion()
{
if (firmwareStore.containsKey("${device.getDeviceNetworkId()}")) {
return firmwareStore.get("${device.getDeviceNetworkId()}")
} else if ((state.firmwareVersion) && ((state.firmwareVersion?.main as Integer) != 255) ) {
if (logEnable) log.debug "Device ${device.displayName}: Loading firmware version from state.firmwareVersion which has value: ${state.firmwareVersion}."
return firmwareStore.get("${device.getDeviceNetworkId()}", [main: (state.firmwareVersion.main as Integer), sub: (state.firmwareVersion.sub as Integer)])
} else {
// Lock a Semaphore which gets released by the handling function after it receives a response from the device
Boolean waitingForDeviceResponse = firmwareMutex.tryAcquire(1, 20, TimeUnit.SECONDS )
if (waitingForDeviceResponse == false) {
log.warn "Device ${device.displayName}, Timed out getting lock to retrieve firmware version for device ${device.displayName}. Try restarting Hubitat."
}
sendToDevice(secure(zwave.versionV1.versionGet()))
// When the firmware report handler is done it will release firmwareMutex lock
// Thus, once code can acquire the Semaphore again, it knows the device responded and the firmware handler has completed
Boolean deviceResponded = firmwareMutex.tryAcquire(1, 15, TimeUnit.SECONDS )
if (deviceResponded == false) {
log.warn "Device ${device.displayName}: Possible processing error getting firmware report for device ${device.displayName}. Didn't get a response in time. Try restarting Hubitat."
}
firmwareMutex.release()
if (firmwareStore.containsKey("${device.getDeviceNetworkId()}")) {
return firmwareStore.get("${device.getDeviceNetworkId()}")
}
}
log.warn "Device ${device.displayName}: Failed to get firmware from device, using a defaul value of main:255, sub:255. The driver will try again next time firmware version is requested."
return [main:255, sub:255]
}
void zwaveEvent(hubitat.zwave.commands.versionv1.VersionReport cmd) {
if (logEnable) log.debug "Device ${device.displayName}: Network id: ${"${device.getDeviceNetworkId()}"}, Received firmware version V1 report: ${cmd}"
if (firmwareStore.containsKey("${device.getDeviceNetworkId()}")) {
firmwareStore.remove("${device.getDeviceNetworkId()}")
}
firmwareStore.put("${device.getDeviceNetworkId()}", [main:cmd.applicationVersion as Integer, sub:cmd.applicationSubVersion as Integer] )
if (txtEnable) log.info "Device ${device.displayName}: firmware version is: ${firmwareStore.get("${device.getDeviceNetworkId()}")}."
// The calling function getFirmwareVersion() is waiting for this handler to finish, which is indicated by releasing a Semaphore.
firmwareMutex.release()
}
void zwaveEvent(hubitat.zwave.commands.versionv2.VersionReport cmd) {processFirmwareReport(cmd) }
void zwaveEvent(hubitat.zwave.commands.versionv3.VersionReport cmd) {processFirmwareReport(cmd) }
void processFirmwareReport(cmd)
{
if (logEnable) log.debug "Device ${device.displayName}: Network id: ${"${device.getDeviceNetworkId()}"}, Received firmware version report: ${cmd}"
if (firmwareStore.containsKey("${device.getDeviceNetworkId()}")) {
firmwareStore.remove("${device.getDeviceNetworkId()}")
}
firmwareStore.put("${device.getDeviceNetworkId()}", [main:cmd.firmware0Version as Integer, sub:cmd.firmware0SubVersion as Integer] )
if (txtEnable) log.info "Device ${device.displayName}: firmware version is: ${firmwareStore.get("${device.getDeviceNetworkId()}")}."
firmwareMutex.release()
}
//////////////////////////////////////////////////////////////////////
////// Z-Wave Helper Functions ///////
////// Format messages, Send to Device, secure Messages ///////
//////////////////////////////////////////////////////////////////////
void zwaveEvent(hubitat.zwave.commands.securityv1.SecurityMessageEncapsulation cmd) {
Map parseMap = state.ZwaveClassVersions?.collectEntries{k, v -> [(k as Integer) : (v as Integer)]}
// The following lines should only impact firmware gets that occur before the classes are obtained.
if (parseMap.is( null )) {
parseMap = [:]
}
if (!parseMap.containsKey(0x86 as Integer)) {
parseMap.put(0x86 as Integer, 1 as Integer)
}
hubitat.zwave.Command encapsulatedCommand = cmd.encapsulatedCommand(parseMap)
if (encapsulatedCommand) {
zwaveEvent(encapsulatedCommand)
}
}
void zwaveEvent(hubitat.zwave.commands.multichannelv3.MultiChannelCmdEncap cmd) { processMultichannelEncapsulatedCommand( cmd) }
void zwaveEvent(hubitat.zwave.commands.multichannelv4.MultiChannelCmdEncap cmd) { processMultichannelEncapsulatedCommand( cmd) }
void processMultichannelEncapsulatedCommand( cmd)
{
Map parseMap = state.ZwaveClassVersions?.collectEntries{k, v -> [(k as Integer) : (v as Integer)]}
// The following lines should only impact firmware gets that occur before the classes are obtained.
if (parseMap.is( null )) {
parseMap = [:]
}
if (!parseMap.containsKey(0x86 as Integer)) {
parseMap.put(0x86 as Integer, 1 as Integer)
}
log.debug "Device ${device.displayName}: Processing Multi Channel Encapsulated Command: ${cmd}"
def encapsulatedCommand = cmd.encapsulatedCommand(parseMap)
log.debug "Device ${device.displayName}: Parsed Multi Channel Encapsulated Command: ${encapsulatedCommand} for endpoint ${cmd.sourceEndPoint}."
if (encapsulatedCommand) {
zwaveEvent(encapsulatedCommand, cmd.sourceEndPoint as Integer)
}
}
void parse(String description) {
Map parseMap = state.ZwaveClassVersions?.collectEntries{k, v -> [(k as Integer) : (v as Integer)]}
// The following 2 lines should only impact firmware gets that occur before the classes are obtained.
if (parseMap.is( null )) parseMap = [:]
if(!parseMap.containsKey(0x86 as Integer)) parseMap.put(0x86 as Integer, 1 as Integer)
hubitat.zwave.Command cmd = zwave.parse(description, parseMap)
if (cmd) {
zwaveEvent(cmd)
}
}
void sendToDevice(List<hubitat.zwave.Command> cmds) { sendHubCommand(new hubitat.device.HubMultiAction(commands(cmds), hubitat.device.Protocol.ZWAVE)) }
void sendToDevice(hubitat.zwave.Command cmd) { sendHubCommand(new hubitat.device.HubAction(cmd, hubitat.device.Protocol.ZWAVE)) }
void sendToDevice(String cmd) { sendHubCommand(new hubitat.device.HubAction(cmd, hubitat.device.Protocol.ZWAVE)) }
List<String> commands(List<hubitat.zwave.Command> cmds, Long delay=200) { return delayBetween(cmds.collect{ it }, delay) }
String secure(String cmd, ep = null){
if (ep) {
return zwaveSecureEncap(zwave.multiChannelV3.multiChannelCmdEncap(destinationEndPoint: ep).encapsulate(cmd))
} else {
return zwaveSecureEncap(cmd)
}
}
String secure(hubitat.zwave.Command cmd, ep = null){
if (ep) {
return zwaveSecureEncap(zwave.multiChannelV3.multiChannelCmdEncap(destinationEndPoint: ep).encapsulate(cmd))
} else {
return zwaveSecureEncap(cmd)
}
}
void zwaveEvent(hubitat.zwave.Command cmd) {
if (logEnable) log.debug "For ${device.displayName}, skipping command: ${cmd}"
}
//////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
//////////// Learn the Z-Wave Class Versions Actually Implemented ////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
/*
0x20:2 (32) // Basic
0x25: (37) // Switch Binary
0x26: (38) // Switch Multilevel
0x5B:3, (91) // Central Scene, Max is 3
0x6C (108)// supervision
0x70:1, (112)// Configuration. Max is 2
0x86:3, (134) // version V1, Max is 3
*/
@Field static ConcurrentHashMap<String, Map> deviceClasses = new ConcurrentHashMap<String, Map>()
@Field static Semaphore classVersionMutex = new Semaphore(2)
String productKey()
{
String manufacturer = hubitat.helper.HexUtils.integerToHexString( device.getDataValue("manufacturer").toInteger(), 2)
String deviceType = hubitat.helper.HexUtils.integerToHexString( device.getDataValue("deviceType").toInteger(), 2)
String deviceID = hubitat.helper.HexUtils.integerToHexString( device.getDataValue("deviceId").toInteger(), 2)
Map deviceFirmware = getFirmwareVersion() ?: [main:255 as Integer, sub:255 as Integer]
Integer firmwareMain = deviceFirmware.get("main") as Integer
Integer firmwareSub = deviceFirmware.get("sub") as Integer
String key = "${manufacturer}:${deviceType}:${deviceID}:${firmwareMain}:${firmwareSub}"
// if (logEnable) log.debug "Product key in function productKey manufacturer:deviceType:deviceID:firmwareMain:firmwareSub is set to: ${key}."
return key
}
Map getClasses() {
String key = productKey()
return deviceClasses.get(key, [:])
}
synchronized Map getZwaveClassVersionMap(){
// All the inclusters supported by the device
List<Integer> deviceInclusters = getDataValue("inClusters")?.split(",").collect{ hexStrToUnsignedInt(it) as Integer }
deviceInclusters += getDataValue("secureInClusters")?.split(",").collect{ hexStrToUnsignedInt(it) as Integer }
if (!deviceInclusters.contains(32)) deviceInclusters += 32
if ( getClasses().is( null) || (getClasses().size()) == 0)
{
if (logEnable) log.debug "Device ${device.displayName}: product: ${productKey()}, initialize class versions using state.ZwaveClassVersions which is ${state.ZwaveClassVersions}"
state.ZwaveClassVersions?.each{
getClasses().put(it.key as Integer, it.value as Integer)
}
}
if (logEnable) log.warn "Version 2.2.4 of Hubitat has an error in processing the central scene report. Forcing central scene to version 1."
getClasses().put(0x5B as Integer, 1 as Integer)
if (logEnable) log.debug "Device ${device.displayName}: Current classes for product key ${productKey()} are ${getClasses()}."
List<Integer> neededClasses = []
deviceInclusters.each { if (!getClasses().containsKey(it as Integer)) (neededClasses << it ) }
neededClasses = neededClasses.unique().sort()
if (neededClasses.size() == 0)
{
if (logEnable) log.debug "Device ${device.displayName}: Already collected all command classes. Classes are: " + getClasses()
return getClasses()
} else {
if (logEnable) log.debug "Device ${device.displayName}: Retrieving command class versions. Missing Class count: ${neededClasses}."
try
{
neededClasses.each {
classVersionMutex.tryAcquire(1, 5, TimeUnit.SECONDS )
if (logEnable) log.debug "Device ${device.displayName}: Getting version information for Zwave command class: " + it
sendToDevice(secure(zwave.versionV3.versionCommandClassGet(requestedCommandClass:it.toInteger())))
}
classVersionMutex.tryAcquire(2, 5, TimeUnit.SECONDS )
if (logEnable) log.debug "Device ${device.displayName}: Stored command classes are: " + getClasses()
// classVersionMutex.release(2)
}
catch (Exception ex)
{
log.warn "Device ${device.displayName}: An Error occurred when attempting to get input controls. Error: ${ex}."
}
finally
{
classVersionMutex.release(2)
return getClasses()
}
}
}
// There are 3 versions of command class reports - could just include only the highest and let Groovy resolve!
void zwaveEvent(hubitat.zwave.commands.versionv1.VersionCommandClassReport cmd) { processVersionCommandClassReport (cmd) }
void zwaveEvent(hubitat.zwave.commands.versionv2.VersionCommandClassReport cmd) { processVersionCommandClassReport (cmd) }
void zwaveEvent(hubitat.zwave.commands.versionv3.VersionCommandClassReport cmd) { processVersionCommandClassReport (cmd) }
void processVersionCommandClassReport (cmd) {
if (logEnable) log.debug "Initializing device ${device.displayName}, Adding command class info with class: ${cmd.requestedCommandClass}, version: ${cmd.commandClassVersion}"
if ( getClasses().containsKey(cmd.requestedCommandClass as Integer)) getClasses().remove(cmd.requestedCommandClass as Integer)
getClasses().put(cmd.requestedCommandClass as Integer, cmd.commandClassVersion as Integer)
classVersionMutex.release(1)
}
///////////////////////////////////////////////////////////////////////////////////////////////
/////////////// Central Scene Processing ////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
@Field static Map<String, String> CCButtonState = [:]
String getCCButtonState(Integer button) {
String key = "${device.getDeviceNetworkId()}.Button.${button}"
return CCButtonState.get(key)
}
String putCCButtonState(Integer button, String state)
{
String key = "${device.getDeviceNetworkId()}.Button.${button}"
CCButtonState.put(key, state)
return CCButtonState.get(key)
}
// The 'get" is the same in all versions of command class so just use the highest version supported!
void getCentralSceneInfo() {
sendToDevice(secure( zwave.centralSceneV3.centralSceneSupportedGet() ))
}
// ====================
void zwaveEvent(hubitat.zwave.commands.centralscenev1.CentralSceneSupportedReport cmd) {
if(logEnable) log.debug "Central Scene V1 Supported Report Info ${cmd}"
sendEvent(name: "numberOfButtons", value: cmd.supportedScenes)
}
void zwaveEvent(hubitat.zwave.commands.centralscenev2.CentralSceneSupportedReport cmd) {
if(logEnable) log.debug "Central Scene V2 Supported Report Info ${cmd}"
sendEvent(name: "numberOfButtons", value: cmd.supportedScenes)
}
void zwaveEvent(hubitat.zwave.commands.centralscenev3.CentralSceneSupportedReport cmd) {
if(logEnable) log.debug "Central Scene V3 Supported Report Info ${cmd}"
sendEvent(name: "numberOfButtons", value: cmd.supportedScenes)
}
// This next 2 functions operates as a backup in case a release report was lost on the network
// It will force a release to be sent if there has been a hold event and then
// a release has not occurred within the central scene hold button refresh period.
// The central scene hold button refresh period is 200 mSec for old devices (state.slowRefresh == false), else it is 55 seconds.
void forceReleaseMessage(button)
{
// only need to force a release hold if the button state is "held" when the timer expires
log.warn "Device ${device.displayName}: Central Scene Release message for button ${button} not received before timeout - Faking a release message!"
sendEvent(name:"released", value:button , type:"digital", descriptionText:"${device.displayName} button ${button} forced release")
putCCButtonState(button as Integer, "released")
}
void forceReleaseHold01(){ forceReleaseMessage(1)}
void forceReleaseHold02(){ forceReleaseMessage(2)}
void forceReleaseHold03(){ forceReleaseMessage(3)}
void forceReleaseHold04(){ forceReleaseMessage(4)}
void forceReleaseHold05(){ forceReleaseMessage(5)}
void forceReleaseHold06(){ forceReleaseMessage(6)}
void forceReleaseHold07(){ forceReleaseMessage(7)}
void forceReleaseHold08(){ forceReleaseMessage(8)}
void cancelLostReleaseTimer(button)
{
try {
switch (button)
{
case 1: unschedule(forceReleaseHold01); break
case 2: unschedule(forceReleaseHold02); break
case 3: unschedule(forceReleaseHold03); break
case 4: unschedule(forceReleaseHold04); break
case 5: unschedule(forceReleaseHold05); break
case 6: unschedule(forceReleaseHold06); break
case 7: unschedule(forceReleaseHold07); break
case 8: unschedule(forceReleaseHold08); break
default : log.warn "Device ${device.displayName}: Attempted to process lost release message code for button ${button}, but this is an error as code handles a maximum of 8 buttons."
}
}
catch (Exception ex) { log.debug "Device ${device.displayName}: Exception in function cancelLostReleaseTimer: ${ex}"}
}
void setReleaseGuardTimer(button)
{
// The code starts a release hold timer which will force a "release" to be issued
// if a refresh isn't received within the slow refresh period!
// If you get a refresh, executing again restarts the timer!
// Timer is canceled by the cancelLostReleaseTimer if a "real" release is received.
switch (button)
{
case 1: runIn(60, forceReleaseHold01); break
case 2: runIn(60, forceReleaseHold02); break
case 3: runIn(60, forceReleaseHold03); break
case 4: runIn(60, forceReleaseHold04); break
case 5: runIn(60, forceReleaseHold05); break
case 6: runIn(60, forceReleaseHold06); break
case 7: runIn(60, forceReleaseHold07); break
case 8: runIn(60, forceReleaseHold08); break
default : log.warn "Device ${device.displayName}: Attempted to process lost release message code for button ${button}, but this is an error as code handles a maximum of 8 buttons."
}
}
// ================== End of code to help handle a missing "Released" messages =====================
int tapCount(attribute)
{
// Converts a Central Scene command.keyAttributes value into a tap count
// Returns negative numbers for special values of Released (-1) and Held (-2).
switch (attribute)
{
case 0:
return 1
break
case 1: // Released
return -1
break
case 2: // Held
return -2
break
default : // For 3 or grater, subtract 1 from the attribute to get # of taps.
return (attribute - 1)
break
}
}
void zwaveEvent(hubitat.zwave.commands.centralscenev1.CentralSceneNotification cmd) { ProcessCCReport(cmd) }
void zwaveEvent(hubitat.zwave.commands.centralscenev2.CentralSceneNotification cmd) { ProcessCCReport(cmd) }
void zwaveEvent(hubitat.zwave.commands.centralscenev3.CentralSceneNotification cmd) { ProcessCCReport(cmd) }
synchronized void ProcessCCReport(cmd) {
Map event = [type:"physical", isStateChange:true]
if(logEnable) log.debug "Device ${device.displayName}: Received Central Scene Notification ${cmd}"
def taps = tapCount(cmd.keyAttributes)
if (getCCButtonState(cmd.sceneNumber as Integer) == "held")
{
// if currently holding, and receive anything except another hold or a release,
// then cancel any outstanding lost "release" message timer ...
if ((taps != (-2)) && (taps != (-1)))
{
// If you receive anything other than a release event, it means
// that the prior release event from the device was lost, so Hubitat
// is still in held state. Fix this by forcing a release message to be sent
// before doing anything else
forceReleaseMessage(cmd.sceneNumber)
}
// And cancel any timer that may be running for this held button.
cancelLostReleaseTimer(cmd.sceneNumber)
}
switch (taps)
{
case -1:
cancelLostReleaseTimer(cmd.sceneNumber)
event.name = "released"
event.value = cmd.sceneNumber
event.descriptionText="${device.displayName} button ${event.value} released"
if (txtEnable) log.info event.descriptionText
putCCButtonState(cmd.sceneNumber as Integer, event.name)
sendEvent(event)
break
case -2:
event.name = "held"
event.value = cmd.sceneNumber
if (getCCButtonState(cmd.sceneNumber as Integer) == "held")
{
// If currently holding and receive a refresh, don't send another hold message, Just report that still holding
// Refresh received every 55 seconds if slowRefresh is enabled by the device, else its received every 200 mSeconds.
if (logEnable) log.debug "Still Holding button ${cmd.sceneNumber}"
} else {
event.descriptionText="${device.displayName} button ${event.value} held"
if (logEnable) log.debug event.descriptionText
putCCButtonState(cmd.sceneNumber as Integer, event.name)
sendEvent(event)
}
// The following starts a guard timer to force a release hold if you don't get a refresh within the slow refresh period!
// If you get a refresh, executing again restarts the timer!
setReleaseGuardTimer(cmd.sceneNumber)
break
case 1:
event.name = "pushed"
event.value= cmd.sceneNumber
event.descriptionText="${device.displayName} button ${event.value} pushed"
if (txtEnable) log.info event.descriptionText
putCCButtonState(cmd.sceneNumber as Integer, event.name)
sendEvent(event)
break
case 2:
event.name = "doubleTapped"
event.value=cmd.sceneNumber
event.descriptionText="${device.displayName} button ${cmd.sceneNumber} doubleTapped"
if (txtEnable) log.info event.descriptionText
putCCButtonState(cmd.sceneNumber as Integer, event.name)
sendEvent(event)
break