Update ecobeeAwayFromHome.groovy
[smartapps.git] / official / step-notifier.groovy
1 /**
2  *  Step Notifier
3  *
4  *  Copyright 2014 Jeff's Account
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: "Step Notifier",
18     namespace: "smartthings",
19     author: "SmartThings",
20     description: "Use a step tracker device to track daily step goals and trigger various device actions when your goals are met!",
21     category: "SmartThings Labs",
22         iconUrl: "https://s3.amazonaws.com/smartapp-icons/Partner/jawbone-up.png",
23         iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Partner/jawbone-up@2x.png"
24 )
25
26 preferences {
27         page(name: "setupNotifications")
28         page(name: "timeIntervalInput", title: "Only during a certain time") {
29                 section {
30                         input "starting", "time", title: "Starting", required: false
31                         input "ending", "time", title: "Ending", required: false
32                 }
33         }
34 }
35
36 def setupNotifications() {
37     
38     dynamicPage(name: "setupNotifications", title: "Configure Your Goal Notifications.", install: true, uninstall: true) {      
39     
40                 section("Select your Jawbone UP") {
41                         input "jawbone", "capability.stepSensor", title: "Jawbone UP", required: true, multiple: false
42                 }
43            
44         section("Notify Me When"){
45                         input "thresholdType", "enum", title: "Select When to Notify", required: false, defaultValue: "Goal Reached", options: ["Goal","Threshold"], submitOnChange:true
46             if (settings.thresholdType) {
47                 if (settings.thresholdType == "Threshold") {
48                         input "threshold", "number", title: "Enter Step Threshold", description: "Number", required: true
49                 }
50             }
51                 }
52         
53                 section("Via a push notification and/or an SMS message"){
54             input("recipients", "contact", title: "Send notifications to") {
55                 input "phone", "phone", title: "Phone Number (for SMS, optional)", required: false
56                 input "notificationType", "enum", title: "Select Notification", required: false, defaultValue: "None", options: ["None", "Push", "SMS", "Both"]
57             }
58                 }
59         
60         section("Flash the Lights") {
61                 input "lights", "capability.switch", title: "Which Lights?", required: false, multiple: true
62                 input "flashCount", "number", title: "How Many Times?", defaultValue: 5, required: false           
63         }
64         
65         section("Change the Color of the Lights") {
66                 input "hues", "capability.colorControl", title: "Which Hue Bulbs?", required:false, multiple:true
67             input "color", "enum", title: "Hue Color?", required: false, multiple:false, options: ["Red","Green","Blue","Yellow","Orange","Purple","Pink"]
68                         input "lightLevel", "enum", title: "Light Level?", required: false, options: [10,20,30,40,50,60,70,80,90,100]
69                         input "duration", "number", title: "Duration in Seconds?", defaultValue: 30, required: false
70         }
71         
72         section("Play a song on the Sonos") {
73                         input "sonos", "capability.musicPlayer", title: "On this Sonos player", required: false, submitOnChange:true
74             if (settings.sonos) {
75                                 input "song","enum",title:"Play this track or radio station", required:true, multiple: false, options: songOptions()  
76                                 input "resumePlaying", "bool", title: "Resume currently playing music after notification", required: false, defaultValue: true                
77                 input "volume", "number", title: "Temporarily change volume", description: "0-100%", required: false
78                 input "songDuration", "number", title: "Play for this many seconds", defaultValue: 60, description: "0-100%", required: true
79             }
80
81                 }
82     }
83 }
84
85 private songOptions() {
86
87         // Make sure current selection is in the set
88         /*
89         def options = new LinkedHashSet()
90         if (state.selectedSong?.station) {
91                 options << state.selectedSong.station
92         }
93         else if (state.selectedSong?.description) {
94                 // TODO - Remove eventually? 'description' for backward compatibility
95                 options << state.selectedSong.description
96         }
97
98         // Query for recent tracks
99         def states = sonos.statesSince("trackData", new Date(0), [max:30])
100         def dataMaps = states.collect{it.jsonValue}
101         options.addAll(dataMaps.collect{it.station})
102
103         log.trace "${options.size()} songs in list"
104         options.take(20) as List*/
105         state.selectedSong = "SomeTrack"
106 }
107
108 private saveSelectedSong() {
109         /*
110         try {
111                 def thisSong = song
112                 log.info "Looking for $thisSong"
113                 def songs = sonos.statesSince("trackData", new Date(0), [max:30]).collect{it.jsonValue}
114                 log.info "Searching ${songs.size()} records"
115
116                 def data = songs.find {s -> s.station == thisSong}
117                 log.info "Found ${data?.station}"
118                 if (data) {
119                         state.selectedSong = data
120                         log.debug "Selected song = $state.selectedSong"
121                 }
122                 else if (song == state.selectedSong?.station) {
123                         log.debug "Selected existing entry '$song', which is no longer in the last 20 list"
124                 }
125                 else {
126                         log.warn "Selected song '$song' not found"
127                 }
128         }
129         catch (Throwable t) {
130                 log.error t
131         }*/
132         state.selectedSong = "SomeTrack"        
133 }
134
135 def installed() {
136         log.debug "Installed with settings: ${settings}"
137
138         initialize()
139 }
140
141 def updated() {
142         log.debug "Updated with settings: ${settings}"
143
144         unsubscribe()
145         initialize()
146 }
147
148 def initialize() {
149
150         log.trace "Entering initialize()"
151     
152         state.lastSteps = 0
153         state.steps = jawbone.currentValue("steps").toInteger()
154     state.goal = jawbone.currentValue("goal").toInteger()
155     
156         subscribe (jawbone,"goal",goalHandler)
157     subscribe (jawbone,"steps",stepHandler)
158     
159     if (song) {
160                 saveSelectedSong()
161         }
162     
163         log.trace "Exiting initialize()"    
164 }
165
166 def goalHandler(evt) {
167
168         log.trace "Entering goalHandler()"
169
170         def goal = evt.value.toInteger()
171     
172     state.goal = goal
173     
174     log.trace "Exiting goalHandler()"
175 }
176
177 def stepHandler(evt) {
178
179         log.trace "Entering stepHandler()"
180     
181     log.debug "Event Value ${evt.value}"
182     log.debug "state.steps = ${state.steps}"
183     log.debug "state.goal = ${state.goal}"
184
185         def steps = evt.value.toInteger()
186     
187     state.lastSteps = state.steps
188     state.steps = steps
189     
190     def stepGoal
191     if (settings.thresholdType == "Goal")
192         stepGoal = state.goal
193     else
194         stepGoal = settings.threshold
195     
196     if ((state.lastSteps < stepGoal) && (state.steps >= stepGoal)) { // only trigger when crossing through the goal threshold
197     
198     // goal achieved for the day! Yay! Lets tell someone!
199     
200         if (settings.notificationType != "None") { // Push or SMS Notification requested
201
202             if (location.contactBookEnabled) {
203                 sendNotificationToContacts(stepMessage, recipients)
204             }
205             else {
206
207                 def options = [
208                     method: settings.notificationType.toLowerCase(),
209                     phone: settings.phone
210                 ]
211
212                 sendNotification(stepMessage, options)
213             }
214         }
215         
216         if (settings.sonos) { // play a song on the Sonos as requested
217         
218                 // runIn(1, sonosNotification, [overwrite: false])
219             sonosNotification()
220             
221         }  
222         
223         if (settings.hues) { // change the color of hue bulbs ras equested
224         
225                 // runIn(1, hueNotification, [overwrite: false])
226             hueNotification()
227         
228         }        
229         
230         if (settings.lights) { // flash the lights as requested
231         
232                         // runIn(1, lightsNotification, [overwrite: false])
233                 lightsNotification()
234         
235         }
236     
237     }
238     
239         log.trace "Exiting stepHandler()"    
240
241 }
242
243
244 def lightsNotification() {
245
246         // save the current state of the lights 
247     
248     log.trace "Save current state of lights"
249     
250         state.previousLights = [:]
251
252         lights.each {
253                 state.previousLights[it.id] = it.currentValue("switch")
254         }
255     
256     // Flash the light on and off 5 times for now - this could be configurable 
257             
258     log.trace "Now flash the lights"
259     
260     for (i in 1..flashCount) {
261            
262         lights.on()
263         pause(500)
264         lights.off()
265                
266     }
267     
268     // restore the original state
269     
270     log.trace "Now restore the original state of lights"    
271     
272         lights.each {
273                 it."${state.previousLights[it.id]}"()
274         }   
275
276
277 }
278
279 def hueNotification() {
280
281         log.trace "Entering hueNotification()"
282
283         def hueColor = 0
284         if(color == "Blue")
285                 hueColor = 70//60
286         else if(color == "Green")
287                 hueColor = 39//30
288         else if(color == "Yellow")
289                 hueColor = 25//16
290         else if(color == "Orange")
291                 hueColor = 10
292         else if(color == "Purple")
293                 hueColor = 75
294         else if(color == "Pink")
295                 hueColor = 83
296
297
298         state.previousHue = [:]
299
300         hues.each {
301                 state.previousHue[it.id] = [
302                         "switch": it.currentValue("switch"),
303                         "level" : it.currentValue("level"),
304                         "hue": it.currentValue("hue"),
305                         "saturation": it.currentValue("saturation")
306                 ]
307         }
308
309         log.debug "current values = ${state.previousHue}"
310
311         def newValue = [hue: hueColor, saturation: 100, level: (lightLevel as Integer) ?: 100]
312         log.debug "new value = $newValue"
313
314         hues*.setColor(newValue)
315         setTimer()
316     
317         log.trace "Exiting hueNotification()"
318     
319 }
320
321 def setTimer()
322 {
323         log.debug "runIn ${duration}, resetHue"
324         runIn(duration, resetHue, [overwrite: false])
325 }
326
327
328 def resetHue()
329 {
330     log.trace "Entering resetHue()"
331         settings.hues.each {
332                 it.setColor(state.previousHue[it.id])
333         }
334     log.trace "Exiting resetHue()"    
335 }
336
337 def sonosNotification() {
338
339         log.trace "sonosNotification()"
340     
341     if (settings.song) {
342     
343                 if (settings.resumePlaying) {
344                 if (settings.volume)
345                                 sonos.playTrackAndResume(state.selectedSong, settings.songDuration, settings.volume)
346             else
347                 sonos.playTrackAndResume(state.selectedSong, settings.songDuration)
348         } else {
349                 if (settings.volume)
350                                 sonos.playTrackAtVolume(state.selectedSong, settings.volume)
351             else
352                 sonos.playTrack(state.selectedSong)
353         }
354         
355                 sonos.on() // make sure it is playing
356         
357         }
358
359         log.trace "Exiting sonosNotification()"
360 }