PX4RCCalibration.cc 34.8 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
/*=====================================================================
 
 QGroundControl Open Source Ground Control Station
 
 (c) 2009, 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 
 This file is part of the QGROUNDCONTROL project
 
 QGROUNDCONTROL 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.
 
 QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
 
 ======================================================================*/


/// @file
///     @brief PX4 RC Calibration Widget
///     @author Don Gagne <don@thegagnes.com

#include <QMessageBox>

#include "PX4RCCalibration.h"
#include "UASManager.h"

Don Gagne's avatar
Don Gagne committed
34
const int PX4RCCalibration::_updateInterval = 150;              ///< Interval for timer which updates radio channel widgets
35
const int PX4RCCalibration::_rcCalPWMCenterPoint = ((PX4RCCalibration::_rcCalPWMValidMaxValue - PX4RCCalibration::_rcCalPWMValidMinValue) / 2.0f) + PX4RCCalibration::_rcCalPWMValidMinValue;
Don Gagne's avatar
Don Gagne committed
36 37 38 39 40 41 42 43
const int PX4RCCalibration::_rcCalPWMValidMinValue = 1300;      ///< Largest valid minimum PWM Min range value
const int PX4RCCalibration::_rcCalPWMValidMaxValue = 1700;      ///< Smallest valid maximum PWM Max range value
const int PX4RCCalibration::_rcCalPWMDefaultMinValue = 1000;    ///< Default value for Min if not set
const int PX4RCCalibration::_rcCalPWMDefaultMaxValue = 2000;    ///< Default value for Max if not set
const int PX4RCCalibration::_rcCalPWMDefaultTrimValue = PX4RCCalibration::_rcCalPWMCenterPoint;    ///< Default value for Trim if not set
const int PX4RCCalibration::_rcCalRoughCenterDelta = 200;       ///< Delta around center point which is considered to be roughly centered
const float PX4RCCalibration::_rcCalMoveDelta = 300.0f;         ///< Amount of delta which is considered stick movement
const float PX4RCCalibration::_rcCalMinDelta = 100.0f;          ///< Amount of delta allowed around min value to consider channel at min
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

const struct PX4RCCalibration::FunctionInfo PX4RCCalibration::_rgFunctionInfo[PX4RCCalibration::rcCalFunctionMax] = {
    // Name                  Inversion Message   Parameter          required
    { "Roll / Aileron",     "Move stick left.", "RC_MAP_ROLL",      true },
    { "Pitch / Elevator",   "Move stick down.", "RC_MAP_PITCH",     true },
    { "Yaw / Rudder",       "Move stick left",  "RC_MAP_YAW",       true },
    { "Throttle",           "Move stick down",  "RC_MAP_THROTTLE",  true },
    { "Main Mode Switch",   NULL,               "RC_MAP_MODE_SW",   true },
    { "Posctl switch",      NULL,               "RC_MAP_POSCTL_SW", false },
    { "Loiter Switch",      NULL,               "RC_MAP_LOITER_SW", false },
    { "Return Switch",      NULL,               "RC_MAP_RETURN_SW", false },
    { "Flaps",              NULL,               "RC_MAP_FLAPS",     false },
    { "Aux1",               NULL,               "RC_MAP_AUX1",      false },
    { "Aux2",               NULL,               "RC_MAP_AUX2",      false },
};

PX4RCCalibration::PX4RCCalibration(QWidget *parent) :
    QWidget(parent),
    _chanCount(0),
    _rcCalState(rcCalStateChannelWait),
    _mav(NULL),
Don Gagne's avatar
Don Gagne committed
65 66
    _paramMgr(NULL),
    _parameterListUpToDateSignalled(false),
67 68 69 70 71 72 73
    _ui(new Ui::PX4RCCalibration)
{
    _ui->setupUi(this);
    
    // Initialize arrays of widget control pointers. This allows for more efficient code writing using "for" loops.
    for (int chan=0; chan<_chanMax; chan++) {
        QString radioWidgetName("radio%1Widget");
Don Gagne's avatar
Don Gagne committed
74
        QString radioWidgetUserName("Channel %1");
75
        
Don Gagne's avatar
Don Gagne committed
76
        RCChannelWidget* radioWidget = findChild<RCChannelWidget*>(radioWidgetName.arg(chan+1));
77 78
        Q_ASSERT(radioWidget);
        
Don Gagne's avatar
Don Gagne committed
79
        radioWidget->setTitle(radioWidgetUserName.arg(chan+1));
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

        _rgRadioWidget[chan] = radioWidget;
    }
    
    _setActiveUAS(UASManager::instance()->getActiveUAS());
    
    // Connect signals
    bool fSucceeded;
    Q_UNUSED(fSucceeded);
    
    fSucceeded = connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(_setActiveUAS(UASInterface*)));
    Q_ASSERT(fSucceeded);

    fSucceeded = connect(_ui->spektrumPairButton, SIGNAL(clicked(bool)), this, SLOT(_toggleSpektrumPairing(bool)));
    Q_ASSERT(fSucceeded);
    
    _updateTimer.setInterval(150);
    _updateTimer.start();
    fSucceeded = connect(&_updateTimer, SIGNAL(timeout()), this, SLOT(_updateView()));
    Q_ASSERT(fSucceeded);

    fSucceeded= connect(_ui->rcCalCancel, SIGNAL(clicked(void)), this, SLOT(_rcCalCancel(void)));
    Q_ASSERT(fSucceeded);

    fSucceeded= connect(_ui->rcCalSkip, SIGNAL(clicked(void)), this, SLOT(_rcCalSkip(void)));
    Q_ASSERT(fSucceeded);

    fSucceeded= connect(_ui->rcCalTryAgain, SIGNAL(clicked(void)), this, SLOT(_rcCalTryAgain(void)));
    Q_ASSERT(fSucceeded);

    fSucceeded= connect(_ui->rcCalNext, SIGNAL(clicked(void)), this, SLOT(_rcCalNext(void)));
    Q_ASSERT(fSucceeded);
    
    _rcCalChannelWait(true);
}

/// @brief Resets internal calibration values to their initial state in preparation for a new calibration sequence.
void PX4RCCalibration::_resetInternalCalibrationValues(void)
{
    // Set all raw channels to not reversed and center point values
    for (size_t i=0; i<_chanMax; i++) {
        struct ChannelInfo* info = &_rgChannelInfo[i];
        info->function = rcCalFunctionMax;
        info->reversed = false;
        info->rcMin = PX4RCCalibration::_rcCalPWMCenterPoint;
        info->rcMax = PX4RCCalibration::_rcCalPWMCenterPoint;
        info->rcTrim = PX4RCCalibration::_rcCalPWMCenterPoint;
    }
    
    // Initialize function mapping to function channel not set
    for (size_t i=0; i<rcCalFunctionMax; i++) {
        _rgFunctionChannelMapping[i] = _chanMax;
    }
    
    _showMinMaxOnRadioWidgets(false);
Don Gagne's avatar
Don Gagne committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    _showTrimOnRadioWidgets(false);
}

/// @brief Resets internal calibration values to their initial state in preparation for a new calibration sequence.
void PX4RCCalibration::_setInternalCalibrationValuesFromParameters(void)
{
    Q_ASSERT(_paramMgr);
    
    if (_parameterListUpToDateSignalled) {
        // Initialize all function mappings to not set
        
        for (size_t i=0; i<_chanMax; i++) {
            struct ChannelInfo* info = &_rgChannelInfo[i];
            info->function = rcCalFunctionMax;
        }
        
        for (size_t i=0; i<rcCalFunctionMax; i++) {
            _rgFunctionChannelMapping[i] = _chanMax;
        }
        
        // FIXME: Hardwired component id
        
        // Pull parameters and update
        
        QString minTpl("RC%1_MIN");
        QString maxTpl("RC%1_MAX");
        QString trimTpl("RC%1_TRIM");
        QString revTpl("RC%1_REV");
        QVariant value;
        bool paramFound;
        bool convertOk;
        
        for (int i = 0; i < _chanMax; ++i) {
            struct ChannelInfo* info = &_rgChannelInfo[i];
            
            paramFound = _paramMgr->getParameterValue(50, trimTpl.arg(i+1), value);
            Q_ASSERT(paramFound);
            if (paramFound) {
                info->rcTrim = value.toInt(&convertOk);
                Q_ASSERT(convertOk);
            }
            
            paramFound = _paramMgr->getParameterValue(50, minTpl.arg(i+1), value);
            Q_ASSERT(paramFound);
            if (paramFound) {
                info->rcMin = value.toInt(&convertOk);
                Q_ASSERT(convertOk);
            }

            paramFound = _paramMgr->getParameterValue(50, maxTpl.arg(i+1), value);
            Q_ASSERT(paramFound);
            if (paramFound) {
                info->rcMax = value.toInt(&convertOk);
                Q_ASSERT(convertOk);
            }

            paramFound = _paramMgr->getParameterValue(50, revTpl.arg(i+1), value);
            Q_ASSERT(paramFound);
            if (paramFound) {
                float floatReversed = value.toFloat(&convertOk);
                Q_ASSERT(convertOk);
                Q_ASSERT(floatReversed == 1.0f || floatReversed == -1.0f);
                info->reversed = floatReversed == -1.0f;
            }
        }
        
        for (int i=0; i<rcCalFunctionMax; i++) {
            int32_t paramChannel;
            
            paramFound = _paramMgr->getParameterValue(50, _rgFunctionInfo[i].parameterName, value);
            Q_ASSERT(paramFound);
            if (paramFound) {
                paramChannel = value.toInt(&convertOk);
                Q_ASSERT(convertOk);
                
                if (paramChannel != 0) {
                    _rgFunctionChannelMapping[i] = paramChannel - 1;
                    _rgChannelInfo[paramChannel - 1].function = (enum rcCalFunctions)i;
                }
            }
        }
        
        _showMinMaxOnRadioWidgets(true);
        _showTrimOnRadioWidgets(true);
    }
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
}

/// @brief Sets a connected Spektrum receiver into bind mode
void PX4RCCalibration::_toggleSpektrumPairing(bool enabled)
{
    Q_UNUSED(enabled);
    
    if (!_ui->dsm2RadioButton->isChecked() && !_ui->dsmxRadioButton->isChecked()
        && !_ui->dsmx8RadioButton->isChecked()) {
        // Reject
        QMessageBox warnMsgBox;
        warnMsgBox.setText(tr("Please select a Spektrum Protocol Version"));
        warnMsgBox.setInformativeText(tr("Please select either DSM2 or DSM-X\ndirectly below the pair button,\nbased on the receiver type."));
        warnMsgBox.setStandardButtons(QMessageBox::Ok);
        warnMsgBox.setDefaultButton(QMessageBox::Ok);
        (void)warnMsgBox.exec();
        return;
    }
    
    UASInterface* mav = UASManager::instance()->getActiveUAS();
    if (mav) {
        int rxSubType;
        if (_ui->dsm2RadioButton->isChecked())
            rxSubType = 0;
        else if (_ui->dsmxRadioButton->isChecked())
            rxSubType = 1;
        else // if (_ui->dsmx8RadioButton->isChecked())
            rxSubType = 2;
        mav->pairRX(0, rxSubType);
    }
}

void PX4RCCalibration::_setActiveUAS(UASInterface* active)
{
    // Disconnect old signals
    if (_mav) {
        disconnect(_mav, SIGNAL(remoteControlChannelRawChanged(int,float)), this, SLOT(_remoteControlChannelRawChanged(int,float)));
Don Gagne's avatar
Don Gagne committed
257 258
        disconnect(_paramMgr, SIGNAL(parameterListUpToDate()), this, SLOT(_parameterListUpToDate()));
        _paramMgr = NULL;
259 260 261 262 263 264 265 266 267 268
    }
    
    _mav = active;
    
    if (_mav) {
        // Connect new signals
        bool fSucceeded;
        Q_UNUSED(fSucceeded);
        fSucceeded =  connect(_mav, SIGNAL(remoteControlChannelRawChanged(int,float)), this, SLOT(_remoteControlChannelRawChanged(int,float)));
        Q_ASSERT(fSucceeded);
Don Gagne's avatar
Don Gagne committed
269 270 271 272 273 274
        
        _paramMgr = _mav->getParamManager();
        Q_ASSERT(_paramMgr);

        fSucceeded = connect(_paramMgr, SIGNAL(parameterListUpToDate()), this, SLOT(_parameterListUpToDate()));
        Q_ASSERT(fSucceeded);
275 276 277 278 279
    }

    setEnabled(_mav ? true : false);
}

Don Gagne's avatar
Don Gagne committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
/// @brief Validates the current settings against the calibration rules resetting values as necessary.
void PX4RCCalibration::_validateCalibration(void)
{
    for (int chan = 0; chan<_chanMax; chan++) {
        struct ChannelInfo* info = &_rgChannelInfo[chan];
        
        if (chan < _chanCount) {
            // Validate Min/Max values. Although the channel appears as available we still may
            // not have good min/max/trim values for it. Set to defaults if needed.
            if (info->rcMin > _rcCalPWMValidMinValue || info->rcMax < _rcCalPWMValidMaxValue) {
                info->rcMin = _rcCalPWMDefaultMinValue;
                info->rcMax = _rcCalPWMDefaultMaxValue;
                info->rcTrim = _rcCalPWMDefaultTrimValue;
            }
        } else {
            // Unavailable channels are set to defaults
            info->rcMin = _rcCalPWMDefaultMinValue;
            info->rcMax = _rcCalPWMDefaultMaxValue;
            info->rcTrim = _rcCalPWMDefaultTrimValue;
            info->reversed = false;
        }
    }
}


305 306 307 308 309 310 311 312
/// @brief Saves the rc calibration values to the board parameters.
///     @param trimsOnly true: write only trim values, false: write all calibration values
void PX4RCCalibration::_writeCalibration(bool trimsOnly)
{
    if (!_mav) return;
    
    _mav->endRadioControlCalibration();
    
Don Gagne's avatar
Don Gagne committed
313 314
    _validateCalibration();
    
315 316 317 318 319 320 321 322
    QGCUASParamManagerInterface* paramMgr = _mav->getParamManager();
    Q_ASSERT(paramMgr);
    
    QString minTpl("RC%1_MIN");
    QString maxTpl("RC%1_MAX");
    QString trimTpl("RC%1_TRIM");
    QString revTpl("RC%1_REV");
    
Don Gagne's avatar
Don Gagne committed
323 324 325 326
    for (int chan = 0; chan<_chanMax; chan++) {
        struct ChannelInfo* info = &_rgChannelInfo[chan];
        int oneBasedChannel = chan + 1;
        paramMgr->setPendingParam(0, trimTpl.arg(oneBasedChannel), info->rcTrim);
327
        if (!trimsOnly) {
Don Gagne's avatar
Don Gagne committed
328 329 330
            paramMgr->setPendingParam(0, minTpl.arg(oneBasedChannel), info->rcMin);
            paramMgr->setPendingParam(0, maxTpl.arg(oneBasedChannel), info->rcMax);
            paramMgr->setPendingParam(0, revTpl.arg(oneBasedChannel), info->reversed ? -1.0f : 1.0f);
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 358
        }
    }
    
    if (!trimsOnly) {
        // Write function mapping parameters
        for (size_t i=0; i<rcCalFunctionMax; i++) {
            int32_t paramChannel;
            if (_rgFunctionChannelMapping[i] == _chanMax) {
                // 0 signals no mapping
                paramChannel = 0;
            } else {
                // Note that the channel value is 1-based
                paramChannel = _rgFunctionChannelMapping[i] + 1;
            }
            paramMgr->setPendingParam(0, _rgFunctionInfo[i].parameterName, paramChannel);
        }
    }
    
    //let the param mgr manage sending all the pending RC_foo updates and persisting after
    paramMgr->sendPendingParameters(true, true);
}

/// @brief This routine is called whenever a raw value for an RC channel changes. Depending on the current
/// calibration state, it will update internal values and ui accordingly.
///     @param chan RC channel on which signal is coming from (0-based)
///     @param fval Current value for channel
void PX4RCCalibration::_remoteControlChannelRawChanged(int chan, float fval)
{
Don Gagne's avatar
Don Gagne committed
359
    Q_ASSERT(chan >=0 && chan <= _chanMax);
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384

    // We always update raw values
    _rcRawValue[chan] = fval;
    
    // Update state machine
    switch (_rcCalState) {
        case rcCalStateChannelWait:
            // While we are waiting detect the minimum number of RC channels
            if (chan + 1 > (int)_chanCount) {
                _chanCount = chan + 1;
                if (_chanCount >= _chanMinimum) {
                    _ui->rcCalNext->setEnabled(true);
                    _ui->rcCalStatus->setText(tr("Detected %1 radio channels.").arg(_chanCount));
                } else if (_chanCount < _chanMinimum) {
                    _ui->rcCalStatus->setText(tr("Detected %1 radio channels. To operate PX4, you need at least %2 channels.").arg(_chanCount).arg(_chanMinimum));
                }
            }
            
            // Capture raw values so channel widgets are live
            _rcRawValue[chan] = fval;
            break;
            
        case rcCalStateIdentify:
            if (!_rcCalStateChannelComplete) {
                // If this channel is already used in a mapping we can't used it again
Don Gagne's avatar
Don Gagne committed
385
                bool channelAlreadyMapped = !(_rgChannelInfo[chan].function == rcCalFunctionMax);
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
                
                // If the channel moved considerably, pick it
                if (!channelAlreadyMapped && fabsf(_rcValueSave[chan] - fval) > _rcCalMoveDelta) {
                    Q_ASSERT(_rcCalStateCurrentChannel >= 0 && _rcCalStateCurrentChannel < rcCalFunctionMax);
                    _rgFunctionChannelMapping[_rcCalStateCurrentChannel] = chan;
                    _rgChannelInfo[chan].function = (enum rcCalFunctions)_rcCalStateCurrentChannel;
                    _updateView();
                    
                    // Confirm found channel
                    QString msg = tr("Found %1 [Channel %2]").arg(_rgFunctionInfo[_rcCalStateCurrentChannel].functionName).arg(chan);
                    _ui->rcCalFound->setText(msg);
                    //qDebug() << msg;
                    _ui->rcCalTryAgain->setEnabled(true);
                    _ui->rcCalNext->setEnabled(true);
                    _ui->rcCalSkip->setEnabled(false);
                    _rcCalStateChannelComplete =true;
                }
            }
            break;
            
        case rcCalStateMinMax:
Don Gagne's avatar
Don Gagne committed
407 408
            if (fval < _rgChannelInfo[chan].rcMin && fval <= _rcCalPWMValidMinValue) {
                _rgRadioWidget[chan]->setMinValid(true);
409 410
                _rgChannelInfo[chan].rcMin = fval;
            }
Don Gagne's avatar
Don Gagne committed
411 412
            if (fval > _rgChannelInfo[chan].rcMax  && fval >= _rcCalPWMValidMaxValue) {
                _rgRadioWidget[chan]->setMaxValid(true);
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
                _rgChannelInfo[chan].rcMax = fval;
            }
            break;
            
        case rcCalStateCenterThrottle:
            // If the throttle is roughly centered, enable the Next button
            Q_ASSERT(_rgFunctionChannelMapping[rcCalFunctionThrottle] != _chanMax);
            if (chan == _rgFunctionChannelMapping[rcCalFunctionThrottle] &&
                 fabsf(fval - _rcCalPWMCenterPoint) < _rcCalRoughCenterDelta) {
                _ui->rcCalNext->setEnabled(true);
            }
            break;
        
        case rcCalStateDetectInversion:
            if (!_rcCalStateChannelComplete) {
                // We only care about the channel we are looking for
                Q_ASSERT(_rcCalStateCurrentChannel >= 0 && _rcCalStateCurrentChannel < rcCalFunctionMax);
                if (chan == _rgFunctionChannelMapping[_rcCalStateCurrentChannel]) {
                    // If the channel moved considerably use it to determine inversion
                    if (fabsf(_rcValueSave[chan] - fval) > _rcCalMoveDelta) {
                        // Request was made to move channel to a lower value. If value goes up the channel is reversed.
                        bool reversed = fval > _rcValueSave[chan];
                        
                        _rgChannelInfo[_rcCalStateCurrentChannel].reversed = reversed;
                        _updateView();
                        
                        // Confirm inversion detection
                        QString msg = tr("Channel for %1 ").arg(_rgFunctionInfo[_rcCalStateCurrentChannel].functionName);
                        if (reversed) {
                            msg += tr("is reversed.");
                        } else {
                            msg += tr("is not reversed.");
                        }
                        _ui->rcCalFound->setText(msg);
                        //qDebug() << msg;
                        _ui->rcCalTryAgain->setEnabled(true);
                        _ui->rcCalNext->setEnabled(true);
                        _ui->rcCalSkip->setEnabled(false);
                        _rcCalStateChannelComplete =true;
                    }
                }
            }
            break;
            
        case rcCalStateTrims:
Don Gagne's avatar
Don Gagne committed
458 459 460 461 462 463 464 465 466 467 468
            // Update the trim values for attitude functions only
            if (_rgChannelInfo[chan].function >= rcCalFunctionFirstAttitudeFunction && _rgChannelInfo[chan].function <= rcCalFunctionLastAttitudeFunction) {
                int mappedChannel = _rgFunctionChannelMapping[_rgChannelInfo[chan].function];
                
                // All Attitude Functions should be mapped
                Q_ASSERT(mappedChannel != rcCalFunctionMax);
                
                _rgChannelInfo[mappedChannel].rcTrim = _rcRawValue[mappedChannel];
            }
            
            // Once the throttle is lowered we enable the next button
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
            Q_ASSERT(_rgFunctionChannelMapping[rcCalFunctionThrottle] != rcCalFunctionMax);
            if (chan == _rgFunctionChannelMapping[rcCalFunctionThrottle]) {
                bool enableNext = false;
                
                // If the value is close enough to min consider the throttle to be lowered (taking into account reversing)
                if ((_rgChannelInfo[chan].reversed && fabsf(_rgChannelInfo[chan].rcMax - fval) < _rcCalMinDelta) ||
                    fabsf(_rgChannelInfo[chan].rcMin - fval) < _rcCalMinDelta) {
                    enableNext = true;
                }
                _ui->rcCalNext->setEnabled(enableNext);
            }
            break;
    
        default:
            // Nothing special required for state
            break;
    }
}

void PX4RCCalibration::_updateView()
{
    // Update the available channels
    for (int chan=0; chan<_chanCount; chan++) {
        _rgRadioWidget[chan]->setEnabled(true);
        
        struct ChannelInfo* info = &_rgChannelInfo[chan];
Don Gagne's avatar
Don Gagne committed
495 496
        _rgRadioWidget[chan]->setValueAndMinMax(_rcRawValue[chan], info->rcMin, info->rcMax);
        _rgRadioWidget[chan]->setTrim(info->rcTrim);
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    }
    
    // Disable non-available channels
    for (int chan=_chanCount; chan<_chanMax; chan++) {
        _rgRadioWidget[chan]->setEnabled(false);
    }
    
    // Update the channel names for all channels
    for (int chan=0; chan<_chanMax; chan++) {
        struct ChannelInfo* info = &_rgChannelInfo[chan];
        
        QString name;
        int oneBasedChannel = chan+1;
        if (info->function == rcCalFunctionMax) {
            name = tr("Channel %1").arg(oneBasedChannel);
        } else {
            name = tr("%1 [Channel %2]").arg(_rgFunctionInfo[info->function].functionName).arg(oneBasedChannel);
        }
Don Gagne's avatar
Don Gagne committed
515
        _rgRadioWidget[chan]->setTitle(name);
516 517 518 519 520 521 522 523
    }
}

/// @brief Cancels the current calibration process and returns to the Channel Wait state.
void PX4RCCalibration::_rcCalCancel(void)
{
    _mav->endRadioControlCalibration();
    _rcCalChannelWait(true);
Don Gagne's avatar
Don Gagne committed
524
    _setInternalCalibrationValuesFromParameters();
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
}

void PX4RCCalibration::_rcCalSkip(void)
{
    // Skip is only allowed for optional function mappings
    Q_ASSERT(_rcCalState ==rcCalStateIdentify);
    
    // This will move us to the next function mapping
    _rcCalNextIdentifyChannelMapping();
}

/// @brief Resets the state machine such that you can retry an identify or inversion detection on a specific
// function.
void PX4RCCalibration::_rcCalTryAgain(void)
{
    // FIXME: NYI for all states
    QMessageBox::information(this, "Not Yet Implemented", "Try Again has not yet been implemented.");
}

/// @brief Called when the Next button is called from the RC Calibration tab. This will either start the calibration process
/// or move it on to the next step.
void PX4RCCalibration::_rcCalNext(void)
{
    switch (_rcCalState) {
        case rcCalStateChannelWait:
            _rcCalBegin();
            break;
            
        case rcCalStateBegin:
            _rcCalStateCurrentChannel = -1;    // _rcCalNextIdentifyChannelMapping will bump up to 0 to start sequence
            _rcCalNextIdentifyChannelMapping();
            break;
            
        case rcCalStateIdentify:
            _rcCalNextIdentifyChannelMapping();
            break;
            
        case rcCalStateMinMax:
            _updateView();
            _rcCalCenterThrottle();
            break;
            
        case rcCalStateCenterThrottle:
            // Setup for inversion detection channel
            _rcCalStateCurrentChannel = rcCalFunctionFirstAttitudeFunction - 1; // _rcCalNextDetectChannelInversion will ++ to start sequence
            _rcCalNextDetectChannelInversion();
            break;
            
        case rcCalStateDetectInversion:
            _rcCalNextDetectChannelInversion();
            break;
            
        case rcCalStateTrims:
            _rcCalSave();
            break;
            
        case rcCalStateSave:
            _writeCalibration(false /* !trimsOnly */);
            _rcCalChannelWait(false);
            break;
            
        default:
            Q_ASSERT(false);
            break;
    }
}

/// @brief Setup for the Channel Wait state of calibration.
///     @param firstTime true: this is the first time a calibration is being performed since this widget was created
void PX4RCCalibration::_rcCalChannelWait(bool firstTime)
{
    _rcCalState = rcCalStateChannelWait;
    
Don Gagne's avatar
Don Gagne committed
598 599 600 601 602
    if (firstTime) {
        _resetInternalCalibrationValues();
    } else {
        _setInternalCalibrationValuesFromParameters();
    }
Don Gagne's avatar
Don Gagne committed
603 604 605 606 607 608 609 610 611 612 613 614 615

    if (_chanCount == 0) {
        _ui->rcCalFound->setText(tr("Please turn on Radio"));
        _ui->rcCalNext->setEnabled(false);
    } else {
        if (_chanCount >= _chanMinimum) {
            _ui->rcCalNext->setEnabled(true);
            _ui->rcCalStatus->setText(tr("Detected %1 radio channels.").arg(_chanCount));
        } else if (_chanCount < _chanMinimum) {
            _ui->rcCalNext->setEnabled(false);
            _ui->rcCalStatus->setText(tr("Detected %1 radio channels. To operate PX4, you need at least %2 channels.").arg(_chanCount).arg(_chanMinimum));
        }
    }
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    
    if (firstTime) {
        _ui->rcCalFound->clear();
    } else {
        _ui->rcCalFound->setText(tr("Calibration complete"));
    }
    
    _ui->rcCalNext->setText(tr("Start"));
    _ui->rcCalCancel->setEnabled(false);
    _ui->rcCalSkip->setEnabled(false);
    _ui->rcCalTryAgain->setEnabled(false);
}

/// @brief Set up for the Begin state of calibration.
void PX4RCCalibration::_rcCalBegin(void)
{
    Q_ASSERT(_chanCount >= _chanMinimum);
    
    _rcCalState = rcCalStateBegin;
    
Don Gagne's avatar
Don Gagne committed
636 637
    _resetInternalCalibrationValues();
    
638 639 640 641 642 643 644 645 646
    // Let the mav known we are starting calibration. This should turn off motors and so forth.
    // FIXME: XXX magic number: Set to 1 for radio input disable
    _mav->startRadioControlCalibration(1);
    
    _ui->rcCalNext->setText(tr("Next"));
    _ui->rcCalCancel->setEnabled(true);
    _ui->rcCalStatus->setText(tr("Starting RC calibration.\n\n"
                                "Ensure RC transmitter and receiver are powered and connected. It is recommended to disconnect all motors for additional safety, however, the system is designed to not arm during the calibration.\n\n"
                                "Reset all transmitter trims to center, then click Next to continue"));
Don Gagne's avatar
Don Gagne committed
647
    _ui->rcCalFound->clear();
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
}

/// @brief Saves the current channel values, so that we can detect when the use moves an input.
void PX4RCCalibration::_rcCalSaveCurrentValues(void)
{
    for (unsigned i = 0; i < _chanMax; i++) {
        _rcValueSave[i] = _rcRawValue[i];
    }
}

/// @brief Set up for the Identify state of calibration which assigns channels to control functions.
void PX4RCCalibration::_rcCalNextIdentifyChannelMapping(void)
{
    // Move to next channel
    _rcCalStateCurrentChannel++;
    Q_ASSERT(_rcCalStateCurrentChannel >= 0 && _rcCalStateCurrentChannel <= rcCalFunctionMax);
    
    // Be careful not to switch the state until we have a valid value in _rcCalStateCurrentChannel. Otherwise an rc signal could come through
    // and cause _remoteControlChannelRawChanged to get confused.
    _rcCalState = rcCalStateIdentify;
    _rcCalStateChannelComplete = false;
    
    if (_rcCalStateCurrentChannel == rcCalFunctionMax) {
        // If we have processed all channels move to next calibration step
        _rcCalReadChannelsMinMax();
        return;
    }
    
    // Save the current mapping, so we can reset if user decides to skip
    _rcCalStateIdentifyOldMapping = _rgFunctionChannelMapping[_rcCalStateCurrentChannel];
    
    // Save the current channel values so we can detect movement
    _rcCalSaveCurrentValues();
    
    _ui->rcCalStatus->setText(tr("Detecting %1 ...").arg(_rgFunctionInfo[_rcCalStateCurrentChannel].functionName));
    _ui->rcCalFound->setText(tr("Please move stick, switch or potentiometer for this channel all the way up/down or left/right."));
    
    _ui->rcCalNext->setEnabled(false);
    _ui->rcCalTryAgain->setEnabled(false);
    _ui->rcCalSkip->setEnabled(!_rgFunctionInfo[_rcCalStateCurrentChannel].required);
    _ui->rcCalCancel->setEnabled(true);
}

/// @brief Sets up for the Min/Max state of calibration.
void PX4RCCalibration::_rcCalReadChannelsMinMax(void)
{
    _rcCalState = rcCalStateMinMax;
    
    _ui->rcCalStatus->setText(tr("Please move the sticks to their extreme positions, including all switches. Click Next when complete."));
    _ui->rcCalFound->clear();
    
    _ui->rcCalNext->setEnabled(true);
    _ui->rcCalTryAgain->setEnabled(false);
    _ui->rcCalSkip->setEnabled(false);
    _ui->rcCalCancel->setEnabled(true);
    
    _showMinMaxOnRadioWidgets(true);
}

/// @brief Sets up for the Center Throttle state of Calibration which is required prior to detecting channel inversions.
void PX4RCCalibration::_rcCalCenterThrottle(void)
{
    _rcCalState = rcCalStateCenterThrottle;
    
    _ui->rcCalStatus->setText(tr("Next we will be determining which channels need to be reversed.\n\n"
                                "Please center the throttle stick prior to that. The stick should be roughly centered - the exact position is not relevant.\n"
                                "Once centered, leave it there until asked to move it.\n\n"
                                "Click the Next button when done. Next button will only enable when throttle is centered."));
    _ui->rcCalFound->clear();

    _ui->rcCalNext->setEnabled(false);
    _ui->rcCalTryAgain->setEnabled(false);
    _ui->rcCalSkip->setEnabled(false);
    _ui->rcCalCancel->setEnabled(true);
}

/// @brief Set up the Detect Channel Inversion state of calibration.
void PX4RCCalibration::_rcCalNextDetectChannelInversion(void)
{    
    // Move to next channel. We only detect inversion on Attitude control functions.
    _rcCalStateCurrentChannel++;
    Q_ASSERT(_rcCalStateCurrentChannel >= rcCalFunctionFirstAttitudeFunction && _rcCalStateCurrentChannel <= rcCalFunctionLastAttitudeFunction + 1);
    if (_rcCalStateCurrentChannel > rcCalFunctionLastAttitudeFunction) {
        // If we have processed all functions move to next calibration step
        _rcCalTrims();
        return;
    }
    
    // Be careful not to switch the state until we have a valid value in _rcCalStateCurrentChannel. Otherwise an rc signal could come through
    // and cause _remoteControlChannelRawChanged to get confused.
    _rcCalState = rcCalStateDetectInversion;
    _rcCalStateChannelComplete = false;

    
    // Save the current channel values so we can detect movement
    _rcCalSaveCurrentValues();
    
    const struct FunctionInfo* info = &_rgFunctionInfo[_rcCalStateCurrentChannel];
    
    _ui->rcCalStatus->setText(tr("Detecting reversed channels: %1 ...").arg(info->functionName));
    _ui->rcCalFound->setText(info->inversionMsg);

    _ui->rcCalNext->setEnabled(false);
    _ui->rcCalTryAgain->setEnabled(false);
    _ui->rcCalSkip->setEnabled(false);
    _ui->rcCalCancel->setEnabled(true);
}

/// @brief Set up the Trims state of calibration.
void PX4RCCalibration::_rcCalTrims(void)
{
    _rcCalState = rcCalStateTrims;
    
    _ui->rcCalStatus->setText(tr("Next we will be determining Trim values for the two attitude control sticks:\n"
                                "Please set the Throttle stick to the lowest throttle position and leave it there.\n"
                                "Click the Next button to save Trims. Next button will only enable when throttle is lowered."));
    _ui->rcCalFound->clear();

    _ui->rcCalNext->setEnabled(false);
    _ui->rcCalTryAgain->setEnabled(false);
    _ui->rcCalSkip->setEnabled(false);
    _ui->rcCalCancel->setEnabled(true);
Don Gagne's avatar
Don Gagne committed
770 771
    
    _showTrimOnRadioWidgets(true);
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
}

/// @brief Set up the Save state of calibration.
void PX4RCCalibration::_rcCalSave(void)
{
    _rcCalState = rcCalStateSave;
    
    _ui->rcCalStatus->setText(tr("The current calibration settings are now displayed for each channel on screen.\n\n"
                                "Click the Next button to upload calibration to board. Click Cancel if you don't want to save these values."));
    _ui->rcCalFound->clear();

    _ui->rcCalNext->setEnabled(true);
    _ui->rcCalTryAgain->setEnabled(false);
    _ui->rcCalSkip->setEnabled(false);
    _ui->rcCalCancel->setEnabled(true);
Don Gagne's avatar
Don Gagne committed
787 788 789 790 791 792
    
    // This updates the internal values according to the validation rules. Then _updateView will tick and update ui
    // such that the settings that will be written our are displayed.
    _validateCalibration();
    
    _showMinMaxOnRadioWidgets(true);
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
}

/// @brief This is used by unit test code to force the calibration state machine to the specified state.
/// With this you can write individual unit tests for each calibration state. Should only be called by
/// unit test code.
void PX4RCCalibration::_unitTestForceCalState(enum rcCalStates state) {

    switch (state) {
        case rcCalStateBegin:
            _rcCalBegin();
            break;
            
        case rcCalStateIdentify:
            _rcCalStateCurrentChannel = -1;    // _rcCalNextIdentifyChannelMapping will bump up to 0 to start sequence
            _rcCalNextIdentifyChannelMapping();
            break;
            
        case rcCalStateMinMax:
            _rcCalReadChannelsMinMax();
            break;
            
        case rcCalStateCenterThrottle:
            _rcCalCenterThrottle();
            break;
            
        case rcCalStateDetectInversion:
            _rcCalStateCurrentChannel = -1;    // _rcCalNextDetectChannelInversion will bump up to 0 to start sequence
            _rcCalNextDetectChannelInversion();
            break;
            
        case rcCalStateTrims:
            _rcCalTrims();
            break;
            
        default:
            // Unsupported force state
            Q_ASSERT(false);
            break;
    }
}

/// @brief Shows or hides the min/max values of the channel widgets.
///     @param show true: show the min/max values, false: hide the min/max values
void PX4RCCalibration::_showMinMaxOnRadioWidgets(bool show)
{
Don Gagne's avatar
Don Gagne committed
838 839 840
    // Force a view update to widget have current values
    _updateView();
    
841
    // Turn on min/max display for all radio widgets
Don Gagne's avatar
Don Gagne committed
842 843
    for (int i=0; i<_chanMax; i++) {
        RCChannelWidget* radioWidget = _rgRadioWidget[i];
844 845 846
        Q_ASSERT(radioWidget);
        
        radioWidget->showMinMax(show);
Don Gagne's avatar
Don Gagne committed
847 848 849 850 851 852 853 854 855 856 857
        if (show) {
            if (radioWidget->min() <= _rcCalPWMValidMinValue) {
                radioWidget->setMinValid(true);
            }
            if (radioWidget->max() >= _rcCalPWMValidMaxValue) {
                radioWidget->setMaxValid(true);
            }
        } else {
            radioWidget->setMinValid(false);
            radioWidget->setMaxValid(false);
        }
858
    }
Don Gagne's avatar
Don Gagne committed
859 860 861 862 863 864 865
}

/// @brief Shows or hides the trim values of the channel widgets.
///     @param show true: show the trim values, false: hide the trim values
void PX4RCCalibration::_showTrimOnRadioWidgets(bool show)
{
    // Turn on trim display for all radio widgets
866
    for (int i=0; i<_chanMax; i++) {
Don Gagne's avatar
Don Gagne committed
867
        RCChannelWidget* radioWidget = _rgRadioWidget[i];
868 869
        Q_ASSERT(radioWidget);
        
Don Gagne's avatar
Don Gagne committed
870 871 872 873 874 875 876 877 878 879
        radioWidget->showTrim(show);
    }
}

void PX4RCCalibration::_parameterListUpToDate(void)
{
    _parameterListUpToDateSignalled = true;
    
    if (_rcCalState == rcCalStateChannelWait) {
        _setInternalCalibrationValuesFromParameters();
880 881
    }
}