JoystickSDL.cc 1.92 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include "JoystickSDL.h"

#include "QGCApplication.h"

#include <QQmlEngine>

JoystickSDL::JoystickSDL(const QString& name, int axisCount, int buttonCount, int index, MultiVehicleManager* multiVehicleManager)
    : Joystick(name,axisCount,buttonCount,multiVehicleManager)
    , _index(index)
{
}

QMap<QString, Joystick*> JoystickSDL::discover(MultiVehicleManager* _multiVehicleManager) {
    static QMap<QString, Joystick*> ret;

    if (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE) < 0) {
        qWarning() << "Couldn't initialize SimpleDirectMediaLayer:" << SDL_GetError();
        return ret;
    }

    // Load available joysticks

    qCDebug(JoystickLog) << "Available joysticks";

    for (int i=0; i<SDL_NumJoysticks(); i++) {
        QString name = SDL_JoystickName(i);

        if (!ret.contains(name)) {
            int axisCount, buttonCount;

            SDL_Joystick* sdlJoystick = SDL_JoystickOpen(i);
            axisCount = SDL_JoystickNumAxes(sdlJoystick);
            buttonCount = SDL_JoystickNumButtons(sdlJoystick);
            SDL_JoystickClose(sdlJoystick);

            qCDebug(JoystickLog) << "\t" << name << "axes:" << axisCount << "buttons:" << buttonCount;
            ret[name] = new JoystickSDL(name, axisCount, buttonCount, i, _multiVehicleManager);
        } else {
            qCDebug(JoystickLog) << "\tSkipping duplicate" << name;
        }
    }
    return ret;
}

bool JoystickSDL::open(void) {
    sdlJoystick = SDL_JoystickOpen(_index);

    if (!sdlJoystick) {
	qCWarning(JoystickLog) << "SDL_JoystickOpen failed:" << SDL_GetError();
	return false;
    }

    return true;
}

void JoystickSDL::close(void) {
    SDL_JoystickClose(sdlJoystick);
}

bool JoystickSDL::update(void)
{
    SDL_JoystickUpdate();
    return true;
}

bool JoystickSDL::getButton(int i) {
    return !!SDL_JoystickGetButton(sdlJoystick, i);
}

int JoystickSDL::getAxis(int i) {
    return SDL_JoystickGetAxis(sdlJoystick, i);
}