2014-04-27 18:02:39 -07:00
|
|
|
package joystick
|
2014-04-26 03:11:51 -07:00
|
|
|
|
|
|
|
import (
|
2014-11-19 15:45:59 -08:00
|
|
|
"errors"
|
2014-04-26 03:11:51 -07:00
|
|
|
"github.com/hybridgroup/go-sdl2/sdl"
|
|
|
|
"github.com/hybridgroup/gobot"
|
|
|
|
)
|
|
|
|
|
2014-11-16 12:25:48 -08:00
|
|
|
var _ gobot.AdaptorInterface = (*JoystickAdaptor)(nil)
|
|
|
|
|
2014-07-22 13:55:19 -07:00
|
|
|
type joystick interface {
|
|
|
|
Close()
|
|
|
|
InstanceID() sdl.JoystickID
|
|
|
|
}
|
|
|
|
|
2014-04-26 03:11:51 -07:00
|
|
|
type JoystickAdaptor struct {
|
|
|
|
gobot.Adaptor
|
2014-07-22 13:55:19 -07:00
|
|
|
joystick joystick
|
2014-11-19 15:45:59 -08:00
|
|
|
connect func(*JoystickAdaptor) (err error)
|
2014-04-26 03:11:51 -07:00
|
|
|
}
|
|
|
|
|
2014-10-20 10:46:03 -05:00
|
|
|
// NewJoysctickAdaptor creates a new adaptor with specified name.
|
|
|
|
// It creates a connect function to joystick in position 0
|
|
|
|
// or panics if no joystick can be found
|
2014-05-22 20:28:26 -07:00
|
|
|
func NewJoystickAdaptor(name string) *JoystickAdaptor {
|
2014-04-27 18:02:39 -07:00
|
|
|
return &JoystickAdaptor{
|
2014-07-07 17:12:45 -07:00
|
|
|
Adaptor: *gobot.NewAdaptor(
|
|
|
|
name,
|
|
|
|
"JoystickAdaptor",
|
|
|
|
),
|
2014-11-19 15:45:59 -08:00
|
|
|
connect: func(j *JoystickAdaptor) (err error) {
|
2014-04-27 18:02:39 -07:00
|
|
|
sdl.Init(sdl.INIT_JOYSTICK)
|
|
|
|
if sdl.NumJoysticks() > 0 {
|
|
|
|
j.joystick = sdl.JoystickOpen(0)
|
2014-11-19 15:45:59 -08:00
|
|
|
return
|
2014-04-27 18:02:39 -07:00
|
|
|
}
|
2014-11-19 15:45:59 -08:00
|
|
|
return errors.New("No joystick available")
|
2014-04-27 18:02:39 -07:00
|
|
|
},
|
2014-04-26 03:11:51 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-10-20 10:46:03 -05:00
|
|
|
// Connect returns true if connection to device is succesfull
|
2014-11-19 23:21:19 -08:00
|
|
|
func (j *JoystickAdaptor) Connect() (errs []error) {
|
|
|
|
if err := j.connect(j); err != nil {
|
|
|
|
return []error{err}
|
|
|
|
}
|
|
|
|
return
|
2014-04-26 03:11:51 -07:00
|
|
|
}
|
|
|
|
|
2014-10-20 10:46:03 -05:00
|
|
|
// Finalize closes connection to device
|
2014-11-19 23:21:19 -08:00
|
|
|
func (j *JoystickAdaptor) Finalize() (errs []error) {
|
2014-04-27 18:02:39 -07:00
|
|
|
j.joystick.Close()
|
2014-11-19 23:21:19 -08:00
|
|
|
return
|
2014-04-26 03:11:51 -07:00
|
|
|
}
|