JoystickInput.cc 11.5 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*=====================================================================
======================================================================*/

/**
 * @file
 *   @brief Joystick interface
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *   @author Andreas Romer <mavteam@student.ethz.ch>
 *
 */

#include "JoystickInput.h"

#include <QDebug>
#include <limits.h>
#include "UAS.h"
#include "UASManager.h"
19
#include "QGC.h"
20
#include <QMutexLocker>
Lorenz Meier's avatar
Lorenz Meier committed
21
#include <QSettings>
22
#include <math.h>
pixhawk's avatar
pixhawk committed
23 24 25 26 27 28

/**
 * The coordinate frame of the joystick axis is the aeronautical frame like shown on this image:
 * @image html http://pixhawk.ethz.ch/wiki/_media/standards/body-frame.png Aeronautical frame
 */
JoystickInput::JoystickInput() :
29 30 31 32 33 34 35 36 37 38 39
    sdlJoystickMin(-32768.0f),
    sdlJoystickMax(32767.0f),
    uas(NULL),
    done(false),
    rollAxis(-1),
    pitchAxis(-1),
    yawAxis(-1),
    throttleAxis(-1),
    joystickName(""),
    joystickID(-1),
    joystickNumButtons(0)
pixhawk's avatar
pixhawk committed
40
{
Lorenz Meier's avatar
Lorenz Meier committed
41 42
    loadSettings();

43
    for (int i = 0; i < 10; i++) {
pixhawk's avatar
pixhawk committed
44 45 46 47
        calibrationPositive[i] = sdlJoystickMax;
        calibrationNegative[i] = sdlJoystickMin;
    }

48 49
    // Start this thread. This allows the Joystick Settings window to work correctly even w/o any UASes connected.
    start();
pixhawk's avatar
pixhawk committed
50 51
}

52 53
JoystickInput::~JoystickInput()
{
Lorenz Meier's avatar
Lorenz Meier committed
54
    storeSettings();
LM's avatar
LM committed
55
    done = true;
Lorenz Meier's avatar
Lorenz Meier committed
56 57 58 59
}

void JoystickInput::loadSettings()
{
60 61 62 63 64 65 66 67 68 69 70 71
//    // Load defaults from settings
//    QSettings settings;
//    settings.sync();
//    settings.beginGroup("QGC_JOYSTICK_INPUT");
//    xAxis = (settings.value("X_AXIS_MAPPING", xAxis).toInt());
//    yAxis = (settings.value("Y_AXIS_MAPPING", yAxis).toInt());
//    thrustAxis = (settings.value("THRUST_AXIS_MAPPING", thrustAxis).toInt());
//    yawAxis = (settings.value("YAW_AXIS_MAPPING", yawAxis).toInt());
//    autoButtonMapping = (settings.value("AUTO_BUTTON_MAPPING", autoButtonMapping).toInt());
//    stabilizeButtonMapping = (settings.value("STABILIZE_BUTTON_MAPPING", stabilizeButtonMapping).toInt());
//    manualButtonMapping = (settings.value("MANUAL_BUTTON_MAPPING", manualButtonMapping).toInt());
//    settings.endGroup();
Lorenz Meier's avatar
Lorenz Meier committed
72 73 74 75
}

void JoystickInput::storeSettings()
{
76 77 78 79 80 81 82 83 84 85 86 87
//    // Store settings
//    QSettings settings;
//    settings.beginGroup("QGC_JOYSTICK_INPUT");
//    settings.setValue("X_AXIS_MAPPING", xAxis);
//    settings.setValue("Y_AXIS_MAPPING", yAxis);
//    settings.setValue("THRUST_AXIS_MAPPING", thrustAxis);
//    settings.setValue("YAW_AXIS_MAPPING", yawAxis);
//    settings.setValue("AUTO_BUTTON_MAPPING", autoButtonMapping);
//    settings.setValue("STABILIZE_BUTTON_MAPPING", stabilizeButtonMapping);
//    settings.setValue("MANUAL_BUTTON_MAPPING", manualButtonMapping);
//    settings.endGroup();
//    settings.sync();
88 89 90
}


pixhawk's avatar
pixhawk committed
91 92 93 94
void JoystickInput::setActiveUAS(UASInterface* uas)
{
    // Only connect / disconnect is the UAS is of a controllable UAS class
    UAS* tmp = 0;
LM's avatar
LM committed
95 96
    if (this->uas)
    {
pixhawk's avatar
pixhawk committed
97
        tmp = dynamic_cast<UAS*>(this->uas);
LM's avatar
LM committed
98 99
        if(tmp)
        {
100
            disconnect(this, SIGNAL(joystickChanged(double,double,double,double,int,int,int)), tmp, SLOT(setManualControlCommands(double,double,double,double,int,int,int)));
pixhawk's avatar
pixhawk committed
101 102 103 104 105 106
            disconnect(this, SIGNAL(buttonPressed(int)), tmp, SLOT(receiveButton(int)));
        }
    }

    this->uas = uas;

107
    if (this->uas)
LM's avatar
LM committed
108
    {
109 110 111 112 113
        tmp = dynamic_cast<UAS*>(this->uas);
        if(tmp) {
            connect(this, SIGNAL(joystickChanged(double,double,double,double,int,int,int)), tmp, SLOT(setManualControlCommands(double,double,double,double,int,int,int)));
            connect(this, SIGNAL(buttonPressed(int)), tmp, SLOT(receiveButton(int)));
        }
114
    }
pixhawk's avatar
pixhawk committed
115 116 117 118 119
}

void JoystickInput::init()
{
    // INITIALIZE SDL Joystick support
120
    if (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE) < 0) {
pixhawk's avatar
pixhawk committed
121 122 123 124
        printf("Couldn't initialize SimpleDirectMediaLayer: %s\n", SDL_GetError());
    }

    // Enumerate joysticks and select one
125
    numJoysticks = SDL_NumJoysticks();
pixhawk's avatar
pixhawk committed
126

127
    // Wait for joysticks if none are connected
128
    while (numJoysticks == 0 && !done)
LM's avatar
LM committed
129
    {
Lorenz Meier's avatar
Lorenz Meier committed
130
        QGC::SLEEP::msleep(400);
pixhawk's avatar
pixhawk committed
131
        // INITIALIZE SDL Joystick support
LM's avatar
LM committed
132 133
        if (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE) < 0)
        {
pixhawk's avatar
pixhawk committed
134 135
            printf("Couldn't initialize SimpleDirectMediaLayer: %s\n", SDL_GetError());
        }
136
        numJoysticks = SDL_NumJoysticks();
pixhawk's avatar
pixhawk committed
137
    }
138 139 140 141
    if (done)
    {
        return;
    }
pixhawk's avatar
pixhawk committed
142

143 144
    qDebug() << QString("%1 Input devices found:").arg(numJoysticks);
    for(int i=0; i < numJoysticks; i++ )
LM's avatar
LM committed
145
    {
146 147 148 149 150
        qDebug() << QString("\t- %1").arg(SDL_JoystickName(i));
        SDL_Joystick* x = SDL_JoystickOpen(i);
        qDebug() << QString("Number of Axes: %1").arg(QString::number(SDL_JoystickNumAxes(x)));
        qDebug() << QString("Number of Buttons: %1").arg(QString::number(SDL_JoystickNumButtons(x)));
        SDL_JoystickClose(x);
pixhawk's avatar
pixhawk committed
151 152
    }

153 154
    // And attach to the first joystick found to start.
    setActiveJoystick(0);
155 156 157

    // Make sure active UAS is set
    setActiveUAS(UASManager::instance()->getActiveUAS());
pixhawk's avatar
pixhawk committed
158
}
159

160 161 162 163
void JoystickInput::shutdown()
{
    done = true;
}
pixhawk's avatar
pixhawk committed
164 165 166

/**
 * @brief Execute the Joystick process
167 168
 * Note that the SDL procedure is polled. This is because connecting and disconnecting while the event checker is running
 * fails as of SDL 1.2. It is therefore much easier to just poll for the joystick we want to sample.
pixhawk's avatar
pixhawk committed
169 170 171 172 173
 */
void JoystickInput::run()
{
    init();

174
    forever
LM's avatar
LM committed
175 176 177
    {
        if (done)
        {
178 179 180
            done = false;
            exit();
            return;
LM's avatar
LM committed
181
        }
pixhawk's avatar
pixhawk committed
182

183 184
        // Poll the joystick for new values.
        SDL_JoystickUpdate();
pixhawk's avatar
pixhawk committed
185

186
        // Emit all necessary signals for all axes.
187
        for (int i = 0; i < joystickNumAxes; i++)
188 189 190
        {
            // First emit the uncalibrated values for each axis based on their ID.
            // This is generally not used for controlling a vehicle, but a UI representation, so it being slightly off is fine.
191 192 193 194 195 196 197 198 199
            float axisValue = SDL_JoystickGetAxis(joystick, i);
            if (joystickAxesInverted[i])
            {
                axisValue = (axisValue - calibrationNegative[i]) / (calibrationPositive[i] - calibrationNegative[i]);
            }
            else
            {
                axisValue = (axisValue - calibrationPositive[i]) / (calibrationNegative[i] - calibrationPositive[i]);
            }
200
            axisValue = 1.0f - axisValue;
201 202 203 204 205 206

            // If the joystick isn't limited to [0:1.0], map it into [-1.0:1.0].
            if (!joystickAxesRangeLimited[i])
            {
                axisValue = axisValue * 2.0f - 1.0f;
            }
207 208 209 210

            // Bound rounding errors
            if (axisValue > 1.0f) axisValue = 1.0f;
            if (axisValue < -1.0f) axisValue = -1.0f;
211 212 213 214 215
            if (joystickAxes[i] != axisValue)
            {
                joystickAxes[i] = axisValue;
                emit axisValueChanged(i, axisValue);
            }
216
        }
pixhawk's avatar
pixhawk committed
217 218

        // Build up vectors describing the hat position
219
        int hatPosition = SDL_JoystickGetHat(joystick, 0);
220 221 222 223 224 225 226 227 228 229
        int newYHat = 0;
        if ((SDL_HAT_UP & hatPosition) > 0) newYHat = 1;
        if ((SDL_HAT_DOWN & hatPosition) > 0) newYHat = -1;
        int newXHat = 0;
        if ((SDL_HAT_LEFT & hatPosition) > 0) newXHat = -1;
        if ((SDL_HAT_RIGHT & hatPosition) > 0) newXHat = 1;
        if (newYHat != yHat || newXHat != xHat)
        {
            xHat = newXHat;
            yHat = newYHat;
230
            emit hatDirectionChanged(newXHat, newYHat);
231
        }
pixhawk's avatar
pixhawk committed
232

233
        // Emit signals for each button individually
234
        for (int i = 0; i < joystickNumButtons; i++)
LM's avatar
LM committed
235
        {
236
            // If the button was down, but now it's up, trigger a buttonPressed event
237
            quint16 lastButtonState = joystickButtons & (1 << i);
238
            if (SDL_JoystickGetButton(joystick, i) && !lastButtonState)
LM's avatar
LM committed
239
            {
pixhawk's avatar
pixhawk committed
240
                emit buttonPressed(i);
241
                joystickButtons |= 1 << i;
242 243 244 245
            }
            else if (!SDL_JoystickGetButton(joystick, i) && lastButtonState)
            {
                emit buttonReleased(i);
246
                joystickButtons &= ~(1 << i);
pixhawk's avatar
pixhawk committed
247 248
            }
        }
249 250

        // Now signal an update for all UI together.
251 252 253 254 255
        float roll = rollAxis > -1?joystickAxes[rollAxis]:NAN;
        float pitch = pitchAxis > -1?joystickAxes[pitchAxis]:NAN;
        float yaw = yawAxis > -1?joystickAxes[yawAxis]:NAN;
        float throttle = throttleAxis > -1?joystickAxes[throttleAxis]:NAN;
        emit joystickChanged(roll, pitch, yaw, throttle, xHat, yHat, joystickButtons);
pixhawk's avatar
pixhawk committed
256 257

        // Sleep, update rate of joystick is approx. 50 Hz (1000 ms / 50 = 20 ms)
258
        QGC::SLEEP::msleep(20);
pixhawk's avatar
pixhawk committed
259 260
    }
}
261

262 263
void JoystickInput::setActiveJoystick(int id)
{
264 265 266 267 268 269 270
    if (joystick && SDL_JoystickOpened(joystickID))
    {
        SDL_JoystickClose(joystick);
        joystick = NULL;
        joystickID = -1;
    }

271 272
    joystickID = id;
    joystick = SDL_JoystickOpen(joystickID);
273
    if (joystick && SDL_JoystickOpened(joystickID))
274
    {
275
        SDL_JoystickUpdate();
276
        // Update joystick configuration.
277
        joystickName = QString(SDL_JoystickName(joystickID));
278 279 280
        joystickNumButtons = SDL_JoystickNumButtons(joystick);
        joystickNumAxes = SDL_JoystickNumAxes(joystick);

281
        // Update cached joystick values
282
        joystickAxes.clear();
283
        joystickAxesInverted.clear();
284
        joystickAxesRangeLimited.clear();
285
        for (int i = 0; i < joystickNumAxes; i++)
286
        {
287 288 289
            int axisValue = SDL_JoystickGetAxis(joystick, i);
            joystickAxes.append(axisValue);
            emit axisValueChanged(i, axisValue);
290 291

            joystickAxesInverted.append(false);
292
            joystickAxesRangeLimited.append(false);
293 294
        }
        joystickButtons = 0;
295 296 297 298 299 300 301 302
        for (int i = 0; i < joystickNumButtons; i++)
        {
            if (SDL_JoystickGetButton(joystick, i))
            {
                emit buttonPressed(i);
                joystickButtons |= 1 << i;
            }
        }
303 304 305 306 307 308
        qDebug() << QString("Switching to joystick '%1' with %2 buttons/%3 axes").arg(joystickName, QString::number(joystickNumButtons), QString::number(joystickNumAxes));
    }
    else
    {
        joystickNumButtons = 0;
        joystickNumAxes = 0;
309 310 311
    }
}

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
void JoystickInput::setAxisMapping(int axis, JOYSTICK_INPUT_MAPPING newMapping)
{
    switch (newMapping)
    {
        case JOYSTICK_INPUT_MAPPING_ROLL:
            rollAxis = axis;
            break;
        case JOYSTICK_INPUT_MAPPING_PITCH:
            pitchAxis = axis;
            break;
        case JOYSTICK_INPUT_MAPPING_YAW:
            yawAxis = axis;
            break;
        case JOYSTICK_INPUT_MAPPING_THROTTLE:
            throttleAxis = axis;
            break;
        case JOYSTICK_INPUT_MAPPING_NONE:
        default:
            if (rollAxis == axis)
            {
                rollAxis = -1;
            }
            if (pitchAxis == axis)
            {
                pitchAxis = -1;
            }
            if (yawAxis == axis)
            {
                yawAxis = -1;
            }
            if (throttleAxis == axis)
            {
                throttleAxis = -1;
            }
            break;
    }
}

void JoystickInput::setAxisInversion(int axis, bool inverted)
{
    if (axis < joystickAxesInverted.size())
    {
        joystickAxesInverted[axis] = inverted;
    }
}

358 359 360 361 362 363 364 365
void JoystickInput::setAxisRangeLimit(int axis, bool rangeLimited)
{
    if (axis < joystickAxesRangeLimited.size())
    {
        joystickAxesRangeLimited[axis] = rangeLimited;
    }
}

366
float JoystickInput::getCurrentValueForAxis(int axis)
367
{
368
    if (axis < joystickAxes.size())
369
    {
370
        return joystickAxes[axis];
371 372
    }
    return 0.0f;
373
}