68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package inputs
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
type JoystickEvent struct {
|
|
Time uint32 // Event timestamp in milliseconds
|
|
Value int16 // Value of the event (button press or axis movement)
|
|
Type uint8 // Event type (button or axis)
|
|
Number uint8 // Axis/button number
|
|
}
|
|
|
|
const (
|
|
JS_EVENT_BUTTON = 0x01 // Button pressed/released
|
|
JS_EVENT_AXIS = 0x02 // Joystick moved
|
|
JS_EVENT_INIT = 0x80 // Initial state of device
|
|
)
|
|
|
|
func Start() {
|
|
// Open the joystick device file
|
|
file, err := os.Open("/dev/input/js0")
|
|
if err != nil {
|
|
fmt.Println("Error opening joystick:", err)
|
|
return
|
|
}
|
|
defer file.Close()
|
|
|
|
// Continuously read joystick events
|
|
for {
|
|
var e JoystickEvent
|
|
err := binary.Read(file, binary.LittleEndian, &e)
|
|
if err != nil {
|
|
fmt.Println("Error reading joystick event:", err)
|
|
return
|
|
}
|
|
|
|
// Handle the event
|
|
handleJoystickEvent(e)
|
|
|
|
// Sleep to avoid flooding output
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
}
|
|
|
|
// handleJoystickEvent processes joystick events.
|
|
func handleJoystickEvent(e JoystickEvent) {
|
|
if e.Type&JS_EVENT_INIT != 0 {
|
|
// Ignore initial state events
|
|
return
|
|
}
|
|
|
|
if e.Type&JS_EVENT_BUTTON != 0 {
|
|
if e.Value == 1 {
|
|
fmt.Printf("Button %d pressed\n", e.Number)
|
|
} else {
|
|
fmt.Printf("Button %d released\n", e.Number)
|
|
}
|
|
}
|
|
|
|
if e.Type&JS_EVENT_AXIS != 0 {
|
|
fmt.Printf("Axis %d moved to %d\n", e.Number, e.Value)
|
|
}
|
|
}
|