forked from ethayer/user-lock-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zwave-lock.groovy
689 lines (643 loc) · 26.8 KB
/
zwave-lock.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
metadata {
// Automatically generated. Make future change here.
definition (name: "Z-Wave Lock Reporting", namespace: "smartthings", author: "SmartThings") {
capability "Actuator"
capability "Lock"
capability "Polling"
capability "Refresh"
capability "Sensor"
capability "Lock Codes"
capability "Battery"
command "unlockwtimeout"
fingerprint deviceId: "0x4003", inClusters: "0x98"
fingerprint deviceId: "0x4004", inClusters: "0x98"
}
simulator {
status "locked": "command: 9881, payload: 00 62 03 FF 00 00 FE FE"
status "unlocked": "command: 9881, payload: 00 62 03 00 00 00 FE FE"
reply "9881006201FF,delay 4200,9881006202": "command: 9881, payload: 00 62 03 FF 00 00 FE FE"
reply "988100620100,delay 4200,9881006202": "command: 9881, payload: 00 62 03 00 00 00 FE FE"
}
tiles {
standardTile("toggle", "device.lock", width: 2, height: 2) {
state "locked", label:'locked', action:"lock.unlock", icon:"st.locks.lock.locked", backgroundColor:"#79b821", nextState:"unlocking"
state "unlocked", label:'unlocked', action:"lock.lock", icon:"st.locks.lock.unlocked", backgroundColor:"#ffffff", nextState:"locking"
state "unknown", label:"unknown", action:"lock.lock", icon:"st.locks.lock.unknown", backgroundColor:"#ffffff", nextState:"locking"
state "locking", label:'locking', icon:"st.locks.lock.locked", backgroundColor:"#79b821"
state "unlocking", label:'unlocking', icon:"st.locks.lock.unlocked", backgroundColor:"#ffffff"
}
standardTile("lock", "device.lock", inactiveLabel: false, decoration: "flat") {
state "default", label:'lock', action:"lock.lock", icon:"st.locks.lock.locked", nextState:"locking"
}
standardTile("unlock", "device.lock", inactiveLabel: false, decoration: "flat") {
state "default", label:'unlock', action:"lock.unlock", icon:"st.locks.lock.unlocked", nextState:"unlocking"
}
valueTile("battery", "device.battery", inactiveLabel: false, decoration: "flat") {
state "battery", label:'${currentValue}% battery', unit:""
}
standardTile("refresh", "device.lock", inactiveLabel: false, decoration: "flat") {
state "default", label:'', action:"refresh.refresh", icon:"st.secondary.refresh"
}
main "toggle"
details(["toggle", "lock", "unlock", "battery", "refresh"])
}
}
import physicalgraph.zwave.commands.doorlockv1.*
import physicalgraph.zwave.commands.usercodev1.*
def parse(String description) {
def result = null
if (description.startsWith("Err")) {
if (state.sec) {
result = createEvent(descriptionText:description, displayed:false)
} else {
result = createEvent(
descriptionText: "This lock failed to complete the network security key exchange. If you are unable to control it via SmartThings, you must remove it from your network and add it again.",
eventType: "ALERT",
name: "secureInclusion",
value: "failed",
displayed: true,
)
}
} else {
def cmd = zwave.parse(description, [ 0x98: 1, 0x72: 2, 0x85: 2, 0x86: 1 ])
if (cmd) {
result = zwaveEvent(cmd)
}
}
log.debug "\"$description\" parsed to ${result.inspect()}"
result
}
def zwaveEvent(physicalgraph.zwave.commands.securityv1.SecurityMessageEncapsulation cmd) {
def encapsulatedCommand = cmd.encapsulatedCommand([0x62: 1, 0x71: 2, 0x80: 1, 0x85: 2, 0x63: 1, 0x98: 1, 0x86: 1])
// log.debug "encapsulated: $encapsulatedCommand"
if (encapsulatedCommand) {
zwaveEvent(encapsulatedCommand)
}
}
def zwaveEvent(physicalgraph.zwave.commands.securityv1.NetworkKeyVerify cmd) {
createEvent(name:"secureInclusion", value:"success", descriptionText:"Secure inclusion was successful")
}
def zwaveEvent(physicalgraph.zwave.commands.securityv1.SecurityCommandsSupportedReport cmd) {
state.sec = cmd.commandClassSupport.collect { String.format("%02X ", it) }.join()
if (cmd.commandClassControl) {
state.secCon = cmd.commandClassControl.collect { String.format("%02X ", it) }.join()
}
log.debug "Security command classes: $state.sec"
createEvent(name:"secureInclusion", value:"success", descriptionText:"Lock is securely included")
}
def zwaveEvent(DoorLockOperationReport cmd) {
def result = []
def map = [ name: "lock" ]
if (cmd.doorLockMode == 0xFF) {
map.value = "locked"
} else if (cmd.doorLockMode >= 0x40) {
map.value = "unknown"
} else if (cmd.doorLockMode & 1) {
map.value = "unlocked with timeout"
} else {
map.value = "unlocked"
if (state.assoc != zwaveHubNodeId) {
log.debug "setting association"
result << response(secure(zwave.associationV1.associationSet(groupingIdentifier:1, nodeId:zwaveHubNodeId)))
result << response(zwave.associationV1.associationSet(groupingIdentifier:2, nodeId:zwaveHubNodeId))
result << response(secure(zwave.associationV1.associationGet(groupingIdentifier:1)))
}
}
result ? [createEvent(map), *result] : createEvent(map)
}
def zwaveEvent(physicalgraph.zwave.commands.alarmv2.AlarmReport cmd) {
def result = []
def map = null
if (cmd.zwaveAlarmType == 6) {
if (1 <= cmd.zwaveAlarmEvent && cmd.zwaveAlarmEvent < 10) {
map = [ name: "lock", value: (cmd.zwaveAlarmEvent & 1) ? "locked" : "unlocked" ]
}
switch(cmd.zwaveAlarmEvent) {
case 1:
map.descriptionText = "$device.displayName was manually locked"
break
case 2:
map.descriptionText = "$device.displayName was manually unlocked"
break
case 5:
if (cmd.eventParameter) {
map.descriptionText = "$device.displayName was locked with code ${cmd.eventParameter.first()}"
map.data = [ usedCode: cmd.eventParameter[0] ]
}
break
case 6:
if (cmd.eventParameter) {
map.descriptionText = "$device.displayName was unlocked with code ${cmd.eventParameter.first()}"
map.data = [ usedCode: cmd.eventParameter[0] ]
}
break
case 9:
map.descriptionText = "$device.displayName was autolocked"
break
case 7:
case 8:
case 0xA:
map = [ name: "lock", value: "unknown", descriptionText: "$device.displayName was not locked fully" ]
break
case 0xB:
map = [ name: "lock", value: "unknown", descriptionText: "$device.displayName is jammed" ]
break
case 0xC:
map = [ name: "codeChanged", value: "all", descriptionText: "$device.displayName: all user codes deleted", isStateChange: true ]
allCodesDeleted()
break
case 0xD:
if (cmd.eventParameter) {
map = [ name: "codeReport", value: cmd.eventParameter[0], data: [ code: "" ], isStateChange: true ]
map.descriptionText = "$device.displayName code ${map.value} was deleted"
map.isStateChange = (state["code$map.value"] != "")
state["code$map.value"] = ""
} else {
map = [ name: "codeChanged", descriptionText: "$device.displayName: user code deleted", isStateChange: true ]
}
break
case 0xE:
map = [ name: "codeChanged", value: cmd.alarmLevel, descriptionText: "$device.displayName: user code added", isStateChange: true ]
if (cmd.eventParameter) {
map.value = cmd.eventParameter[0]
result << response(requestCode(cmd.eventParameter[0]))
}
break
case 0xF:
map = [ name: "codeChanged", descriptionText: "$device.displayName: user code not added, duplicate", isStateChange: true ]
break
case 0x10:
map = [ name: "tamper", value: "detected", descriptionText: "$device.displayName: keypad temporarily disabled", displayed: true ]
break
case 0x11:
map = [ descriptionText: "$device.displayName: keypad is busy" ]
break
case 0x12:
map = [ name: "codeChanged", descriptionText: "$device.displayName: program code changed", isStateChange: true ]
break
case 0x13:
map = [ name: "tamper", value: "detected", descriptionText: "$device.displayName: code entry attempt limit exceeded", displayed: true ]
break
default:
map = map ?: [ descriptionText: "$device.displayName: alarm event $cmd.zwaveAlarmEvent", displayed: false ]
break
}
} else if (cmd.zwaveAlarmType == 7) {
map = [ name: "tamper", value: "detected", displayed: true ]
switch (cmd.zwaveAlarmEvent) {
case 0:
map.value = "clear"
map.descriptionText = "$device.displayName: tamper alert cleared"
break
case 1:
case 2:
map.descriptionText = "$device.displayName: intrusion attempt detected"
break
case 3:
map.descriptionText = "$device.displayName: covering removed"
break
case 4:
map.descriptionText = "$device.displayName: invalid code"
break
default:
map.descriptionText = "$device.displayName: tamper alarm $cmd.zwaveAlarmEvent"
break
}
} else switch(cmd.alarmType) {
case 21: // Manually locked
case 18: // Locked with keypad
case 24: // Locked by command (Kwikset 914)
case 27: // Autolocked
map = [ name: "lock", value: "locked" ]
break
case 16: // Note: for levers this means it's unlocked, for non-motorized deadbolt, it's just unsecured and might not get unlocked
case 19:
map = [ name: "lock", value: "unlocked" ]
if (cmd.alarmLevel) {
map.descriptionText = "$device.displayName was unlocked with code $cmd.alarmLevel"
map.data = [ usedCode: cmd.alarmLevel ]
}
break
case 22:
case 25: // Kwikset 914 unlocked by command
map = [ name: "lock", value: "unlocked" ]
break
case 9:
case 17:
case 23:
case 26:
map = [ name: "lock", value: "unknown", descriptionText: "$device.displayName bolt is jammed" ]
break
case 13:
map = [ name: "codeChanged", value: cmd.alarmLevel, descriptionText: "$device.displayName code $cmd.alarmLevel was added", isStateChange: true ]
result << response(requestCode(cmd.alarmLevel))
break
case 32:
map = [ name: "codeChanged", value: "all", descriptionText: "$device.displayName: all user codes deleted", isStateChange: true ]
allCodesDeleted()
case 33:
map = [ name: "codeReport", value: cmd.alarmLevel, data: [ code: "" ], isStateChange: true ]
map.descriptionText = "$device.displayName code $cmd.alarmLevel was deleted"
map.isStateChange = (state["code$cmd.alarmLevel"] != "")
state["code$cmd.alarmLevel"] = ""
break
case 112:
map = [ name: "codeChanged", value: cmd.alarmLevel, descriptionText: "$device.displayName code $cmd.alarmLevel changed", isStateChange: true ]
result << response(requestCode(cmd.alarmLevel))
break
case 130: // Yale YRD batteries replaced
map = [ descriptionText: "$device.displayName batteries replaced", isStateChange: true ]
break
case 131:
map = [ /*name: "codeChanged", value: cmd.alarmLevel,*/ descriptionText: "$device.displayName code $cmd.alarmLevel is duplicate", isStateChange: false ]
break
case 161:
if (cmd.alarmLevel == 2) {
map = [ descriptionText: "$device.displayName front escutcheon removed", isStateChange: true ]
} else {
map = [ descriptionText: "$device.displayName detected failed user code attempt", isStateChange: true ]
}
break
case 167:
if (!state.lastbatt || (new Date().time) - state.lastbatt > 12*60*60*1000) {
map = [ descriptionText: "$device.displayName: battery low", isStateChange: true ]
result << response(secure(zwave.batteryV1.batteryGet()))
} else {
map = [ name: "battery", value: device.currentValue("battery"), descriptionText: "$device.displayName: battery low", displayed: true ]
}
break
case 168:
map = [ name: "battery", value: 1, descriptionText: "$device.displayName: battery level critical", displayed: true ]
break
case 169:
map = [ name: "battery", value: 0, descriptionText: "$device.displayName: battery too low to operate lock", isStateChange: true ]
break
default:
map = [ displayed: false, descriptionText: "$device.displayName: alarm event $cmd.alarmType level $cmd.alarmLevel" ]
break
}
result ? [createEvent(map), *result] : createEvent(map)
}
def zwaveEvent(UserCodeReport cmd) {
def result = []
def name = "code$cmd.userIdentifier"
def code = cmd.code
def map = [:]
if (cmd.userIdStatus == UserCodeReport.USER_ID_STATUS_OCCUPIED ||
(cmd.userIdStatus == UserCodeReport.USER_ID_STATUS_STATUS_NOT_AVAILABLE && cmd.user && code != "**********"))
{
if (code == "**********") { // Schlage locks send us this instead of the real code
state.blankcodes = true
code = state["set$name"] ?: decrypt(state[name]) ?: code
state.remove("set$name".toString())
}
if (!code && cmd.userIdStatus == 1) { // Schlage touchscreen sends blank code to notify of a changed code
map = [ name: "codeChanged", value: cmd.userIdentifier, displayed: true, isStateChange: true ]
map.descriptionText = "$device.displayName code $cmd.userIdentifier " + (state[name] ? "changed" : "was added")
code = state["set$name"] ?: decrypt(state[name]) ?: "****"
state.remove("set$name".toString())
} else {
map = [ name: "codeReport", value: cmd.userIdentifier, data: [ code: code ] ]
map.descriptionText = "$device.displayName code $cmd.userIdentifier is set"
map.displayed = (cmd.userIdentifier != state.requestCode && cmd.userIdentifier != state.pollCode)
map.isStateChange = (code != decrypt(state[name]))
}
result << createEvent(map)
} else {
map = [ name: "codeReport", value: cmd.userIdentifier, data: [ code: "" ] ]
if (state.blankcodes && state["reset$name"]) { // we deleted this code so we can tell that our new code gets set
map.descriptionText = "$device.displayName code $cmd.userIdentifier was reset"
map.displayed = map.isStateChange = false
result << createEvent(map)
state["set$name"] = state["reset$name"]
result << response(setCode(cmd.userIdentifier, state["reset$name"]))
state.remove("reset$name".toString())
} else {
if (state[name]) {
map.descriptionText = "$device.displayName code $cmd.userIdentifier was deleted"
} else {
map.descriptionText = "$device.displayName code $cmd.userIdentifier is not set"
}
map.displayed = (cmd.userIdentifier != state.requestCode && cmd.userIdentifier != state.pollCode)
map.isStateChange = state[name] as Boolean
result << createEvent(map)
}
code = ""
}
state[name] = code ? encrypt(code) : code
if (cmd.userIdentifier == state.requestCode) { // reloadCodes() was called, keep requesting the codes in order
if (state.requestCode + 1 > state.codes || state.requestCode >= 30) {
state.remove("requestCode") // done
} else {
state.requestCode = state.requestCode + 1 // get next
result << response(requestCode(state.requestCode))
}
}
if (cmd.userIdentifier == state.pollCode) {
if (state.pollCode + 1 > state.codes || state.pollCode >= 30) {
state.remove("pollCode") // done
} else {
state.pollCode = state.pollCode + 1
}
}
log.debug "code report parsed to ${result.inspect()}"
result
}
def zwaveEvent(UsersNumberReport cmd) {
def result = []
state.codes = cmd.supportedUsers
if (state.requestCode && state.requestCode <= cmd.supportedUsers) {
result << response(requestCode(state.requestCode))
}
result
}
def zwaveEvent(physicalgraph.zwave.commands.associationv2.AssociationReport cmd) {
def result = []
if (cmd.nodeId.any { it == zwaveHubNodeId }) {
state.remove("associationQuery")
log.debug "$device.displayName is associated to $zwaveHubNodeId"
result << createEvent(descriptionText: "$device.displayName is associated")
state.assoc = zwaveHubNodeId
if (cmd.groupingIdentifier == 2) {
result << response(zwave.associationV1.associationRemove(groupingIdentifier:1, nodeId:zwaveHubNodeId))
}
} else if (cmd.groupingIdentifier == 1) {
result << response(secure(zwave.associationV1.associationSet(groupingIdentifier:1, nodeId:zwaveHubNodeId)))
} else if (cmd.groupingIdentifier == 2) {
result << response(zwave.associationV1.associationSet(groupingIdentifier:2, nodeId:zwaveHubNodeId))
}
result
}
def zwaveEvent(physicalgraph.zwave.commands.timev1.TimeGet cmd) {
def result = []
def now = new Date().toCalendar()
if(location.timeZone) now.timeZone = location.timeZone
result << createEvent(descriptionText: "$device.displayName requested time update", displayed: false)
result << response(secure(zwave.timeV1.timeReport(
hourLocalTime: now.get(Calendar.HOUR_OF_DAY),
minuteLocalTime: now.get(Calendar.MINUTE),
secondLocalTime: now.get(Calendar.SECOND)))
)
result
}
def zwaveEvent(physicalgraph.zwave.commands.basicv1.BasicSet cmd) {
// The old Schlage locks use group 1 for basic control - we don't want that, so unsubscribe from group 1
def result = [ createEvent(name: "lock", value: cmd.value ? "unlocked" : "locked") ]
result << response(zwave.associationV1.associationRemove(groupingIdentifier:1, nodeId:zwaveHubNodeId))
if (state.assoc != zwaveHubNodeId) {
result << response(zwave.associationV1.associationGet(groupingIdentifier:2))
}
result
}
def zwaveEvent(physicalgraph.zwave.commands.batteryv1.BatteryReport cmd) {
def map = [ name: "battery", unit: "%" ]
if (cmd.batteryLevel == 0xFF) {
map.value = 1
map.descriptionText = "$device.displayName has a low battery"
} else {
map.value = cmd.batteryLevel
}
state.lastbatt = new Date().time
createEvent(map)
}
def zwaveEvent(physicalgraph.zwave.commands.manufacturerspecificv2.ManufacturerSpecificReport cmd) {
def result = []
def msr = String.format("%04X-%04X-%04X", cmd.manufacturerId, cmd.productTypeId, cmd.productId)
log.debug "msr: $msr"
updateDataValue("MSR", msr)
result << createEvent(descriptionText: "$device.displayName MSR: $msr", isStateChange: false)
result
}
def zwaveEvent(physicalgraph.zwave.commands.versionv1.VersionReport cmd) {
def fw = "${cmd.applicationVersion}.${cmd.applicationSubVersion}"
updateDataValue("fw", fw)
if (state.MSR == "003B-6341-5044") {
updateDataValue("ver", "${cmd.applicationVersion >> 4}.${cmd.applicationVersion & 0xF}")
}
def text = "$device.displayName: firmware version: $fw, Z-Wave version: ${cmd.zWaveProtocolVersion}.${cmd.zWaveProtocolSubVersion}"
createEvent(descriptionText: text, isStateChange: false)
}
def zwaveEvent(physicalgraph.zwave.commands.applicationstatusv1.ApplicationBusy cmd) {
def msg = cmd.status == 0 ? "try again later" :
cmd.status == 1 ? "try again in $cmd.waitTime seconds" :
cmd.status == 2 ? "request queued" : "sorry"
createEvent(displayed: true, descriptionText: "$device.displayName is busy, $msg")
}
def zwaveEvent(physicalgraph.zwave.commands.applicationstatusv1.ApplicationRejectedRequest cmd) {
createEvent(displayed: true, descriptionText: "$device.displayName rejected the last request")
}
def zwaveEvent(physicalgraph.zwave.Command cmd) {
createEvent(displayed: false, descriptionText: "$device.displayName: $cmd")
}
def lockAndCheck(doorLockMode) {
secureSequence([
zwave.doorLockV1.doorLockOperationSet(doorLockMode: doorLockMode),
zwave.doorLockV1.doorLockOperationGet()
], 4200)
}
def lock() {
lockAndCheck(DoorLockOperationSet.DOOR_LOCK_MODE_DOOR_SECURED)
}
def unlock() {
lockAndCheck(DoorLockOperationSet.DOOR_LOCK_MODE_DOOR_UNSECURED)
}
def unlockwtimeout() {
lockAndCheck(DoorLockOperationSet.DOOR_LOCK_MODE_DOOR_UNSECURED_WITH_TIMEOUT)
}
def refresh() {
def cmds = [secure(zwave.doorLockV1.doorLockOperationGet())]
if (state.assoc == zwaveHubNodeId) {
log.debug "$device.displayName is associated to ${state.assoc}"
} else if (!state.associationQuery) {
log.debug "checking association"
cmds << "delay 4200"
cmds << zwave.associationV1.associationGet(groupingIdentifier:2).format() // old Schlage locks use group 2 and don't secure the Association CC
cmds << secure(zwave.associationV1.associationGet(groupingIdentifier:1))
state.associationQuery = new Date().time
} else if (new Date().time - state.associationQuery.toLong() > 9000) {
log.debug "setting association"
cmds << "delay 6000"
cmds << zwave.associationV1.associationSet(groupingIdentifier:2, nodeId:zwaveHubNodeId).format()
cmds << secure(zwave.associationV1.associationSet(groupingIdentifier:1, nodeId:zwaveHubNodeId))
cmds << zwave.associationV1.associationGet(groupingIdentifier:2).format()
cmds << secure(zwave.associationV1.associationGet(groupingIdentifier:1))
state.associationQuery = new Date().time
}
log.debug "refresh sending ${cmds.inspect()}"
cmds
}
def poll() {
def cmds = []
if (state.assoc != zwaveHubNodeId && secondsPast(state.associationQuery, 19 * 60)) {
log.debug "setting association"
cmds << zwave.associationV1.associationSet(groupingIdentifier:2, nodeId:zwaveHubNodeId).format()
cmds << secure(zwave.associationV1.associationSet(groupingIdentifier:1, nodeId:zwaveHubNodeId))
cmds << zwave.associationV1.associationGet(groupingIdentifier:2).format()
cmds << "delay 6000"
cmds << secure(zwave.associationV1.associationGet(groupingIdentifier:1))
cmds << "delay 6000"
state.associationQuery = new Date().time
} else {
// Only check lock state if it changed recently or we haven't had an update in an hour
def latest = device.currentState("lock")?.date?.time
if (!latest || !secondsPast(latest, 6 * 60) || secondsPast(state.lastPoll, 55 * 60)) {
cmds << secure(zwave.doorLockV1.doorLockOperationGet())
state.lastPoll = (new Date()).time
} else if (!state.MSR) {
cmds << zwave.manufacturerSpecificV1.manufacturerSpecificGet().format()
} else if (!state.fw) {
cmds << zwave.versionV1.versionGet().format()
} else if (!state.codes) {
state.pollCode = 1
cmds << secure(zwave.userCodeV1.usersNumberGet())
} else if (state.pollCode && state.pollCode <= state.codes) {
cmds << requestCode(state.pollCode)
} else if (!state.lastbatt || (new Date().time) - state.lastbatt > 53*60*60*1000) {
cmds << secure(zwave.batteryV1.batteryGet())
} else if (!state.enc) {
encryptCodes()
state.enc = 1
}
}
log.debug "poll is sending ${cmds.inspect()}"
// Send code data as event
reportAllCodes(state)
device.activity()
cmds ?: null
}
private def encryptCodes() {
def keys = new ArrayList(state.keySet().findAll { it.startsWith("code") })
keys.each { key ->
def match = (key =~ /^code(\d+)$/)
if (match) try {
def keynum = match[0][1].toInteger()
if (keynum > 30 && !state[key]) {
state.remove(key)
} else if (state[key] && !state[key].startsWith("~")) {
log.debug "encrypting $key: ${state[key].inspect()}"
state[key] = encrypt(state[key])
}
} catch (java.lang.NumberFormatException e) { }
}
}
def requestCode(codeNumber) {
secure(zwave.userCodeV1.userCodeGet(userIdentifier: codeNumber))
}
def reloadAllCodes() {
def cmds = []
if (!state.codes) {
state.requestCode = 1
cmds << secure(zwave.userCodeV1.usersNumberGet())
} else {
if(!state.requestCode) state.requestCode = 1
cmds << requestCode(codeNumber)
}
cmds
}
def setCode(codeNumber, code) {
def strcode = code
log.debug "setting code $codeNumber to $code"
if (code instanceof String) {
code = code.toList().findResults { if(it > ' ' && it != ',' && it != '-') it.toCharacter() as Short }
} else {
strcode = code.collect{ it as Character }.join()
}
if (state.blankcodes) {
// Can't just set, we won't be able to tell if it was successful
if (state["code$codeNumber"] != "") {
if (state["setcode$codeNumber"] != strcode) {
state["resetcode$codeNumber"] = strcode
return deleteCode(codeNumber)
}
} else {
state["setcode$codeNumber"] = strcode
}
}
secureSequence([
zwave.userCodeV1.userCodeSet(userIdentifier:codeNumber, userIdStatus:1, user:code),
zwave.userCodeV1.userCodeGet(userIdentifier:codeNumber)
], 7000)
}
def deleteCode(codeNumber) {
log.debug "deleting code $codeNumber"
secureSequence([
zwave.userCodeV1.userCodeSet(userIdentifier:codeNumber, userIdStatus:0),
zwave.userCodeV1.userCodeGet(userIdentifier:codeNumber)
], 7000)
}
def updateCodes(codeSettings) {
if(codeSettings instanceof String) codeSettings = util.parseJson(codeSettings)
def set_cmds = []
def get_cmds = []
codeSettings.each { name, updated ->
def current = decrypt(state[name])
if (name.startsWith("code")) {
def n = name[4..-1].toInteger()
log.debug "$name was $current, set to $updated"
if (updated?.size() >= 4 && updated != current) {
def cmds = setCode(n, updated)
set_cmds << cmds.first()
get_cmds << cmds.last()
} else if ((current && updated == "") || updated == "0") {
def cmds = deleteCode(n)
set_cmds << cmds.first()
get_cmds << cmds.last()
} else if (updated && updated.size() < 4) {
// Entered code was too short
codeSettings["code$n"] = current
}
} else log.warn("unexpected entry $name: $updated")
}
if (set_cmds) {
return response(delayBetween(set_cmds, 2200) + ["delay 2200"] + delayBetween(get_cmds, 4200))
}
}
def getCode(codeNumber) {
decrypt(state["code$codeNumber"])
}
def getAllCodes() {
state.findAll { it.key.startsWith 'code' }.collectEntries {
[it.key, (it.value instanceof String && it.value.startsWith("~")) ? decrypt(it.value) : it.value]
}
}
private secure(physicalgraph.zwave.Command cmd) {
zwave.securityV1.securityMessageEncapsulation().encapsulate(cmd).format()
}
private secureSequence(commands, delay=4200) {
delayBetween(commands.collect{ secure(it) }, delay)
}
private Boolean secondsPast(timestamp, seconds) {
if (!(timestamp instanceof Number)) {
if (timestamp instanceof Date) {
timestamp = timestamp.time
} else if ((timestamp instanceof String) && timestamp.isNumber()) {
timestamp = timestamp.toLong()
} else {
return true
}
}
return (new Date().time - timestamp) > (seconds * 1000)
}
private allCodesDeleted() {
if (state.codes instanceof Integer) {
(1..state.codes).each { n ->
if (state["code$n"]) {
result << createEvent(name: "codeReport", value: n, data: [ code: "" ], descriptionText: "code $n was deleted",
displayed: false, isStateChange: true)
}
state["code$n"] = ""
}
}
}
def reportAllCodes(state) {
def map = [ name: "reportAllCodes", data: [:], displayed: false, isStateChange: false, type: "physical" ]
state.each { entry ->
//iterate through all the state entries and add them to the event data to be handled by application event handlers
if ( entry.key ==~ /^code\d{1,}/ && entry.value.startsWith("~") ) {
map.data.put(entry.key, decrypt(entry.value))
} else {
map.data.put(entry.key, entry.value)
}
}
sendEvent(map)
}