2014-04-28 09:02:39 +08:00
|
|
|
package joystick
|
2014-04-26 18:11:51 +08:00
|
|
|
|
|
|
|
import (
|
2023-09-23 18:32:31 +08:00
|
|
|
"fmt"
|
|
|
|
"strconv"
|
2014-11-23 11:54:32 +08:00
|
|
|
|
2023-09-23 18:32:31 +08:00
|
|
|
js "github.com/0xcafed00d/joystick"
|
2023-11-16 03:51:52 +08:00
|
|
|
|
|
|
|
"gobot.io/x/gobot/v2"
|
2014-04-26 18:11:51 +08:00
|
|
|
)
|
|
|
|
|
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
|
2023-09-23 18:32:31 +08:00
|
|
|
id string
|
|
|
|
joystick js.Joystick
|
2023-06-13 01:51:25 +08:00
|
|
|
connect func(*Adaptor) error
|
2014-04-26 18:11:51 +08:00
|
|
|
}
|
|
|
|
|
2016-09-26 03:07:36 +08:00
|
|
|
// NewAdaptor returns a new Joystick Adaptor.
|
2023-09-23 18:32:31 +08:00
|
|
|
// Pass in the ID of the joystick you wish to connect to.
|
|
|
|
func NewAdaptor(id string) *Adaptor {
|
2016-09-26 03:07:36 +08:00
|
|
|
return &Adaptor{
|
2017-02-02 23:24:48 +08:00
|
|
|
name: gobot.DefaultName("Joystick"),
|
2023-06-13 01:51:25 +08:00
|
|
|
connect: func(j *Adaptor) error {
|
2023-09-23 18:32:31 +08:00
|
|
|
i, err := strconv.Atoi(id)
|
|
|
|
if err != nil {
|
2023-11-16 03:51:52 +08:00
|
|
|
return fmt.Errorf("invalid joystick ID: %v", err)
|
2023-06-13 01:51:25 +08:00
|
|
|
}
|
2023-09-23 18:32:31 +08:00
|
|
|
|
|
|
|
joy, err := js.Open(i)
|
|
|
|
if err != nil {
|
2023-11-16 03:51:52 +08:00
|
|
|
return fmt.Errorf("no joystick available: %v", err)
|
2014-04-28 09:02:39 +08:00
|
|
|
}
|
2023-09-23 18:32:31 +08:00
|
|
|
|
|
|
|
j.id = id
|
|
|
|
j.joystick = joy
|
|
|
|
return nil
|
2014-04-28 09:02:39 +08:00
|
|
|
},
|
2014-04-26 18:11:51 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-12 23:27:08 +08:00
|
|
|
// Name returns the adaptors name
|
2016-09-26 03:07:36 +08:00
|
|
|
func (j *Adaptor) Name() string { return j.name }
|
|
|
|
|
2024-02-12 23:27:08 +08:00
|
|
|
// SetName sets the adaptors name
|
2016-09-26 03:07:36 +08:00
|
|
|
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
|
2023-06-13 01:51:25 +08:00
|
|
|
func (j *Adaptor) Connect() error {
|
|
|
|
return j.connect(j)
|
2014-04-26 18:11:51 +08:00
|
|
|
}
|
|
|
|
|
2015-01-03 21:06:08 +08:00
|
|
|
// Finalize closes connection to joystick
|
2023-06-13 01:51:25 +08:00
|
|
|
func (j *Adaptor) Finalize() error {
|
2014-04-28 09:02:39 +08:00
|
|
|
j.joystick.Close()
|
2023-06-13 01:51:25 +08:00
|
|
|
return nil
|
2014-04-26 18:11:51 +08:00
|
|
|
}
|