forked from bravenel/SmartThings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRule Machine Old
More file actions
550 lines (510 loc) · 20.8 KB
/
Rule Machine Old
File metadata and controls
550 lines (510 loc) · 20.8 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
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
/**
* Rule Machine
*
* Copyright 2015 Bruce Ravenel
*
* 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: "Rule Machine",
namespace: "bravenel",
author: "Bruce Ravenel",
description: "Rule Machine",
category: "Convenience",
iconUrl: "https://s3.amazonaws.com/smartapp-icons/MyApps/Cat-MyApps.png",
iconX2Url: "https://s3.amazonaws.com/smartapp-icons/MyApps/Cat-MyApps@2x.png"
)
preferences {
page(name: "selectRule")
page(name: "selectConditions")
page(name: "defineRule")
page(name: "certainTime")
}
def selectRule() {
dynamicPage(name: "selectRule", title: "Select Conditions, Rule and Results", uninstall: true, install: true) {
section() {
label title: "Name the Rule", required: true
input "howMany", "number", title: "How many conditions?", required: true, range: "1..*"
def condLabel = conditionLabel()
href "selectConditions", title: "Define Conditions", description: condLabel ?: "Tap to set", required: true, state: condLabel ? "complete" : null
href "defineRule", title: "Define the Rule", description: state.str ? state.str : "Tap to set", state: state.str ? "complete" : null
def phrases = location.helloHome?.getPhrases()*.label
input "myPhraseTrue", "enum", title: "Routine to run when true", required: false, options: phrases.sort()
input "switchTrue", "capability.switch", title: "Switches to turn on when true", required: false, multiple: true
input "myPhraseFalse", "enum", title: "Routine to run when false", required: false, options: phrases.sort()
input "switchFalse", "capability.switch", title: "Switches to turn off when false", required: false, multiple: true
}
}
}
def selectConditions() {
dynamicPage(name: "selectConditions", title: "Select Conditions", uninstall: false) {
// section("") {input "howMany", "number", title: "How many conditions?", required: true, range: "1..*", submitOnChange: true}
if(howMany) {
for (int i = 1; i <= howMany; i++) {
def thisCapab = "rCapab$i"
section("Condtion #$i") {
getCapab(thisCapab)
def myCapab = settings.find {it.key == thisCapab}
if(myCapab) {
def xCapab = myCapab.value
if(!(xCapab in ["Time of day", "Days of week", "Mode"])) {
def thisDev = "rDev$i"
getDevs(xCapab, thisDev)
def myDev = settings.find {it.key == thisDev}
if(myDev) if(myDev.value.size() > 1) getAnyAll(thisDev)
if(xCapab in ["Temperature", "Humidity", "Illuminance"]) getRelational(thisDev)
}
getState(xCapab, i)
}
}
}
}
}
}
def defineRule() {
dynamicPage(name:"defineRule",title: "Define the Rule", uninstall: false) {
state.n = 0
state.str = ""
state.eval = []
section() {
inputLeftAndRight(false)
}
}
}
def certainTime() {
dynamicPage(name:"certainTime",title: "Only during a certain time", uninstall: false) {
section() {
input "startingX", "enum", title: "Starting at", options: ["A specific time", "Sunrise", "Sunset"], defaultValue: "A specific time", submitOnChange: true
if(startingX in [null, "A specific time"]) input "starting", "time", title: "Start time", required: false
else {
if(startingX == "Sunrise") input "startSunriseOffset", "number", range: "*..*", title: "Offset in minutes (+/-)", required: false
else if(startingX == "Sunset") input "startSunsetOffset", "number", range: "*..*", title: "Offset in minutes (+/-)", required: false
}
}
section() {
input "endingX", "enum", title: "Ending at", options: ["A specific time", "Sunrise", "Sunset"], defaultValue: "A specific time", submitOnChange: true
if(endingX in [null, "A specific time"]) input "ending", "time", title: "End time", required: false
else {
if(endingX == "Sunrise") input "endSunriseOffset", "number", range: "*..*", title: "Offset in minutes (+/-)", required: false
else if(endingX == "Sunset") input "endSunsetOffset", "number", range: "*..*", title: "Offset in minutes (+/-)", required: false
}
}
}
}
def getDevs(myCapab, dev) {
def thisName = ""
def thisCapab = ""
switch(myCapab) {
case "Switch":
thisName = "Switches"
thisCapab = "switch"
break
case "Motion":
thisName = "Motion sensors"
thisCapab = "motionSensor"
break
case "Acceleration":
thisName = "Acceleration sensors"
thisCapab = "accelerationSensor"
break
case "Contact":
thisName = "Contact sensors"
thisCapab = "contactSensor"
break
case "Presence":
thisName = "Presence sensors"
thisCapab = "presenceSensor"
break
case "Lock":
thisName = "Locks"
thisCapab = "lock"
break
case "Temperature":
thisName = "Temperature sensors"
thisCapab = "temperatureMeasurement"
break
case "Humidity":
thisName = "Humidity sensors"
thisCapab = "relativeHumidityMeasurement"
break
case "Illuminance":
thisName = "Illuminance sensors"
thisCapab = "illuminanceMeasurement"
}
def result = input dev, "capability.$thisCapab", title: thisName, required: true, multiple: true, submitOnChange: true
}
def getAnyAll(myDev) {
def result = input "All$myDev", "bool", title: "All of these?", defaultValue: false
}
def getRelational(myDev) {
def result = input "Rel$myDev", "enum", title: "Choose comparison", required: true, options: ["=", "!=", "<", ">", "<=", ">="]
}
def getCapab(myCapab) {
def myOptions = ["Switch", "Motion", "Acceleration", "Contact", "Presence", "Lock", "Temperature", "Humidity", "Illuminance", "Time of day", "Days of week", "Mode"]
def result = input myCapab, "enum", title: "Select capability", required: true, options: myOptions.sort(), submitOnChange: true
}
def getState(myCapab, n) {
def result = null
def days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
if (myCapab == "Switch") result = input "state$n", "enum", title: "Switch state", options: ["on", "off"]
else if(myCapab == "Motion") result = input "state$n", "enum", title: "Motion state", options: ["active", "inactive"], defaultValue: "active"
else if(myCapab == "Acceleration") result = input "state$n", "enum", title: "Acceleration state", options: ["active", "inactive"]
else if(myCapab == "Contact") result = input "state$n", "enum", title: "Contact state", options: ["open", "closed"]
else if(myCapab == "Presence") result = input "state$n", "enum", title: "Presence state", options: ["present", "not present"], defaultValue: "present"
else if(myCapab == "Lock") result = input "state$n", "enum", title: "Lock state", options: ["locked", "unlocked"]
else if(myCapab == "Temperature") result = input "state$n", "number", title: "Temperature"
else if(myCapab == "Humidity") result = input "state$n", "number", title: "Humidity"
else if(myCapab == "Illuminance") result = input "state$n", "number", title: "Illuminance"
else if(myCapab == "Mode") result = input "modes", "mode", title: "When mode is", multiple: true, required: false
else if(myCapab == "Days of week") result = input "days", "enum", title: "On certain days of the week", multiple: true, required: false, options: days
else if(myCapab == "Time of day") {
def timeLabel = timeIntervalLabel()
href "certainTime", title: "During a certain time", description: timeLabel ?: "Tap to set", state: timeLabel ? "complete" : null
}
}
def inputLeft(sub) {
def conds = []
for (int i = 1; i <= howMany; i++) conds << conditionLabelN(i)
input "subCondL$state.n", "bool", title: "Enter subrule for left?", submitOnChange: true
if(settings["subCondL$state.n"]) {
state.str = state.str + "("
state.eval << "("
paragraph(state.str)
inputLeftAndRight(true)
input "moreConds$state.n", "bool", title: "More conditions?", submitOnChange: true
if(settings["moreConds$state.n"]) inputRight(sub)
} else {
input "condL$state.n", "enum", title: "Which condition?", options: conds, submitOnChange: true
if(settings["condL$state.n"]) {
state.str = state.str + settings["condL$state.n"]
def myCond = 0
for (int i = 1; i <= howMany; i++) if(conditionLabelN(i) == settings["condL$state.n"]) myCond = i
state.eval << myCond
paragraph(state.str)
}
}
}
def inputRight(sub) {
state.n = state.n + 1
input "operator$state.n", "enum", title: "Choose: AND, OR, Done", options: ["AND", "OR", "Done"], submitOnChange: true
if(settings["operator$state.n"]) if(settings["operator$state.n"] != "Done") {
state.str = state.str + " " + settings["operator$state.n"] + " "
state.eval << settings["operator$state.n"]
paragraph(state.str)
def conds = []
for (int i = 1; i <= howMany; i++) conds << conditionLabelN(i)
input "subCondR$state.n", "bool", title: "Enter subrule for right?", submitOnChange: true
if(settings["subCondR$state.n"]) {
state.str = state.str + "("
state.eval << "("
paragraph(state.str)
inputLeftAndRight(true)
input "moreConds$state.n", "bool", title: "More conditions on right?", submitOnChange: true
if(settings["moreConds$state.n"]) inputRight(sub)
} else {
input "condR$state.n", "enum", title: "Which condition?", options: conds, submitOnChange: true
if(settings["condR$state.n"]) {
state.str = state.str + settings["condR$state.n"]
def myCond = 0
for (int i = 1; i <= howMany; i++) if(conditionLabelN(i) == settings["condR$state.n"]) myCond = i
state.eval << myCond
paragraph(state.str)
}
if(sub) {
input "endOfSub$state.n", "bool", title: "End of subrule?", submitOnChange: true
if(settings["endOfSub$state.n"]) {
state.str = state.str + ")"
state.eval << ")"
paragraph(state.str)
return
}
}
input "moreConds$state.n", "bool", title: "More conditions on right?", submitOnChange: true
if(settings["moreConds$state.n"]) inputRight()
}
}
}
def inputLeftAndRight(sub) {
state.n = state.n + 1
inputLeft(sub)
inputRight(sub)
}
// initialization code below
def scheduleTimeOfDay() {
def start = null
def stop = null
def s = getSunriseAndSunset(zipCode: zipCode, sunriseOffset: startSunriseOffset, sunsetOffset: startSunsetOffset)
if(startingX == "Sunrise") start = s.sunrise.time
else if(startingX == "Sunset") start = s.sunset.time
else if(starting) start = timeToday(starting,location.timeZone).time
s = getSunriseAndSunset(zipCode: zipCode, sunriseOffset: endSunriseOffset, sunsetOffset: endSunsetOffset)
if(endingX == "Sunrise") stop = s.sunrise.time
else if(endingX == "Sunset") stop = s.sunset.time
else if(ending) stop = timeToday(ending,location.timeZone).time
schedule(start, "startHandler")
schedule(stop, "stopHandler")
if(startingX in ["Sunrise", "Sunset"] || endingX in ["Sunrise", "Sunset"])
schedule("2015-01-09T00:00:29.000-0700", "scheduleTimeOfDay") // in case sunset/sunrise; change daily
}
def installed() {
initialize()
}
def updated() {
unschedule()
unsubscribe()
initialize()
}
def initialize() {
for (int i = 1; i <= howMany; i++) {
def capab = (settings.find {it.key == "rCapab$i"}).value
if (capab == "Mode") subscribe(location, "mode", allHandler)
else if(capab == "Time of day") scheduleTimeOfDay()
else if(capab == "Days of week") schedule("2015-01-09T00:00:10.000-0700", "runRule")
else subscribe((settings.find{it.key == "rDev$i"}).value, capab.toLowerCase(), allHandler)
}
state.success = null
runRule()
}
// Main rule evaluation code follows
def compare(a, rel, b) {
def result = true
if (rel == "=") result = a == b
else if(rel == "!=") result = a != b
else if(rel == ">") result = a > b
else if(rel == "<") result = a < b
else if(rel == ">=") result = a >= b
else if(rel == "<=") result = a <= b
return result
}
def checkCondAny(dev, state, cap, rel) {
def result = false
if (cap == "Temperature") dev.currentTemperature.each {result = result || compare(it, rel, state)}
else if(cap == "Humidity") dev.currentHumidity.each {result = result || compare(it, rel, state)}
else if(cap == "Illuminance") dev.currentIlluminance.each {result = result || compare(it, rel, state)}
else if(cap == "Switch") result = state in dev.currentSwitch
else if(cap == "Motion") result = state in dev.currentMotion
else if(cap == "Acceleration") result = state in dev.currentAcceleration
else if(cap == "Contact") result = state in dev.currentContact
else if(cap == "Presence") result = state in dev.currentPresence
else if(cap == "Lock") result = state in dev.currentLock
// log.debug "CheckAny $cap $result"
return result
}
def checkCondAll(dev, state, cap, rel) {
def flip = ["on": "off",
"off": "on",
"active": "inactive",
"inactive": "active",
"open": "closed",
"closed": "open",
"present": "not present",
"not present": "present",
"locked": "unlocked",
"unlocked": "locked"]
def result = true
if (cap == "Temperature") dev.currentTemperature.each {result = result && compare(it, rel, state)}
else if(cap == "Humidity") dev.currentHumidity.each {result = result && compare(it, rel, state)}
else if(cap == "Illuminance") dev.currentIlluminance.each {result = result && compare(it, rel, state)}
else if(cap == "Switch") result = !(flip[state] in dev.currentSwitch)
else if(cap == "Motion") result = !(flip[state] in dev.currentMotion)
else if(cap == "Acceleration") result = !(flip[state] in dev.currentAcceleration)
else if(cap == "Contact") result = !(flip[state] in dev.currentContact)
else if(cap == "Presence") result = !(flip[state] in dev.currentPresence)
else if(cap == "Lock") result = !(flip[state] in dev.currentLock)
// log.debug "CheckAll $cap $result"
return result
}
def getOperand(i) {
def result = true
def capab = (settings.find {it.key == "rCapab$i"}).value
if (capab == "Mode") result = modeOk
else if(capab == "Time of day") result = timeOk
else if(capab == "Days of week") result = daysOk
else {
def myDev = settings.find {it.key == "rDev$i"}
def myState = settings.find {it.key == "state$i"}
def myRel = settings.find {it.key == "RelrDev$i"}
def myAll = settings.find {it.key == "AllrDev$i"}
if(myAll) {
if(myAll.value) result = checkCondAll(myDev.value, myState.value, capab, myRel ? myRel.value : 0)
else result = checkCondAny(myDev.value, myState.value, capab, myRel ? myRel.value : 0)
} else result = checkCondAny(myDev.value, myState.value, capab, myRel ? myRel.value : 0)
}
// log.debug "operand is $result"
return result
}
def findRParen() {
def noMatch = true
while(noMatch) {
if(state.eval[state.token] == ")") {
if(state.parenLev == 0) return
else state.parenLev = state.parenLev - 1
} else if(state.eval[state.token] == "(") state.parenLev = state.parenLev + 1
state.token = state.token + 1
if(state.token >= state.eval.size) return
}
}
def disEval() {
if(state.eval[state.token] == "(") {
state.parenLev = 0
findRParen()
}
if(state.token >= state.eval.size) return
state.token = state.token + 1
}
def evalTerm() {
def result = true
def thisTok = state.eval[state.token]
// log.debug "evalTerm tok is $thisTok"
if (thisTok == "(") {
state.token = state.token + 1
result = eval()
} else result = getOperand(thisTok)
state.token = state.token + 1
// log.debug "evalTerm is $result"
return result
}
def eval() {
def result = evalTerm()
while(true) {
if(state.token >= state.eval.size) return result
def thisTok = state.eval[state.token]
// log.debug "eval: $thisTok"
if (thisTok == "OR") {
if(result) {
disEval()
return true
}
} else if (thisTok == "AND") {
if(!result) {
disEval()
return false
}
} else if (thisTok == ")") return result
state.token = state.token + 1
result = evalTerm()
}
}
def runRule() {
state.token = 0
def success = eval()
if(success != state.success) {
if(success) {
if(myPhraseTrue) location.helloHome.execute(myPhraseTrue)
if(switchTrue) switchTrue.on()
} else {
if(myPhraseFalse) location.helloHome.execute(myPhraseFalse)
if(switchFalse) switchFalse.off()
}
state.success = success
log.debug (success ? "Success" : "Failure")
}
}
def allHandler(evt) {
log.debug "Handler: $evt.displayName $evt.name $evt.value"
runRule()
}
def startHandler() {
runRule()
}
def stopHandler() {
runRule()
}
// private execution filter methods below
private conditionLabel() {
def result = ""
for (int i = 1; i <= howMany; i++) {
result = result + conditionLabelN(i)
if((i + 1) <= howMany) result = result + "\n"
}
return result
}
private conditionLabelN(i) {
def result = ""
def thisCapab = settings.find {it.key == "rCapab$i"}
if(thisCapab.value == "Time of day") result = "Time between " + timeIntervalLabel()
else if(thisCapab.value == "Days of week") result = "Day i" + (days.size() > 1 ? "n " + days : "s " + days[0])
else if (thisCapab.value == "Mode") result = "Mode i" + (modes.size() > 1 ? "n " + modes : "s " + modes[0])
else {
def thisDev = settings.find {it.key == "rDev$i"}
def thisAll = settings.find {it.key == "AllrDev$i"}
def myAny = thisAll ? "any " : ""
if(thisCapab.value == "Temperature") result = "Temperature of "
else if(thisCapab.value == "Humidity") result = "Humidity of "
else if(thisCapab.value == "Illuminance") result = "Illuminance of "
result = result + (myAny ? thisDev.value : thisDev.value[0]) + " " + ((thisAll ? thisAll.value : false) ? "all " : myAny)
def thisRel = settings.find {it.key == "RelrDev$i"}
if(thisCapab.value in ["Temperature", "Humidity", "Illuminance"]) result = result + " " + thisRel.value + " "
def thisState = settings.find {it.key == "state$i"}
result = result + thisState.value
}
return result
}
private hhmm(time, fmt = "h:mm a") {
def t = timeToday(time, location.timeZone)
def f = new java.text.SimpleDateFormat(fmt)
f.setTimeZone(location.timeZone ?: timeZone(time))
f.format(t)
}
private offset(value) {
def result = value ? ((value > 0 ? "+" : "") + value + " min") : ""
}
private timeIntervalLabel() {
def result = ""
if (startingX == "Sunrise" && endingX == "Sunrise") result = "Sunrise" + offset(startSunriseOffset) + " and Sunrise" + offset(endSunriseOffset)
else if (startingX == "Sunrise" && endingX == "Sunset") result = "Sunrise" + offset(startSunriseOffset) + " and Sunset" + offset(endSunsetOffset)
else if (startingX == "Sunset" && endingX == "Sunrise") result = "Sunset" + offset(startSunsetOffset) + " and Sunrise" + offset(endSunriseOffset)
else if (startingX == "Sunset" && endingX == "Sunset") result = "Sunset" + offset(startSunsetOffset) + " and Sunset" + offset(endSunsetOffset)
else if (startingX == "Sunrise" && ending) result = "Sunrise" + offset(startSunriseOffset) + " and " + hhmm(ending, "h:mm a z")
else if (startingX == "Sunset" && ending) result = "Sunset" + offset(startSunsetOffset) + " and " + hhmm(ending, "h:mm a z")
else if (starting && endingX == "Sunrise") result = hhmm(starting) + " and Sunrise" + offset(endSunriseOffset)
else if (starting && endingX == "Sunset") result = hhmm(starting) + " and Sunset" + offset(endSunsetOffset)
else if (starting && ending) result = hhmm(starting) + " and " + hhmm(ending, "h:mm a z")
}
private getModeOk() {
def result = !modes || modes.contains(location.mode)
// log.trace "modeOk = $result"
return result
}
private getDaysOk() {
def result = true
if (days) {
def df = new java.text.SimpleDateFormat("EEEE")
if (location.timeZone) df.setTimeZone(location.timeZone)
else df.setTimeZone(TimeZone.getTimeZone("America/New_York"))
def day = df.format(new Date())
result = days.contains(day)
}
// log.trace "daysOk = $result"
return result
}
private getTimeOk() {
def result = true
if ((starting && ending) ||
(starting && endingX in ["Sunrise", "Sunset"]) ||
(startingX in ["Sunrise", "Sunset"] && ending) ||
(startingX in ["Sunrise", "Sunset"] && endingX in ["Sunrise", "Sunset"])) {
def currTime = now()
def start = null
def stop = null
def s = getSunriseAndSunset(zipCode: zipCode, sunriseOffset: startSunriseOffset, sunsetOffset: startSunsetOffset)
if(startingX == "Sunrise") start = s.sunrise.time
else if(startingX == "Sunset") start = s.sunset.time
else if(starting) start = timeToday(starting,location.timeZone).time
s = getSunriseAndSunset(zipCode: zipCode, sunriseOffset: endSunriseOffset, sunsetOffset: endSunsetOffset)
if(endingX == "Sunrise") stop = s.sunrise.time
else if(endingX == "Sunset") stop = s.sunset.time
else if(ending) stop = timeToday(ending,location.timeZone).time
result = start < stop ? currTime >= start && currTime <= stop : currTime <= stop || currTime >= start
}
// log.trace "getTimeOk = $result"
return result
}