forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
joystick_adaptor.go
54 lines (45 loc) · 1.15 KB
/
joystick_adaptor.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
package joystick
import (
"errors"
"github.com/hybridgroup/go-sdl2/sdl"
"github.com/hybridgroup/gobot"
)
var _ gobot.Adaptor = (*JoystickAdaptor)(nil)
type joystick interface {
Close()
InstanceID() sdl.JoystickID
}
// JoystickAdaptor represents a connection to a joystick
type JoystickAdaptor struct {
name string
joystick joystick
connect func(*JoystickAdaptor) (err error)
}
// NewJoystickAdaptor returns a new JoystickAdaptor with specified name.
func NewJoystickAdaptor(name string) *JoystickAdaptor {
return &JoystickAdaptor{
name: name,
connect: func(j *JoystickAdaptor) (err error) {
sdl.Init(sdl.INIT_JOYSTICK)
if sdl.NumJoysticks() > 0 {
j.joystick = sdl.JoystickOpen(0)
return
}
return errors.New("No joystick available")
},
}
}
// Name returns the JoystickAdaptors name
func (j *JoystickAdaptor) Name() string { return j.name }
// Connect connects to the joystick
func (j *JoystickAdaptor) Connect() (errs []error) {
if err := j.connect(j); err != nil {
return []error{err}
}
return
}
// Finalize closes connection to joystick
func (j *JoystickAdaptor) Finalize() (errs []error) {
j.joystick.Close()
return
}