Update Switches.groovy
[smartapps.git] / official / turn-off-with-motion.groovy
1 /**
2  *  Turn Off With Motion
3  *
4  *  Copyright 2014 Kristopher Kubicki
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
7  *  in compliance with the License. You may obtain a copy of the License at:
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
12  *  on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
13  *  for the specific language governing permissions and limitations under the License.
14  *
15  */
16 definition(
17     name: "Turn Off With Motion",
18     namespace: "KristopherKubicki",
19     author: "Kristopher Kubicki",
20     description: "Turns off a device if there is motion",
21     category: "My Apps",
22     iconUrl: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience.png",
23     iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience@2x.png")
24
25
26
27 preferences {
28         section("Turn off when there's movement..."){
29                 input "motion1", "capability.motionSensor", title: "Where?", multiple: true
30         }
31         section("And on when there's been no movement for..."){
32                 input "minutes1", "number", title: "Minutes?"
33         }
34         section("Turn off/on light(s)..."){
35                 input "switches", "capability.switch", multiple: true
36         }
37 }
38
39
40 def installed()
41 {
42         subscribe(motion1, "motion", motionHandler)
43         schedule("0 * * * * ?", "scheduleCheck")
44 }
45
46 def updated()
47 {
48         unsubscribe()
49         subscribe(motion1, "motion", motionHandler)
50         unschedule()
51         schedule("0 * * * * ?", "scheduleCheck")
52 }
53
54 def motionHandler(evt) {
55         log.debug "$evt.name: $evt.value"
56
57         if (evt.value == "active") {
58                 log.debug "turning on lights"
59                 switches.off()
60                 state.inactiveAt = null
61         } else if (evt.value == "inactive") {
62                 if (!state.inactiveAt) {
63                         state.inactiveAt = now()
64                 }
65         }
66 }
67
68 def scheduleCheck() {
69         log.debug "schedule check, ts = ${state.inactiveAt}"
70         if (state.inactiveAt) {
71                 def elapsed = now() - state.inactiveAt
72                 def threshold = 1000 * 60 * minutes1
73                 if (elapsed >= threshold) {
74                         log.debug "turning off lights"
75                         switches.on()
76                         state.inactiveAt = null
77                 }
78                 else {
79                         log.debug "${elapsed / 1000} sec since motion stopped"
80                 }
81         }
82 }