73 lines
2.0 KiB
Go
73 lines
2.0 KiB
Go
package input
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"fmt"
|
|
"io"
|
|
"time"
|
|
)
|
|
|
|
// linuxInputEvent holds a decoded evdev record, independent of native word size.
|
|
type linuxInputEvent struct {
|
|
Secs, USecs int64
|
|
Type, Code uint16
|
|
Value int32
|
|
}
|
|
|
|
func (e linuxInputEvent) String() string {
|
|
return fmt.Sprintf("time=%s type=%#04x code=%#04x value=%d", e.Time(), e.Type, e.Code, e.Value)
|
|
}
|
|
|
|
func (e linuxInputEvent) Time() time.Time {
|
|
return time.Unix(e.Secs, e.USecs*int64(time.Microsecond))
|
|
}
|
|
|
|
// readLinuxInputEvent reads one little-endian Linux event for a 4- or 8-byte
|
|
// native word. Short records return the error from io.ReadFull.
|
|
func readLinuxInputEvent(r io.Reader, wordSize int) (linuxInputEvent, error) {
|
|
var e linuxInputEvent
|
|
if wordSize != 4 && wordSize != 8 {
|
|
return e, fmt.Errorf("input: unsupported word size %d", wordSize)
|
|
}
|
|
var data [24]byte
|
|
if _, err := io.ReadFull(r, data[:2*wordSize+8]); err != nil {
|
|
return e, err
|
|
}
|
|
if wordSize == 4 {
|
|
e.Secs = int64(int32(binary.LittleEndian.Uint32(data[:4])))
|
|
e.USecs = int64(binary.LittleEndian.Uint32(data[4:8]))
|
|
} else {
|
|
e.Secs = int64(binary.LittleEndian.Uint64(data[:8]))
|
|
e.USecs = int64(binary.LittleEndian.Uint64(data[8:16]))
|
|
}
|
|
offset := 2 * wordSize
|
|
e.Type = binary.LittleEndian.Uint16(data[offset:])
|
|
e.Code = binary.LittleEndian.Uint16(data[offset+2:])
|
|
e.Value = int32(binary.LittleEndian.Uint32(data[offset+4:]))
|
|
return e, nil
|
|
}
|
|
|
|
// buttonState pairs one press with one release and ignores contact bounce.
|
|
// Access is confined to the button's event-reading goroutine.
|
|
type buttonState struct {
|
|
pressedAt, releasedAt time.Time
|
|
pressed bool
|
|
}
|
|
|
|
func (b *buttonState) press(at time.Time) {
|
|
if b.pressed || (!b.releasedAt.IsZero() && at.Sub(b.releasedAt) < 30*time.Millisecond) {
|
|
return
|
|
}
|
|
b.pressedAt, b.pressed = at, true
|
|
}
|
|
|
|
func (b *buttonState) release(at time.Time) (time.Duration, bool) {
|
|
if !b.pressed {
|
|
return 0, false
|
|
}
|
|
b.pressed = false
|
|
b.releasedAt = at
|
|
duration := at.Sub(b.pressedAt)
|
|
return duration, duration >= 0
|
|
}
|