Issues With Creating SDL2 Joystick Bindings With Node FFI

482 Views Asked by At

I've been trying to write an object to use the Joystick class from the SDL2 library with NodeJS using the FFI module, but keep running into problems. It appears to work as expected roughly 50% of the time, but at other times, the program claims it's unable to find a connected joystick (using SDL_GetError()).

Here's a sample of the code:

// Constructor...
function Joystick(deviceId){    
    this.joystickPointer = ref.refType('pointer');

    this.SDL = ffi.Library("SDL2.dll", {    
    "SDL_Init": ["Uint32", ["string"]],
    "SDL_Quit": ["void", []],
    "SDL_JoystickOpen": ["pointer", ["int"]],
    "SDL_NumJoysticks": ["int", []],
    "SDL_JoystickName": ["string", [this.joystickPointer]],
    "SDL_JoystickNumButtons": ["int", [this.joystickPointer]],
    "SDL_JoystickGetButton": ["Uint8", [this.joystickPointer, "int"]],
    "SDL_JoystickNumAxes": ["int", [this.joystickPointer]],
    "SDL_JoystickGetAxis": ["int16", [this.joystickPointer, "int"]],
    "SDL_JoystickGetAttached": ["bool", [this.joystickPointer]],
    "SDL_JoystickClose": ["void", [this.joystickPointer]],
    "SDL_JoystickUpdate": ["void", []],
    "SDL_GetError": ["string", []]
    });

        // Setup
    this.deviceId = deviceId || 0;
    this.SDL.SDL_Init("SDL_INIT_JOYSTICK");
    this.joystickObject = this.SDL.SDL_JoystickOpen(this.deviceId);

        // Poll Joystick
        this.deviceCount = this.SDL.SDL_NumJoysticks();
    this.buttons = this.SDL.SDL_JoystickNumButtons(this.joystickObject);
    this.name = this.SDL.SDL_JoystickName(this.joystickObject);

        // Cleanup
        this.SDL.SDL_JoystickClose(this.joystickObject);
        this.SDL.SDL_Quit();    

    return false;
}

var testJoystick = new Joystick(0);
console.log(testJoystick.name);

When it fails, SDL_GetError() gives me the following error message:

"Joystick hasn't been opened yet" 

Any ideas?

1

There are 1 best solutions below

0
On

I suspect there were too many issues in the code above to make it work as expected. In the end, I came up with a different solution...

I found a static, lower level input library - http://forums.tigsource.com/index.php?topic=10675.0 - wrote a skeletal library over the top of it, linked it, then applied it...

It works great and is much, much lighter than SDL...

Will have to put it on GIT or Bitbucket within the next few days if I have time.