Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Turn on a switch when in Away mode and it's night
*
* Author: Steve Sell steve.sell@gmail.com
*/
preferences {
section("Turn on..."){
input "switches", "capability.switch", multiple: true, required: true
}
}
def installed() {
log.debug "Installed with settings: ${settings}"
initialize()
}
def updated(settings) {
log.debug "Updated with settings: ${settings}"
unsubscribe()
unschedule("turn_off")
unschedule("turn_on")
initialize()
}
def initialize()
{
subscribe(location, modeChangeHandler)
}
def modeChangeHandler(evt) {
def sunRiseAndSunset = getSunriseAndSunset()
def timenow = now()
def sunrise_time = sunRiseAndSunset.sunrise.time
def sunset_time = sunRiseAndSunset.sunset.time
def isNight = false
if (timenow > sunset_time || timenow < sunrise_time) {
log.debug "$timenow is not between sunrise: $sunrise_time and sunset: $sunset_time"
isNight = true
}
if (evt.value == "Away")
{
if (isNight) // It's night already
{
turn_on() // Turn on the lights
}
else // It's not night yet, just schedule the lights to come on at sunset
{
unschedule("turn_on")
runOnce(sunset_time, "turn_on")
}
}
else // We changed to another mode other than "Away" so unschedule everything
{
unschedule("turn_off")
unschedule("turn_on")
}
}
def turn_off() {
// Turn off the switches and schedule them to come on at sunset
def sunRiseAndSunset = getSunriseAndSunset()
switches?.off()
unschedule("turn_on")
runOnce(sunRiseAndSunset.sunset.time, "turn_on")
}
def turn_on() {
// Turn on the switches and schedule them to turn off at sunset
def sunRiseAndSunset = getSunriseAndSunset()
switches?.on()
unschedule("turn_off")
runOnce(sunRiseAndSunset.sunrise.time, "turn_off")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.