1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-27 13:48:56 +08:00
hybridgroup.gobot/platforms/joystick/joystick_adaptor.go

55 lines
1.2 KiB
Go
Raw Normal View History

2014-04-27 18:02:39 -07:00
package joystick
import (
2014-11-19 15:45:59 -08:00
"errors"
"github.com/hybridgroup/go-sdl2/sdl"
"github.com/hybridgroup/gobot"
)
var _ gobot.AdaptorInterface = (*JoystickAdaptor)(nil)
2014-07-22 13:55:19 -07:00
type joystick interface {
Close()
InstanceID() sdl.JoystickID
}
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)
}
// 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
},
}
}
// Connect returns true if connection to device is succesfull
func (j *JoystickAdaptor) Connect() (errs []error) {
if err := j.connect(j); err != nil {
return []error{err}
}
return
}
// Finalize closes connection to device
func (j *JoystickAdaptor) Finalize() (errs []error) {
2014-04-27 18:02:39 -07:00
j.joystick.Close()
return
}