-
Notifications
You must be signed in to change notification settings - Fork 0
/
device.go
102 lines (82 loc) · 1.58 KB
/
device.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
package keypresslog
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"io/ioutil"
"os"
"strings"
"unsafe"
)
type DeviceReader interface {
Read() (chan Event, error)
GetId() int
GetName() string
}
type device struct {
id int
name string
}
func Find() []DeviceReader {
var ret []DeviceReader
for i := 0; i < MAX_FILES; i++ {
buff, err := ioutil.ReadFile(fmt.Sprintf(EVENTS_PATH_TPL, i))
if err != nil {
break
}
ret = append(ret, newDeviceReader(buff, i))
}
return ret
}
func (d *device) GetName() string {
return d.name
}
func (d *device) GetId() int {
return d.id
}
func (d *device) Read() (chan Event, error) {
ret := make(chan Event)
eventSize := int(unsafe.Sizeof(Event{}))
fd, err := os.Open(fmt.Sprintf(DEVICE_FILE_TPL, d.GetId()))
switch {
case os.IsPermission(err):
close(ret)
fd.Close()
return ret, errors.New("You don't have permissions to read this device")
case err != nil:
close(ret)
fd.Close()
return ret, err
}
go func() {
tmp := make([]byte, eventSize)
for {
n, err := fd.Read(tmp)
if err != nil {
close(ret)
fd.Close()
panic(err)
}
if n <= 0 {
continue
}
var event Event
if err := binary.Read(bytes.NewBuffer(tmp), binary.LittleEndian, &event); err != nil {
close(ret)
fd.Close()
panic(err)
}
ret <- event
}
}()
return ret, nil
}
func newDeviceReader(buff []byte, id int) DeviceReader {
rd := bufio.NewReader(bytes.NewReader(buff))
rd.ReadLine()
dev, _, _ := rd.ReadLine()
split := strings.Split(string(dev), "=")
return DeviceReader(&device{id, split[1]})
}