-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkeyboard_listener.go
48 lines (40 loc) · 946 Bytes
/
keyboard_listener.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
package kindleland
import (
"bytes"
"encoding/binary"
"fmt"
"os"
"time"
)
// NewKeyboardListener takes the path to a /dev/input/* device and returns
// a chan on which events will be pushed when they occur.
func NewKeyboardListener(path string) (chan KeyboardEvent, error) {
channel := make(chan KeyboardEvent)
keyboard, err := os.Open(path)
if err != nil {
close(channel)
return channel, err
}
buf := make([]byte, 16)
go func() {
for {
if _, err := keyboard.Read(buf); err != nil {
fmt.Println(err)
break
}
var event Event
if err := binary.Read(bytes.NewReader(buf), binary.LittleEndian, &event); err != nil {
break
}
kevent := KeyboardEvent{
Time: time.Unix(int64(event.Time.Seconds), int64(event.Time.Microseconds)*1000),
Type: KeyEventType(event.Value),
Key: KeyType(event.Code),
}
channel <- kevent
}
close(channel)
keyboard.Close()
}()
return channel, nil
}