322418655d4b46a08f03c1b18a88845dea3976b2
[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 }
106
107 private saveSelectedSong() {
108         try {
109                 def thisSong = song
110                 log.info "Looking for $thisSong"
111                 def songs = sonos.statesSince("trackData", new Date(0), [max:30]).collect{it.jsonValue}
112                 log.info "Searching ${songs.size()} records"
113
114                 def data = songs.find {s -> s.station == thisSong}
115                 log.info "Found ${data?.station}"
116                 if (data) {
117                         state.selectedSong = data
118                         log.debug "Selected song = $state.selectedSong"
119                 }
120                 else if (song == state.selectedSong?.station) {
121                         log.debug "Selected existing entry '$song', which is no longer in the last 20 list"
122                 }
123                 else {
124                         log.warn "Selected song '$song' not found"
125                 }
126         }
127         catch (Throwable t) {
128                 log.error t
129         }
130 }
131
132 def installed() {
133         log.debug "Installed with settings: ${settings}"
134
135         initialize()
136 }
137
138 def updated() {
139         log.debug "Updated with settings: ${settings}"
140
141         unsubscribe()
142         initialize()
143 }
144
145 def initialize() {
146
147         log.trace "Entering initialize()"
148     
149         state.lastSteps = 0
150     state.steps = jawbone.currentValue("steps").toInteger()
151     state.goal = jawbone.currentValue("goal").toInteger()
152     
153         subscribe (jawbone,"goal",goalHandler)
154     subscribe (jawbone,"steps",stepHandler)
155     
156     if (song) {
157                 saveSelectedSong()
158         }
159     
160         log.trace "Exiting initialize()"    
161 }
162
163 def goalHandler(evt) {
164
165         log.trace "Entering goalHandler()"
166
167         def goal = evt.value.toInteger()
168     
169     state.goal = goal
170     
171     log.trace "Exiting goalHandler()"
172 }
173
174 def stepHandler(evt) {
175
176         log.trace "Entering stepHandler()"
177     
178     log.debug "Event Value ${evt.value}"
179     log.debug "state.steps = ${state.steps}"
180     log.debug "state.goal = ${state.goal}"
181
182         def steps = evt.value.toInteger()
183     
184     state.lastSteps = state.steps
185     state.steps = steps
186     
187     def stepGoal
188     if (settings.thresholdType == "Goal")
189         stepGoal = state.goal
190     else
191         stepGoal = settings.threshold
192     
193     if ((state.lastSteps < stepGoal) && (state.steps >= stepGoal)) { // only trigger when crossing through the goal threshold
194     
195     // goal achieved for the day! Yay! Lets tell someone!
196     
197         if (settings.notificationType != "None") { // Push or SMS Notification requested
198
199             if (location.contactBookEnabled) {
200                 sendNotificationToContacts(stepMessage, recipients)
201             }
202             else {
203
204                 def options = [
205                     method: settings.notificationType.toLowerCase(),
206                     phone: settings.phone
207                 ]
208
209                 sendNotification(stepMessage, options)
210             }
211         }
212         
213         if (settings.sonos) { // play a song on the Sonos as requested
214         
215                 // runIn(1, sonosNotification, [overwrite: false])
216             sonosNotification()
217             
218         }  
219         
220         if (settings.hues) { // change the color of hue bulbs ras equested
221         
222                 // runIn(1, hueNotification, [overwrite: false])
223             hueNotification()
224         
225         }        
226         
227         if (settings.lights) { // flash the lights as requested
228         
229                         // runIn(1, lightsNotification, [overwrite: false])
230                 lightsNotification()
231         
232         }
233     
234     }
235     
236         log.trace "Exiting stepHandler()"    
237
238 }
239
240
241 def lightsNotification() {
242
243         // save the current state of the lights 
244     
245     log.trace "Save current state of lights"
246     
247         state.previousLights = [:]
248
249         lights.each {
250                 state.previousLights[it.id] = it.currentValue("switch")
251         }
252     
253     // Flash the light on and off 5 times for now - this could be configurable 
254             
255     log.trace "Now flash the lights"
256     
257     for (i in 1..flashCount) {
258            
259         lights.on()
260         pause(500)
261         lights.off()
262                
263     }
264     
265     // restore the original state
266     
267     log.trace "Now restore the original state of lights"    
268     
269         lights.each {
270                 it."${state.previousLights[it.id]}"()
271         }   
272
273
274 }
275
276 def hueNotification() {
277
278         log.trace "Entering hueNotification()"
279
280         def hueColor = 0
281         if(color == "Blue")
282                 hueColor = 70//60
283         else if(color == "Green")
284                 hueColor = 39//30
285         else if(color == "Yellow")
286                 hueColor = 25//16
287         else if(color == "Orange")
288                 hueColor = 10
289         else if(color == "Purple")
290                 hueColor = 75
291         else if(color == "Pink")
292                 hueColor = 83
293
294
295         state.previousHue = [:]
296
297         hues.each {
298                 state.previousHue[it.id] = [
299                         "switch": it.currentValue("switch"),
300                         "level" : it.currentValue("level"),
301                         "hue": it.currentValue("hue"),
302                         "saturation": it.currentValue("saturation")
303                 ]
304         }
305
306         log.debug "current values = ${state.previousHue}"
307
308         def newValue = [hue: hueColor, saturation: 100, level: (lightLevel as Integer) ?: 100]
309         log.debug "new value = $newValue"
310
311         hues*.setColor(newValue)
312         setTimer()
313     
314         log.trace "Exiting hueNotification()"
315     
316 }
317
318 def setTimer()
319 {
320         log.debug "runIn ${duration}, resetHue"
321         runIn(duration, resetHue, [overwrite: false])
322 }
323
324
325 def resetHue()
326 {
327     log.trace "Entering resetHue()"
328         settings.hues.each {
329                 it.setColor(state.previousHue[it.id])
330         }
331     log.trace "Exiting resetHue()"    
332 }
333
334 def sonosNotification() {
335
336         log.trace "sonosNotification()"
337     
338     if (settings.song) {
339     
340                 if (settings.resumePlaying) {
341                 if (settings.volume)
342                                 sonos.playTrackAndResume(state.selectedSong, settings.songDuration, settings.volume)
343             else
344                 sonos.playTrackAndResume(state.selectedSong, settings.songDuration)
345         } else {
346                 if (settings.volume)
347                                 sonos.playTrackAtVolume(state.selectedSong, settings.volume)
348             else
349                 sonos.playTrack(state.selectedSong)
350         }
351         
352                 sonos.on() // make sure it is playing
353         
354         }
355
356         log.trace "Exiting sonosNotification()"
357 }