Checkpoint

This commit is contained in:
maze authored and maze committed 2026-10-29 17:28:51 +01:00
1 parent 7b6db17870
commit 0295eb1ad2
125 files changed
+59376

No files matched your search

+121
View File
@@ -0,0 +1,121 @@
package rotary
import (
"context"
"github.com/sirupsen/logrus"
"periph.io/x/conn/v3/gpio"
)
type Rotary struct {
s1, s2, key gpio.PinIO
state [4]state
}
func NewRotary(s1, s2, key gpio.PinIO) (*Rotary, error) {
return &Rotary{
s1: s1,
s2: s2,
key: key,
}, nil
}
func (r *Rotary) log() *logrus.Entry {
return logrus.WithField("input", "rotary")
}
func (r *Rotary) Run(ctx context.Context) <-chan Event {
r.s1.In(gpio.PullNoChange, gpio.BothEdges)
r.s2.In(gpio.PullNoChange, gpio.BothEdges)
update := make(chan state)
go r.waitForEdgeOnPin(ctx, r.s1, update)
go r.waitForEdgeOnPin(ctx, r.s2, update)
go r.waitForEdgeOnPin(ctx, r.key, update)
keys := make(chan Event)
go r.process(ctx, update, keys)
return keys
}
func (r *Rotary) waitForEdgeOnPin(ctx context.Context, pin gpio.PinIO, update chan<- state) error {
log := r.log().WithField("pin", pin.Name())
for {
select {
case <-ctx.Done():
log.Debug("context done")
return ctx.Err()
default:
log.Trace("waiting for edge")
if !pin.WaitForEdge(-1) {
log.Trace("wait for edge failed")
continue
}
level := pin.Read()
log.WithField("level", level).Trace("edge detected")
update <- state{
pin: pin,
level: level,
}
}
}
}
func (r *Rotary) process(ctx context.Context, update <-chan state, keys chan<- Event) {
log := r.log()
for {
select {
case <-ctx.Done():
return
case newState := <-update:
switch newState.pin {
case r.key:
if newState.level == gpio.High {
log.Debug("key release detected")
keys <- KeyRelease
} else {
log.Debug("key press detected")
keys <- KeyPress
}
default:
if newState == r.state[3] {
continue
}
r.state = [4]state{
r.state[1],
r.state[2],
r.state[3],
newState,
}
if isCW(r.state) {
log.Debug("clockwise rotation detected")
keys <- Clockwise
} else if isCCW(r.state) {
log.Debug("counter clockwise rotation detected")
keys <- CounterClockwise
}
}
}
}
}
type state struct {
pin gpio.PinIO
level gpio.Level
}
func stateEq(a, b [4]state) bool {
return a[0].level == b[0].level && a[1].level == b[1].level && a[2].level == b[2].level && a[3].level == b[3].level
}
func isCW(s [4]state) bool {
return s[0].level == gpio.High && s[1].level == gpio.High && s[2].level == gpio.Low && s[3].level == gpio.Low
}
func isCCW(s [4]state) bool {
return s[0].level == gpio.High && s[1].level == gpio.Low && s[2].level == gpio.Low && s[3].level == gpio.High
}
+10
View File
@@ -0,0 +1,10 @@
package rotary
type Event uint8
const (
Clockwise Event = iota
CounterClockwise
KeyPress
KeyRelease
)