Permalink
Switch branches/tags
PROD_2018.11.05 PROD_2018.10.30 PROD_2018.10.23 PROD_2018.10.16 PROD_2018.10.09 PROD_2018.10.02 PROD_2018.09.25 PROD_2018.09.18 PROD_2018.09.11 PROD_2018.09.05 PROD_2018.08.28 PROD_2018.08.21 PROD_2018.08.14 PROD_2018.08.07 PROD_2018.07.31 PROD_2018.07.24 PROD_2018.07.17 PROD_2018.07.10 PROD_2018.07.03 PROD_2018.06.26 PROD_2018.06.19 PROD_2018.06.12 PROD_2018.06.06 PROD_2018.05.31 PROD_2018.05.22 PROD_2018.05.15 PROD_2018.05.08 PROD_2018.05.01 PROD_2018.04.24 PROD_2018.04.17 PROD_2018.04.10 PROD_2018.04.03 PROD_2018.03.27 PROD_2018.03.20 PROD_2018.03.13 PROD_2018.03.06 PROD_2018.02.27 PROD_2018.02.20 PROD_2018.02.13 PROD_2018.02.06 PROD_2018.01.30 PROD_2018.01.23 PROD_2018.01.17 PROD_2017.12.12 PROD_2017.12.05 PROD_2017.11.14 PROD_2017.11.07 PROD_2017.10.31 PROD_2017.10.25 PROD_2017.10.19 PROD_2017.10.10 PROD_2017.10.03 PROD_2017.09.26 PROD_2017.09.19 PROD_2017.09.12 PROD_2017.09.05 PROD_2017.08.29 PROD_2017.08.22 PROD_2017.08.15 PROD_2017.08.08 PROD_2017.08.01 PROD_2017.07.25 PROD_2017.07.18 PROD_2017.07.11 PROD_2017.07.05 PROD_2017.06.27 PROD_2017.06.20 PROD_2017.06.13 PROD_2017.06.06 PROD_2017.05.31 PROD_2017.05.23 PROD_2017.05.16 PROD_2017.05.09 PROD_2017.05.02 PROD_2017.04.25 PROD_2017.04.18 PROD_2017.04.11 PROD_2017.04.04 PROD_2017.03.28 PROD_2017.03.21 PROD_2017.03.14 PROD_2017.03.07 PROD_2017.03.01 PROD_2017.02.22 PROD_2017.02.14 PROD_2017.02.07 PROD_2017.01.31 PROD_2017.01.24 PROD_2017.01.18 PROD_2017.01.10 PROD_2016.12.07 PROD_2016.11.22 PROD_2016.11.15 PROD_2016.11.08 PROD_2016.11.01 PROD_2016.10.25 PROD_2016.10.18 PROD_2016.10.11 PROD_2016.10.04 PROD_2016.09.27
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
1124 lines (918 sloc) 31.3 KB
/**
* Copyright 2016 SmartThings
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*
* Gentle Wake Up
*
* Author: Steve Vlaminck
* Date: 2013-03-11
*
* https://s3.amazonaws.com/smartapp-icons/HealthAndWellness/App-SleepyTime.png
* https://s3.amazonaws.com/smartapp-icons/HealthAndWellness/App-SleepyTime%402x.png
* Gentle Wake Up turns on your lights slowly, allowing you to wake up more
* naturally. Once your lights have reached full brightness, optionally turn on
* more things, or send yourself a text for a more gentle nudge into the waking
* world (you may want to set your normal alarm as a backup plan).
*
*/
definition(
name: "Gentle Wake Up",
namespace: "smartthings",
author: "SmartThings",
description: "Dim your lights up slowly, allowing you to wake up more naturally.",
category: "Health & Wellness",
iconUrl: "https://s3.amazonaws.com/smartapp-icons/HealthAndWellness/App-SleepyTime.png",
iconX2Url: "https://s3.amazonaws.com/smartapp-icons/HealthAndWellness/App-SleepyTime@2x.png",
pausable: true
)
preferences {
page(name: "rootPage")
page(name: "schedulingPage")
page(name: "completionPage")
page(name: "numbersPage")
page(name: "controllerExplanationPage")
page(name: "unsupportedDevicesPage")
}
def rootPage() {
dynamicPage(name: "rootPage", title: "", install: true, uninstall: true) {
section("What to dim") {
input(name: "dimmers", type: "capability.switchLevel", title: "Dimmers", description: null, multiple: true, required: true, submitOnChange: true)
if (dimmers) {
if (dimmersContainUnsupportedDevices()) {
href(name: "toUnsupportedDevicesPage", page: "unsupportedDevicesPage", title: "Some of your selected dimmers don't seem to be supported", description: "Tap here to fix it", required: true)
}
href(name: "toNumbersPage", page: "numbersPage", title: "Duration & Direction", description: numbersPageHrefDescription(), state: "complete")
}
}
if (dimmers) {
section("Gentle Wake Up Has A Controller") {
href(title: "Learn how to control Gentle Wake Up", page: "controllerExplanationPage", description: null)
}
section("Rules For Dimming") {
href(name: "toSchedulingPage", page: "schedulingPage", title: "Automation", description: schedulingHrefDescription() ?: "Set rules for when to start", state: schedulingHrefDescription() ? "complete" : "")
input(name: "manualOverride", type: "enum", options: ["cancel": "Cancel dimming", "jumpTo": "Jump to the end"], title: "When one of the dimmers is manually turned off…", description: "dimming will continue", required: false, multiple: false)
href(name: "toCompletionPage", title: "Completion Actions", page: "completionPage", state: completionHrefDescription() ? "complete" : "", description: completionHrefDescription() ?: "Set rules for what to do when dimming completes")
}
section {
// TODO: fancy label
label(title: "Label This SmartApp", required: false, defaultValue: "", description: "Highly recommended", submitOnChange: true)
}
}
}
}
def unsupportedDevicesPage() {
def unsupportedDimmers = dimmers.findAll { !hasSetLevelCommand(it) }
dynamicPage(name: "unsupportedDevicesPage") {
if (unsupportedDimmers) {
section("These devices do not support the setLevel command") {
unsupportedDimmers.each {
paragraph deviceLabel(it)
}
}
section {
input(name: "dimmers", type: "capability.sensor", title: "Please remove the above devices from this list.", submitOnChange: true, multiple: true)
}
section {
paragraph "If you think there is a mistake here, please contact support."
}
} else {
section {
paragraph "You're all set. You can hit the back button, now. Thanks for cleaning up your settings :)"
}
}
}
}
def controllerExplanationPage() {
dynamicPage(name: "controllerExplanationPage", title: "How To Control Gentle Wake Up") {
section("With other SmartApps", hideable: true, hidden: false) {
paragraph "When this SmartApp is installed, it will create a controller device which you can use in other SmartApps for even more customizable automation!"
paragraph "The controller acts like a switch so any SmartApp that can control a switch can control Gentle Wake Up, too!"
paragraph "Routines and 'Smart Lighting' are great ways to automate Gentle Wake Up."
}
section("More about the controller", hideable: true, hidden: true) {
paragraph "You can find the controller with your other 'Things'. It will look like this."
image "http://f.cl.ly/items/2O0v0h41301U14042z3i/GentleWakeUpController-tile-stopped.png"
paragraph "You can start and stop Gentle Wake up by tapping the control on the right."
image "http://f.cl.ly/items/3W323J3M1b3K0k0V3X3a/GentleWakeUpController-tile-running.png"
paragraph "If you look at the device details screen, you will find even more information about Gentle Wake Up and more fine grain controls."
image "http://f.cl.ly/items/291s3z2I2Q0r2q0x171H/GentleWakeUpController-richTile-stopped.png"
paragraph "The slider allows you to jump to any point in the dimming process. Think of it as a percentage. If Gentle Wake Up is set to dim down as you fall asleep, but your book is just too good to put down; simply drag the slider to the left and Gentle Wake Up will give you more time to finish your chapter and drift off to sleep."
image "http://f.cl.ly/items/0F0N2G0S3v1q0L0R3J3Y/GentleWakeUpController-richTile-running.png"
paragraph "In the lower left, you will see the amount of time remaining in the dimming cycle. It does not count down evenly. Instead, it will update whenever the slider is updated; typically every 6-18 seconds depending on the duration of your dimming cycle."
paragraph "Of course, you may also tap the middle to start or stop the dimming cycle at any time."
}
section("Starting and stopping the SmartApp itself", hideable: true, hidden: true) {
paragraph "Tap the 'play' button on the SmartApp to start or stop dimming."
image "http://f.cl.ly/items/0R2u1Z2H30393z2I2V3S/GentleWakeUp-appTouch2.png"
}
section("Turning off devices while dimming", hideable: true, hidden: true) {
paragraph "It's best to use other Devices and SmartApps for triggering the Controller device. However, that isn't always an option."
paragraph "If you turn off a switch that is being dimmed, it will either continue to dim, stop dimming, or jump to the end of the dimming cycle depending on your settings."
paragraph "Unfortunately, some switches take a little time to turn off and may not finish turning off before Gentle Wake Up sets its dim level again. You may need to try a few times to get it to stop."
paragraph "That's why it's best to use devices that aren't currently dimming. Remember that you can use other SmartApps to toggle the controller. :)"
}
}
}
def numbersPage() {
dynamicPage(name:"numbersPage", title:"") {
section {
paragraph(name: "pGraph", title: "These lights will dim", fancyDeviceString(dimmers))
}
section {
input(name: "duration", type: "number", title: "For this many minutes", description: "30", required: false, defaultValue: 30)
}
section {
input(name: "startLevel", type: "number", range: "0..99", title: "From this level", defaultValue: defaultStart(), description: "Current Level", required: false, multiple: false)
input(name: "endLevel", type: "number", range: "0..99", title: "To this level", defaultValue: defaultEnd(), description: "Between 0 and 99", required: true, multiple: false)
}
def colorDimmers = dimmersWithSetColorCommand()
if (colorDimmers) {
section {
input(name: "colorize", type: "bool", title: "Gradually change the color of ${fancyDeviceString(colorDimmers)}", description: null, required: false, defaultValue: "true")
}
}
}
}
def defaultStart() {
if (usesOldSettings() && direction && direction == "Down") {
return 99
}
return 0
}
def defaultEnd() {
if (usesOldSettings() && direction && direction == "Down") {
return 0
}
return 99
}
def startLevelLabel() {
if (usesOldSettings()) { // using old settings
if (direction && direction == "Down") { // 99 -> 1
return "99%"
}
return "0%"
}
return hasStartLevel() ? "${startLevel}%" : "Current Level"
}
def endLevelLabel() {
if (usesOldSettings()) {
if (direction && direction == "Down") { // 99 -> 1
return "0%"
}
return "99%"
}
return "${endLevel}%"
}
def weekdays() {
["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
}
def weekends() {
["Saturday", "Sunday"]
}
def schedulingPage() {
dynamicPage(name: "schedulingPage", title: "Rules For Automatically Dimming Your Lights") {
section("Use Other SmartApps!") {
href(title: "Learn how to control Gentle Wake Up", page: "controllerExplanationPage", description: null)
}
section("Allow Automatic Dimming") {
input(name: "days", type: "enum", title: "On These Days", description: "Every day", required: false, multiple: true, options: weekdays() + weekends())
}
section("Start Dimming...") {
input(name: "startTime", type: "time", title: "At This Time", description: null, required: false)
input(name: "modeStart", title: "When Entering This Mode", type: "mode", required: false, mutliple: false, submitOnChange: true, description: null)
if (modeStart) {
input(name: "modeStop", title: "Stop when leaving '${modeStart}' mode", type: "bool", required: false)
}
}
}
}
def completionPage() {
dynamicPage(name: "completionPage", title: "Completion Rules") {
section("Switches") {
input(name: "completionSwitches", type: "capability.switch", title: "Set these switches", description: null, required: false, multiple: true, submitOnChange: true)
if (completionSwitches) {
input(name: "completionSwitchesState", type: "enum", title: "To", description: null, required: false, multiple: false, options: ["on", "off"], defaultValue: "on")
input(name: "completionSwitchesLevel", type: "number", title: "Optionally, Set Dimmer Levels To", description: null, required: false, multiple: false, range: "(0..99)")
}
}
section("Notifications") {
input("recipients", "contact", title: "Send notifications to", required: false) {
if (completionPhoneNumber) {
input(name: "completionPhoneNumber", type: "phone", title: "Text This Number", description: "Phone number", required: false)
}
input(name: "completionPush", type: "bool", title: "Send A Push Notification", description: "Phone number", required: false)
}
input(name: "completionMusicPlayer", type: "capability.musicPlayer", title: "Speak Using This Music Player", required: false)
input(name: "completionMessage", type: "text", title: "With This Message", description: null, required: false)
}
section("Modes and Phrases") {
input(name: "completionMode", type: "mode", title: "Change ${location.name} Mode To", description: null, required: false)
input(name: "completionPhrase", type: "enum", title: "Execute The Phrase", description: null, required: false, multiple: false, options: location.helloHome.getPhrases().label)
}
section("Delay") {
input(name: "completionDelay", type: "number", title: "Delay This Many Minutes Before Executing These Actions", description: "0", required: false)
}
}
}
// ========================================================
// Handlers
// ========================================================
def installed() {
log.debug "Installing 'Gentle Wake Up' with settings: ${settings}"
initialize()
}
def updated() {
log.debug "Updating 'Gentle Wake Up' with settings: ${settings}"
unschedule()
def controller = getController()
if (controller) {
controller.label = app.label
}
initialize()
}
private initialize() {
stop("settingsChange")
if (startTime) {
log.debug "scheduling dimming routine to run at $startTime"
schedule(startTime, "scheduledStart")
}
// TODO: make this an option
subscribe(app, appHandler)
subscribe(location, locationHandler)
if (manualOverride) {
subscribe(dimmers, "switch.off", stopDimmersHandler)
}
if (!getAllChildDevices()) {
// create controller device and set name to the label used here
def dni = "${new Date().getTime()}"
log.debug "app.label: ${app.label}"
addChildDevice("smartthings", "Gentle Wake Up Controller", dni, null, ["label": app.label])
state.controllerDni = dni
}
}
def appHandler(evt) {
log.debug "appHandler evt: ${evt.value}"
if (evt.value == "touch") {
if (atomicState.running) {
stop("appTouch")
} else {
start("appTouch")
}
}
}
def locationHandler(evt) {
log.debug "locationHandler evt: ${evt.value}"
if (!modeStart) {
return
}
def isSpecifiedMode = (evt.value == modeStart)
def modeStopIsTrue = (modeStop && modeStop != "false")
if (isSpecifiedMode && canStartAutomatically()) {
start("modeChange")
} else if (!isSpecifiedMode && modeStopIsTrue) {
stop("modeChange")
}
}
def stopDimmersHandler(evt) {
log.trace "stopDimmersHandler evt: ${evt.value}"
def percentComplete = completionPercentage()
// Often times, the first thing we do is turn lights on or off so make sure we don't stop as soon as we start
if (percentComplete > 2 && percentComplete < 98) {
if (manualOverride == "cancel") {
log.debug "STOPPING in stopDimmersHandler"
stop("manualOverride")
} else if (manualOverride == "jumpTo") {
def end = dynamicEndLevel()
log.debug "Jumping to 99% complete in stopDimmersHandler"
jumpTo(99)
}
} else {
log.debug "not stopping in stopDimmersHandler"
}
}
// ========================================================
// Scheduling
// ========================================================
def scheduledStart() {
if (canStartAutomatically()) {
start("schedule")
}
}
public def start(source) {
log.trace "START"
sendStartEvent(source)
setLevelsInState()
atomicState.running = true
atomicState.runCounter = 0
atomicState.start = new Date().getTime()
schedule("0 * * * * ?", "healthCheck")
increment()
}
public def stop(source) {
log.trace "STOP"
sendStopEvent(source)
atomicState.running = false
atomicState.start = 0
atomicState.runCounter = 0
unschedule("healthCheck")
}
private healthCheck() {
log.trace "'Gentle Wake Up' healthCheck"
if (!atomicState.running) {
return
}
increment()
}
// ========================================================
// Controller
// ========================================================
def sendStartEvent(source) {
log.trace "sendStartEvent(${source})"
def eventData = [
name: "sessionStatus",
value: "running",
descriptionText: "${app.label} has started dimming",
displayed: true,
linkText: app.label,
isStateChange: true
]
if (source == "modeChange") {
eventData.descriptionText += " because of a mode change"
} else if (source == "schedule") {
eventData.descriptionText += " as scheduled"
} else if (source == "appTouch") {
eventData.descriptionText += " because you pressed play on the app"
} else if (source == "controller") {
eventData.descriptionText += " because you pressed play on the controller"
}
sendControllerEvent(eventData)
}
def sendStopEvent(source) {
log.trace "sendStopEvent(${source})"
def eventData = [
name: "sessionStatus",
value: "stopped",
descriptionText: "${app.label} has stopped dimming",
displayed: true,
linkText: app.label,
isStateChange: true
]
if (source == "modeChange") {
eventData.descriptionText += " because of a mode change"
eventData.value += "cancelled"
} else if (source == "schedule") {
eventData.descriptionText = "${app.label} has finished dimming"
} else if (source == "appTouch") {
eventData.descriptionText += " because you pressed play on the app"
eventData.value += "cancelled"
} else if (source == "controller") {
eventData.descriptionText += " because you pressed stop on the controller"
eventData.value += "cancelled"
} else if (source == "settingsChange") {
eventData.descriptionText += " because the settings have changed"
eventData.value += "cancelled"
} else if (source == "manualOverride") {
eventData.descriptionText += " because the dimmer was manually turned off"
eventData.value += "cancelled"
}
// send 100% completion event
sendTimeRemainingEvent(100)
// send a non-displayed 0% completion to reset tiles
sendTimeRemainingEvent(0, false)
// send sessionStatus event last so the event feed is ordered properly
sendControllerEvent(eventData)
}
def sendTimeRemainingEvent(percentComplete, displayed = true) {
log.trace "sendTimeRemainingEvent(${percentComplete})"
def percentCompleteEventData = [
name: "percentComplete",
value: percentComplete as int,
displayed: displayed,
isStateChange: true
]
sendControllerEvent(percentCompleteEventData)
def duration = sanitizeInt(duration, 30)
def timeRemaining = duration - (duration * (percentComplete / 100))
def timeRemainingEventData = [
name: "timeRemaining",
value: displayableTime(timeRemaining),
displayed: displayed,
isStateChange: true
]
sendControllerEvent(timeRemainingEventData)
}
def sendControllerEvent(eventData) {
def controller = getController()
if (controller) {
controller.controllerEvent(eventData)
}
}
def getController() {
def dni = state.controllerDni
if (!dni) {
log.warn "no controller dni"
return null
}
def controller = getChildDevice(dni)
if (!controller) {
log.warn "no controller"
return null
}
log.debug "controller: ${controller}"
return controller
}
// ========================================================
// Setting levels
// ========================================================
private increment() {
if (!atomicState.running) {
return
}
if (atomicState.runCounter == null) {
atomicState.runCounter = 1
} else {
atomicState.runCounter = atomicState.runCounter + 1
}
def percentComplete = completionPercentage()
if (percentComplete > 99) {
percentComplete = 99
}
if (atomicState.runCounter > 100) {
log.error "Force stopping Gentle Wakeup due to too many increments"
// If increment has already been called 100 times, then stop regardless of state
percentComplete = 100
} else {
updateDimmers(percentComplete)
}
if (percentComplete < 99) {
def runAgain = stepDuration()
log.debug "Rescheduling to run again in ${runAgain} seconds"
runIn(runAgain, 'increment', [overwrite: true])
} else {
int completionDelay = completionDelaySeconds()
if (completionDelay) {
log.debug "Finished with steps. Scheduling completion for ${completionDelay} second(s) from now"
runIn(completionDelay, 'completion', [overwrite: true])
unschedule("healthCheck")
// don't let the health check start incrementing again while we wait for the delayed execution of completion
} else {
log.debug "Finished with steps. Execution completion"
completion()
}