Update gentle-wake-up.groovy
[smartapps.git] / official / button-controller.groovy
1 /**
2  *  Copyright 2015 SmartThings
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  *  in compliance with the License. You may obtain a copy of the License at:
6  *
7  *      http://www.apache.org/licenses/LICENSE-2.0
8  *
9  *  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
10  *  on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
11  *  for the specific language governing permissions and limitations under the License.
12  *
13  *      Button Controller
14  *
15  *      Author: SmartThings
16  *      Date: 2014-5-21
17  */
18 definition(
19     name: "Button Controller",
20     namespace: "smartthings",
21     author: "SmartThings",
22     description: "Control devices with buttons like the Aeon Labs Minimote",
23     category: "Convenience",
24     iconUrl: "https://s3.amazonaws.com/smartapp-icons/MyApps/Cat-MyApps.png",
25     iconX2Url: "https://s3.amazonaws.com/smartapp-icons/MyApps/Cat-MyApps@2x.png"
26 )
27
28 preferences {
29         page(name: "selectButton")
30         page(name: "configureButton1")
31         page(name: "configureButton2")
32         page(name: "configureButton3")
33         page(name: "configureButton4")
34
35         page(name: "timeIntervalInput", title: "Only during a certain time") {
36                 section {
37                         input "starting", "time", title: "Starting", required: false
38                         input "ending", "time", title: "Ending", required: false
39                 }
40         }
41 }
42
43 def selectButton() {
44         dynamicPage(name: "selectButton", title: "First, select your button device", nextPage: "configureButton1", uninstall: configured()) {
45                 section {
46                         input "buttonDevice", "capability.button", title: "Button", multiple: false, required: true
47                 }
48
49                 section(title: "More options", hidden: hideOptionsSection(), hideable: true) {
50
51                         def timeLabel = timeIntervalLabel()
52
53                         href "timeIntervalInput", title: "Only during a certain time", description: timeLabel ?: "Tap to set", state: timeLabel ? "complete" : null
54
55                         input "days", "enum", title: "Only on certain days of the week", multiple: true, required: false,
56                                 options: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
57
58                         input "modes", "mode", title: "Only when mode is", multiple: true, required: false
59                 }
60         }
61 }
62
63 def configureButton1() {
64         dynamicPage(name: "configureButton1", title: "Now let's decide how to use the first button",
65                 nextPage: "configureButton2", uninstall: configured(), getButtonSections(1))
66 }
67 def configureButton2() {
68         dynamicPage(name: "configureButton2", title: "If you have a second button, set it up here",
69                 nextPage: "configureButton3", uninstall: configured(), getButtonSections(2))
70 }
71
72 def configureButton3() {
73         dynamicPage(name: "configureButton3", title: "If you have a third button, you can do even more here",
74                 nextPage: "configureButton4", uninstall: configured(), getButtonSections(3))
75 }
76 def configureButton4() {
77         dynamicPage(name: "configureButton4", title: "If you have a fourth button, you rule, and can set it up here",
78                 install: true, uninstall: true, getButtonSections(4))
79 }
80
81 def getButtonSections(buttonNumber) {
82         return {
83                 section("Lights") {
84                         input "lights_${buttonNumber}_pushed", "capability.switch", title: "Pushed", multiple: true, required: false
85                         input "lights_${buttonNumber}_held", "capability.switch", title: "Held", multiple: true, required: false
86                 }
87                 section("Locks") {
88                         input "locks_${buttonNumber}_pushed", "capability.lock", title: "Pushed", multiple: true, required: false
89                         input "locks_${buttonNumber}_held", "capability.lock", title: "Held", multiple: true, required: false
90                 }
91                 section("Sonos") {
92                         input "sonos_${buttonNumber}_pushed", "capability.musicPlayer", title: "Pushed", multiple: true, required: false
93                         input "sonos_${buttonNumber}_held", "capability.musicPlayer", title: "Held", multiple: true, required: false
94                 }
95                 section("Modes") {
96                         input "mode_${buttonNumber}_pushed", "mode", title: "Pushed", required: false
97                         input "mode_${buttonNumber}_held", "mode", title: "Held", required: false
98                 }
99                 def phrases = location.helloHome?.getPhrases()*.label
100                 if (phrases) {
101                         section("Hello Home Actions") {
102                                 log.trace phrases
103                                 input "phrase_${buttonNumber}_pushed", "enum", title: "Pushed", required: false, options: phrases
104                                 input "phrase_${buttonNumber}_held", "enum", title: "Held", required: false, options: phrases
105                         }
106                 }
107         section("Sirens") {
108             input "sirens_${buttonNumber}_pushed","capability.alarm" ,title: "Pushed", multiple: true, required: false
109             input "sirens_${buttonNumber}_held", "capability.alarm", title: "Held", multiple: true, required: false
110         }
111
112                 section("Custom Message") {
113                         input "textMessage_${buttonNumber}", "text", title: "Message", required: false
114                 }
115
116         section("Push Notifications") {
117             input "notifications_${buttonNumber}_pushed","bool" ,title: "Pushed", required: false, defaultValue: false
118             input "notifications_${buttonNumber}_held", "bool", title: "Held", required: false, defaultValue: false
119         }
120
121         section("Sms Notifications") {
122             input "phone_${buttonNumber}_pushed","phone" ,title: "Pushed", required: false
123             input "phone_${buttonNumber}_held", "phone", title: "Held", required: false
124         }
125         }
126 }
127
128 def installed() {
129         initialize()
130 }
131
132 def updated() {
133         unsubscribe()
134         initialize()
135 }
136
137 def initialize() {
138         subscribe(buttonDevice, "button", buttonEvent)
139 }
140
141 def configured() {
142         return buttonDevice || buttonConfigured(1) || buttonConfigured(2) || buttonConfigured(3) || buttonConfigured(4)
143 }
144
145 def buttonConfigured(idx) {
146         return settings["lights_$idx_pushed"] ||
147                 settings["locks_$idx_pushed"] ||
148                 settings["sonos_$idx_pushed"] ||
149                 settings["mode_$idx_pushed"] ||
150         settings["notifications_$idx_pushed"] ||
151         settings["sirens_$idx_pushed"] ||
152         settings["notifications_$idx_pushed"]   ||
153         settings["phone_$idx_pushed"]
154 }
155
156 def buttonEvent(evt){
157         if(allOk) {
158                 def buttonNumber = evt.data // why doesn't jsonData work? always returning [:]
159                 def value = evt.value
160                 log.debug "buttonEvent: $evt.name = $evt.value ($evt.data)"
161                 log.debug "button: $buttonNumber, value: $value"
162
163                 def recentEvents = buttonDevice.eventsSince(new Date(now() - 3000)).findAll{it.value == evt.value && it.data == evt.data}
164                 log.debug "Found ${recentEvents.size()?:0} events in past 3 seconds"
165
166                 if(recentEvents.size <= 1){
167                         switch(buttonNumber) {
168                                 case ~/.*1.*/:
169                                         executeHandlers(1, value)
170                                         break
171                                 case ~/.*2.*/:
172                                         executeHandlers(2, value)
173                                         break
174                                 case ~/.*3.*/:
175                                         executeHandlers(3, value)
176                                         break
177                                 case ~/.*4.*/:
178                                         executeHandlers(4, value)
179                                         break
180                         }
181                 } else {
182                         log.debug "Found recent button press events for $buttonNumber with value $value"
183                 }
184         }
185 }
186
187 def executeHandlers(buttonNumber, value) {
188         log.debug "executeHandlers: $buttonNumber - $value"
189
190         def lights = find('lights', buttonNumber, value)
191         if (lights != null) toggle(lights)
192
193         def locks = find('locks', buttonNumber, value)
194         if (locks != null) toggle(locks)
195
196         def sonos = find('sonos', buttonNumber, value)
197         if (sonos != null) toggle(sonos)
198
199         def mode = find('mode', buttonNumber, value)
200         if (mode != null) changeMode(mode)
201
202         def phrase = find('phrase', buttonNumber, value)
203         if (phrase != null) location.helloHome.execute(phrase)
204
205         def textMessage = findMsg('textMessage', buttonNumber)
206
207         def notifications = find('notifications', buttonNumber, value)
208         if (notifications?.toBoolean()) sendPush(textMessage ?: "Button $buttonNumber was pressed" )
209
210         def phone = find('phone', buttonNumber, value)
211         if (phone != null) sendSms(phone, textMessage ?:"Button $buttonNumber was pressed")
212
213     def sirens = find('sirens', buttonNumber, value)
214     if (sirens != null) toggle(sirens)
215 }
216
217 def find(type, buttonNumber, value) {
218         def preferenceName = type + "_" + buttonNumber + "_" + value
219         def pref = settings[preferenceName]
220         if(pref != null) {
221                 log.debug "Found: $pref for $preferenceName"
222         }
223
224         return pref
225 }
226
227 def findMsg(type, buttonNumber) {
228         def preferenceName = type + "_" + buttonNumber
229         def pref = settings[preferenceName]
230         if(pref != null) {
231                 log.debug "Found: $pref for $preferenceName"
232         }
233
234         return pref
235 }
236
237 def toggle(devices) {
238         log.debug "toggle: $devices = ${devices*.currentValue('switch')}"
239
240         if (devices*.currentValue('switch').contains('on')) {
241                 devices.off()
242         }
243         else if (devices*.currentValue('switch').contains('off')) {
244                 devices.on()
245         }
246         else if (devices*.currentValue('lock').contains('locked')) {
247                 devices.unlock()
248         }
249         else if (devices*.currentValue('lock').contains('unlocked')) {
250                 devices.lock()
251         }
252         else if (devices*.currentValue('alarm').contains('off')) {
253         devices.siren()
254     }
255         else {
256                 devices.on()
257         }
258 }
259
260 def changeMode(mode) {
261         log.debug "changeMode: $mode, location.mode = $location.mode, location.modes = $location.modes"
262
263         if (location.mode != mode && location.modes?.find { it.name == mode }) {
264                 setLocationMode(mode)
265         }
266 }
267
268 // execution filter methods
269 private getAllOk() {
270         modeOk && daysOk && timeOk
271 }
272
273 private getModeOk() {
274         def result = !modes || modes.contains(location.mode)
275         log.trace "modeOk = $result"
276         result
277 }
278
279 private getDaysOk() {
280         def result = true
281         if (days) {
282                 def df = new java.text.SimpleDateFormat("EEEE")
283                 if (location.timeZone) {
284                         df.setTimeZone(location.timeZone)
285                 }
286                 else {
287                         df.setTimeZone(TimeZone.getTimeZone("America/New_York"))
288                 }
289                 def day = df.format(new Date())
290                 result = days.contains(day)
291         }
292         log.trace "daysOk = $result"
293         result
294 }
295
296 private getTimeOk() {
297         def result = true
298         if (starting && ending) {
299                 def currTime = now()
300                 def start = timeToday(starting, location.timeZone).time
301                 def stop = timeToday(ending, location.timeZone).time
302                 result = start < stop ? currTime >= start && currTime <= stop : currTime <= stop || currTime >= start
303         }
304         log.trace "timeOk = $result"
305         result
306 }
307
308 private hhmm(time, fmt = "h:mm a")
309 {
310         def t = timeToday(time, location.timeZone)
311         def f = new java.text.SimpleDateFormat(fmt)
312         f.setTimeZone(location.timeZone ?: timeZone(time))
313         f.format(t)
314 }
315
316 private hideOptionsSection() {
317         (starting || ending || days || modes) ? false : true
318 }
319
320 private timeIntervalLabel() {
321         (starting && ending) ? hhmm(starting) + "-" + hhmm(ending, "h:mm a z") : ""
322 }