This was written just for my use so you will need to update the zipcode, but your welcome to edit as you need. I started with one of the basic templates. For some reason the sunset sunrise event handlers that are commented out in the initialize sub don’t seem to fire as I understand they should that is why I am using the scheduled events. I just wrote this a few days ago but it seems to be working pretty well.
[code]/**
preferences {
section(“When there’s movement…”) {
input “motion1”, “capability.motionSensor”, title: “Where?”, required: true, multiple: false
}
section(“Turn on a light…”) {
input “switch1”, “capability.switch”, required: true, multiple: false
}
}
def installed()
{
initialize()
}
def updated()
{
unsubscribe()
initialize()
}
def initialize() {
//subscribe(location, “sunset”, sunsetHandler)
//subscribe(location, “sunrise”, sunriseHandler)
subscribe(switch1, “switch.off”, switchHandler)
schedule(“0 0 12 * * ?”, sunriseSunsetHandler)
if (issunset()) {
subscribe(motion1, “motion.active”, motionActiveHandler)}
sunriseSunsetHandler()
}
def motionActiveHandler(evt) {
log.debug “Motion detected”
switch1.on()
runIn(60*5,OffTimeHandler)
}
def switchHandler(evt) {
log.debug “Switch turned off”
runIn(15,reupHandler)
}
def OffTimeHandler() {
log.debug “OffTimeHandler”
unsubscribe(motion1)
switch1.off()
runIn(15,reupHandler)
}
def reupHandler() {
log.debug “reupHandler”
if (issunset()) {
subscribe(motion1, “motion.active”, motionActiveHandler)}
}
def sunsetHandler() {
subscribe(motion1, “motion.active”, motionActiveHandler)
}
def sunriseHandler() {
unsubscribe(motion1)
switch1.off()
}
def issunset(){
def WRTimes = getSunriseAndSunset(zipCode: “31088”)
def between = timeOfDayIsBetween(WRTimes.sunset, WRTimes.sunrise, new Date(), location.timeZone)
log.debug “Sunset?:${between}”
return between
}
def sunriseSunsetHandler(){
log.debug “Setting Sunrise Sunset times”
def WRTimes = getSunriseAndSunset(zipCode: “31088”)
schedule(WRTimes.sunrise, sunriseHandler)
schedule(WRTimes.sunset, sunsetHandler)
}
[/code]