JoystickInput.cc 8.82 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 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/*=====================================================================

PIXHAWK Micro Air Vehicle Flying Robotics Toolkit

(c) 2009, 2010 PIXHAWK PROJECT  <http://pixhawk.ethz.ch>

This file is part of the PIXHAWK project

    PIXHAWK is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    PIXHAWK is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with PIXHAWK. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @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"
39
#include "QGC.h"
40
#include <QMutexLocker>
pixhawk's avatar
pixhawk committed
41 42 43 44 45 46

/**
 * 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() :
47 48 49 50 51 52
    sdlJoystickMin(-32768.0f),
    sdlJoystickMax(32767.0f),
    defaultIndex(0),
    uas(NULL),
    uasButtonList(QList<int>()),
    done(false),
53 54 55 56
    thrustAxis(2),
    xAxis(0),
    yAxis(1),
    yawAxis(3),
57
    joystickName(tr("Unitinialized"))
pixhawk's avatar
pixhawk committed
58
{
59
    for (int i = 0; i < 10; i++) {
pixhawk's avatar
pixhawk committed
60 61 62 63 64 65 66
        calibrationPositive[i] = sdlJoystickMax;
        calibrationNegative[i] = sdlJoystickMin;
    }

    connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setActiveUAS(UASInterface*)));

    // Enter main loop
67
    //start();
pixhawk's avatar
pixhawk committed
68 69
}

70 71 72 73 74 75 76 77 78 79 80
JoystickInput::~JoystickInput()
{
	{
		QMutexLocker locker(&this->m_doneMutex);
		done = true;
	}
	this->wait();
	this->deleteLater();
}


pixhawk's avatar
pixhawk committed
81 82 83 84
void JoystickInput::setActiveUAS(UASInterface* uas)
{
    // Only connect / disconnect is the UAS is of a controllable UAS class
    UAS* tmp = 0;
85
    if (this->uas) {
pixhawk's avatar
pixhawk committed
86
        tmp = dynamic_cast<UAS*>(this->uas);
87
        if(tmp) {
pixhawk's avatar
pixhawk committed
88 89 90 91 92 93 94 95
            disconnect(this, SIGNAL(joystickChanged(double,double,double,double,int,int)), tmp, SLOT(setManualControlCommands(double,double,double,double)));
            disconnect(this, SIGNAL(buttonPressed(int)), tmp, SLOT(receiveButton(int)));
        }
    }

    this->uas = uas;

    tmp = dynamic_cast<UAS*>(this->uas);
96
    if(tmp) {
pixhawk's avatar
pixhawk committed
97 98 99
        connect(this, SIGNAL(joystickChanged(double,double,double,double,int,int)), tmp, SLOT(setManualControlCommands(double,double,double,double)));
        connect(this, SIGNAL(buttonPressed(int)), tmp, SLOT(receiveButton(int)));
    }
100
    if (!isRunning()) {
101 102
        start();
    }
pixhawk's avatar
pixhawk committed
103 104 105 106 107
}

void JoystickInput::init()
{
    // INITIALIZE SDL Joystick support
108
    if (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE) < 0) {
pixhawk's avatar
pixhawk committed
109 110 111 112 113 114 115
        printf("Couldn't initialize SimpleDirectMediaLayer: %s\n", SDL_GetError());
    }

    // Enumerate joysticks and select one
    int numJoysticks = SDL_NumJoysticks();

    // Wait for joysticks if none is connected
116
    while (numJoysticks == 0) {
117
        MG::SLEEP::msleep(200);
pixhawk's avatar
pixhawk committed
118
        // INITIALIZE SDL Joystick support
119
        if (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE) < 0) {
pixhawk's avatar
pixhawk committed
120 121 122 123 124 125
            printf("Couldn't initialize SimpleDirectMediaLayer: %s\n", SDL_GetError());
        }
        numJoysticks = SDL_NumJoysticks();
    }

    printf("%d Input devices found:\n", numJoysticks);
126
    for(int i=0; i < SDL_NumJoysticks(); i++ ) {
pixhawk's avatar
pixhawk committed
127
        printf("\t- %s\n", SDL_JoystickName(i));
128
        joystickName = QString(SDL_JoystickName(i));
pixhawk's avatar
pixhawk committed
129 130 131 132 133 134 135
    }

    printf("\nOpened %s\n", SDL_JoystickName(defaultIndex));

    SDL_JoystickEventState(SDL_ENABLE);

    joystick = SDL_JoystickOpen(defaultIndex);
136 137 138

    // Make sure active UAS is set
    setActiveUAS(UASManager::instance()->getActiveUAS());
pixhawk's avatar
pixhawk committed
139 140 141 142 143 144 145 146 147 148
}

/**
 * @brief Execute the Joystick process
 */
void JoystickInput::run()
{

    init();

149 150 151 152 153 154 155 156 157 158
    forever
	{
		{
			QMutexLocker locker(&this->m_doneMutex);
			if(done)
			{
				done = false;
				break;
			}
		}
159
        while(SDL_PollEvent(&event)) {
pixhawk's avatar
pixhawk committed
160 161 162 163

            SDL_JoystickUpdate();

            // Todo check if it would be more beneficial to use the event structure
164
            switch(event.type) {
pixhawk's avatar
pixhawk committed
165 166
            case SDL_KEYDOWN:
                /* handle keyboard stuff here */
167
                //qDebug() << "KEY PRESSED!";
pixhawk's avatar
pixhawk committed
168 169 170 171 172 173 174 175
                break;

            case SDL_QUIT:
                /* Set whatever flags are necessary to */
                /* end the main loop here */
                break;

            case SDL_JOYBUTTONDOWN:  /* Handle Joystick Button Presses */
176
                if ( event.jbutton.button == 0 ) {
177
                    //qDebug() << "BUTTON PRESSED!";
pixhawk's avatar
pixhawk committed
178 179 180 181
                }
                break;

            case SDL_JOYAXISMOTION:  /* Handle Joystick Motion */
182 183
                if ( ( event.jaxis.value < -3200 ) || (event.jaxis.value > 3200 ) ) {
                    if( event.jaxis.axis == 0) {
pixhawk's avatar
pixhawk committed
184 185 186
                        /* Left-right movement code goes here */
                    }

187
                    if( event.jaxis.axis == 1) {
pixhawk's avatar
pixhawk committed
188 189 190 191 192 193
                        /* Up-Down movement code goes here */
                    }
                }
                break;

            default:
194
                //qDebug() << "SDL event occured";
pixhawk's avatar
pixhawk committed
195 196 197 198 199
                break;
            }
        }

        // Display all axes
200
        for(int i = 0; i < SDL_JoystickNumAxes(joystick); i++) {
pixhawk's avatar
pixhawk committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
            //qDebug() << "\rAXIS" << i << "is: " << SDL_JoystickGetAxis(joystick, i);
        }

        // THRUST
        double thrust = ((double)SDL_JoystickGetAxis(joystick, thrustAxis) - calibrationNegative[thrustAxis]) / (calibrationPositive[thrustAxis] - calibrationNegative[thrustAxis]);
        // Has to be inverted for Logitech Wingman
        thrust = 1.0f - thrust;
        // Bound rounding errors
        if (thrust > 1) thrust = 1;
        if (thrust < 0) thrust = 0;
        emit thrustChanged((float)thrust);

        // X Axis
        double x = ((double)SDL_JoystickGetAxis(joystick, xAxis) - calibrationNegative[xAxis]) / (calibrationPositive[xAxis] - calibrationNegative[xAxis]);
        x = 1.0f - x;
        x = x * 2.0f - 1.0f;
        // Bound rounding errors
        if (x > 1.0f) x = 1.0f;
        if (x < -1.0f) x = -1.0f;
        emit xChanged((float)x);

        // Y Axis
        double y = ((double)SDL_JoystickGetAxis(joystick, yAxis) - calibrationNegative[yAxis]) / (calibrationPositive[yAxis] - calibrationNegative[yAxis]);
        y = 1.0f - y;
        y = y * 2.0f - 1.0f;
        // Bound rounding errors
        if (y > 1.0f) y = 1.0f;
        if (y < -1.0f) y = -1.0f;
        emit yChanged((float)y);

        // Yaw Axis

        double yaw = ((double)SDL_JoystickGetAxis(joystick, yawAxis) - calibrationNegative[yawAxis]) / (calibrationPositive[yawAxis] - calibrationNegative[yawAxis]);
        yaw = 1.0f - yaw;
        yaw = yaw * 2.0f - 1.0f;
        // Bound rounding errors
        if (yaw > 1.0f) yaw = 1.0f;
        if (yaw < -1.0f) yaw = -1.0f;
        emit yawChanged((float)yaw);

        // Get joystick hat position, convert it to vector
        int hatPosition = SDL_JoystickGetHat(joystick, 0);

        int xHat,yHat;
        xHat = 0;
        yHat = 0;

        // Build up vectors describing the hat position
        //
        // Coordinate frame for joystick hat:
        //
        //    y
        //    ^
        //    |
        //    |
        //    0 ----> x
        //

        if ((SDL_HAT_UP & hatPosition) > 0) yHat = 1;
        if ((SDL_HAT_DOWN & hatPosition) > 0) yHat = -1;

        if ((SDL_HAT_LEFT & hatPosition) > 0) xHat = -1;
        if ((SDL_HAT_RIGHT & hatPosition) > 0) xHat = 1;

        // Send new values to rest of groundstation
        emit hatDirectionChanged(xHat, yHat);
        emit joystickChanged(y, x, yaw, thrust, xHat, yHat);


        // Display all buttons
271
        for(int i = 0; i < SDL_JoystickNumButtons(joystick); i++) {
pixhawk's avatar
pixhawk committed
272
            //qDebug() << "BUTTON" << i << "is: " << SDL_JoystickGetAxis(joystick, i);
273
            if(SDL_JoystickGetButton(joystick, i)) {
pixhawk's avatar
pixhawk committed
274 275 276
                emit buttonPressed(i);
                // Check if button is a UAS select button

277
                if (uasButtonList.contains(i)) {
pixhawk's avatar
pixhawk committed
278
                    UASInterface* uas = UASManager::instance()->getUASForId(i);
279
                    if (uas) {
pixhawk's avatar
pixhawk committed
280 281 282 283 284 285 286 287
                        UASManager::instance()->setActiveUAS(uas);
                    }
                }
            }

        }

        // Sleep, update rate of joystick is approx. 50 Hz (1000 ms / 50 = 20 ms)
288
        QGC::SLEEP::msleep(20);
pixhawk's avatar
pixhawk committed
289 290 291 292

    }

}
293 294 295 296 297

const QString& JoystickInput::getName()
{
    return joystickName;
}