I came to this thread on a search for how to debounce an openhab rule, and none of these answers are really “correct” in my mind, so I wrote my own version using locks. This will guarantee thread safety in case rules are run concurrently and is very simple to understand. Thought I’d post it in case other people come to this thread for the same reason.
In my case, I’m debouncing a very cheap 433 wireless sensor picked up by rfxcom which often sends 2/3/4 times depending on its mood. State change doesn’t work, as its stateless, and I do need to know when it is triggered again a few seconds later. I left the debug in so its easy to see how it works.
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
var Lock lock = new ReentrantLock()
rule "switch"
when
Item Undecoded received update "107366"
then
// tryLock will acquire the lock if it is available, and fail fast otherwise.
if (lock.tryLock()) {
logInfo("contact", "Contact sensor tripped")
Thread::sleep(300)
lock.unlock()
} else {
logDebug("doors", "Contact sensor tripped, but ignored due to lock")
}
end