From 811d371fdd2ce8672d477deee0306dfad006af3e Mon Sep 17 00:00:00 2001 From: joshua salzedo Date: Fri, 6 Mar 2020 11:38:04 -0800 Subject: [PATCH] Added ability to select a joystick by name - based on https://github.com/hybridgroup/gobot/issues/564#issuecomment-403175041 Signed-off-by: joshua salzedo --- platforms/joystick/joystick_adaptor.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/platforms/joystick/joystick_adaptor.go b/platforms/joystick/joystick_adaptor.go index e3a93da81..576337d5b 100644 --- a/platforms/joystick/joystick_adaptor.go +++ b/platforms/joystick/joystick_adaptor.go @@ -2,6 +2,7 @@ package joystick import ( "errors" + "strings" "gobot.io/x/gobot" @@ -35,6 +36,27 @@ func NewAdaptor() *Adaptor { } } +// Returns a new Joystick Adaptor for an implementation-specific named device +func NewNamedAdaptor(targetName string) *Adaptor { + return &Adaptor{ + name: gobot.DefaultName("Joystick"), + connect: func(adaptor *Adaptor) (err error) { + initErr := sdl.Init(sdl.INIT_JOYSTICK) + if initErr != nil { + return initErr + } + foundIndex := -1 + for i := 0; i < sdl.NumJoysticks(); i++ { + if strings.TrimSpace(targetName) == strings.TrimSpace(sdl.JoystickNameForIndex(i)) { + adaptor.joystick = sdl.JoystickOpen(foundIndex) + return + } + } + return errors.New("cannot find joystick by specified name") + }, + } +} + // Name returns the Adaptors name func (j *Adaptor) Name() string { return j.name }