2014-04-28 09:02:39 +08:00
|
|
|
package joystick
|
2014-04-26 18:11:51 +08:00
|
|
|
|
|
|
|
import (
|
2014-11-20 07:45:59 +08:00
|
|
|
"errors"
|
2014-11-23 11:54:32 +08:00
|
|
|
|
2017-02-02 23:24:48 +08:00
|
|
|
"gobot.io/x/gobot"
|
|
|
|
|
2016-02-21 06:27:24 +08:00
|
|
|
"github.com/veandco/go-sdl2/sdl"
|
2014-04-26 18:11:51 +08:00
|
|
|
)
|
|
|
|
|
2014-07-23 04:55:19 +08:00
|
|
|
type joystick interface {
|
|
|
|
Close()
|
|
|
|
InstanceID() sdl.JoystickID
|
|
|
|
}
|
|
|
|
|
2016-09-26 03:07:36 +08:00
|
|
|
// Adaptor represents a connection to a joystick
|
|
|
|
type Adaptor struct {
|
2014-11-23 11:54:32 +08:00
|
|
|
name string
|
2014-07-23 04:55:19 +08:00
|
|
|
joystick joystick
|
2016-09-26 03:07:36 +08:00
|
|
|
connect func(*Adaptor) (err error)
|
2014-04-26 18:11:51 +08:00
|
|
|
}
|
|
|
|
|
2016-09-26 03:07:36 +08:00
|
|
|
// NewAdaptor returns a new Joystick Adaptor.
|
|
|
|
func NewAdaptor() *Adaptor {
|
|
|
|
return &Adaptor{
|
2017-02-02 23:24:48 +08:00
|
|
|
name: gobot.DefaultName("Joystick"),
|
2016-09-26 03:07:36 +08:00
|
|
|
connect: func(j *Adaptor) (err error) {
|
2014-04-28 09:02:39 +08:00
|
|
|
sdl.Init(sdl.INIT_JOYSTICK)
|
|
|
|
if sdl.NumJoysticks() > 0 {
|
|
|
|
j.joystick = sdl.JoystickOpen(0)
|
2014-11-20 07:45:59 +08:00
|
|
|
return
|
2014-04-28 09:02:39 +08:00
|
|
|
}
|
2014-11-20 07:45:59 +08:00
|
|
|
return errors.New("No joystick available")
|
2014-04-28 09:02:39 +08:00
|
|
|
},
|
2014-04-26 18:11:51 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-26 03:07:36 +08:00
|
|
|
// Name returns the Adaptors name
|
|
|
|
func (j *Adaptor) Name() string { return j.name }
|
|
|
|
|
|
|
|
// SetName sets the Adaptors name
|
|
|
|
func (j *Adaptor) SetName(n string) { j.name = n }
|
2014-11-23 11:54:32 +08:00
|
|
|
|
2015-01-03 21:06:08 +08:00
|
|
|
// Connect connects to the joystick
|
2016-11-08 02:32:12 +08:00
|
|
|
func (j *Adaptor) Connect() (err error) {
|
|
|
|
err = j.connect(j)
|
2014-11-20 15:21:19 +08:00
|
|
|
return
|
2014-04-26 18:11:51 +08:00
|
|
|
}
|
|
|
|
|
2015-01-03 21:06:08 +08:00
|
|
|
// Finalize closes connection to joystick
|
2016-11-08 02:32:12 +08:00
|
|
|
func (j *Adaptor) Finalize() (err error) {
|
2014-04-28 09:02:39 +08:00
|
|
|
j.joystick.Close()
|
2014-11-20 15:21:19 +08:00
|
|
|
return
|
2014-04-26 18:11:51 +08:00
|
|
|
}
|