JoystickSDL.cc 2.31 KB
Newer Older
1 2 3 4 5 6
#include "JoystickSDL.h"

#include "QGCApplication.h"

#include <QQmlEngine>

7 8
JoystickSDL::JoystickSDL(const QString& name, int axisCount, int buttonCount, int hatCount, int index, MultiVehicleManager* multiVehicleManager)
    : Joystick(name,axisCount,buttonCount,hatCount,multiVehicleManager)
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
    , _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)) {
29
            int axisCount, buttonCount, hatCount;
30 31 32 33

            SDL_Joystick* sdlJoystick = SDL_JoystickOpen(i);
            axisCount = SDL_JoystickNumAxes(sdlJoystick);
            buttonCount = SDL_JoystickNumButtons(sdlJoystick);
34
            hatCount = SDL_JoystickNumHats(sdlJoystick);
35 36
            SDL_JoystickClose(sdlJoystick);

37 38
            qCDebug(JoystickLog) << "\t" << name << "axes:" << axisCount << "buttons:" << buttonCount << "hats:" << hatCount;
            ret[name] = new JoystickSDL(name, axisCount, buttonCount, hatCount, i, _multiVehicleManager);
39 40 41 42 43 44 45
        } else {
            qCDebug(JoystickLog) << "\tSkipping duplicate" << name;
        }
    }
    return ret;
}

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

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

    return true;
}

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

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

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

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

75 76 77 78 79 80 81 82 83
uint8_t JoystickSDL::_getHat(int hat,int i) {
    uint8_t hatButtons[] = {SDL_HAT_UP,SDL_HAT_DOWN,SDL_HAT_LEFT,SDL_HAT_RIGHT};

    if ( i < int(sizeof(hatButtons)) ) {
        return !!(SDL_JoystickGetHat(sdlJoystick, hat) & hatButtons[i]);
    }
    return 0;
}