gobot.io/x/gobot@v1.16.0/platforms/joystick/joystick_adaptor.go (about)

     1  package joystick
     2  
     3  import (
     4  	"errors"
     5  
     6  	"gobot.io/x/gobot"
     7  
     8  	"github.com/veandco/go-sdl2/sdl"
     9  )
    10  
    11  type joystick interface {
    12  	Close()
    13  	InstanceID() sdl.JoystickID
    14  }
    15  
    16  // Adaptor represents a connection to a joystick
    17  type Adaptor struct {
    18  	name     string
    19  	joystick joystick
    20  	connect  func(*Adaptor) (err error)
    21  }
    22  
    23  // NewAdaptor returns a new Joystick Adaptor.
    24  func NewAdaptor() *Adaptor {
    25  	return &Adaptor{
    26  		name: gobot.DefaultName("Joystick"),
    27  		connect: func(j *Adaptor) (err error) {
    28  			sdl.Init(sdl.INIT_JOYSTICK)
    29  			if sdl.NumJoysticks() > 0 {
    30  				j.joystick = sdl.JoystickOpen(0)
    31  				return
    32  			}
    33  			return errors.New("No joystick available")
    34  		},
    35  	}
    36  }
    37  
    38  // Name returns the Adaptors name
    39  func (j *Adaptor) Name() string { return j.name }
    40  
    41  // SetName sets the Adaptors name
    42  func (j *Adaptor) SetName(n string) { j.name = n }
    43  
    44  // Connect connects to the joystick
    45  func (j *Adaptor) Connect() (err error) {
    46  	err = j.connect(j)
    47  	return
    48  }
    49  
    50  // Finalize closes connection to joystick
    51  func (j *Adaptor) Finalize() (err error) {
    52  	j.joystick.Close()
    53  	return
    54  }