-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test Code for Super Universal Z-Wave Driver.groovy
1017 lines (840 loc) · 41 KB
/
Test Code for Super Universal Z-Wave 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
/*
Operation Sequence ...
1. Get the device's firmware using: getFirmwareVersionFromDevice(), store it in state.firmware.[main: ##, sub: ##]
2. Get the device's database record using: getDeviceDataFromDatabase
*/
if ( ! state.universalDriverData) { state.universalDriverData = [:] }
metadata {
definition (name: "Testing Super Universal Zwave Plus Dimmer",namespace: "jvm", author: "jvm") {
// Pick one of the following 5 Capabilities. Comment out the remainder.
// capability "Bulb"
// capability "Light"
// capability "Outlet"
// capability "RelaySwitch"
capability "Switch"
// Include the following for dimmable devices.
capability "SwitchLevel"
capability "ChangeLevel"
capability "Initialize"
capability "Configuration"
capability "Refresh"
// 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"]
// The following is for debugging. In final code, it can be removed!
command "getDeviceDataFromDatabase"
// All data used by this driver is stored as a Map (more particulaly, as a Map of Maps)
// in the state variable "state.universalDriverData". The "uninstall" command deletes that key
// to clean up the data before the user changest back to the retular driver
command "uninstall"
command "EraseState"
// 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.universalDriverData?.zwaveParameters?.each { input it.value.input }
}
}
}
/*
//////////////////////////////////////////////////////////////////////
////// 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().
*/
void getDeviceDataFromDatabase()
{
if( state.universalDriverData.zwaveParameters)
{
log.debug "Already have parameter data. No need to retrieving again!"
return
}
if (txtEnable) log.info "Getting Device Information from www.opensmarthouse.org Database"
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)
if (logEnable) log.debug " manufacturer: ${manufacturer}, deviceType: ${deviceType}, deviceID: ${deviceID}, Version: ${state.firmware.main}, SubVersion: ${state.firmware.sub}"
String DeviceInfoURI = "http://www.opensmarthouse.org/dmxConnect/api/zwavedatabase/device/list.php?filter=manufacturer:0x${manufacturer}%20${deviceType}:${deviceID}"
def mydevice
httpGet([uri:DeviceInfoURI])
{ resp->
if(logEnable) log.debug "Response Data: ${resp.data}"
if(logEnable) log.debug "Response Data class: ${resp.data instanceof Map}"
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()
log.debug "state.firmware is ${state.firmware}"
Boolean aboveMinimumVersion = (state.firmware.main > minMainVersion) || ((state.firmware.main == minMainVersion) && (state.firmware.sub >= minSubVersion))
Boolean belowMaximumVersion = (state.firmware.main < maxMainVersion) || ((state.firmware.main == maxMainVersion) && (state.firmware.sub <= maxSubVersion))
aboveMinimumVersion && belowMaximumVersion
}
}
if(logEnable) log.debug "Database Identifier: ${mydevice.id}"
String queryByDatabaseID= "http://www.opensmarthouse.org/dmxConnect/api/zwavedatabase/device/read.php?device_id=${mydevice.id}"
httpGet([uri:queryByDatabaseID])
{ resp->
log.info "Retrieved data for device model: ${resp.data?.label}, Manufacturer: ${resp.data?.manufacturer?.label}"
allParameterData = resp.data.parameters
// if (logEnable) log.debug "Parameter Data in Response: ${allParameterData}"
}
state.universalDriverData.zwaveParameters = createInputControls(allParameterData)
if (logEnable) log.debug newData
}
Map createInputControls(data)
{
Map inputControls = [:]
data.each
{
if (logEnable) log.debug "current data is: $it"
if (it.bitmask.toInteger())
{
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, options: [:]]
newInput.options.put(it.bitmask.toInteger(), "${it.description}")
inputControls.put(it.param_id, [input: newInput, parameterData:[size:it.size]])
}
else // add to the existing bitmap control
{
inputControls[it.param_id].input.options.put(it.bitmask.toInteger(), "${it.label} - ${it.options[1].label}")
}
}
else
{
Map newInput = [name: "configParam${"${it.param_id}".padLeft(3, "0")}", title: "(${it.param_id}) ${it.label}", description: it.description, 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"
}
if(logEnable && deviceOptions) log.debug "deviceOptions is $deviceOptions"
if(logEnable) log.debug "newInput = ${newInput}"
inputControls[it.param_id] = [input: newInput, parameterData:[size:it.size]]
}
}
return inputControls
}
//////////////////////////////////////////////////////////////////////
////// Initialization, update, and uninstall sequence ///////
//////////////////////////////////////////////////////////////////////
void refresh() {
if(txtEnable) "Refreshing device ${device.displayName} status .."
List<hubitat.zwave.Command> cmds=[]
cmds.add(zwave.basicV1.basicGet())
sendToDevice(cmds)
}
void installed()
{
if (!state.universalDriverData) state.universalDriverData = [:]
if (!state.universalDriverData.zwaveParameters) state.universalDriverData.zwaveParameters =[:]
if (!state.ZwaveClassVersions) state.ZwaveClassVersions = [:]
getFirmwareVersionFromDevice() // sets the firmware version in state.firmware[main: ??,sub: ??]
getDeviceDataFromDatabase()
getZwaveClassVersions()
pollDevicesForCurrentValues()
}
void configure()
{
initialize()
}
void EraseState()
{
state.clear()
}
void initialize()
{
if (!state.universalDriverData) state.universalDriverData = [:]
if (!state.universalDriverData.zwaveParameters) state.universalDriverData.zwaveParameters =[:]
if (!state.ZwaveClassVersions) state.ZwaveClassVersions = [:]
getFirmwareVersionFromDevice() // sets the firmware version in state.firmware[main: ??,sub: ??]
pauseExecution(2000)
getZwaveClassVersions()
getDeviceDataFromDatabase()
pollDevicesForCurrentValues()
}
void uninstall()
{
state.remove("parameterTool")
state.remove("universalDriverData")
state.remove("universalDriverState")
state.remove("ZwaveClassVersions")
state.remove("opensmarthouse")
device.removeDataValue("firmwareVersion")
device.removeDataValue("hardwareVersion")
device.removeDataValue("protocolVersion")
device.removeDataValue("zwaveAssociationG1")
device.removeDataValue("zwNodeInfo")
}
void logsOff(){
log.warn "debug logging disabled..."
device.updateSetting("logEnable",[value:"false",type:"bool"])
}
void updated()
{
if (logEnable) log.debug "Updated function called"
if (logEnable) runIn(1800,logsOff)
/*
state.universalDriverData.zwaveParameters is arranged in key : value pairs.
key is the parameter #
value is a map of "input" controls, which is arranged under the sub-key "input"
so values are accessed as v.[input:[defaultValue:0, name:configParam004, options:[0:Normal, 1:Inverted], description:Controls the on/off orientation of the rocker switch, title:(4) Orientation, type:enum]]
*/
def integerSettings = [:]
state.universalDriverData?.zwaveParameters.each { Pkey , Pvalue ->
if( settings.containsKey(Pvalue.input.name))
{
if (logEnable) log.debug "Setting: ${Pvalue.input.name} = ${settings[Pvalue.input.name]}, and is of type ${settings[Pvalue.input.name].class}"
Integer newValue = 0
if (settings[Pvalue.input.name] instanceof ArrayList)
{
settings[Pvalue.input.name].each{ newValue += it as Integer }
}
else {
newValue = settings[Pvalue.input.name] as Integer
}
if (logEnable) log.debug "Parameter ${Pkey}, last retrieved value: ${Pvalue.parameterData.lastRetrievedValue}, New setting value = ${newValue}, Changed: ${(Pvalue.parameterData.lastRetrievedValue as Integer) != newValue}."
if ((Pvalue.parameterData.lastRetrievedValue as Integer) != newValue )
{
setParameter(Pkey, Pvalue.parameterData.size, newValue )
}
}
}
}
//////////////////////////////////////////////////////////////////////
/////// Set, Get, and Process Parameter Values ////////
//////////////////////////////////////////////////////////////////////
void getParameterValue(parameterNumber)
{
if (logEnable) log.debug "Getting value of parameter ${parameterNumber}"
List<hubitat.zwave.Command> cmds=[]
cmds.add(secure(zwave.configurationV1.configurationGet(parameterNumber: parameterNumber as Integer)))
if (cmds) sendToDevice(cmds)
}
void setParameter(parameterNumber, parameterSize, value){
if (txtEnable) log.info "Setting parameter ${parameterNumber}, of size ${parameterSize} to value ${value}."
if (parameterNumber.is( null ) || parameterSize.is( null ) || value.is( null )) {
log.warn "incomplete parameter list supplied..."
log.warn "syntax: setParameter(parameterNumber,parameterSize,value)"
return
}
List<hubitat.zwave.Command> cmds=[]
// All versions of configurationSet work the same!
cmds.add(secure(zwave.configurationV2.configurationSet(scaledConfigurationValue: value as Integer, parameterNumber: parameterNumber as Integer, size: parameterSize as Integer)))
cmds.add "delay 500"
cmds.add(secure(zwave.configurationV1.configurationGet(parameterNumber: parameterNumber as Integer)))
if (cmds) sendToDevice(cmds)
}
void pollDevicesForCurrentValues()
{ // On startup, poll all the devices for their initial values!
state.universalDriverData.zwaveParameters.each { k , v -> getParameterValue(k) }
}
void zwaveEvent(hubitat.zwave.commands.configurationv2.ConfigurationReport cmd) {
if (logEnable) log.debug "Received configuration report for parameter ${cmd.parameterNumber} indicating parameter set to value: ${cmd.scaledConfigurationValue}. Full report contents are: ${cmd}."
String parameterName = "configParam${"${cmd.parameterNumber}".padLeft(3, "0")}"
def currentValue = settings[parameterName]
def reportedValue = cmd.scaledConfigurationValue
// Sometimes the www.opemsmarthouse.org database has the wrong parameter sizes. Following code tries to correct that!
Integer storedSize = state.universalDriverData.zwaveParameters["${cmd.parameterNumber}"].parameterData.size
if (cmd.size != storedSize)
{
log.warn "Configuration report V2 returned from device for parameter ${cmd.parameterNumber} indicates a size of ${cmd.size}, while the database from www.opensmarthouse.org gave a size of ${storedSize}. Please report to developer! Making correction to local database. Please try your parameter setting again."
state.universalDriverData.zwaveParameters["${cmd.parameterNumber}"].input.put("parameterSize", cmd.size)
}
if (currentValue != reportedValue)
{
settings[parameterName] = reportedValue
}
state.universalDriverData.zwaveParameters["$cmd.parameterNumber"].parameterData.lastRetrievedValue = cmd.scaledConfigurationValue
}
// This is the exact same code as the preceding, with a v1 as the signature!
void zwaveEvent(hubitat.zwave.commands.configurationv1.ConfigurationReport cmd) {
if (logEnable) log.debug "Received configuration report for parameter ${cmd.parameterNumber} indicating parameter set to value: ${cmd.scaledConfigurationValue}. Full report contents are: ${cmd}."
String parameterName = "configParam${"${cmd.parameterNumber}".padLeft(3, "0")}"
def currentValue = settings[parameterName]
def reportedValue = cmd.scaledConfigurationValue
// Sometimes the www.opemsmarthouse.org database has the wrong parameter sizes. This tries to correct that!
if (cmd.size != state.universalDriverData.zwaveParameters["$cmd.parameterNumber"].parameterData.size)
{
log.warn "Configuration report V1 returned from device for parameter ${cmd.parameterNumber} indicates a size of ${cmd.size}, while the database from www.opensmarthouse.org gave a size of ${state.universalDriverData.zwaveParameters["$cmd.parameterNumber"].parameterData.size}. Please report to developer! Making correction to local database. Please try your parameter setting again."
state.universalDriverData.zwaveParameters["$cmd.parameterNumber"].parameterData.size = cmd.size
}
if (currentValue != reportedValue)
{
settings[parameterName] = reportedValue
}
state.universalDriverData.zwaveParameters["$cmd.parameterNumber"].parameterData.lastRetrievedValue = cmd.scaledConfigurationValue
}
//////////////////////////////////////////////////////////////////////
////// Handle Supervision request ///////
//////////////////////////////////////////////////////////////////////
void zwaveEvent(hubitat.zwave.commands.supervisionv1.SupervisionGet cmd) {
if (logEnable) log.debug "For ${device.displayName}, Supervision get: ${cmd}"
Map parseMap = state.ZwaveClassVersions.collectEntries{k, v -> [(k as Integer) : (v as Integer)]}
hubitat.zwave.Command encapsulatedCommand = cmd.encapsulatedCommand(parseMap)
if (encapsulatedCommand) {
zwaveEvent(encapsulatedCommand)
}
sendToDevice(new hubitat.zwave.commands.supervisionv1.SupervisionReport(sessionID: cmd.sessionID, reserved: 0, moreStatusUpdates: false, status: 0xFF, duration: 0))
}
//////////////////////////////////////////////////////////////////////
////// Get Device Firmware Version ///////
//////////////////////////////////////////////////////////////////////
void queryForFirmwareReport()
{
if (logEnable) log.debug "Querying for firmware report"
List<hubitat.zwave.Command> cmds = []
cmds.add(zwave.versionV3.versionGet())
sendToDevice(cmds)
}
void getFirmwareVersionFromDevice()
{
if (logEnable) log.debug "Calling getFirmwareVersionFromDevice with !state.firmware ${!state.firmware} and its value is: ${state.get("firmware")}"
if(!(state.firmware && state?.firmware.main && state?.firmware.sub))
{
queryForFirmwareReport()
}
}
void zwaveEvent(hubitat.zwave.commands.versionv1.VersionReport cmd) {
log.debug "For ${device.displayName}, Received V1 version report: ${cmd}"
if (! state.firmware) state.firmware = [:]
state.put("firmware", [main: cmd.applicationVersion, sub: cmd.applicationSubVersion])
log.info "Firmware version is: ${state.get("firmware")}"
}
void zwaveEvent(hubitat.zwave.commands.versionv2.VersionReport cmd) {
log.debug "For ${device.displayName}, Received V2 version report: ${cmd}"
if (! state.firmware) state.firmware = [:]
state.put("firmware", [main: cmd.firmware0Version, sub: cmd.firmware0SubVersion])
log.info "Firmware version is: ${state.get("firmware")}"
}
void zwaveEvent(hubitat.zwave.commands.versionv3.VersionReport cmd) {
log.debug "For ${device.displayName}, Received V3 version report: ${cmd}"
if (! state.firmware) state.firmware = [:]
state.put("firmware", [main: cmd.firmware0Version, sub: cmd.firmware0SubVersion])
log.info "Firmware version is: ${state.get("firmware")}"
}
//////////////////////////////////////////////////////////////////////
////// Z-Wave Helper Functions ///////
////// Format messages, Send to Device, secure Messages ///////
//////////////////////////////////////////////////////////////////////
void zwaveEvent(hubitat.zwave.commands.securityv1.SecurityMessageEncapsulation cmd) {
// hubitat.zwave.Command encapsulatedCommand = cmd.encapsulatedCommand(CMD_CLASS_VERS)
Map parseMap = state.ZwaveClassVersions?.collectEntries{k, v -> [(k as Integer) : (v as Integer)]}
hubitat.zwave.Command encapsulatedCommand = cmd.encapsulatedCommand(parseMap)
if (encapsulatedCommand) {
zwaveEvent(encapsulatedCommand)
}
}
void parse(String description) {
// if (logEnable) log.debug "For ${device.displayName}, parse:${description}"
Map parseMap = state.ZwaveClassVersions?.collectEntries{k, v -> [(k as Integer) : (v 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(secureCommand(cmd), hubitat.device.Protocol.ZWAVE))
}
void sendToDevice(String cmd) {
sendHubCommand(new hubitat.device.HubAction(secureCommand(cmd), hubitat.device.Protocol.ZWAVE))
}
List<String> commands(List<hubitat.zwave.Command> cmds, Long delay=50) {
return delayBetween(cmds.collect{ secureCommand(it) }, delay)
}
String secureCommand(hubitat.zwave.Command cmd) {
secureCommand(cmd.format())
}
String secureCommand(String cmd) {
String encap=""
if (getDataValue("zwaveSecurePairingComplete") != "true") {
return cmd
} else {
encap = "988100"
}
return "${encap}${cmd}"
}
String secure(String cmd){
return zwaveSecureEncap(cmd)
}
String secure(hubitat.zwave.Command cmd){
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
*/
Integer getZwaveClassVersions(){
List<hubitat.zwave.Command> cmds = []
Integer getItems = 0
if(logEnable) log.debug "Current Command Class version state is: ${state.ZwaveClassVersions}"
// All the inclusters suppored by the device
List<Integer> deviceInclusters = getDataValue("inClusters").split(",").collect{ hexStrToUnsignedInt(it) as Integer }
deviceInclusters << 32
// The next list is the classes actually used by this driver. We only need info. on those classes!
List<Integer> driverInclusters = [0x20, 0x25, 0x26, 0x5B, 0x6C, 0x70, 0x86]
driverInclusters.each {
if (deviceInclusters.contains(it))
{
Integer thisClass = it as Integer
if ( !state.ZwaveClassVersions?.get(thisClass as Integer) && !state.ZwaveClassVersions?.get(thisClass as String) )
{
getItems += 1
if(logEnable) log.debug "Requesting Command class version for class 0x${intToHexStr(it)}"
// gets are the same in all command class versions
cmds.add(zwave.versionV3.versionCommandClassGet(requestedCommandClass:it.toInteger()))
}
}
}
if(logEnable) log.debug "Getting ${getItems} command versions which were previously not retrieved."
if(cmds) sendToDevice(cmds)
return getItems
}
// 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 "Processing command class report to update state.ZwaveClassVersions received command ${cmd}. Current stored value array is ${state.ZwaveClassVersions}."
if (! state.containsKey("ZwaveClassVersions")) state.put("ZwaveClassVersions", [(cmd.requestedCommandClass) : (cmd.commandClassVersion)])
else
state.ZwaveClassVersions.put((cmd.requestedCommandClass), (cmd.commandClassVersion))
// For unknown reasons, a get following a put seems to "make sure" the value has been stored in state.
state.get("ZwaveClassVersions")
}
///////////////////////////////////////////////////////////////////////////////////////////////
/////////////// Central Scene Processing ////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// The 'get" is the same in all versions of command class so just use the highest version supported!
void getCentralSceneInfo() {
List<hubitat.zwave.Command> cmds = []
cmds.add( zwave.centralSceneV3.centralSceneSupportedGet() )
sendToDevice(cmds)
}
// ====================
void zwaveEvent(hubitat.zwave.commands.centralscenev1.CentralSceneSupportedReport cmd) {
if(logEnable) log.debug "Central Scene V1 Supported Report Info ${cmd}"
state.centralScene = cmd
sendEvent(name: "numberOfButtons", value: cmd.supportedScenes, isStateChange:true)
}
void zwaveEvent(hubitat.zwave.commands.centralscenev2.CentralSceneSupportedReport cmd) {
if(logEnable) log.debug "Central Scene V2 Supported Report Info ${cmd}"
state.centralScene = cmd
sendEvent(name: "numberOfButtons", value: cmd.supportedScenes, isStateChange:true)
}
void zwaveEvent(hubitat.zwave.commands.centralscenev3.CentralSceneSupportedReport cmd) {
if(logEnable) log.debug "Central Scene V3 Supported Report Info ${cmd}"
state.centralScene = cmd
sendEvent(name: "numberOfButtons", value: cmd.supportedScenes, isStateChange:true)
}
// 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 "Central Scene Release message for button ${button} not received before timeout - Faking a release message!"
sendEvent(name:"released", value:button , type:"digital", isStateChange:true, descriptionText:"${device.displayName} button ${button} forced release")
state.universalDriverState.buttons.put(button, "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 "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 "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 "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)
}
void ProcessCCReport(cmd) {
if (! state.universalDriverState) { state.universalDriverState = [:] }
if (! state.universalDriverState.buttons) { state.universalDriverState.buttons = [:] }
Map event = [type:"physical", isStateChange:true]
if(logEnable) log.debug "Received Central Scene Notification ${cmd}"
def taps = tapCount(cmd.keyAttributes)
if(logEnable) log.debug "Mapping of key attributes to Taps: ${taps}"
if (state.universalDriverState.buttons.get(cmd.sceneNumber) == "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
state.universalDriverState.buttons.put(cmd.sceneNumber, event.name)
sendEvent(event)
break
case -2:
event.name = "held"
event.value = cmd.sceneNumber
if (state.universalDriverState.buttons.get(cmd.sceneNumber) == "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 (txtEnable) log.info "Still Holding button ${cmd.sceneNumber}"
}
else
{
event.descriptionText="${device.displayName} button ${event.value} held"
if (txtEnable) log.info event.descriptionText
state.universalDriverState.buttons.put(cmd.sceneNumber, 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
state.universalDriverState.buttons.put(cmd.sceneNumber, 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
state.universalDriverState.buttons.put(cmd.sceneNumber, event.name)
sendEvent(event)
break
case 3: // Key Pressed 3 times
case 4: // Key Pressed 4 times
case 5: // Key Pressed 5 times
log.warn "Received and Ignored key tapped ${taps} times on button number ${cmd.sceneNumber}. Maximum button taps supported is 2"
break
}
}
//////////////////////////////////////////////////////////////////////
////// Handle Basic Reports and Device Functions ///////
//////////////////////////////////////////////////////////////////////
void zwaveEvent(hubitat.zwave.commands.switchbinaryv1.SwitchBinaryReport cmd) {
if (logEnable) log.debug "Received SwitchBinaryReport v1 containing: ${cmd}"
if (device.hasAttribute("switch") || device.hasCapability("Switch"))
{
if (logEnable) log.debug "${device.displayName} Sending a switch ${(cmd.value ? "on" : "off")} event"
eventProcess( name: "switch", value: (cmd.value ? "on" : "off"),
descriptionText: "Device ${device.displayName} set to ${(cmd.value ? "on" : "off")}.", type: "physical" )
}
}
void zwaveEvent(hubitat.zwave.commands.switchbinaryv2.SwitchBinaryReport cmd) {
if (logEnable) log.debug "Received SwitchBinaryReport v1 containing: ${cmd}"
if (device.hasAttribute("switch") || device.hasCapability("Switch"))
{
if (logEnable) log.debug "${device.displayName} Sending a switch ${(cmd.value ? "on" : "off")} event"
eventProcess( name: "switch", value: (cmd.value ? "on" : "off"),
descriptionText: "Device ${device.displayName} set to ${(cmd.value ? "on" : "off")}.", type: "physical" )
}
}
void zwaveEvent(hubitat.zwave.commands.basicv1.BasicReport cmd) {
if (logEnable) log.debug "Received BasicReport v1 containing: $cmd}"
if (device.hasAttribute("switch") || device.hasCapability("Switch"))
{
eventProcess( name: "switch", value: (cmd.value ? "on" : "off"),
descriptionText: "Device ${device.displayName} set to ${value}.",
type: (state.universalDriverData.get("isDigital") as Boolean ) ? "digital" : "physical" )
}
if ((device.hasAttribute("level") || device.hasCapability("SwitchLevel") ) && (cmd.value != 0))
{
eventProcess( name: "level", value: cmd.value,
descriptionText: "Device ${device.displayName} level set to ${value}%",
type: (state.universalDriverData.get("isDigital") as Boolean ) ? "digital" : "physical" )
}
state.universalDriverData.put("isDigital", false)
}
void zwaveEvent(hubitat.zwave.commands.basicv2.BasicReport cmd) {
if (logEnable) log.debug "Received BasicReport v2 containing: $cmd}"
if ((cmd.value != cmd.targetValue) && (cmd.duration == 0)) log.warn "Received a V2 Basic Report with mismatched value and targetValue and non-zero duration: ${cmd}."
if (device.hasAttribute("switch") || device.hasCapability("Switch"))
{
eventProcess( name: "switch", value: (cmd.targetValue ? "on" : "off"),
descriptionText: "Device ${device.displayName} set to ${value}.",
type: (state.universalDriverData.get("isDigital") as Boolean ) ? "digital" : "physical" )
}
if ((device.hasAttribute("level") || device.hasCapability("SwitchLevel") ) && (cmd.targetValue != 0))
{
eventProcess( name: "level", value: cmd.targetValue,
descriptionText: "Device ${device.displayName} level set to ${value}%",
type: (state.universalDriverData.get("isDigital") as Boolean ) ? "digital" : "physical" )
}
state.universalDriverData.put("isDigital", false)
}
//returns on physical v1
void zwaveEvent(hubitat.zwave.commands.switchmultilevelv1.SwitchMultilevelReport cmd){
processMultilevelReport(cmd)
}
//returns on physical v2
void zwaveEvent(hubitat.zwave.commands.switchmultilevelv2.SwitchMultilevelReport cmd){
processMultilevelReport(cmd)
}
//returns on physical v3
void zwaveEvent(hubitat.zwave.commands.switchmultilevelv3.SwitchMultilevelReport cmd){
processMultilevelReport(cmd)
}
void processMultilevelReport(cmd)
{
if (device.hasAttribute("switch") || device.hasCapability("Switch"))
{
eventProcess( name: "switch", value: (cmd.value ? "on" : "off"),
descriptionText: "Device ${device.displayName} set to ${(cmd.value ? "on" : "off")}", type: "physical" )
}
if ((device.hasAttribute("level") || device.hasCapability("SwitchLevel") ) && (cmd.value != 0))
{
// z-wave level values only go to 99. Treat 99 as a 100%
eventProcess( name: "level", value: (cmd.value == 99) ? 100: cmd.value,
descriptionText: "Device ${device.displayName} level set to ${cmd.value}%", type: "physical" )
}
state.universalDriverData.put("isDigital", false)
}
void eventProcess(Map event) {
if (device.currentValue(event.name).toString() != event.value.toString() ) {
if (logEnable) log.debug "${device.displayName} has current value ${device.currentValue(event.name).toString()} and new event value ${event.value.toString()}."
event.isStateChange=true
sendEvent(event)
}
}
void on() {
if (device.hasCapability("SwitchLevel")) {
Integer levelValue = (device.currentValue("level") as Integer) ?: 99
if (txtEnable) log.info "Turning device ${device.displayName} On to Level: ${levelValue}."
sendToDevice(secure(zwave.basicV1.basicSet(value: levelValue )))
}
else {
if (txtEnable) log.info "Turning device ${device.displayName} to: On."
sendToDevice(secure(zwave.basicV1.basicSet(value: 255 )))
}
if (confirmSend )
{
state.universalDriverData.put("isDigital", true)
sendToDevice (secure(zwave.basicV1.basicGet()))
} else {
sendEvent(name: "switch", value: "on", descriptionText: "Device ${device.displayName} turned on",
type: "digital", isStateChange: (device.currentValue("switch") == "on") ? false : true )
}
}
void off() {
if (txtEnable) log.info "Turning device ${device.displayName} to: Off."
sendToDevice (secure(zwave.basicV1.basicSet(value: 0 )))
if (confirmSend )
{
state.universalDriverData.put("isDigital", true)
sendToDevice (secure(zwave.basicV1.basicGet()))
} else {
sendEvent(name: "switch", value: "off", descriptionText: "Device ${device.displayName} turned off",
type: "digital", isStateChange: (device.currentValue("switch") == "off") ? false : true )
}
}
void setLevel(level, duration = 0)
{
state.universalDriverData.put("isDigital", true)
if (logEnable) log.debug "Executing function setlevel(level, duration)."
if ( level < 0 ) level = 0
if ( level > 99 ) level = 99
if ( duration < 0 ) duration = 0
if ( duration > 120 )
{
log.warn "For device ${device.displayName}, tried to set a dimming duration value greater than 120 seconds. To avoid excessive turn on / off delays, this driver only allows dimming duration values of up to 127."
duration = 120
}
if (level == 0)
{
Boolean stateChange = ((device.currentValue("level") != 0) ? true : false)
sendEvent(name: "switch", value: "off", descriptionText: "Device ${device.displayName} remains at off", type: "digital", isStateChange: stateChange )
List<hubitat.zwave.Command> cmds = []
if (state.ZwaveClassVersions?.get("38") == 1)
{
cmds.add(secure(zwave.switchMultilevelV1.switchMultilevelSet(value: 0)))
log.warn "${device.displayName} does not support dimming duration settting command. Defaulting to dimming duration set by device parameters."
} else {
cmds.add(secure(zwave.switchMultilevelV2.switchMultilevelSet(value: 0, dimmingDuration: duration)))
}
if(cmds) sendToDevice(cmds)
return
}
if (device.hasCapability("SwitchLevel")) {
List<hubitat.zwave.Command> cmds = []
if (state.ZwaveClassVersions?.get("38") < 1)
{
cmds.add(secure(zwave.switchMultilevelV1.switchMultilevelSet(value: level)))
log.warn "${device.displayName} does not support dimming duration settting command. Defaulting to dimming duration set by device parameters."
} else {
cmds.add(secure(zwave.switchMultilevelV2.switchMultilevelSet(value: level, dimmingDuration: duration)))
}
if(cmds) sendToDevice(cmds)
}
if (logEnable) log.debug "Current switch value is ${device.currentValue("switch")}"
if (device.currentValue("switch") == "off")
{
if (logEnable) log.debug "Turning switch on in setlevel function"
sendEvent(name: "switch", value: "on", descriptionText: "Device ${device.displayName} turned on", type: "digital", isStateChange: true)
}
sendEvent(name: "level", value: level, descriptionText: "Device ${device.displayName} set to ${level}%", type: "digital", isStateChange: true)
}
void startLevelChange(direction){
Integer upDown = (direction == "down" ? 1 : 0)
sendToDevice(secure(zwave.switchMultilevelV1.switchMultilevelStartLevelChange(upDown: upDown, ignoreStartLevel: 1, startLevel: 0)))
}
void stopLevelChange(){
List<hubitat.zwave.Command> cmds = []
cmds.add(secure(zwave.switchMultilevelV1.switchMultilevelStopLevelChange()))
cmds.add(secure(zwave.basicV1.basicGet()))
if (cmds) sendToDevice(cmds)
}
//////////////// Send Button Events Resulting from Capabilities Processing /////////////
void sendButtonEvent(action, button, type){
String descriptionText = "${device.displayName} button ${button} was ${action} [${type}]"
if (txtEnable) log.info descriptionText
sendEvent(name:action, value:button, descriptionText:descriptionText, isStateChange:true, type:type)