-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathkeyboard_driver.go
96 lines (76 loc) · 1.62 KB
/
keyboard_driver.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
package keyboard
import (
"log"
"os"
"gobot.io/x/gobot/v2"
)
const (
// Key board event
Key = "key"
)
// Driver is gobot software device to the keyboard
type Driver struct {
name string
connect func(*Driver) error
listen func(*Driver)
stdin *os.File
gobot.Eventer
}
// NewDriver returns a new keyboard Driver.
func NewDriver() *Driver {
k := &Driver{
name: gobot.DefaultName("Keyboard"),
connect: func(k *Driver) error {
if err := configure(); err != nil {
return err
}
k.stdin = os.Stdin
return nil
},
listen: func(k *Driver) {
ctrlc := bytes{3}
for {
var keybuf bytes
if _, err := k.stdin.Read(keybuf[0:3]); err != nil {
panic(err)
}
if keybuf == ctrlc {
proc, err := os.FindProcess(os.Getpid())
if err != nil {
log.Fatal(err)
}
if err := proc.Signal(os.Interrupt); err != nil {
panic(err)
}
break
}
k.Publish(Key, Parse(keybuf))
}
},
Eventer: gobot.NewEventer(),
}
k.AddEvent(Key)
return k
}
// Name returns the Driver Name
func (k *Driver) Name() string { return k.name }
// SetName sets the Driver Name
func (k *Driver) SetName(n string) { k.name = n }
// Connection returns the Driver Connection
func (k *Driver) Connection() gobot.Connection { return nil }
// Start initializes keyboard by grabbing key events as they come in and
// publishing each as a key event
func (k *Driver) Start() error {
if err := k.connect(k); err != nil {
return err
}
go k.listen(k)
return nil
}
// Halt stops keyboard driver
func (k *Driver) Halt() error {
if originalState != "" {
return restore()
}
return nil
}