PX4RCCalibration.cc 45.5 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
/*=====================================================================
 
 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

28
#include <QSettings>
29 30 31

#include "PX4RCCalibration.h"
#include "UASManager.h"
Don Gagne's avatar
Don Gagne committed
32
#include "QGCMessageBox.h"
33

34 35
QGC_LOGGING_CATEGORY(PX4RCCalibrationLog, "PX4RCCalibrationLog")

Don Gagne's avatar
Don Gagne committed
36
const int PX4RCCalibration::_updateInterval = 150;              ///< Interval for timer which updates radio channel widgets
37
const int PX4RCCalibration::_rcCalPWMCenterPoint = ((PX4RCCalibration::_rcCalPWMValidMaxValue - PX4RCCalibration::_rcCalPWMValidMinValue) / 2.0f) + PX4RCCalibration::_rcCalPWMValidMinValue;
Don Gagne's avatar
Don Gagne committed
38
// FIXME: Double check these mins againt 150% throws
Don Gagne's avatar
Don Gagne committed
39 40 41 42
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
Don Gagne's avatar
Don Gagne committed
43 44 45 46 47 48 49
const int PX4RCCalibration::_rcCalRoughCenterDelta = 50;        ///< Delta around center point which is considered to be roughly centered
const int PX4RCCalibration::_rcCalMoveDelta = 300;            ///< Amount of delta past center which is considered stick movement
const int PX4RCCalibration::_rcCalSettleDelta = 20;           ///< Amount of delta which is considered no stick movement
const int PX4RCCalibration::_rcCalMinDelta = 100;             ///< Amount of delta allowed around min value to consider channel at min

const int PX4RCCalibration::_stickDetectSettleMSecs = 500;

Don Gagne's avatar
Don Gagne committed
50
const char*  PX4RCCalibration::_imageFilePrefix = ":/res/calibration/";
51 52 53
const char*  PX4RCCalibration::_imageFileMode1Dir = "mode1/";
const char*  PX4RCCalibration::_imageFileMode2Dir = "mode2/";
const char*  PX4RCCalibration::_imageCenter = "radioCenter.png";
Don Gagne's avatar
Don Gagne committed
54 55 56 57 58 59 60 61 62 63
const char*  PX4RCCalibration::_imageHome = "radioHome.png";
const char*  PX4RCCalibration::_imageThrottleUp = "radioThrottleUp.png";
const char*  PX4RCCalibration::_imageThrottleDown = "radioThrottleDown.png";
const char*  PX4RCCalibration::_imageYawLeft = "radioYawLeft.png";
const char*  PX4RCCalibration::_imageYawRight = "radioYawRight";
const char*  PX4RCCalibration::_imageRollLeft = "radioRollLeft.png";
const char*  PX4RCCalibration::_imageRollRight = "radioRollRight.png";
const char*  PX4RCCalibration::_imagePitchUp = "radioPitchUp";
const char*  PX4RCCalibration::_imagePitchDown = "radioPitchDown";
const char*  PX4RCCalibration::_imageSwitchMinMax = "radioSwitchMinMax";
64

65 66 67
const char* PX4RCCalibration::_settingsGroup = "RadioCalibration";
const char* PX4RCCalibration::_settingsKeyTransmitterMode = "TransmitterMode";

68
const struct PX4RCCalibration::FunctionInfo PX4RCCalibration::_rgFunctionInfo[PX4RCCalibration::rcCalFunctionMax] = {
Don Gagne's avatar
Don Gagne committed
69 70 71 72 73 74 75 76 77 78 79 80
    //Parameter          required
    { "RC_MAP_ROLL" },
    { "RC_MAP_PITCH" },
    { "RC_MAP_YAW" },
    { "RC_MAP_THROTTLE" },
    { "RC_MAP_MODE_SW" },
    { "RC_MAP_POSCTL_SW" },
    { "RC_MAP_LOITER_SW" },
    { "RC_MAP_RETURN_SW" },
    { "RC_MAP_FLAPS" },
    { "RC_MAP_AUX1" },
    { "RC_MAP_AUX2" },
81 82 83 84
};

PX4RCCalibration::PX4RCCalibration(QWidget *parent) :
    QWidget(parent),
Don Gagne's avatar
Don Gagne committed
85
    _currentStep(-1),
86
    _transmitterMode(2),
87 88 89
    _chanCount(0),
    _rcCalState(rcCalStateChannelWait),
    _mav(NULL),
Don Gagne's avatar
Don Gagne committed
90
    _paramMgr(NULL),
Don Gagne's avatar
Don Gagne committed
91 92
    _ui(new Ui::PX4RCCalibration),
    _unitTestMode(false)
93 94 95
{
    _ui->setupUi(this);
    
Don Gagne's avatar
Don Gagne committed
96
    // Initialize arrays of monitor control pointers. This allows for more efficient code writing using "for" loops.
97
    for (int chan=0; chan<_chanMax; chan++) {
Don Gagne's avatar
Don Gagne committed
98
        QString radioWidgetName;
99
        
Don Gagne's avatar
Don Gagne committed
100 101 102 103 104
        radioWidgetName = "channel%1Value";
        RCValueWidget* monitorWidget = findChild<RCValueWidget*>(radioWidgetName.arg(chan+1));
        Q_ASSERT(monitorWidget);
        _rgRCValueMonitorWidget[chan] = monitorWidget;
        monitorWidget->setSmallMode();    // Monitor display uses small display
105
        
Don Gagne's avatar
Don Gagne committed
106 107 108 109
        radioWidgetName = "channel%1Label";
        QLabel* monitorLabel = findChild<QLabel*>(radioWidgetName.arg(chan+1));
        Q_ASSERT(monitorLabel);
        _rgRCValueMonitorLabel[chan] = monitorLabel;
110
    }
Don Gagne's avatar
Don Gagne committed
111 112 113 114 115 116 117 118 119 120 121 122

    // Initialize array of attitude controls. Order here doesn't matter.
    _rgAttitudeControl[0].function = rcCalFunctionThrottle;
    _rgAttitudeControl[0].valueWidget = _ui->throttleValue;
    _rgAttitudeControl[1].function = rcCalFunctionYaw;
    _rgAttitudeControl[1].valueWidget = _ui->yawValue;
    _rgAttitudeControl[2].function = rcCalFunctionRoll;
    _rgAttitudeControl[2].valueWidget = _ui->rollValue;
    _rgAttitudeControl[3].function = rcCalFunctionPitch;
    _rgAttitudeControl[3].valueWidget = _ui->pitchValue;
    _rgAttitudeControl[4].function = rcCalFunctionFlaps;
    _rgAttitudeControl[4].valueWidget = _ui->flapsValue;
123
    
124 125 126 127 128
    // This code assume we already have an active UAS with ready parameters
    _mav = UASManager::instance()->getActiveUAS();
    Q_ASSERT(_mav);
    
    // Connect new signals
129 130 131
    
    bool fSucceeded;
    Q_UNUSED(fSucceeded);
132
    fSucceeded =  connect(_mav, SIGNAL(remoteControlChannelRawChanged(int,float)), this, SLOT(_remoteControlChannelRawChanged(int,float)));
133
    Q_ASSERT(fSucceeded);
134 135 136 137 138
    
    _paramMgr = _mav->getParamManager();
    Q_ASSERT(_paramMgr);
    Q_ASSERT(_paramMgr->parametersReady());
    
Don Gagne's avatar
Don Gagne committed
139
    connect(_ui->spektrumBind, &QPushButton::clicked, this, &PX4RCCalibration::_spektrumBind);
140 141 142 143
    
    _updateTimer.setInterval(150);
    _updateTimer.start();

Don Gagne's avatar
Don Gagne committed
144 145 146 147 148 149 150 151 152
    connect(_ui->rcCalCancel, &QPushButton::clicked, this, &PX4RCCalibration::_stopCalibration);
    connect(_ui->rcCalSkip, &QPushButton::clicked, this, &PX4RCCalibration::_skipButton);
    connect(_ui->rcCalNext, &QPushButton::clicked, this, &PX4RCCalibration::_nextButton);
    
    connect(_ui->rollTrim, &QPushButton::clicked, this, &PX4RCCalibration::_trimNYI);
    connect(_ui->yawTrim, &QPushButton::clicked, this, &PX4RCCalibration::_trimNYI);
    connect(_ui->pitchTrim, &QPushButton::clicked, this, &PX4RCCalibration::_trimNYI);
    connect(_ui->throttleTrim, &QPushButton::clicked, this, &PX4RCCalibration::_trimNYI);
    
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    _loadSettings();

    if (_transmitterMode == 1) {
        _ui->mode1->setChecked(true);
        _mode1Toggled(true);
    } else if (_transmitterMode == 2) {
        _ui->mode2->setChecked(true);
        _mode2Toggled(true);
    } else {
        Q_ASSERT(false);
    }
    
    connect(_ui->mode1, &QAbstractButton::toggled, this, &PX4RCCalibration::_mode1Toggled);
    connect(_ui->mode2, &QAbstractButton::toggled, this, &PX4RCCalibration::_mode2Toggled);
    
Don Gagne's avatar
Don Gagne committed
168
    _stopCalibration();
169 170 171
    
    connect(&_updateTimer, &QTimer::timeout, this, &PX4RCCalibration::_updateView);
    _setInternalCalibrationValuesFromParameters();
Don Gagne's avatar
Don Gagne committed
172
}
173

Don Gagne's avatar
Don Gagne committed
174 175
PX4RCCalibration::~PX4RCCalibration()
{
176
    _storeSettings();
Don Gagne's avatar
Don Gagne committed
177
}
178

Don Gagne's avatar
Don Gagne committed
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 220 221 222 223 224 225 226 227 228 229
/// @brief Returns the state machine entry for the specified state.
const PX4RCCalibration::stateMachineEntry* PX4RCCalibration::_getStateMachineEntry(int step)
{
    static const char* msgBegin = "Lower the Throttle stick all the way down as shown in diagram.\nReset all transmitter trims to center.\n\n"
                                 "It is recommended to disconnect all motors for additional safety, however, the system is designed to not arm during the calibration.\n\n"
                                 "Click Next to continue";
    static const char* msgThrottleUp = "Move the Throttle stick all the way up and hold it there...";
    static const char* msgThrottleDown = "Move the Throttle stick all the way down and leave it there...";
    static const char* msgYawLeft = "Move the Yaw stick all the way to the left and hold it there...";
    static const char* msgYawRight = "Move the Yaw stick all the way to the right and hold it there...";
    static const char* msgRollLeft = "Move the Roll stick all the way to the left and hold it there...";
    static const char* msgRollRight = "Move the Roll stick all the way to the right and hold it there...";
    static const char* msgPitchDown = "Move the Pitch stick all the way down and hold it there...";
    static const char* msgPitchUp = "Move the Pitch stick all the way up and hold it there...";
    static const char* msgPitchCenter = "Allow the Pitch stick to move back to center...";
    static const char* msgAux1Switch = "Move the switch or dial you want to use for Aux1.\n\n"
                                            "You can click Skip if you don't want to assign.";
    static const char* msgAux2Switch = "Move the switch or dial you want to use for Aux2.\n\n"
                                            "You can click Skip if you don't want to assign.";
    static const char* msgSwitchMinMax = "Move all the transmitter switches and/or dials back and forth to their extreme positions.";
    static const char* msgFlapsDetect = "Move the switch or dial you want to use for Flaps back and forth a few times. "
                                            "Then leave the switch/dial at the position you want to use for Flaps fully extended.\n\n"
                                            "Click Next to continue.\n"
                                            "If you won't be using Flaps, click Skip.";
    static const char* msgFlapsUp = "Move the switch or dial you want to use for Flaps to the position you want to use for Flaps fully retracted.";
    static const char* msgComplete = "All settings have been captured. Click Next to write the new parameters to your board.";
    
    static const stateMachineEntry rgStateMachine[] = {
        //Function
        { rcCalFunctionMax,                 msgBegin,           _imageHome,         &PX4RCCalibration::_inputCenterWaitBegin,   &PX4RCCalibration::_saveAllTrims,       NULL },
        { rcCalFunctionThrottle,            msgThrottleUp,      _imageThrottleUp,   &PX4RCCalibration::_inputStickDetect,       NULL,                                   NULL },
        { rcCalFunctionThrottle,            msgThrottleDown,    _imageThrottleDown, &PX4RCCalibration::_inputStickMin,          NULL,                                   NULL },
        { rcCalFunctionYaw,                 msgYawRight,        _imageYawRight,     &PX4RCCalibration::_inputStickDetect,       NULL,                                   NULL },
        { rcCalFunctionYaw,                 msgYawLeft,         _imageYawLeft,      &PX4RCCalibration::_inputStickMin,          NULL,                                   NULL },
        { rcCalFunctionRoll,                msgRollRight,       _imageRollRight,    &PX4RCCalibration::_inputStickDetect,       NULL,                                   NULL },
        { rcCalFunctionRoll,                msgRollLeft,        _imageRollLeft,     &PX4RCCalibration::_inputStickMin,          NULL,                                   NULL },
        { rcCalFunctionPitch,               msgPitchUp,         _imagePitchUp,      &PX4RCCalibration::_inputStickDetect,       NULL,                                   NULL },
        { rcCalFunctionPitch,               msgPitchDown,       _imagePitchDown,    &PX4RCCalibration::_inputStickMin,          NULL,                                   NULL },
        { rcCalFunctionPitch,               msgPitchCenter,     _imageHome,         &PX4RCCalibration::_inputCenterWait,        NULL,                                   NULL },
        { rcCalFunctionMax,                 msgSwitchMinMax,    _imageSwitchMinMax, &PX4RCCalibration::_inputSwitchMinMax,      &PX4RCCalibration::_nextStep,           NULL },
        { rcCalFunctionFlaps,               msgFlapsDetect,     _imageThrottleDown, &PX4RCCalibration::_inputFlapsDetect,       &PX4RCCalibration::_saveFlapsDown,      &PX4RCCalibration::_skipFlaps },
        { rcCalFunctionFlaps,               msgFlapsUp,         _imageThrottleDown, &PX4RCCalibration::_inputFlapsUp,           NULL,                                   NULL },
        { rcCalFunctionAux1,                msgAux1Switch,      _imageThrottleDown, &PX4RCCalibration::_inputSwitchDetect,      NULL,                                   &PX4RCCalibration::_nextStep },
        { rcCalFunctionAux2,                msgAux2Switch,      _imageThrottleDown, &PX4RCCalibration::_inputSwitchDetect,      NULL,                                   &PX4RCCalibration::_nextStep },
        { rcCalFunctionMax,                 msgComplete,        _imageThrottleDown, NULL,                                       &PX4RCCalibration::_writeCalibration,   NULL },
    };
    
    Q_ASSERT(step >=0 && step < (int)(sizeof(rgStateMachine) / sizeof(rgStateMachine[0])));
    
    return &rgStateMachine[step];
}
230

Don Gagne's avatar
Don Gagne committed
231 232 233 234 235 236 237 238 239 240 241 242 243
void PX4RCCalibration::_nextStep(void)
{
    _currentStep++;
    _setupCurrentState();
}


/// @brief Sets up the state machine according to the current step from _currentStep.
void PX4RCCalibration::_setupCurrentState(void)
{
   const stateMachineEntry* state = _getStateMachineEntry(_currentStep);
    
    _ui->rcCalStatus->setText(state->instructions);
244 245
    
    _setHelpImage(state->image);
Don Gagne's avatar
Don Gagne committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    
    _stickDetectChannel = _chanMax;
    _stickDetectSettleStarted = false;
    
    _rcCalSaveCurrentValues();
    
    _ui->rcCalNext->setEnabled(state->nextFn != NULL);
    _ui->rcCalSkip->setEnabled(state->skipFn != NULL);
}

/// @brief This routine is called whenever a raw value for an RC channel changes. It will call the input
/// function as specified by the state machine.
///     @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)
{
    Q_ASSERT(chan >= 0 && chan <= _chanMax);
    
    // We always update raw values
    _rcRawValue[chan] = fval;
    
267
    qCDebug(PX4RCCalibrationLog) << "Raw value" << chan << fval;
Don Gagne's avatar
Don Gagne committed
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    
    if (_currentStep == -1) {
        // Track the receiver channel count by keeping track of how many channels we see
        if (chan + 1 > (int)_chanCount) {
            _chanCount = chan + 1;
            _ui->receiverInfo->setText(tr("%1 channel receiver").arg(_chanCount));
            if (_chanCount < _chanMinimum) {
                _ui->rcCalStatus->setText(tr("Detected %1 radio channels. To operate PX4, you need at least %2 channels.").arg(_chanCount).arg(_chanMinimum));
            } else {
                _ui->rcCalStatus->clear();
            }
        }
    }
    
    if (_currentStep != -1) {
        const stateMachineEntry* state = _getStateMachineEntry(_currentStep);
        Q_ASSERT(state);
        if (state->rcInputFn) {
            (this->*state->rcInputFn)(state->function, chan, fval);
        }
    }
}

void PX4RCCalibration::_nextButton(void)
{
    if (_currentStep == -1) {
        // Need to have enough channels
        if (_chanCount < _chanMinimum) {
            if (_unitTestMode) {
                emit nextButtonMessageBoxDisplayed();
            } else {
Don Gagne's avatar
Don Gagne committed
299
                QGCMessageBox::warning(tr("Receiver"), tr("Detected %1 radio channels. To operate PX4, you need at least %2 channels.").arg(_chanCount).arg(_chanMinimum));
Don Gagne's avatar
Don Gagne committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
            }
            return;
        }
        _startCalibration();
    } else {
        const stateMachineEntry* state = _getStateMachineEntry(_currentStep);
        Q_ASSERT(state);
        Q_ASSERT(state->nextFn);
        (this->*state->nextFn)();
    }
}

void PX4RCCalibration::_skipButton(void)
{
    Q_ASSERT(_currentStep != -1);
    
    const stateMachineEntry* state = _getStateMachineEntry(_currentStep);
    Q_ASSERT(state);
    Q_ASSERT(state->skipFn);
    (this->*state->skipFn)();
}

void PX4RCCalibration::_trimNYI(void)
{
Don Gagne's avatar
Don Gagne committed
324
    QGCMessageBox::warning(tr("Set Trim"), tr("Setting individual trims is not yet implemented. You will need to go through full calibration to set trims."));
Don Gagne's avatar
Don Gagne committed
325 326 327 328 329 330 331 332 333 334
}

void PX4RCCalibration::_saveAllTrims(void)
{
    // We save all trims as the first step. At this point no channels are mapped but it should still
    // allow us to get good trims for the roll/pitch/yaw/throttle even though we don't know which
    // channels they are yet. AS we continue through the process the other channels will get their
    // trims reset to correct values.
    
    for (int i=0; i<_chanCount; i++) {
335
        qCDebug(PX4RCCalibrationLog) << "_saveAllTrims trim" << _rcRawValue[i];
Don Gagne's avatar
Don Gagne committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
        _rgChannelInfo[i].rcTrim = _rcRawValue[i];
    }
    _nextStep();
}

/// @brief Waits for the sticks to be centered, enabling Next when done.
void PX4RCCalibration::_inputCenterWaitBegin(enum rcCalFunctions function, int chan, int value)
{
    Q_UNUSED(function);
    Q_UNUSED(chan);
    Q_UNUSED(value);
    
    // FIXME: Doesn't wait for center
    
    _ui->rcCalNext->setEnabled(true);
}

bool PX4RCCalibration::_stickSettleComplete(int value)
{
    // We are waiting for the stick to settle out to a max position
    
    if (abs(_stickDetectValue - value) > _rcCalSettleDelta) {
        // Stick is moving too much to consider stopped
        
360
        qCDebug(PX4RCCalibrationLog) << "_stickSettleComplete still moving, _stickDetectValue:value" << _stickDetectValue << value;
Don Gagne's avatar
Don Gagne committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376

        _stickDetectValue = value;
        _stickDetectSettleStarted = false;
    } else {
        // Stick is still positioned within the specified small range
        
        if (_stickDetectSettleStarted) {
            // We have already started waiting
            
            if (_stickDetectSettleElapsed.elapsed() > _stickDetectSettleMSecs) {
                // Stick has stayed positioned in one place long enough, detection is complete.
                return true;
            }
        } else {
            // Start waiting for the stick to stay settled for _stickDetectSettleWaitMSecs msecs
            
377
            qCDebug(PX4RCCalibrationLog) << "_stickSettleComplete starting settle timer, _stickDetectValue:value" << _stickDetectValue << value;
Don Gagne's avatar
Don Gagne committed
378 379 380 381 382 383 384 385 386 387 388
            
            _stickDetectSettleStarted = true;
            _stickDetectSettleElapsed.start();
        }
    }
    
    return false;
}

void PX4RCCalibration::_inputStickDetect(enum rcCalFunctions function, int channel, int value)
{
389
    qCDebug(PX4RCCalibrationLog) << "_inputStickDetect function:channel:value" << _rgFunctionInfo[function].parameterName << channel << value;
Don Gagne's avatar
Don Gagne committed
390 391 392 393 394
    
    // If this channel is already used in a mapping we can't use it again
    if (_rgChannelInfo[channel].function != rcCalFunctionMax) {
        return;
    }
395
    
Don Gagne's avatar
Don Gagne committed
396 397 398 399 400 401
    if (_stickDetectChannel == _chanMax) {
        // We have not detected enough movement on a channel yet
        
        if (abs(_rcValueSave[channel] - value) > _rcCalMoveDelta) {
            // Stick has moved far enough to consider it as being selected for the function
            
402
            qCDebug(PX4RCCalibrationLog) << "_inputStickDetect starting settle wait, function:channel:value" << function << channel << value;
Don Gagne's avatar
Don Gagne committed
403 404 405 406 407 408 409 410 411 412
            
            // Setup up to detect stick being pegged to min or max value
            _stickDetectChannel = channel;
            _stickDetectInitialValue = value;
            _stickDetectValue = value;
        }
    } else if (channel == _stickDetectChannel) {
        if (_stickSettleComplete(value)) {
            ChannelInfo* info = &_rgChannelInfo[channel];
            
413
            qCDebug(PX4RCCalibrationLog) << "_inputStickDetect settle complete, function:channel:value" << function << channel << value;
Don Gagne's avatar
Don Gagne committed
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 458 459 460 461 462 463 464 465 466 467 468 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 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
            
            // Stick detection is complete. Stick should be at max position.
            // Map the channel to the function
            _rgFunctionChannelMapping[function] = channel;
            info->function = function;
            
            // Channel should be at max value, if it is below initial set point the the channel is reversed.
            info->reversed = value < _rcValueSave[channel];
            
            if (info->reversed) {
                _rgRCValueMonitorWidget[channel]->setMin(value);
                _rgRCValueMonitorWidget[channel]->setMinValid(true);
                _rgChannelInfo[channel].rcMin = value;
            } else {
                _rgRCValueMonitorWidget[channel]->setMax(value);
                _rgRCValueMonitorWidget[channel]->setMaxValid(true);
                _rgChannelInfo[channel].rcMax = value;
            }
            
            _nextStep();
        }
    }
}

void PX4RCCalibration::_inputStickMin(enum rcCalFunctions function, int channel, int value)
{
    // We only care about the channel mapped to the function we are working on
    if (_rgFunctionChannelMapping[function] != channel) {
        return;
    }

    if (_stickDetectChannel == _chanMax) {
        // Setup up to detect stick being pegged to extreme position
        if (_rgChannelInfo[channel].reversed) {
            if (value > _rcCalPWMCenterPoint + _rcCalMoveDelta) {
                _stickDetectChannel = channel;
                _stickDetectInitialValue = value;
                _stickDetectValue = value;
            }
        } else {
            if (value < _rcCalPWMCenterPoint - _rcCalMoveDelta) {
                _stickDetectChannel = channel;
                _stickDetectInitialValue = value;
                _stickDetectValue = value;
            }
        }
    } else {
        // We are waiting for the selected channel to settle out
        
        if (_stickSettleComplete(value)) {
            ChannelInfo* info = &_rgChannelInfo[channel];
            
            // Stick detection is complete. Stick should be at min position.
            if (info->reversed) {
                _rgRCValueMonitorWidget[channel]->setMax(value);
                _rgRCValueMonitorWidget[channel]->setMaxValid(true);
                _rgChannelInfo[channel].rcMax = value;
            } else {
                _rgRCValueMonitorWidget[channel]->setMin(value);
                _rgRCValueMonitorWidget[channel]->setMinValid(true);
                _rgChannelInfo[channel].rcMin = value;
            }
            
            _nextStep();
        }
    }
}

void PX4RCCalibration::_inputCenterWait(enum rcCalFunctions function, int channel, int value)
{
    // We only care about the channel mapped to the function we are working on
    if (_rgFunctionChannelMapping[function] != channel) {
        return;
    }
    
    if (_stickDetectChannel == _chanMax) {
        // Sticks have not yet moved close enough to center
        
        if (abs(_rcCalPWMCenterPoint - value) < _rcCalRoughCenterDelta) {
            // Stick has moved close enough to center that we can start waiting for it to settle
            _stickDetectChannel = channel;
            _stickDetectInitialValue = value;
            _stickDetectValue = value;
        }
    } else {
        if (_stickSettleComplete(value)) {
            _nextStep();
        }
    }
}

/// @brief Saves min/max for non-mapped channels
void PX4RCCalibration::_inputSwitchMinMax(enum rcCalFunctions function, int channel, int value)
{
    Q_UNUSED(function);

    // If the channel is mapped we already have min/max
    if (_rgChannelInfo[channel].function != rcCalFunctionMax) {
        return;
    }
    
    if (abs(_rcCalPWMCenterPoint - value) > _rcCalMoveDelta) {
        // Stick has moved far enough from center to consider for min/max
        if (value < _rcCalPWMCenterPoint) {
            int minValue = qMin(_rgChannelInfo[channel].rcMin, value);
            
520
            qCDebug(PX4RCCalibrationLog) << "_inputSwitchMinMax setting min channel:min" << channel << minValue;
Don Gagne's avatar
Don Gagne committed
521 522 523 524 525 526 527
            
            _rgChannelInfo[channel].rcMin = minValue;
            _rgRCValueMonitorWidget[channel]->setMin(minValue);
            _rgRCValueMonitorWidget[channel]->setMinValid(true);
        } else {
            int maxValue = qMax(_rgChannelInfo[channel].rcMax, value);
            
528
            qCDebug(PX4RCCalibrationLog) << "_inputSwitchMinMax setting max channel:max" << channel << maxValue;
Don Gagne's avatar
Don Gagne committed
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
            
            _rgChannelInfo[channel].rcMax = maxValue;
            _rgRCValueMonitorWidget[channel]->setMax(maxValue);
            _rgRCValueMonitorWidget[channel]->setMaxValid(true);
        }
    }
}

void PX4RCCalibration::_skipFlaps(void)
{
    // Flaps channel may have been identified. Clear it out.
    for (int i=0; i<_chanCount; i++) {
        if (_rgChannelInfo[i].function == PX4RCCalibration::rcCalFunctionFlaps) {
            _rgChannelInfo[i].function = rcCalFunctionMax;
        }
    }
    _rgFunctionChannelMapping[PX4RCCalibration::rcCalFunctionFlaps] = _chanMax;

    // Skip over flap steps
    _currentStep += 2;
    _setupCurrentState();
}

void PX4RCCalibration::_saveFlapsDown(void)
{
    int channel = _rgFunctionChannelMapping[rcCalFunctionFlaps];
    
    if (channel == _chanMax) {
        // Channel not yet mapped, still waiting for switch to move
        if (_unitTestMode) {
            emit nextButtonMessageBoxDisplayed();
        } else {
Don Gagne's avatar
Don Gagne committed
561
            QGCMessageBox::warning(tr("Flaps switch"), tr("Flaps switch has not yet been detected."));
Don Gagne's avatar
Don Gagne committed
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
        }
        return;
    }
    
    Q_ASSERT(channel != -1);
    ChannelInfo* info = &_rgChannelInfo[channel];
    
    int rcValue = _rcRawValue[channel];
    
    // Switch detection is complete. Switch should be at flaps fully extended position.
    
    // Channel should be at max value, if it is below initial set point the channel is reversed.
    info->reversed = rcValue < _rcValueSave[channel];
    
    if (info->reversed) {
        _rgRCValueMonitorWidget[channel]->setMin(rcValue);
        _rgRCValueMonitorWidget[channel]->setMinValid(true);
        _rgChannelInfo[channel].rcMin = rcValue;
    } else {
        _rgRCValueMonitorWidget[channel]->setMax(rcValue);
        _rgRCValueMonitorWidget[channel]->setMaxValid(true);
        _rgChannelInfo[channel].rcMax = rcValue;
    }
    
    _nextStep();
}

void PX4RCCalibration::_inputFlapsUp(enum rcCalFunctions function, int channel, int value)
{
591 592
    Q_UNUSED(function);
    
Don Gagne's avatar
Don Gagne committed
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
    // FIXME: Duplication
    
    Q_ASSERT(function == rcCalFunctionFlaps);
    
    // We only care about the channel mapped to flaps
    if (_rgFunctionChannelMapping[rcCalFunctionFlaps] != channel) {
        return;
    }
    
    if (_stickDetectChannel == _chanMax) {
        // Setup up to detect stick being pegged to extreme position
        if (_rgChannelInfo[channel].reversed) {
            if (value > _rcCalPWMCenterPoint + _rcCalMoveDelta) {
                _stickDetectChannel = channel;
                _stickDetectInitialValue = value;
                _stickDetectValue = value;
            }
        } else {
            if (value < _rcCalPWMCenterPoint - _rcCalMoveDelta) {
                _stickDetectChannel = channel;
                _stickDetectInitialValue = value;
                _stickDetectValue = value;
            }
        }
    } else {
        // We are waiting for the selected channel to settle out
        
        if (_stickSettleComplete(value)) {
            ChannelInfo* info = &_rgChannelInfo[channel];
            
            // Stick detection is complete. Stick should be at min position.
            if (info->reversed) {
                _rgRCValueMonitorWidget[channel]->setMax(value);
                _rgRCValueMonitorWidget[channel]->setMaxValid(true);
                _rgChannelInfo[channel].rcMax = value;
            } else {
                _rgRCValueMonitorWidget[channel]->setMin(value);
                _rgRCValueMonitorWidget[channel]->setMinValid(true);
                _rgChannelInfo[channel].rcMin = value;
            }
            
            _nextStep();
        }
    }
}

void PX4RCCalibration::_switchDetect(enum rcCalFunctions function, int channel, int value, bool moveToNextStep)
{
    // If this channel is already used in a mapping we can't use it again
    if (_rgChannelInfo[channel].function != rcCalFunctionMax) {
        return;
    }
    
    if (abs(_rcValueSave[channel] - value) > _rcCalMoveDelta) {
        ChannelInfo* info = &_rgChannelInfo[channel];
        
        // Switch has moved far enough to consider it as being selected for the function
        
        // Map the channel to the function
        _rgChannelInfo[channel].function = function;
        _rgFunctionChannelMapping[function] = channel;
        info->function = function;
        
656
        qCDebug(PX4RCCalibrationLog) << "Function:" << function << "mapped to:" << channel;
Don Gagne's avatar
Don Gagne committed
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
        
        if (moveToNextStep) {
            _nextStep();
        }
    }
}

void PX4RCCalibration::_inputSwitchDetect(enum rcCalFunctions function, int channel, int value)
{
    _switchDetect(function, channel, value, true /* move to next step after detection */);
}

void PX4RCCalibration::_inputFlapsDetect(enum rcCalFunctions function, int channel, int value)
{
    _switchDetect(function, channel, value, false /* do not move to next step after detection */);
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
}

/// @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;
    }
    
687
    // Initialize attitude function mapping to function channel not set
688 689 690 691 692
    for (size_t i=0; i<rcCalFunctionMax; i++) {
        _rgFunctionChannelMapping[i] = _chanMax;
    }
    
    _showMinMaxOnRadioWidgets(false);
Don Gagne's avatar
Don Gagne committed
693
    _showTrimOnRadioWidgets(false);
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    
    // Reserve the existing Flight Mode switch settings channels so we don't re-use them
    
    static const rcCalFunctions rgFlightModeFunctions[] = {
        rcCalFunctionModeSwitch,
        rcCalFunctionPosCtlSwitch,
        rcCalFunctionLoiterSwitch,
        rcCalFunctionReturnSwitch };
    static const size_t crgFlightModeFunctions = sizeof(rgFlightModeFunctions) / sizeof(rgFlightModeFunctions[0]);

    int componentId = _paramMgr->getDefaultComponentId();
    for (size_t i=0; i < crgFlightModeFunctions; i++) {
        QVariant value;
        enum rcCalFunctions curFunction = rgFlightModeFunctions[i];
        
        bool paramFound = _paramMgr->getParameterValue(componentId, _rgFunctionInfo[curFunction].parameterName, value);
        Q_ASSERT(paramFound);
Don Gagne's avatar
Don Gagne committed
711
        Q_UNUSED(paramFound);
712 713
        
        bool ok;
714
        int switchChannel = value.toInt(&ok);
715 716 717 718 719 720
        Q_ASSERT(ok);
        Q_UNUSED(ok);
        
        // Parameter: 1-based channel, 0=not mapped
        // _rgFunctionChannelMapping: 0-based channel, _chanMax=not mapped
        
721 722 723 724
        if (switchChannel != 0) {
            qCDebug(PX4RCCalibrationLog) << "Reserving 0-based switch channel" << switchChannel - 1;
            _rgFunctionChannelMapping[curFunction] = switchChannel - 1;
            _rgChannelInfo[switchChannel - 1].function = curFunction;
725 726
        }
    }
Don Gagne's avatar
Don Gagne committed
727 728
}

Don Gagne's avatar
Don Gagne committed
729
/// @brief Sets internal calibration values from the stored parameters
Don Gagne's avatar
Don Gagne committed
730 731 732 733
void PX4RCCalibration::_setInternalCalibrationValuesFromParameters(void)
{
    Q_ASSERT(_paramMgr);
    
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
    // 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;
    int componentId = _paramMgr->getDefaultComponentId();
    
    for (int i = 0; i < _chanMax; ++i) {
        struct ChannelInfo* info = &_rgChannelInfo[i];
Don Gagne's avatar
Don Gagne committed
760
        
761 762 763 764 765
        paramFound = _paramMgr->getParameterValue(componentId, trimTpl.arg(i+1), value);
        Q_ASSERT(paramFound);
        if (paramFound) {
            info->rcTrim = value.toInt(&convertOk);
            Q_ASSERT(convertOk);
Don Gagne's avatar
Don Gagne committed
766 767
        }
        
768 769 770 771 772
        paramFound = _paramMgr->getParameterValue(componentId, minTpl.arg(i+1), value);
        Q_ASSERT(paramFound);
        if (paramFound) {
            info->rcMin = value.toInt(&convertOk);
            Q_ASSERT(convertOk);
Don Gagne's avatar
Don Gagne committed
773 774
        }

775 776 777 778 779 780
        paramFound = _paramMgr->getParameterValue(componentId, maxTpl.arg(i+1), value);
        Q_ASSERT(paramFound);
        if (paramFound) {
            info->rcMax = value.toInt(&convertOk);
            Q_ASSERT(convertOk);
        }
Don Gagne's avatar
Don Gagne committed
781

782 783 784 785 786 787 788
        paramFound = _paramMgr->getParameterValue(componentId, 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;
Don Gagne's avatar
Don Gagne committed
789
        }
790 791 792 793
    }
    
    for (int i=0; i<rcCalFunctionMax; i++) {
        int32_t paramChannel;
Don Gagne's avatar
Don Gagne committed
794
        
795 796 797 798 799
        paramFound = _paramMgr->getParameterValue(componentId, _rgFunctionInfo[i].parameterName, value);
        Q_ASSERT(paramFound);
        if (paramFound) {
            paramChannel = value.toInt(&convertOk);
            Q_ASSERT(convertOk);
Don Gagne's avatar
Don Gagne committed
800
            
801 802 803
            if (paramChannel != 0) {
                _rgFunctionChannelMapping[i] = paramChannel - 1;
                _rgChannelInfo[paramChannel - 1].function = (enum rcCalFunctions)i;
Don Gagne's avatar
Don Gagne committed
804 805 806
            }
        }
    }
807 808 809
    
    _showMinMaxOnRadioWidgets(true);
    _showTrimOnRadioWidgets(true);
810 811 812
}

/// @brief Sets a connected Spektrum receiver into bind mode
Don Gagne's avatar
Don Gagne committed
813 814 815 816
void PX4RCCalibration::_spektrumBind(void)
{

    Q_ASSERT(_mav);
817
    
Don Gagne's avatar
Don Gagne committed
818 819 820 821 822 823 824 825 826 827 828
    QMessageBox bindTypeMsg(this);
    
    bindTypeMsg.setWindowModality(Qt::ApplicationModal);
    QPushButton* dsm2Mode = bindTypeMsg.addButton("DSM2", QMessageBox::AcceptRole);
    QPushButton* dsmx7Mode = bindTypeMsg.addButton("DSMX (7 channels or less)", QMessageBox::AcceptRole);
    QPushButton* dsmx8Mode = bindTypeMsg.addButton("DSMX (8 channels or more)", QMessageBox::AcceptRole);
    bindTypeMsg.addButton(QMessageBox::Cancel);
    
    bindTypeMsg.setWindowTitle(tr("Spektrum Bind"));
    bindTypeMsg.setText(tr("Place Spektrum satellite receiver in bind mode. Select which mode below."));
    
829
    int bindType = 0;
Don Gagne's avatar
Don Gagne committed
830 831 832 833 834 835 836 837 838 839 840
    if (bindTypeMsg.exec() != QMessageBox::Cancel) {
        if (bindTypeMsg.clickedButton() == dsm2Mode) {
            bindType = 0;
        } else if (bindTypeMsg.clickedButton() == dsmx7Mode) {
            bindType = 1;
        } else if (bindTypeMsg.clickedButton() == dsmx8Mode) {
            bindType = 2;
        } else {
            Q_ASSERT(false);
        }
        _mav->pairRX(0, bindType);
841 842 843
    }
}

Don Gagne's avatar
Don Gagne committed
844 845 846 847 848 849 850 851 852 853
/// @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) {
854
                qCDebug(PX4RCCalibrationLog) << "_validateCalibration resetting channel" << chan;
Don Gagne's avatar
Don Gagne committed
855 856
                info->rcMin = _rcCalPWMDefaultMinValue;
                info->rcMax = _rcCalPWMDefaultMaxValue;
Don Gagne's avatar
Don Gagne committed
857 858 859 860 861 862 863
                info->rcTrim = info->rcMin + ((info->rcMax - info->rcMin) / 2);
            } else {
                switch (_rgChannelInfo[chan].function) {
                    case rcCalFunctionThrottle:
                    case rcCalFunctionYaw:
                    case rcCalFunctionRoll:
                    case rcCalFunctionPitch:
864 865 866 867 868 869
                        // Make sure trim is within min/max
                        if (info->rcTrim < info->rcMin) {
                            info->rcTrim = info->rcMin;
                        } else if (info->rcTrim > info->rcMax) {
                            info->rcTrim = info->rcMax;
                        }
Don Gagne's avatar
Don Gagne committed
870 871 872 873 874 875 876
                        break;
                    default:
                        // Non-attitude control channels have calculated trim
                        info->rcTrim = info->rcMin + ((info->rcMax - info->rcMin) / 2);
                        break;
                }
                
Don Gagne's avatar
Don Gagne committed
877 878 879
            }
        } else {
            // Unavailable channels are set to defaults
880
            qCDebug(PX4RCCalibrationLog) << "_validateCalibration resetting unavailable channel" << chan;
Don Gagne's avatar
Don Gagne committed
881 882
            info->rcMin = _rcCalPWMDefaultMinValue;
            info->rcMax = _rcCalPWMDefaultMaxValue;
Don Gagne's avatar
Don Gagne committed
883
            info->rcTrim = info->rcMin + ((info->rcMax - info->rcMin) / 2);
Don Gagne's avatar
Don Gagne committed
884 885 886 887 888 889
            info->reversed = false;
        }
    }
}


890
/// @brief Saves the rc calibration values to the board parameters.
Don Gagne's avatar
Don Gagne committed
891
void PX4RCCalibration::_writeCalibration(void)
892 893 894 895 896
{
    if (!_mav) return;
    
    _mav->endRadioControlCalibration();
    
Don Gagne's avatar
Don Gagne committed
897 898
    _validateCalibration();
    
899 900 901 902 903 904 905 906
    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
907
    // Note that the rc parameters are all float, so you must cast to float in order to get the right QVariant
Don Gagne's avatar
Don Gagne committed
908 909 910
    for (int chan = 0; chan<_chanMax; chan++) {
        struct ChannelInfo* info = &_rgChannelInfo[chan];
        int oneBasedChannel = chan + 1;
Don Gagne's avatar
Don Gagne committed
911 912 913 914
        paramMgr->setPendingParam(0, trimTpl.arg(oneBasedChannel), (float)info->rcTrim);
        paramMgr->setPendingParam(0, minTpl.arg(oneBasedChannel), (float)info->rcMin);
        paramMgr->setPendingParam(0, maxTpl.arg(oneBasedChannel), (float)info->rcMax);
        paramMgr->setPendingParam(0, revTpl.arg(oneBasedChannel), info->reversed ? -1.0f : 1.0f);
915 916
    }
    
Don Gagne's avatar
Don Gagne committed
917 918 919 920 921 922 923 924 925
    // 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;
926
        }
Don Gagne's avatar
Don Gagne committed
927
        paramMgr->setPendingParam(0, _rgFunctionInfo[i].parameterName, paramChannel);
928 929
    }
    
930 931 932 933 934
    // If the RC_CHAN_COUNT parameter is available write the channel count
    if (paramMgr->getComponentForParam("RC_CHAN_CNT").count() != 0) {
        paramMgr->setPendingParam(0, "RC_CHAN_CNT", _chanCount);
    }

935 936 937
    //let the param mgr manage sending all the pending RC_foo updates and persisting after
    paramMgr->sendPendingParameters(true, true);
    
Don Gagne's avatar
Don Gagne committed
938
    _stopCalibration();
939 940 941 942 943 944
}

void PX4RCCalibration::_updateView()
{
    // Update the available channels
    for (int chan=0; chan<_chanCount; chan++) {
Don Gagne's avatar
Don Gagne committed
945 946 947 948
        RCValueWidget* valueWidget = _rgRCValueMonitorWidget[chan];
        
        valueWidget->setVisible(true);
        _rgRCValueMonitorLabel[chan]->setVisible(true);
949
        //qCDebug(PX4RCCalibrationLog) << "Visible" << valueWidget->objectName() << chan;
950 951
        
        struct ChannelInfo* info = &_rgChannelInfo[chan];
Don Gagne's avatar
Don Gagne committed
952 953 954
        valueWidget->setValueAndMinMax(_rcRawValue[chan], info->rcMin, info->rcMax);
        valueWidget->setTrim(info->rcTrim);
        valueWidget->setReversed(info->reversed);
955 956
    }
    
Don Gagne's avatar
Don Gagne committed
957 958 959
    // Update attitude controls
    for (int i=0; i<_attitudeControls; i++) {
        struct AttitudeInfo* attitudeInfo = &_rgAttitudeControl[i];
960
        
Don Gagne's avatar
Don Gagne committed
961 962 963 964
        if (_rgFunctionChannelMapping[attitudeInfo->function] != _chanMax) {
            int channel = _rgFunctionChannelMapping[attitudeInfo->function];
            struct ChannelInfo* info = &_rgChannelInfo[channel];
            RCValueWidget* valueWidget = attitudeInfo->valueWidget;
965
            
Don Gagne's avatar
Don Gagne committed
966 967 968
            attitudeInfo->valueWidget->setValueAndMinMax(_rcRawValue[channel], info->rcMin, info->rcMax);
            valueWidget->setTrim(info->rcTrim);
            valueWidget->setReversed(info->reversed);
Don Gagne's avatar
Don Gagne committed
969 970
        }
    }
971
    
Don Gagne's avatar
Don Gagne committed
972 973 974 975
    // Hide non-available channels
    for (int chan=_chanCount; chan<_chanMax; chan++) {
        _rgRCValueMonitorWidget[chan]->setVisible(false);
        _rgRCValueMonitorLabel[chan]->setVisible(false);
976
        qCDebug(PX4RCCalibrationLog) << "Hiding channel" << _rgRCValueMonitorWidget[chan]->objectName() << chan;
977 978 979
    }
}

Don Gagne's avatar
Don Gagne committed
980 981
/// @brief Starts the calibration process
void PX4RCCalibration::_startCalibration(void)
982 983 984
{
    Q_ASSERT(_chanCount >= _chanMinimum);
    
Don Gagne's avatar
Don Gagne committed
985 986
    _resetInternalCalibrationValues();
    
987
    // Let the mav known we are starting calibration. This should turn off motors and so forth.
Don Gagne's avatar
Don Gagne committed
988
    _mav->startRadioControlCalibration();
989 990 991 992
    
    _ui->rcCalNext->setText(tr("Next"));
    _ui->rcCalCancel->setEnabled(true);
    
Don Gagne's avatar
Don Gagne committed
993 994
    _currentStep = 0;
    _setupCurrentState();
995 996
}

Don Gagne's avatar
Don Gagne committed
997 998
/// @brief Cancels the calibration process, setting things back to initial state.
void PX4RCCalibration::_stopCalibration(void)
999
{
Don Gagne's avatar
Don Gagne committed
1000
    _currentStep = -1;
1001
    
Don Gagne's avatar
Don Gagne committed
1002 1003 1004 1005 1006
    if (_mav) {
        _mav->endRadioControlCalibration();
        _setInternalCalibrationValuesFromParameters();
    } else {
        _resetInternalCalibrationValues();
1007 1008
    }
    
Don Gagne's avatar
Don Gagne committed
1009
    _ui->rcCalStatus->clear();
1010

Don Gagne's avatar
Don Gagne committed
1011
    _ui->rcCalNext->setText(tr("Calibrate"));
1012
    _ui->rcCalNext->setEnabled(true);
Don Gagne's avatar
Don Gagne committed
1013
    _ui->rcCalCancel->setEnabled(false);
1014
    _ui->rcCalSkip->setEnabled(false);
1015 1016
    
    _setHelpImage(_imageCenter);
1017 1018
}

Don Gagne's avatar
Don Gagne committed
1019 1020
/// @brief Saves the current channel values, so that we can detect when the use moves an input.
void PX4RCCalibration::_rcCalSaveCurrentValues(void)
1021
{
1022
	qCDebug(PX4RCCalibrationLog) << "_rcCalSaveCurrentValues";
Don Gagne's avatar
Don Gagne committed
1023 1024 1025
    for (unsigned i = 0; i < _chanMax; i++) {
        _rcValueSave[i] = _rcRawValue[i];
    }
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
}

/// @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->rcCalNext->setEnabled(true);
    _ui->rcCalSkip->setEnabled(false);
    _ui->rcCalCancel->setEnabled(true);
Don Gagne's avatar
Don Gagne committed
1039 1040 1041 1042 1043 1044
    
    // 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);
1045 1046 1047 1048 1049 1050 1051
}

/// @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)
{
    // Turn on min/max display for all radio widgets
Don Gagne's avatar
Don Gagne committed
1052
    for (int i=0; i<_chanMax; i++) {
Don Gagne's avatar
Don Gagne committed
1053
        RCValueWidget* radioWidget = _rgRCValueMonitorWidget[i];
1054 1055 1056
        Q_ASSERT(radioWidget);
        
        radioWidget->showMinMax(show);
Don Gagne's avatar
Don Gagne committed
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
        if (show) {
            if (radioWidget->min() <= _rcCalPWMValidMinValue) {
                radioWidget->setMinValid(true);
            }
            if (radioWidget->max() >= _rcCalPWMValidMaxValue) {
                radioWidget->setMaxValid(true);
            }
        } else {
            radioWidget->setMinValid(false);
            radioWidget->setMaxValid(false);
        }
1068
    }
Don Gagne's avatar
Don Gagne committed
1069 1070 1071 1072 1073 1074 1075
}

/// @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
1076
    for (int i=0; i<_chanMax; i++) {
Don Gagne's avatar
Don Gagne committed
1077
        RCValueWidget* radioWidget = _rgRCValueMonitorWidget[i];
1078 1079
        Q_ASSERT(radioWidget);
        
Don Gagne's avatar
Don Gagne committed
1080 1081 1082 1083
        radioWidget->showTrim(show);
    }
}

1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141

void PX4RCCalibration::_loadSettings(void)
{
    QSettings settings;
    
    settings.beginGroup(_settingsGroup);
    _transmitterMode = settings.value(_settingsKeyTransmitterMode, 2).toInt();
    settings.endGroup();
    
    if (_transmitterMode != 1 || _transmitterMode != 2) {
        _transmitterMode = 2;
    }
}

void PX4RCCalibration::_storeSettings(void)
{
    QSettings settings;
    
    settings.beginGroup(_settingsGroup);
    settings.setValue(_settingsKeyTransmitterMode, _transmitterMode);
    settings.endGroup();
}

void PX4RCCalibration::_mode1Toggled(bool checked)
{
    if (checked) {
        _transmitterMode = 1;
        if (_currentStep != -1) {
            const stateMachineEntry* state = _getStateMachineEntry(_currentStep);
            _setHelpImage(state->image);
        }
    }
}

void PX4RCCalibration::_mode2Toggled(bool checked)
{
    if (checked) {
        _transmitterMode = 2;
        if (_currentStep != -1) {
            const stateMachineEntry* state = _getStateMachineEntry(_currentStep);
            _setHelpImage(state->image);
        }
    }
}

void PX4RCCalibration::_setHelpImage(const char* imageFile)
{
    QString file = _imageFilePrefix;
    
    if (_transmitterMode == 1) {
        file += _imageFileMode1Dir;
    } else if (_transmitterMode == 2) {
        file += _imageFileMode2Dir;
    } else {
        Q_ASSERT(false);
    }
    file += imageFile;
    
1142
    qCDebug(PX4RCCalibrationLog) << "_setHelpImage" << file;
1143 1144 1145
    
    _ui->radioIcon->setPixmap(QPixmap(file));
}