JoystickSDL.cc 1.93 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
#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;
}

Gregory Dymarek's avatar
Gregory Dymarek committed
45
bool JoystickSDL::_open(void) {
46 47 48
    sdlJoystick = SDL_JoystickOpen(_index);

    if (!sdlJoystick) {
Gregory Dymarek's avatar
Gregory Dymarek committed
49 50
        qCWarning(JoystickLog) << "SDL_JoystickOpen failed:" << SDL_GetError();
        return false;
51 52 53 54 55
    }

    return true;
}

Gregory Dymarek's avatar
Gregory Dymarek committed
56
void JoystickSDL::_close(void) {
57 58 59
    SDL_JoystickClose(sdlJoystick);
}

Gregory Dymarek's avatar
Gregory Dymarek committed
60
bool JoystickSDL::_update(void)
61 62 63 64 65
{
    SDL_JoystickUpdate();
    return true;
}

Gregory Dymarek's avatar
Gregory Dymarek committed
66
bool JoystickSDL::_getButton(int i) {
67 68 69
    return !!SDL_JoystickGetButton(sdlJoystick, i);
}

Gregory Dymarek's avatar
Gregory Dymarek committed
70
int JoystickSDL::_getAxis(int i) {
71 72 73
    return SDL_JoystickGetAxis(sdlJoystick, i);
}