Joystick.cc 17.8 KB
Newer Older
1 2 3 4 5 6 7 8 9
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

10 11 12 13 14 15 16 17 18

#include "Joystick.h"
#include "QGC.h"
#include "AutoPilotPlugin.h"
#include "UAS.h"

#include <QSettings>

QGC_LOGGING_CATEGORY(JoystickLog, "JoystickLog")
19
QGC_LOGGING_CATEGORY(JoystickValuesLog, "JoystickValuesLog")
20 21 22

const char* Joystick::_settingsGroup =              "Joysticks";
const char* Joystick::_calibratedSettingsKey =      "Calibrated";
Don Gagne's avatar
Don Gagne committed
23
const char* Joystick::_buttonActionSettingsKey =    "ButtonActionName%1";
24 25 26 27 28 29 30 31 32
const char* Joystick::_throttleModeSettingsKey =    "ThrottleMode";

const char* Joystick::_rgFunctionSettingsKey[Joystick::maxFunction] = {
    "RollAxis",
    "PitchAxis",
    "YawAxis",
    "ThrottleAxis"
};

33
Joystick::Joystick(const QString& name, int axisCount, int buttonCount, int hatCount, MultiVehicleManager* multiVehicleManager)
Gregory Dymarek's avatar
Gregory Dymarek committed
34
    : _exitThread(false)
35 36 37
    , _name(name)
    , _axisCount(axisCount)
    , _buttonCount(buttonCount)
38 39 40
    , _hatCount(hatCount)
    , _hatButtonCount(4*hatCount)
    , _totalButtonCount(_buttonCount+_hatButtonCount)
Don Gagne's avatar
Don Gagne committed
41
    , _calibrationMode(CalibrationModeOff)
42 43 44
    , _rgAxisValues(NULL)
    , _rgCalibration(NULL)
    , _rgButtonValues(NULL)
45 46
    , _lastButtonBits(0)
    , _throttleMode(ThrottleModeCenterZero)
47 48
    , _activeVehicle(NULL)
    , _pollingStartedForCalibration(false)
49
    , _multiVehicleManager(multiVehicleManager)
50
{
51

52 53
    _rgAxisValues = new int[_axisCount];
    _rgCalibration = new Calibration_t[_axisCount];
54
    _rgButtonValues = new bool[_totalButtonCount];
55 56

    for (int i=0; i<_axisCount; i++) {
57 58
        _rgAxisValues[i] = 0;
    }
59
    for (int i=0; i<_totalButtonCount; i++) {
60 61
        _rgButtonValues[i] = false;
    }
62

63 64 65 66 67
    _loadSettings();
}

Joystick::~Joystick()
{
68 69 70
    delete _rgAxisValues;
    delete _rgCalibration;
    delete _rgButtonValues;
71 72 73 74 75
}

void Joystick::_loadSettings(void)
{
    QSettings   settings;
76

77 78
    settings.beginGroup(_settingsGroup);
    settings.beginGroup(_name);
79

80 81
    bool badSettings = false;
    bool convertOk;
82

83
    qCDebug(JoystickLog) << "_loadSettings " << _name;
84

85
    _calibrated = settings.value(_calibratedSettingsKey, false).toBool();
86

87 88
    _throttleMode = (ThrottleMode_t)settings.value(_throttleModeSettingsKey, ThrottleModeCenterZero).toInt(&convertOk);
    badSettings |= !convertOk;
89

90
    qCDebug(JoystickLog) << "_loadSettings calibrated:throttlemode:badsettings" << _calibrated << _throttleMode << badSettings;
91

92 93 94 95
    QString minTpl  ("Axis%1Min");
    QString maxTpl  ("Axis%1Max");
    QString trimTpl ("Axis%1Trim");
    QString revTpl  ("Axis%1Rev");
96

97
    for (int axis=0; axis<_axisCount; axis++) {
98
        Calibration_t* calibration = &_rgCalibration[axis];
99

100 101
        calibration->center = settings.value(trimTpl.arg(axis), 0).toInt(&convertOk);
        badSettings |= !convertOk;
102

103 104
        calibration->min = settings.value(minTpl.arg(axis), -32768).toInt(&convertOk);
        badSettings |= !convertOk;
105

106
        calibration->max = settings.value(maxTpl.arg(axis), 32767).toInt(&convertOk);
107
        badSettings |= !convertOk;
108

109
        calibration->reversed = settings.value(revTpl.arg(axis), false).toBool();
110

111 112
        qCDebug(JoystickLog) << "_loadSettings axis:min:max:trim:reversed:badsettings" << axis << calibration->min << calibration->max << calibration->center << calibration->reversed << badSettings;
    }
113

114 115
    for (int function=0; function<maxFunction; function++) {
        int functionAxis;
116

117 118
        functionAxis = settings.value(_rgFunctionSettingsKey[function], -1).toInt(&convertOk);
        badSettings |= !convertOk || (functionAxis == -1);
119

120
        _rgFunctionAxis[function] = functionAxis;
121

122 123
        qCDebug(JoystickLog) << "_loadSettings function:axis:badsettings" << function << functionAxis << badSettings;
    }
124

Don Gagne's avatar
Don Gagne committed
125
    for (int button=0; button<_totalButtonCount; button++) {
126
        _rgButtonActions << settings.value(QString(_buttonActionSettingsKey).arg(button), QString()).toString();
Don Gagne's avatar
Don Gagne committed
127
        qCDebug(JoystickLog) << "_loadSettings button:action" << button << _rgButtonActions[button];
128
    }
129

130 131 132 133 134 135 136 137 138
    if (badSettings) {
        _calibrated = false;
        settings.setValue(_calibratedSettingsKey, false);
    }
}

void Joystick::_saveSettings(void)
{
    QSettings settings;
139

140 141
    settings.beginGroup(_settingsGroup);
    settings.beginGroup(_name);
142

143 144
    settings.setValue(_calibratedSettingsKey, _calibrated);
    settings.setValue(_throttleModeSettingsKey, _throttleMode);
145

146
    qCDebug(JoystickLog) << "_saveSettings calibrated:throttlemode" << _calibrated << _throttleMode;
147 148 149 150 151

    QString minTpl  ("Axis%1Min");
    QString maxTpl  ("Axis%1Max");
    QString trimTpl ("Axis%1Trim");
    QString revTpl  ("Axis%1Rev");
152

153
    for (int axis=0; axis<_axisCount; axis++) {
154
        Calibration_t* calibration = &_rgCalibration[axis];
155

156 157 158 159
        settings.setValue(trimTpl.arg(axis), calibration->center);
        settings.setValue(minTpl.arg(axis), calibration->min);
        settings.setValue(maxTpl.arg(axis), calibration->max);
        settings.setValue(revTpl.arg(axis), calibration->reversed);
160

161 162 163 164 165 166 167 168
        qCDebug(JoystickLog) << "_saveSettings name:axis:min:max:trim:reversed"
                                << _name
                                << axis
                                << calibration->min
                                << calibration->max
                                << calibration->center
                                << calibration->reversed;
    }
169

170 171 172 173
    for (int function=0; function<maxFunction; function++) {
        settings.setValue(_rgFunctionSettingsKey[function], _rgFunctionAxis[function]);
        qCDebug(JoystickLog) << "_saveSettings name:function:axis" << _name << function << _rgFunctionSettingsKey[function];
    }
174

Don Gagne's avatar
Don Gagne committed
175
    for (int button=0; button<_totalButtonCount; button++) {
176 177 178 179 180 181 182 183 184 185 186
        settings.setValue(QString(_buttonActionSettingsKey).arg(button), _rgButtonActions[button]);
        qCDebug(JoystickLog) << "_saveSettings button:action" << button << _rgButtonActions[button];
    }
}

/// Adjust the raw axis value to the -1:1 range given calibration information
float Joystick::_adjustRange(int value, Calibration_t calibration)
{
    float valueNormalized;
    float axisLength;
    float axisBasis;
187

188 189 190 191 192 193 194 195 196
    if (value > calibration.center) {
        axisBasis = 1.0f;
        valueNormalized = value - calibration.center;
        axisLength =  calibration.max - calibration.center;
    } else {
        axisBasis = -1.0f;
        valueNormalized = calibration.center - value;
        axisLength =  calibration.center - calibration.min;
    }
197

198
    float axisPercent = valueNormalized / axisLength;
199

200
    float correctedValue = axisBasis * axisPercent;
201

202 203 204
    if (calibration.reversed) {
        correctedValue *= -1.0f;
    }
205

206 207 208 209 210 211 212 213 214 215 216 217 218
#if 0
    qCDebug(JoystickLog) << "_adjustRange corrected:value:min:max:center:reversed:basis:normalized:length"
                            << correctedValue
                            << value
                            << calibration.min
                            << calibration.max
                            << calibration.center
                            << calibration.center
                            << axisBasis
                            << valueNormalized
                            << axisLength;
#endif

219
    return std::max(-1.0f, std::min(correctedValue, 1.0f));
220 221 222 223 224
}


void Joystick::run(void)
{
Gregory Dymarek's avatar
Gregory Dymarek committed
225
    _open();
226

227
    while (!_exitThread) {
Gregory Dymarek's avatar
Gregory Dymarek committed
228
    _update();
229 230 231

        // Update axes
        for (int axisIndex=0; axisIndex<_axisCount; axisIndex++) {
Gregory Dymarek's avatar
Gregory Dymarek committed
232
            int newAxisValue = _getAxis(axisIndex);
233 234 235 236
            // Calibration code requires signal to be emitted even if value hasn't changed
            _rgAxisValues[axisIndex] = newAxisValue;
            emit rawAxisValueChanged(axisIndex, newAxisValue);
        }
237

238 239
        // Update buttons
        for (int buttonIndex=0; buttonIndex<_buttonCount; buttonIndex++) {
Gregory Dymarek's avatar
Gregory Dymarek committed
240
            bool newButtonValue = _getButton(buttonIndex);
241 242 243 244 245
            if (newButtonValue != _rgButtonValues[buttonIndex]) {
                _rgButtonValues[buttonIndex] = newButtonValue;
                emit rawButtonPressedChanged(buttonIndex, newButtonValue);
            }
        }
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

        // Update hat - append hat buttons to the end of the normal button list
        int numHatButtons = 4;
        for (int hatIndex=0; hatIndex<_hatCount; hatIndex++) {
            for (int hatButtonIndex=0; hatButtonIndex<numHatButtons; hatButtonIndex++) {
                // Create new index value that includes the normal button list
                int rgButtonValueIndex = hatIndex*numHatButtons + hatButtonIndex + _buttonCount;
                // Get hat value from joystick
                bool newButtonValue = _getHat(hatIndex,hatButtonIndex);
                if (newButtonValue != _rgButtonValues[rgButtonValueIndex]) {
                    _rgButtonValues[rgButtonValueIndex] = newButtonValue;
                    emit rawButtonPressedChanged(rgButtonValueIndex, newButtonValue);
                }
            }
        }
261

Don Gagne's avatar
Don Gagne committed
262
        if (_calibrationMode != CalibrationModeCalibrating) {
263 264
            int     axis = _rgFunctionAxis[rollFunction];
            float   roll = _adjustRange(_rgAxisValues[axis], _rgCalibration[axis]);
265

266 267
                    axis = _rgFunctionAxis[pitchFunction];
            float   pitch = _adjustRange(_rgAxisValues[axis], _rgCalibration[axis]);
268

269 270
                    axis = _rgFunctionAxis[yawFunction];
            float   yaw = _adjustRange(_rgAxisValues[axis], _rgCalibration[axis]);
271

272 273 274
                    axis = _rgFunctionAxis[throttleFunction];
            float   throttle = _adjustRange(_rgAxisValues[axis], _rgCalibration[axis]);

275 276 277 278 279
            float roll_limited = std::max(static_cast<float>(-M_PI_4), std::min(roll, static_cast<float>(M_PI_4)));
            float pitch_limited = std::max(static_cast<float>(-M_PI_4), std::min(pitch, static_cast<float>(M_PI_4)));
            float yaw_limited = std::max(static_cast<float>(-M_PI_4), std::min(yaw, static_cast<float>(M_PI_4)));
            float throttle_limited = std::max(static_cast<float>(-M_PI_4), std::min(throttle, static_cast<float>(M_PI_4)));

280
            // Map from unit circle to linear range and limit
281 282 283 284
            roll =      std::max(-1.0f, std::min(tanf(asinf(roll_limited)), 1.0f));
            pitch =     std::max(-1.0f, std::min(tanf(asinf(pitch_limited)), 1.0f));
            yaw =       std::max(-1.0f, std::min(tanf(asinf(yaw_limited)), 1.0f));
            throttle =  std::max(-1.0f, std::min(tanf(asinf(throttle_limited)), 1.0f));
285

286
            // Adjust throttle to 0:1 range
287
            if (_throttleMode == ThrottleModeCenterZero && _activeVehicle->supportsThrottleModeCenterZero()) {
288
                throttle = std::max(0.0f, throttle);
289
            } else {
290 291
                throttle = (throttle + 1.0f) / 2.0f;
            }
292

293
            // Set up button pressed information
294

295
            // We only send the buttons the firmwware has reserved
296
            int reservedButtonCount = _activeVehicle->manualControlReservedButtonCount();
297
            if (reservedButtonCount == -1) {
298
                reservedButtonCount = _totalButtonCount;
299
            }
300

301 302
            quint16 newButtonBits = 0;      // New set of button which are down
            quint16 buttonPressedBits = 0;  // Buttons pressed for manualControl signal
303

304
            for (int buttonIndex=0; buttonIndex<_totalButtonCount; buttonIndex++) {
305
                quint16 buttonBit = 1 << buttonIndex;
306

307 308
                if (!_rgButtonValues[buttonIndex]) {
                    // Button up, just record it
309 310 311
                    newButtonBits |= buttonBit;
                } else {
                    if (_lastButtonBits & buttonBit) {
312
                        // Button was up last time through, but is now down which indicates a button press
313
                        qCDebug(JoystickLog) << "button triggered" << buttonIndex;
314

315 316
                        if (buttonIndex >= reservedButtonCount) {
                            // Button is above firmware reserved set
Don Gagne's avatar
Don Gagne committed
317 318 319
                            QString buttonAction =_rgButtonActions[buttonIndex];
                            if (!buttonAction.isEmpty()) {
                                _buttonAction(buttonAction);
320 321 322
                            }
                        }
                    }
323 324

                    // Mark the button as pressed as long as its pressed
325
                    buttonPressedBits |= buttonBit;
326 327
                }
            }
328

329
            _lastButtonBits = newButtonBits;
330

331
            qCDebug(JoystickValuesLog) << "name:roll:pitch:yaw:throttle" << name() << roll << -pitch << yaw << throttle;
332

333
            emit manualControl(roll, -pitch, yaw, throttle, buttonPressedBits, _activeVehicle->joystickMode());
334
        }
335

336 337 338
        // Sleep, update rate of joystick is approx. 25 Hz (1000 ms / 25 = 40 ms)
        QGC::SLEEP::msleep(40);
    }
339

Gregory Dymarek's avatar
Gregory Dymarek committed
340
    _close();
341 342
}

343
void Joystick::startPolling(Vehicle* vehicle)
344
{
345 346 347 348 349 350
    if (vehicle) {

        // If a vehicle is connected, disconnect it
        if (_activeVehicle) {
            UAS* uas = _activeVehicle->uas();
            disconnect(this, &Joystick::manualControl, uas, &UAS::setExternalControlSetpoint);
351
        }
352 353

        // Always set up the new vehicle
354
        _activeVehicle = vehicle;
355 356 357 358 359 360 361 362 363 364 365 366 367 368

        // Only connect the new vehicle if it wants joystick data
        if (vehicle->joystickEnabled()) {
            _pollingStartedForCalibration = false;

            UAS* uas = _activeVehicle->uas();
            connect(this, &Joystick::manualControl, uas, &UAS::setExternalControlSetpoint);
            // FIXME: ****
            //connect(this, &Joystick::buttonActionTriggered, uas, &UAS::triggerAction);
        }
    }


    if (!isRunning()) {
369 370
        _exitThread = false;
        start();
371 372 373 374 375
    }
}

void Joystick::stopPolling(void)
{
376
    if (isRunning()) {
377 378 379 380 381 382

        if (_activeVehicle && _activeVehicle->joystickEnabled()) {
            UAS* uas = _activeVehicle->uas();

            disconnect(this, &Joystick::manualControl,          uas, &UAS::setExternalControlSetpoint);
        }
Don Gagne's avatar
Don Gagne committed
383 384
        // FIXME: ****
        //disconnect(this, &Joystick::buttonActionTriggered,  uas, &UAS::triggerAction);
385

386 387
        _exitThread = true;
        }
388 389 390 391
}

void Joystick::setCalibration(int axis, Calibration_t& calibration)
{
392
    if (!_validAxis(axis)) {
393 394 395
        qCWarning(JoystickLog) << "Invalid axis index" << axis;
        return;
    }
396

397 398 399 400 401 402 403 404
    _calibrated = true;
    _rgCalibration[axis] = calibration;
    _saveSettings();
    emit calibratedChanged(_calibrated);
}

Joystick::Calibration_t Joystick::getCalibration(int axis)
{
405
    if (!_validAxis(axis)) {
406 407
        qCWarning(JoystickLog) << "Invalid axis index" << axis;
    }
408

409 410 411 412 413
    return _rgCalibration[axis];
}

void Joystick::setFunctionAxis(AxisFunction_t function, int axis)
{
414
    if (!_validAxis(axis)) {
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
        qCWarning(JoystickLog) << "Invalid axis index" << axis;
        return;
    }

    _calibrated = true;
    _rgFunctionAxis[function] = axis;
    _saveSettings();
    emit calibratedChanged(_calibrated);
}

int Joystick::getFunctionAxis(AxisFunction_t function)
{
    if (function < 0 || function >= maxFunction) {
        qCWarning(JoystickLog) << "Invalid function" << function;
    }

    return _rgFunctionAxis[function];
}

QStringList Joystick::actions(void)
{
    QStringList list;
Don Gagne's avatar
Don Gagne committed
437 438

    list << "Arm" << "Disarm";
439 440 441 442

    if (_activeVehicle) {
        list << _activeVehicle->flightModes();
    }
443

444 445 446
    return list;
}

Don Gagne's avatar
Don Gagne committed
447
void Joystick::setButtonAction(int button, const QString& action)
448
{
449
    if (!_validButton(button)) {
450 451 452
        qCWarning(JoystickLog) << "Invalid button index" << button;
        return;
    }
453

Don Gagne's avatar
Don Gagne committed
454
    qDebug() << "setButtonAction" << action;
455

456 457 458 459 460
    _rgButtonActions[button] = action;
    _saveSettings();
    emit buttonActionsChanged(buttonActions());
}

Don Gagne's avatar
Don Gagne committed
461
QString Joystick::getButtonAction(int button)
462
{
463
    if (!_validButton(button)) {
464 465
        qCWarning(JoystickLog) << "Invalid button index" << button;
    }
466

467 468 469 470 471 472
    return _rgButtonActions[button];
}

QVariantList Joystick::buttonActions(void)
{
    QVariantList list;
473

Don Gagne's avatar
Don Gagne committed
474
    for (int button=0; button<_totalButtonCount; button++) {
475 476
        list += QVariant::fromValue(_rgButtonActions[button]);
    }
477

478 479 480 481 482 483 484 485 486 487 488 489 490 491
    return list;
}

int Joystick::throttleMode(void)
{
    return _throttleMode;
}

void Joystick::setThrottleMode(int mode)
{
    if (mode < 0 || mode >= ThrottleModeMax) {
        qCWarning(JoystickLog) << "Invalid throttle mode" << mode;
        return;
    }
492

493 494 495 496 497
    _throttleMode = (ThrottleMode_t)mode;
    _saveSettings();
    emit throttleModeChanged(_throttleMode);
}

Don Gagne's avatar
Don Gagne committed
498
void Joystick::startCalibrationMode(CalibrationMode_t mode)
499
{
Don Gagne's avatar
Don Gagne committed
500 501 502 503
    if (mode == CalibrationModeOff) {
        qWarning() << "Incorrect mode CalibrationModeOff";
        return;
    }
504

Don Gagne's avatar
Don Gagne committed
505
    _calibrationMode = mode;
506

507 508
    if (!isRunning()) {
        _pollingStartedForCalibration = true;
509
        startPolling(_multiVehicleManager->activeVehicle());
510
    }
511 512
}

Don Gagne's avatar
Don Gagne committed
513
void Joystick::stopCalibrationMode(CalibrationMode_t mode)
514
{
Don Gagne's avatar
Don Gagne committed
515 516 517 518
    if (mode == CalibrationModeOff) {
        qWarning() << "Incorrect mode: CalibrationModeOff";
        return;
    }
519

Don Gagne's avatar
Don Gagne committed
520 521 522 523
    if (mode == CalibrationModeCalibrating) {
        _calibrationMode = CalibrationModeMonitor;
    } else {
        _calibrationMode = CalibrationModeOff;
524 525 526
        if (_pollingStartedForCalibration) {
            stopPolling();
        }
527 528
    }
}
529

Don Gagne's avatar
Don Gagne committed
530 531
void Joystick::_buttonAction(const QString& action)
{
532 533 534 535
    if (!_activeVehicle || !_activeVehicle->joystickEnabled()) {
        return;
    }

Don Gagne's avatar
Don Gagne committed
536 537 538 539
    if (action == "Arm") {
        _activeVehicle->setArmed(true);
    } else if (action == "Disarm") {
        _activeVehicle->setArmed(false);
540 541
    } else if (_activeVehicle->flightModes().contains(action)) {
        _activeVehicle->setFlightMode(action);
Don Gagne's avatar
Don Gagne committed
542 543 544 545 546
    } else {
        qCDebug(JoystickLog) << "_buttonAction unknown action:" << action;
    }
}

547 548 549 550 551 552 553
bool Joystick::_validAxis(int axis)
{
    return axis >= 0 && axis < _axisCount;
}

bool Joystick::_validButton(int button)
{
554
    return button >= 0 && button < _totalButtonCount;
555 556
}