/
keys.go
49 lines (41 loc) · 1.24 KB
/
keys.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
package engine
import (
"gobot.io/x/gobot/platforms/keyboard"
)
// AddKeyboardDevice will add the keyboard device and start handling key presses. This MUST be called before Start.
func (e *Engine) AddKeyboardDevice() {
keys := keyboard.NewDriver()
keys.On(keyboard.Key, func(data interface{}) {
e.handleKeyPress(data.(keyboard.KeyEvent))
})
e.robot.AddDevice(keys)
}
// GetLastKeyPressed will return the last key that was pressed or an empty string if none.
func (e *Engine) GetLastKeyPressed() string {
lastKey := e.lastKeyPressed
e.lastKeyPressed = ""
return lastKey
}
// handleKeyPress handles a key press event.
func (e *Engine) handleKeyPress(key keyboard.KeyEvent) {
// convert some common key presses into human readable strings
var lastKeyPressed string
switch key.Key {
case keyboard.ArrowUp:
lastKeyPressed = "arrowup"
case keyboard.ArrowDown:
lastKeyPressed = "arrowdown"
case keyboard.ArrowLeft:
lastKeyPressed = "arrowleft"
case keyboard.ArrowRight:
lastKeyPressed = "arrowright"
case keyboard.Spacebar:
lastKeyPressed = "spacebar"
case keyboard.Escape:
lastKeyPressed = "escape"
default:
lastKeyPressed = string(key.Key)
}
e.lastKeyPressed = lastKeyPressed
debug("Key pressed: %s (%d)", lastKeyPressed, key.Key)
}