Update step-notifier.groovy
[smartapps.git] / official / turn-on-before-sunset.groovy
1 /**
2  *  Turn on before Sunset
3  *
4  *  Copyright 2015 SmartThings
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 on before Sunset",
18         namespace: "exmaples",
19         author: "SmartThings",
20         description: "Turn on lights a number of minutes before sunset, based on your location's geofence",
21         category: "My Apps",
22         iconUrl: "https://s3.amazonaws.com/smartapp-icons/ModeMagic/rise-and-shine.png",
23         iconX2Url: "https://s3.amazonaws.com/smartapp-icons/ModeMagic/rise-and-shine@2x.png",
24         iconX3Url: "https://s3.amazonaws.com/smartapp-icons/ModeMagic/rise-and-shine@2x.png")
25
26 preferences {
27     section("Lights") {
28         input "switches", "capability.switch", title: "Which lights to turn on?"
29         input "offset", "number", title: "Turn on this many minutes before sunset"
30     }
31 }
32
33 def installed() {
34     initialize()
35 }
36
37 def updated() {
38     unsubscribe()
39     initialize()
40 }
41
42 def initialize() {
43     subscribe(location, "sunsetTime", sunsetTimeHandler)
44
45     //schedule it to run today too
46     scheduleTurnOn(location.currentValue("sunsetTime"))
47 }
48
49 def sunsetTimeHandler(evt) {
50     //when I find out the sunset time, schedule the lights to turn on with an offset
51     scheduleTurnOn(evt.value)
52 }
53
54 def scheduleTurnOn(sunsetString) {
55     //get the Date value for the string
56     def sunsetTime = Date.parse("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", sunsetString)
57
58     //calculate the offset
59     def timeBeforeSunset = new Date(sunsetTime.time - (offset * 60 * 1000))
60
61     log.debug "Scheduling for: $timeBeforeSunset (sunset is $sunsetTime)"
62
63     //schedule this to run one time
64     runOnce(timeBeforeSunset, turnOn)
65 }
66
67 def turnOn() {
68     log.debug "turning on lights"
69     switches.on()
70 }