ghettoptt/debouncer/debouncer.go

54 lines
934 B
Go
Raw Normal View History

2024-10-10 20:40:29 +00:00
package debouncer
import "time"
type Debouncer struct {
input <-chan bool
C <-chan bool
}
func New(ch <-chan bool) *Debouncer {
output := make(chan bool)
var currentState bool
var lastState bool
falseTimer := time.NewTimer(0)
falseTimer.Stop()
go func() {
for {
select {
case <-falseTimer.C:
if !currentState && lastState {
output <- false
lastState = false
} else {
falseTimer.Reset(200 * time.Millisecond)
}
case v, ok := <-ch:
if !ok {
falseTimer.Reset(200 * time.Millisecond)
<-falseTimer.C
output <- false
close(output)
return
}
if v {
if !lastState {
output <- true
lastState = true
falseTimer.Reset(200 * time.Millisecond)
}
currentState = true
} else {
falseTimer.Reset(200 * time.Millisecond)
currentState = false
}
}
}
}()
d := &Debouncer{input: ch, C: output}
return d
}