-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
kbrotary.go
127 lines (107 loc) · 2.29 KB
/
kbrotary.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//go:build tinygo && (rp2040 || stm32 || k210 || esp32c3 || nrf || (avr && (atmega328p || atmega328pb)))
package keyboard
import (
"machine"
"tinygo.org/x/drivers/encoders"
)
type RotaryKeyboard struct {
State []State
Keys [][]Keycode
callback Callback
enc *encoders.QuadratureDevice
oldValue int
}
func (d *Device) AddRotaryKeyboard(rotA, rotB machine.Pin, keys [][]Keycode) *RotaryKeyboard {
state := make([]State, 2)
enc := encoders.NewQuadratureViaInterrupt(rotA, rotB)
enc.Configure(encoders.QuadratureConfig{
Precision: 4,
})
keydef := make([][]Keycode, LayerCount)
for l := 0; l < len(keydef); l++ {
keydef[l] = make([]Keycode, len(state))
}
for l := 0; l < len(keys); l++ {
for kc := 0; kc < len(keys[l]); kc++ {
keydef[l][kc] = keys[l][kc]
}
}
k := &RotaryKeyboard{
State: state,
Keys: keydef,
callback: func(layer, index int, state State) {},
enc: enc,
}
d.kb = append(d.kb, k)
return k
}
func (d *RotaryKeyboard) SetCallback(fn Callback) {
d.callback = fn
}
func (d *RotaryKeyboard) Callback(layer, index int, state State) {
if d.callback != nil {
d.callback(layer, index, state)
}
}
func (d *RotaryKeyboard) Get() []State {
rot := []bool{false, false}
if newValue := d.enc.Position(); newValue != d.oldValue {
if newValue < d.oldValue {
rot[0] = true
} else {
rot[1] = true
}
d.oldValue = newValue
}
for c, current := range rot {
switch d.State[c] {
case None:
if current {
d.State[c] = NoneToPress
} else {
}
case NoneToPress:
if current {
d.State[c] = Press
} else {
d.State[c] = PressToRelease
}
case Press:
if current {
} else {
d.State[c] = PressToRelease
}
case PressToRelease:
if current {
d.State[c] = NoneToPress
} else {
d.State[c] = None
}
}
}
return d.State
}
func (d *RotaryKeyboard) Key(layer, index int) Keycode {
if layer >= LayerCount {
return 0
}
if index >= len(d.Keys[layer]) {
return 0
}
return d.Keys[layer][index]
}
func (d *RotaryKeyboard) SetKeycode(layer, index int, key Keycode) {
if layer >= LayerCount {
return
}
if index >= len(d.Keys[layer]) {
return
}
d.Keys[layer][index] = key
}
func (d *RotaryKeyboard) GetKeyCount() int {
return len(d.State)
}
func (d *RotaryKeyboard) Init() error {
return nil
}