forked from muxa/hubitat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscene-switch-instance.groovy
More file actions
377 lines (323 loc) · 9.87 KB
/
scene-switch-instance.groovy
File metadata and controls
377 lines (323 loc) · 9.87 KB
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
/**
* Scene Switch v1.1.0
*
* Copyright 2019-2020 Mikhail Diatchenko (@muxa)
*
* Based on Switch Bindings Instance code by Joel Wetzel
*
*
* 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.
*
*/
import groovy.json.*
definition(
parent: "muxa:Scene Switch",
name: "Scene Switch Instance",
namespace: "muxa",
author: "Mikhail Diatchenko",
description: "Child app that is instantiated by the Scene Switch app.",
category: "Convenience",
iconUrl: "",
iconX2Url: "",
iconX3Url: "")
def switches0 = [
name: "switches0",
type: "capability.switch",
title: "Switches Scene 0 (off)",
description: "Switches to turn off by the scene switch (Scene 0).",
multiple: true,
required: true
]
def switches1 = [
name: "switches1",
type: "capability.switch",
title: "Switches Scene 1",
description: "Switches to turn on by the scene switch for Scene 1.",
multiple: true,
required: true
]
def switches2 = [
name: "switches2",
type: "capability.switch",
title: "Switches Scene 2",
description: "Switches to turn on by the scene switch for Scene 2.",
multiple: true,
required: false
]
def switches3 = [
name: "switches3",
type: "capability.switch",
title: "Switches Scene 3",
description: "Switches to turn on by the scene switch for Scene 3.",
multiple: true,
required: false
]
def sceneSwitch = [
name: "sceneSwitch",
type: "capability.switch",
title: "Scene Switch",
multiple: false,
required: true
]
def sceneToggleDuration = [
name: "sceneToggleDuration",
type: "number",
title: "Scene Toggle Duration (milliseconds)",
description: "???",
defaultValue: 1000,
required: true
]
def nameOverride = [
name: "nameOverride",
type: "string",
title: "Name",
multiple: false,
required: true
]
def enableLogging = [
name: "enableLogging",
type: "bool",
title: "Enable Debug Logging?",
defaultValue: false,
required: true
]
preferences {
page(name: "mainPage", title: "", install: true, uninstall: true) {
section("<h2>Scene Switch</h2>") {
input nameOverride
}
section("") {
input sceneSwitch
paragraph "<b>WARINING:</b> do not include the Scene Switch in scenes"
input switches0
input switches1
input switches2
input switches3
input sceneToggleDuration
}
section () {
input enableLogging
}
}
}
def installed() {
log.info "Installed with settings: ${settings}"
initialize()
}
def updated() {
log.info "Updated with settings: ${settings}"
unsubscribe()
initialize()
}
def initialize() {
app.updateLabel(nameOverride)
state.currentScene = 0 // off
setupSubscriptions()
log "Initialised ${nameOverride}"
}
def getNextScene() {
switch (state.currentScene) {
case -1:
return 0
case 0:
return 1
case 1:
if (switches2 && switches2.size() > 0) {
return 2
}
if (switches3 && switches3.size() > 0) {
return 3
}
return 0
case 2:
if (switches3 && switches3.size() > 0) {
return 3
}
return 0
case 3:
return 0
}
}
def getSceneSwitches(sceneNumber) {
switch (sceneNumber) {
case 0:
return switches0
case 1:
return switches1
case 2:
return switches2
case 3:
return switches3
}
}
def applySwitchQueue(queue) {
log.debug "Apply switch queue: ${queue} (${queue.size()})"
if (queue.size() == 0) {
state.remove('switchQueue')
return
}
state.switchQueue = queue
// TODO: add a delay to automatically clear queue if it takes to long
switches0.each { s ->
def targetValue = queue.get(s.id)
//log.debug "Target value for ${s.id}: ${targetValue}"
switch (targetValue) {
case 'on':
log.debug "Turn ${s} on"
s.on()
break
case 'off':
log.debug "Turn ${s} off"
s.off()
break
}
}
}
def activateScene(sceneNumber) {
log "Activate scene ${sceneNumber}"
if (state.currentScene > 0)
state.lastUsedScene = state.currentScene
def previousScene = state.currentScene
state.currentScene = sceneNumber
if (sceneNumber == 0) {
def switchQueue = [:]
switches0
.findAll { it.currentValue('switch') == 'on' }
.each { switchQueue[it.id] = 'off' }
applySwitchQueue(switchQueue)
} else {
def previousSwitches = getSceneSwitches(previousScene)
def currentSwitches = getSceneSwitches(sceneNumber)
def switchQueue = [:]
//log "Previous scene ${previousScene}. Switches: ${previousSwitches}"
previousSwitches.each { s ->
def onSwitch = currentSwitches.find { it.id == s.id }
if (onSwitch == null) {
if (s.currentValue('switch') == 'on') {
//log "- ${s} turn off"
switchQueue[s.id] = 'off'
} else {
//log "- ${s} is already off"
}
} else {
//log "- ${s} keep on for next scene"
}
}
//log "Current scene ${sceneNumber}. Switches ${currentSwitches}"
currentSwitches.each { s ->
if (s.currentValue('switch') == 'off') {
//log "- ${s} turn on"
switchQueue[s.id] = 'on'
} else {
//log "- ${s} already on"
}
}
applySwitchQueue(switchQueue)
}
}
def sceneSwitchHandler(evt) {
log "Scene switch ${evt.value}"
if (evt.value == "off") {
// record time when switched off to track if we switched it back in quckly to change scene
state.sceneSwitchLastOff = now()
runInMillis(sceneToggleDuration ?: 1000, 'delayedLinkedSwitchesOff')
} else {
// check if it's just on or should change scene
if (state.sceneSwitchLastOff) {
def offDurationMillis = now() - state.sceneSwitchLastOff
if (offDurationMillis < (sceneToggleDuration ?: 1000)) {
// change scene
def nextScene = getNextScene()
if (nextScene == 0)
nextScene = 1
log "Change scene to: ${nextScene} (from ${state.currentScene})"
activateScene(nextScene)
return
}
}
// turn on last scene
def lastUsedScene = state.lastUsedScene ?: 1
log "Turn back on scene ${lastUsedScene}"
activateScene(lastUsedScene)
}
}
def delayedLinkedSwitchesOff() {
if (sceneSwitch.currentValue("switch") == "off") {
// scene switch is still off (i.e it was not toggled back on to change the scene)
// turn off all the switches
activateScene(0)
}
}
def linkedSwitchHandler(evt) {
log "Linked switch ${evt.displayName} is ${evt.value}."
def deviceId = evt.getDeviceId().toString()
if (state.switchQueue?.containsKey(deviceId)) {
// linked switch toggled by master switch
state.switchQueue.remove(deviceId)
if (state.switchQueue.size() == 0) {
log "Scene ${state.currentScene} activated"
} else {
log "Waiting for queue to be processed: ${state.switchQueue}"
}
} else {
// linked switch turned manually.
// detect scene and set scene switch accordingly
if (evt.value == "off") {
if (allSwitchesAreOff()) {
// all switches are off. activate scene 0 and turn the scene switch off
state.currentScene = 0
log "All linked switches are off. Turn off the scene switch"
bypassSceneSwitchSubscription {
sceneSwitch.off()
}
}
} else if (sceneSwitch.currentValue("switch") == "off") {
state.currentScene = -1
log "Scene override. Turning scene switch on" // because one of the linked switched switched on
// TODO: detect scene
bypassSceneSwitchSubscription {
sceneSwitch.on()
}
}
}
}
def allSwitchesAreOff() {
return switches0.find { it.currentValue("switch") == "on" } == null
}
def bypassSceneSwitchSubscription(Closure callback) {
// we need to bypass subscriptions, so that we don't get a feedback switches what we toggle in `callback`
// to do that we need to delay restoring subscriptions, since switch events arrive asynchrounousl
log "Unsubscribe from scene switch events"
unsubscribe(sceneSwitch, "switch", 'sceneSwitchHandler')
callback();
// restore subscription
runInMillis(500, 'setupSceneSwitchSubscription')
}
def setupSubscriptions() {
setupSceneSwitchSubscription()
setupLinkedSwitchesSubscription()
}
def setupSceneSwitchSubscription() {
log "(Re)subscribe to scene switch events"
subscribe(sceneSwitch, "switch", sceneSwitchHandler)
}
def setupLinkedSwitchesSubscription() {
log "(Re)subscribe to linked switches events"
subscribe(switches0, "switch", linkedSwitchHandler)
// TODO: make sure that all switches are handled (assuming switches0 contains all switches from other scenes)
//subscribe(switches1, "switch", linkedSwitchHandler)
//subscribe(switches2, "switch", linkedSwitchHandler)
//subscribe(switches3, "switch", linkedSwitchHandler)
}
def log(msg) {
if (enableLogging) {
log.debug msg
}
}