-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
kbuart.go
142 lines (123 loc) · 2.49 KB
/
kbuart.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
//go:build tinygo
package keyboard
import (
"machine"
)
type UartKeyboard struct {
State []State
Keys [][]Keycode
callback Callback
uart *machine.UART
buf []byte
}
func (d *Device) AddUartKeyboard(size int, uart *machine.UART, keys [][]Keycode) *UartKeyboard {
state := make([]State, size)
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 := &UartKeyboard{
State: state,
Keys: keydef,
callback: func(layer, index int, state State) {},
uart: uart,
buf: make([]byte, 0, 3),
}
d.kb = append(d.kb, k)
return k
}
func (d *UartKeyboard) SetCallback(fn Callback) {
d.callback = fn
}
func (d *UartKeyboard) Callback(layer, index int, state State) {
if d.callback != nil {
d.callback(layer, index, state)
}
}
func (d *UartKeyboard) Get() []State {
uart := d.uart
for i := range d.State {
switch d.State[i] {
case NoneToPress:
d.State[i] = Press
case PressToRelease:
d.State[i] = None
}
}
for uart.Buffered() > 0 {
data, _ := uart.ReadByte()
d.buf = append(d.buf, data)
if len(d.buf) == 3 {
index := (int(d.buf[1]) << 8) + int(d.buf[2])
current := false
switch d.buf[0] {
case 0xAA: // press
current = true
case 0x55: // release
current = false
default:
d.buf[0], d.buf[1] = d.buf[1], d.buf[2]
d.buf = d.buf[:2]
continue
}
switch d.State[index] {
case None:
if current {
d.State[index] = NoneToPress
} else {
}
case NoneToPress:
if current {
d.State[index] = Press
} else {
d.State[index] = PressToRelease
}
case Press:
if current {
} else {
d.State[index] = PressToRelease
}
case PressToRelease:
if current {
d.State[index] = NoneToPress
} else {
d.State[index] = None
}
}
d.buf = d.buf[:0]
}
}
return d.State
}
func (d *UartKeyboard) 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 *UartKeyboard) SetKeycode(layer, index int, key Keycode) {
if layer >= LayerCount {
return
}
if index >= len(d.Keys[layer]) {
return
}
d.Keys[layer][index] = key
}
func (d *UartKeyboard) GetKeyCount() int {
return len(d.State)
}
func (d *UartKeyboard) Init() error {
for d.uart.Buffered() > 0 {
d.uart.ReadByte()
}
return nil
}