Let debouncer delay be configurable

This commit is contained in:
Torjus Håkestad 2024-10-10 23:13:00 +02:00
parent dc40185002
commit 5d09d99ff5
Signed by: torjus
SSH Key Fingerprint: SHA256:KjAds8wHfD2mBYK2H815s/+ABcSdcIHUndwHEdSxml4
3 changed files with 12 additions and 11 deletions

View File

@ -7,7 +7,7 @@ type Debouncer struct {
C <-chan bool
}
func New(ch <-chan bool) *Debouncer {
func New(ch <-chan bool, window time.Duration) *Debouncer {
output := make(chan bool)
var currentState bool
var lastState bool
@ -21,11 +21,11 @@ func New(ch <-chan bool) *Debouncer {
output <- false
lastState = false
} else {
falseTimer.Reset(200 * time.Millisecond)
falseTimer.Reset(window)
}
case v, ok := <-ch:
if !ok {
falseTimer.Reset(200 * time.Millisecond)
falseTimer.Reset(window)
<-falseTimer.C
output <- false
close(output)
@ -35,12 +35,12 @@ func New(ch <-chan bool) *Debouncer {
if !lastState {
output <- true
lastState = true
falseTimer.Reset(200 * time.Millisecond)
falseTimer.Reset(window)
}
currentState = true
} else {
falseTimer.Reset(200 * time.Millisecond)
falseTimer.Reset(window)
currentState = false
}

View File

@ -10,7 +10,7 @@ import (
func TestDebouncer(t *testing.T) {
t.Run("Simple", func(t *testing.T) {
ch := make(chan bool)
d := debouncer.New(ch)
d := debouncer.New(ch, 200*time.Millisecond)
go func() {
ch <- true
@ -23,7 +23,7 @@ func TestDebouncer(t *testing.T) {
})
t.Run("TrueTrueTrueFalse", func(t *testing.T) {
ch := make(chan bool)
d := debouncer.New(ch)
d := debouncer.New(ch, 200*time.Millisecond)
go func() {
ch <- true
ch <- true
@ -40,7 +40,7 @@ func TestDebouncer(t *testing.T) {
})
t.Run("Debounce", func(t *testing.T) {
ch := make(chan bool)
d := debouncer.New(ch)
d := debouncer.New(ch, 200*time.Millisecond)
go func() {
ch <- true
time.Sleep(10 * time.Millisecond)
@ -65,7 +65,7 @@ func TestDebouncer(t *testing.T) {
})
t.Run("DebounceDelay", func(t *testing.T) {
ch := make(chan bool)
d := debouncer.New(ch)
d := debouncer.New(ch, 200*time.Millisecond)
go func() {
ch <- true
ch <- false

View File

@ -7,6 +7,7 @@ import (
"net/http"
"os"
"os/signal"
"time"
"git.t-juice.club/torjus/ghettoptt/bus"
"git.t-juice.club/torjus/ghettoptt/debouncer"
@ -15,7 +16,7 @@ import (
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const Version = "v0.1.3"
const Version = "v0.1.4"
func main() {
// Setup logger
@ -73,7 +74,7 @@ func main() {
doneCtx, doneCancel := context.WithCancel(srvCtx)
defer doneCancel()
debouncer := debouncer.New(eventCh)
debouncer := debouncer.New(eventCh, 400*time.Millisecond)
go func() {
var done bool
for !done {