Hey everyone, I’m trying to set up a door automation where if the door is open for more than a minute, I get a notification. I’ve been experimenting with Groovy, but my script isn’t quite working as expected. Here’s what I’ve tried so far:
I created a variable to capture the current time when the door opens and another to set the delay. I thought adding the delay to the current time and using runIn() would work, but it doesn’t seem to hold off the notification. Instead, the notification triggers immediately. I’m not sure if I’m calculating the delay correctly or if there’s a better way to handle this.
Here’s the code I’m working with:
groovy
preferences {
section(“Select a sensor…”) {
input “doorSensor”, “capability.contactSensor”, title: “Door Sensor”, multiple: false
}
section(“Select a notification method”) {
input “notificationMethod”, “capability.notification”, title: “Notification Method”, multiple: false
}
}
def installed() {
subscribe(doorSensor, “contact.open”, doorHandler)
}
def updated() {
unsubscribe()
subscribe(doorSensor, “contact.open”, doorHandler)
}
def doorHandler(evt) {
def currentTime = now()
def delay = 60000 // 1 minute in milliseconds
runIn(currentTime + delay, sendNotification)
}
def sendNotification() {
notificationMethod.sendNotification(“The door has been open for more than a minute!”)
}
I suspect the issue might be with how runIn() handles the timing. Maybe there’s a more efficient way to delay the event or track the door’s state over time. I’ve heard about using variables to track the last time the door opened, but I’m not sure how to implement that correctly.
Has anyone else tackled a similar automation? I’d love to hear your tips or see examples of how you handle delays in your scripts. Thanks in advance for your help!