-
Notifications
You must be signed in to change notification settings - Fork 42
/
SmartApp_SuperState.groovy
618 lines (580 loc) · 21.7 KB
/
SmartApp_SuperState.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
/**
* superState 1.0
*
* Copyright 2015 Mike Maxwell
*
* Device (switch/dimmer/color) state capture and replay utility.
* - resulting scene is assigned to a child device
* - scene devices are editable post capture (recapture/add/delete)
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*
*/
definition(
name: "superState",
namespace: "mmaxwell",
author: "Mike Maxwell",
description: "Device state capture, replay and edit tool",
category: "Convenience",
iconUrl: "https://s3.amazonaws.com/smartapp-icons/ModeMagic/Cat-ModeMagic.png",
iconX2Url: "https://s3.amazonaws.com/smartapp-icons/ModeMagic/[email protected]",
iconX3Url: "https://s3.amazonaws.com/smartapp-icons/ModeMagic/[email protected]"
)
preferences {
page(name: "main")
page(name: "group",nextPage : "main")
page(name: "scene",nextPage : "main")
//page(name: "delete",nextPage: "main")
}
def main(){
def nextGroupIDX = getNextGroupIDX()
def nextGroupID = "g${nextGroupIDX}"
dynamicPage(name: "main", title: "superState", uninstall: true,install: true) {
section("Device groups"){
def prefGroups = getGroupMaps()
prefGroups.each(){ prefGroup ->
href(
name : prefGroup.key
,title : prefGroup.value
,required : false
,params : [groupID:prefGroup.key]
,page : "group"
,description: null
,state : isGroupComplete(prefGroup.key)
)
}
}
section(){
//always have a link for adding a new group
href(
name : nextGroupID
,title : "Add a device group..."
,required : false
,params : [groupID:nextGroupID]
,page : "group"
,description: null
)
}
}
}
def group(params){
def groupID = params.groupID
def switchID = groupID + "dswitches"
def lockID = groupID + "dlocks"
def relayID = groupID + "drelays"
def valveID = groupID + "dvalves"
def doorID = groupID + "ddoors"
def nextSceneIDX = getNextSceneIDX(groupID)
def nextSceneID = "${groupID}s${nextSceneIDX}"
dynamicPage(name: "group", title: getGroupPageTitle(groupID), uninstall: false,install: false) {
section() {
input(
name : groupID
,title : "Group Name"
,multiple : false
,required : true
,type : "text"
)
}
section("Scenes"){
def prefScenes = getSceneMaps(groupID)
prefScenes.each(){ prefScene ->
href(
name : prefScene.key
,title : prefScene.value
,required : false
,params : [sceneID:prefScene.key]
,page : "scene"
,state : "complete"
,description: null
)
}
}
//need to skip this section if groupID.value is null
//some bug here if we create a scene before the group is saved
//log.debug "settings on group page:${settings}"
if (settings[groupID]){
section(){
//always have a link for adding a new scene
href(
name : nextSceneID
,title : "Add a Scene..."
,required : false
,params : [sceneID:nextSceneID]
,page : "scene"
,description: null
)
}
}
section("Devices"){
input(
name : switchID
,title : "Switches"
,multiple : true
,required : false
,type : "capability.switch"
)
/*
input(
name : relayID
,title : "Relays"
,multiple : true
,required : false
,type : "capability.relayswitch"
)
input(
name : lockID
,title : "Locks"
,multiple : true
,required : false
,type : "capability.lock"
)
input(
name : valveID
,title : "Valves"
,multiple : true
,required : false
,type : "capability.valve"
)
input(
name : doorID
,title : "Doors"
,multiple : true
,required : false
,type : "capability.doorcontrol"
)
*/
}
}
}
def scene(params){
def sceneID = params.sceneID
dynamicPage(name: "scene", title: getSceneTitle(sceneID), install: false) {
section() {
input(
name : sceneID
,type : "text"
,title : "Name for this Scene..."
,required : true
)
}
}
}
def installed() {
state.deviceMaps = [:]
state.vtMaps = [:]
//log.debug "Installed with settings: ${settings}"
}
def updated() {
//log.debug "Updated with settings: ${settings}"
unsubscribe()
manageChildDevices()
def sceneSwitches = getChildDevices()
subscribe(sceneSwitches,"switch",cmdHandler)
//remove stale device maps...
cleanDeviceMaps()
log.debug "deviceMaps:${state.deviceMaps}"
//log.debug "settings:${settings}"
//log.debug "vtMaps:${state.vtMaps}"
}
def cleanDeviceMaps(){
//loop though device maps, remove those not in in device groups
def allDeviceIDs = []
def groupIDs = getGroupMaps()
//log.debug "test:${getDeviceKeysFromGroup("g1")}"
groupIDs.each{ groupID ->
def deviceKeys = getDeviceKeysFromGroup(groupID.key)
//log.debug "devicesKeys:${deviceKeys}"
deviceKeys.each{ deviceKey ->
//log.debug "stDevices:${this[deviceKey]}"
def stDevices = this[deviceKey]
stDevices.each{ stDevice ->
allDeviceIDs.push(stDevice.id)
//log.debug "~~~~${stDevice.id}~~~~"
}
}
}
//log.debug "stDevices:${allDeviceIDs}"
def toRemove = []
state.deviceMaps.each{ deviceMap ->
//log.debug "device:${deviceMap.key}"
if (!allDeviceIDs.contains(deviceMap.key)){
//state.deviceMaps.remove(deviceMap.key)
//log.debug "remove me:${deviceMap.key}"
toRemove.push(deviceMap.key)
}
}
//log.debug "remove these:${toRemove}"
toRemove.each{ it ->
state.deviceMaps.remove(it)
}
}
/************** ****************
virtual child device switch to scene mappings
state.vtMaps [virtualChildDevice.Id:sceneID]
[2ef9cc26-c9c6-4445-bac9-59457f194f88:g1s2,.....]
scene device to scene and settings mappings
state.deviceMaps [deviceMap,deviceMap,...]
deviceMap [deviceID:[name:deviceName,old:[settingsMap],scenes:[sceneMap,sceneMap,...]]
sceneMap [sceneID:[settingsMap]]
settingsMap [attribute:value,attribute:value,...]
[9b5c043e-ede1-443f-a245-33095e548a4e:[old:[switch:null], scenes:[g1s2:[switch:on], g1s1:[switch:on]], name:Pantry Lights]],...]
*************** ***************/
def manageChildDevices(){
def newVs
def networkID
def vTileName
def vTileLabel
def deviceID
def uiGroups = getGroupMaps()
//need to loop through all groups, then each scene
uiGroups.each{ group ->
def scenes = getSceneMaps(group.key)
//log.debug "makechild Group:${group.key}"
//log.debug "makechild scenes:${scenes}"
scenes.each{ scene ->
//log.debug "makechild scene:${scene.key}"
if (!state.vtMaps.containsValue(scene.key)) {
//log.debug "missing:${scene.key} ${scene.value}"
networkID = app.id + "/" + scene.key
vTileName = "${group.key}-${scene.key}"
vTileLabel = "${group.value}-${scene.value}"
newVs = addChildDevice("mmaxwell", "superState switch", networkID, null, [name: "${vTileName}", label: "${vTileLabel}", completedSetup: true])
deviceID = newVs.id
state.vtMaps << [(deviceID):scene.key]
} else {
//log.debug "vs exists already"
}
}
}
//now go thhrough vtMaps, remove any children not in settings
//vt:2ef9cc26-c9c6-4445-bac9-59457f194f88=g1s2 should be deleted
state.vtMaps.each{ it ->
log.debug "vsm:${it}"
if (!settings.containsKey(it.value)){
log.debug "vt:${it} should be deleted"
//won't let me delete..., says in use???
//networkID = app.id + "/" + it.value
//deleteChildDevice(networkID)
}
}
//log.debug "vtMaps:${state.vtMaps}"
}
def cmdHandler(evt){
def sceneID = state.vtMaps[evt.deviceId]
def nid = app.id + "/" + sceneID
def cmd = evt.data.split("~")[1]
def logInfo = true
def stateMapsOK = true
if (logInfo) log.info "cmdHandler- scene:${sceneID} name:${evt.name} value:${evt.value} cmd:${cmd}"
//log.debug "cmdHandler- state.deviceMaps:${state.deviceMaps}"
//events to ignore
if (cmd in ["warn","override"]) return
def isOverride = false
def sceneSwitches = getChildDevices()
def callingSwitch = getChildDevice(nid)
//check if other scene switches are activeted
sceneSwitches.each{ sceneSwitch ->
//log.debug "cmdHandler - sceneSwitch:${sceneSwitch.name} value:${sceneSwitch.currentValue("switch")} evtName:${evt.deviceId}"
if (sceneSwitch.currentValue("switch") != "off" && sceneSwitch.id != evt.deviceId){
sceneSwitch.overrideScene()
isOverride = true
if (logInfo) log.info "cmdHandler- override request from ${evt.displayName} to ${sceneSwitch.displayName}"
}
}
if (evt.value == "on" && cmd == "snap"){
if (logInfo) log.info "cmdHandler- ${sceneID} snap request"
sceneSnap(sceneID,true)
callingSwitch.off()
return
}
if (evt.value == "on" && isOverride){
if (logInfo) log.info "cmdHandler- ${sceneID} on with ignore snap request"
stateMapsOK = setScene(sceneID,true,false)
//return
} else
if (evt.value == "on"){
if (logInfo) log.info "cmdHandler- ${sceneID} on request"
sceneSnap(sceneID,false)
stateMapsOK = setScene(sceneID,true,false)
//return
} else
if (evt.value == "off" && cmd == "restore"){
if (logInfo) log.info "cmdHandler- ${sceneID} off with restore request"
stateMapsOK = setScene(sceneID,false,true)
//return
} else
if (evt.value == "off"){
if (logInfo) log.info "cmdHandler- ${sceneID} off request"
setScene(sceneID,false,false)
//return
} else log.debug "last man standing"
if (!stateMapsOK){
log.warn state.mapsCheck.replace("sceneSwitchName",evt.displayName)
callingSwitch.warn()
}
}
def setScene(sceneID,turnOn,restore){
//if turnOn == false and restore == true, we reset the state to old
//if turnOn == false and restore == false, then just turn everything off...
//if turnOn == true, we turn on the scene, restore doesn't matter
log.debug "setScene sceneID:${sceneID} turnOn:${turnOn} restore:${restore}"
def sceneMap = [:]
def savedMap
def deviceMap = [:]
def deviceKeys = getDeviceKeysFromScene(sceneID) //represents list of devices included in this group
def hasDevices = deviceKeys.size() != 0
def success = true
def missingDevices = []
state.mapsCheck = ""
def logInfo = false
if (hasDevices){
deviceKeys.each{ deviceKey ->
def groupDevices = this[deviceKey] //devices in this group from prefs
groupDevices.each{ stDevice ->
deviceMap = state.deviceMaps[stDevice.id]
if (deviceMap != null){
sceneMap = deviceMap.scenes[sceneID]
if (sceneMap != null){
if (restore){
savedMap = deviceMap.old
//
def crntEqualsSaved = true
def crntEqualsScene = true
//log.debug "${stDevice.displayName}: saved:${savedMap} scene:${sceneMap}"
sceneMap.each{ attribute ->
def crntValue = stDevice.currentValue(attribute.key).toString()
//log.debug "current- attr:${attribute.key} value:${crntValue}"
//log.debug "attr:${attribute.key} crnt:${crntValue} save:${savedMap[attribute.key].value} scene:${attribute.value}"
if (attribute.value.toString() != crntValue){
//log.debug "NEQ scene attr:[${attribute.value}][${crntValue}]"
if (crntEqualsScene){
//log.debug "set false"
crntEqualsScene = false
}
}
//def savedAttribute = savedMap[attribute.key]
if ("${savedMap[attribute.key].value}" != crntValue){
//log.debug "NEQ save attr:[${savedMap[attribute.key].value}][${crntValue}]"
if (crntEqualsSaved){
//log.debug "set false"
crntEqualsSaved = false
}
}
}
log.debug "${stDevice.displayName}: crntEqualsSaved:${crntEqualsSaved} crntEqualsScene:${crntEqualsScene}"
}
if (turnOn){
// scene on request
if (logInfo) log.info "scene on request for ${sceneID} ${stDevice.displayName}"
//this device goes on
if (sceneMap.switch == "on"){
//color
if (sceneMap.color) {
stDevice.on()
def colorMap = [hue:sceneMap.hue.toInteger(),saturation:sceneMap.saturation.toInteger(),level:sceneMap.level]
stDevice.setColor(colorMap)
log.debug "color:${stDevice.displayName}, ON"
//dimmer
} else if (sceneMap.level){
stDevice.setLevel(sceneMap.level)
log.debug "dimmer:${stDevice.displayName}, ON"
//switch
} else {
stDevice.on()
log.debug "switch:${stDevice.displayName}, ON"
}
//this device goes off
} else {
stDevice.off()
log.debug "${stDevice.displayName}, OFF"
}
} else {
if (restore){
// scene off request with restore
if (logInfo) log.info "scene off request with restore for ${sceneID} ${stDevice.displayName}"
//replace with restore code
stDevice.off()
} else {
//scene off request
if (logInfo) log.info "scene off request for ${sceneID} ${stDevice.displayName}"
stDevice.off()
}
}
} else {
log.debug "setScene- sceneMap is null????"
success = false
}
} else {
//log.debug "setScene- no scene snapped stDevice:${stDevice.displayName}"
missingDevices.push(stDevice.displayName)
success = false
}
}//group device loop
}//device keys loop
if (!success) state.mapsCheck = "Device(s):${missingDevices.toListString()} for scene 'sceneSwitchName' have not been snapped, please re-snap the scene."
//no devices
} else {
log.debug "setScene- no devices"
state.mapsCheck = "No devices are selected for device group '${getGroupDisplayNameFromScene(sceneID)}', select your devices and snap a scene."
success = false
}
return success
}
def sceneSnap(sceneID,isNew) {
def attributesToSave = ['hue', 'saturation', 'color', 'switch', 'level']
//def attributesToSave = ['color', 'switch', 'level']
def allAttributes = []
def savedMap
def newMap
def dataMap
def deviceMap
def sceneMap
def deviceKeys = getDeviceKeysFromScene(sceneID)
//initial snapshot
if (isNew){
deviceKeys.each{ deviceKey ->
//log.debug "deviceKey:${deviceKey}"
def groupDevices = this[deviceKey]
//log.debug "groupDevices:${groupDevices}"
groupDevices.each{ stDevice ->
//log.debug "stDevice:${stDevice}"
allAttributes = stDevice.supportedAttributes.collect{it.toString()}
newMap = [:]
savedMap = [:]
deviceMap = [:]
dataMap = [:]
sceneMap = [:]
//check if device has a device map
if (!state.deviceMaps.containsKey(stDevice.id)){
//log.debug "add device:${stDevice.id} and scene:${sceneID}"
allAttributes.each {attribute ->
if (attributesToSave.contains(attribute)){
newMap << [(attribute):stDevice.currentValue(attribute)]
savedMap << [(attribute):null]
}
}
sceneMap = [(sceneID):newMap]
dataMap = [name:stDevice.displayName, old:savedMap,scenes:sceneMap]
deviceMap = [(stDevice.id):dataMap]
state.deviceMaps << deviceMap
} else {
//does it have this scene?
deviceMap = state.deviceMaps[stDevice.id]
if (!deviceMap.scenes.containsKey(sceneID)){
//log.debug "add scene:${sceneID} to device:${stDevice.id}"
allAttributes.each {attribute ->
if (attributesToSave.contains(attribute)){
newMap << [(attribute):stDevice.currentValue(attribute)]
}
}
sceneMap = [(sceneID):newMap]
deviceMap.scenes << sceneMap
} else {
//resnap settings here
//log.debug "resnap for device:${stDevice.id} scene:${sceneID}"
sceneMap = deviceMap.scenes[sceneID]
allAttributes.each {attribute ->
if (attributesToSave.contains(attribute)){
sceneMap[attribute] = stDevice.currentValue(attribute)
}
}
}
}
}
}
//snapshot used to save previous state
} else {
//specific device map
//9b5c043e-ede1-443f-a245-33095e548a4e:[old:[switch:null], scenes:[g1s2:[switch:on], g1s1:[switch:on]], name:Pantry Lights]]
//save previous state
deviceKeys.each{ deviceKey ->
def groupDevices = this[deviceKey]
groupDevices.each{ stDevice ->
//old:[level:null, saturation:null, color:null, hue:null, switch:null]
deviceMap = state.deviceMaps[stDevice.id]
if (deviceMap != null){
savedMap = deviceMap.old
savedMap.each{ attribute ->
deviceMap.old[attribute.key] = stDevice.currentValue(attribute.key)
}
}
}
}
//log.debug "sceneSnap- ${sceneID} savedMap:${savedMap}"
}
//log.debug "sceneSnap ${sceneID} isNew:${isNew}"
//log.debug "state.deviceMaps:${state.deviceMaps}"
}
/**********************************************
UI preference settings methods
***********************************************/
def isGroupComplete(groupID){
def boolean hasScenes = getSceneMaps(groupID) ?: false
def boolean hasDevices = getDeviceLists(groupID) ?: false
if (hasScenes && hasDevices) return "complete"
else return "incomplete"
}
def getDeviceKeysFromGroup(groupID){
return settings.findAll(){it.key ==~ /${groupID}d[a-z,A-Z]+/}.keySet()
}
def getDeviceLists(groupID){
// [g1:Master, g1s1:some Scene, g1dswitches:[AeonD11, Bar Strip]]
//all device lists gxdxxxx
return settings.findAll(){it.key ==~ /${groupID}d[a-z,A-Z]+/}
}
def getDeviceKeysFromScene(sceneID){
//get group from scene
def groupID = sceneID.replaceFirst(/s[0-9]+/,"")
return settings.findAll(){it.key ==~ /${groupID}d[a-z,A-Z]+/}.keySet()
}
def getGroupDisplayNameFromScene(sceneID){
def groupID = sceneID.replaceFirst(/s[0-9]+/,"")
return settings[groupID]
}
def getSceneDisplayNameFromScene(sceneID){
return settings[sceneID]
}
def getGroupPageTitle(groupID){
return settings[groupID] ?: "Device Group ${groupID.replace("g","")}"
}
def getSceneTitle(sceneID){
return settings[sceneID] ?: sceneID.replace("g","Group ").replace("s",", Scene ")
}
def getGroupMaps(){
return settings.findAll(){it.key ==~ /g[0-9]+/}.sort{it.key}
}
def getSceneMaps(groupID){
//scene key format : g1s1
return settings.findAll(){it.key ==~ /${groupID}s[0-9]+/}.sort{it.key}
}
def getNextGroupIDX(){
def found = settings.findAll(){it.key ==~ /g[0-9]+/}
def next = 0
def crnt
found.each(){ it.key
crnt = it.key.replace("g","").toInteger()
if (crnt > next ) next = crnt
}
next ++
return next
}
def getNextSceneIDX(groupID){
def found = settings.findAll(){it.key ==~ /${groupID}s[0-9]+/}
def next = 0
def crnt
found.each(){ it.key
crnt = it.key.replace("${groupID}s","").toInteger()
if (crnt > next ) next = crnt
}
next ++
return next
}