RadioComponentController.cc 41.5 KB
Newer Older
1 2 3 4
/*=====================================================================
 
 QGroundControl Open Source Ground Control Station
 
Don Gagne's avatar
Don Gagne committed
5
 (c) 2009, 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 
 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
Don Gagne's avatar
Don Gagne committed
25
///     @brief Radio Config Qml Controller
26 27
///     @author Don Gagne <don@thegagnes.com

Don Gagne's avatar
Don Gagne committed
28
#include "RadioComponentController.h"
Don Gagne's avatar
Don Gagne committed
29
#include "QGCMessageBox.h"
30
#include "AutoPilotPluginManager.h"
31

Don Gagne's avatar
Don Gagne committed
32 33 34
#include <QSettings>

QGC_LOGGING_CATEGORY(RadioComponentControllerLog, "RadioComponentControllerLog")
35

36 37 38 39 40
#ifdef UNITTEST_BUILD
// Nasty hack to expose controller to unit test code
RadioComponentController* RadioComponentController::_unitTestController = NULL;
#endif

Don Gagne's avatar
Don Gagne committed
41 42
const int RadioComponentController::_updateInterval = 150;              ///< Interval for timer which updates radio channel widgets
const int RadioComponentController::_rcCalPWMCenterPoint = ((RadioComponentController::_rcCalPWMValidMaxValue - RadioComponentController::_rcCalPWMValidMinValue) / 2.0f) + RadioComponentController::_rcCalPWMValidMinValue;
Don Gagne's avatar
Don Gagne committed
43
// FIXME: Double check these mins againt 150% throws
Don Gagne's avatar
Don Gagne committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
const int RadioComponentController::_rcCalPWMValidMinValue = 1300;      ///< Largest valid minimum PWM Min range value
const int RadioComponentController::_rcCalPWMValidMaxValue = 1700;      ///< Smallest valid maximum PWM Max range value
const int RadioComponentController::_rcCalPWMDefaultMinValue = 1000;    ///< Default value for Min if not set
const int RadioComponentController::_rcCalPWMDefaultMaxValue = 2000;    ///< Default value for Max if not set
const int RadioComponentController::_rcCalRoughCenterDelta = 50;        ///< Delta around center point which is considered to be roughly centered
const int RadioComponentController::_rcCalMoveDelta = 300;            ///< Amount of delta past center which is considered stick movement
const int RadioComponentController::_rcCalSettleDelta = 20;           ///< Amount of delta which is considered no stick movement
const int RadioComponentController::_rcCalMinDelta = 100;             ///< Amount of delta allowed around min value to consider channel at min

const int RadioComponentController::_stickDetectSettleMSecs = 500;

const char*  RadioComponentController::_imageFilePrefix = "calibration/";
const char*  RadioComponentController::_imageFileMode1Dir = "mode1/";
const char*  RadioComponentController::_imageFileMode2Dir = "mode2/";
const char*  RadioComponentController::_imageCenter = "radioCenter.png";
const char*  RadioComponentController::_imageHome = "radioHome.png";
const char*  RadioComponentController::_imageThrottleUp = "radioThrottleUp.png";
const char*  RadioComponentController::_imageThrottleDown = "radioThrottleDown.png";
const char*  RadioComponentController::_imageYawLeft = "radioYawLeft.png";
const char*  RadioComponentController::_imageYawRight = "radioYawRight.png";
const char*  RadioComponentController::_imageRollLeft = "radioRollLeft.png";
const char*  RadioComponentController::_imageRollRight = "radioRollRight.png";
const char*  RadioComponentController::_imagePitchUp = "radioPitchUp.png";
const char*  RadioComponentController::_imagePitchDown = "radioPitchDown.png";
const char*  RadioComponentController::_imageSwitchMinMax = "radioSwitchMinMax.png";

const char* RadioComponentController::_settingsGroup = "RadioCalibration";
const char* RadioComponentController::_settingsKeyTransmitterMode = "TransmitterMode";

const struct RadioComponentController::FunctionInfo RadioComponentController::_rgFunctionInfo[RadioComponentController::rcCalFunctionMax] = {
Don Gagne's avatar
Don Gagne committed
74 75 76 77 78 79 80 81 82
    //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" },
83
    { "RC_MAP_ACRO_SW" },
Don Gagne's avatar
Don Gagne committed
84 85 86
    { "RC_MAP_FLAPS" },
    { "RC_MAP_AUX1" },
    { "RC_MAP_AUX2" },
87 88
};

Don Gagne's avatar
Don Gagne committed
89
RadioComponentController::RadioComponentController(void) :
Don Gagne's avatar
Don Gagne committed
90
    _currentStep(-1),
91
    _transmitterMode(2),
92 93
    _chanCount(0),
    _rcCalState(rcCalStateChannelWait),
Don Gagne's avatar
Don Gagne committed
94 95 96 97 98
    _unitTestMode(false),
    _statusText(NULL),
    _cancelButton(NULL),
    _nextButton(NULL),
    _skipButton(NULL)
99
{
100 101 102 103 104
#ifdef UNITTEST_BUILD
    // Nasty hack to expose controller to unit test code
    _unitTestController = this;
#endif

Don Gagne's avatar
Don Gagne committed
105
    connect(_uas, &UASInterface::remoteControlChannelRawChanged, this, &RadioComponentController::_remoteControlChannelRawChanged);
106 107
    _loadSettings();
    
Don Gagne's avatar
Don Gagne committed
108 109 110 111 112
    _resetInternalCalibrationValues();
}

void RadioComponentController::start(void)
{
Don Gagne's avatar
Don Gagne committed
113
    _stopCalibration();
114
    _setInternalCalibrationValuesFromParameters();
Don Gagne's avatar
Don Gagne committed
115
}
116

Don Gagne's avatar
Don Gagne committed
117
RadioComponentController::~RadioComponentController()
Don Gagne's avatar
Don Gagne committed
118
{
119
    _storeSettings();
Don Gagne's avatar
Don Gagne committed
120
}
121

Don Gagne's avatar
Don Gagne committed
122
/// @brief Returns the state machine entry for the specified state.
Don Gagne's avatar
Don Gagne committed
123
const RadioComponentController::stateMachineEntry* RadioComponentController::_getStateMachineEntry(int step)
Don Gagne's avatar
Don Gagne committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
{
    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
Don Gagne's avatar
Don Gagne committed
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
        { rcCalFunctionMax,                 msgBegin,           _imageHome,         &RadioComponentController::_inputCenterWaitBegin,   &RadioComponentController::_saveAllTrims,       NULL },
        { rcCalFunctionThrottle,            msgThrottleUp,      _imageThrottleUp,   &RadioComponentController::_inputStickDetect,       NULL,                                           NULL },
        { rcCalFunctionThrottle,            msgThrottleDown,    _imageThrottleDown, &RadioComponentController::_inputStickMin,          NULL,                                           NULL },
        { rcCalFunctionYaw,                 msgYawRight,        _imageYawRight,     &RadioComponentController::_inputStickDetect,       NULL,                                           NULL },
        { rcCalFunctionYaw,                 msgYawLeft,         _imageYawLeft,      &RadioComponentController::_inputStickMin,          NULL,                                           NULL },
        { rcCalFunctionRoll,                msgRollRight,       _imageRollRight,    &RadioComponentController::_inputStickDetect,       NULL,                                           NULL },
        { rcCalFunctionRoll,                msgRollLeft,        _imageRollLeft,     &RadioComponentController::_inputStickMin,          NULL,                                           NULL },
        { rcCalFunctionPitch,               msgPitchUp,         _imagePitchUp,      &RadioComponentController::_inputStickDetect,       NULL,                                           NULL },
        { rcCalFunctionPitch,               msgPitchDown,       _imagePitchDown,    &RadioComponentController::_inputStickMin,          NULL,                                           NULL },
        { rcCalFunctionPitch,               msgPitchCenter,     _imageHome,         &RadioComponentController::_inputCenterWait,        NULL,                                           NULL },
        { rcCalFunctionMax,                 msgSwitchMinMax,    _imageSwitchMinMax, &RadioComponentController::_inputSwitchMinMax,      &RadioComponentController::_advanceState,       NULL },
        { rcCalFunctionFlaps,               msgFlapsDetect,     _imageThrottleDown, &RadioComponentController::_inputFlapsDetect,       &RadioComponentController::_saveFlapsDown,      &RadioComponentController::_skipFlaps },
        { rcCalFunctionFlaps,               msgFlapsUp,         _imageThrottleDown, &RadioComponentController::_inputFlapsUp,           NULL,                                           NULL },
        { rcCalFunctionAux1,                msgAux1Switch,      _imageThrottleDown, &RadioComponentController::_inputSwitchDetect,      NULL,                                           &RadioComponentController::_advanceState },
        { rcCalFunctionAux2,                msgAux2Switch,      _imageThrottleDown, &RadioComponentController::_inputSwitchDetect,      NULL,                                           &RadioComponentController::_advanceState },
        { rcCalFunctionMax,                 msgComplete,        _imageThrottleDown, NULL,                                               &RadioComponentController::_writeCalibration,   NULL },
Don Gagne's avatar
Don Gagne committed
167 168 169 170 171 172
    };
    
    Q_ASSERT(step >=0 && step < (int)(sizeof(rgStateMachine) / sizeof(rgStateMachine[0])));
    
    return &rgStateMachine[step];
}
173

Don Gagne's avatar
Don Gagne committed
174
void RadioComponentController::_advanceState(void)
Don Gagne's avatar
Don Gagne committed
175 176 177 178 179 180 181
{
    _currentStep++;
    _setupCurrentState();
}


/// @brief Sets up the state machine according to the current step from _currentStep.
Don Gagne's avatar
Don Gagne committed
182
void RadioComponentController::_setupCurrentState(void)
Don Gagne's avatar
Don Gagne committed
183 184 185
{
   const stateMachineEntry* state = _getStateMachineEntry(_currentStep);
    
Don Gagne's avatar
Don Gagne committed
186
    _statusText->setProperty("text", state->instructions);
187 188
    
    _setHelpImage(state->image);
Don Gagne's avatar
Don Gagne committed
189 190 191 192 193 194
    
    _stickDetectChannel = _chanMax;
    _stickDetectSettleStarted = false;
    
    _rcCalSaveCurrentValues();
    
Don Gagne's avatar
Don Gagne committed
195 196
    _nextButton->setEnabled(state->nextFn != NULL);
    _skipButton->setEnabled(state->skipFn != NULL);
Don Gagne's avatar
Don Gagne committed
197 198 199 200 201 202
}

/// @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
Don Gagne's avatar
Don Gagne committed
203
void RadioComponentController::_remoteControlChannelRawChanged(int chan, float fval)
Don Gagne's avatar
Don Gagne committed
204
{
Don Gagne's avatar
Don Gagne committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    if (chan >= 0 && chan <= _chanMax) {
        // We always update raw values
        _rcRawValue[chan] = fval;
        emit channelRCValueChanged(chan, _rcRawValue[chan]);
        
        // Signal attitude rc values to Qml if mapped
        if (_rgChannelInfo[chan].function != rcCalFunctionMax) {
            switch (_rgChannelInfo[chan].function) {
                case rcCalFunctionRoll:
                    emit rollChannelRCValueChanged(_rcRawValue[chan]);
                    break;
                case rcCalFunctionPitch:
                    emit pitchChannelRCValueChanged(_rcRawValue[chan]);
                    break;
                case rcCalFunctionYaw:
                    emit yawChannelRCValueChanged(_rcRawValue[chan]);
                    break;
                case rcCalFunctionThrottle:
                    emit throttleChannelRCValueChanged(_rcRawValue[chan]);
                    break;
                default:
                    break;

Don Gagne's avatar
Don Gagne committed
228 229
            }
        }
Don Gagne's avatar
Don Gagne committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
            
        qCDebug(RadioComponentControllerLog) << "Raw value" << chan << fval;
        
        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;
                emit channelCountChanged(_chanCount);
            }
        }
        
        if (_currentStep != -1) {
            const stateMachineEntry* state = _getStateMachineEntry(_currentStep);
            Q_ASSERT(state);
            if (state->rcInputFn) {
                (this->*state->rcInputFn)(state->function, chan, fval);
            }
Don Gagne's avatar
Don Gagne committed
247 248 249 250
        }
    }
}

Don Gagne's avatar
Don Gagne committed
251
void RadioComponentController::nextButtonClicked(void)
Don Gagne's avatar
Don Gagne committed
252 253 254 255 256 257 258
{
    if (_currentStep == -1) {
        // Need to have enough channels
        if (_chanCount < _chanMinimum) {
            if (_unitTestMode) {
                emit nextButtonMessageBoxDisplayed();
            } else {
Don Gagne's avatar
Don Gagne committed
259
                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
260 261 262 263 264 265 266 267 268 269 270 271
            }
            return;
        }
        _startCalibration();
    } else {
        const stateMachineEntry* state = _getStateMachineEntry(_currentStep);
        Q_ASSERT(state);
        Q_ASSERT(state->nextFn);
        (this->*state->nextFn)();
    }
}

Don Gagne's avatar
Don Gagne committed
272
void RadioComponentController::skipButtonClicked(void)
Don Gagne's avatar
Don Gagne committed
273 274 275 276 277 278 279 280 281
{
    Q_ASSERT(_currentStep != -1);
    
    const stateMachineEntry* state = _getStateMachineEntry(_currentStep);
    Q_ASSERT(state);
    Q_ASSERT(state->skipFn);
    (this->*state->skipFn)();
}

Don Gagne's avatar
Don Gagne committed
282
void RadioComponentController::cancelButtonClicked(void)
Don Gagne's avatar
Don Gagne committed
283
{
Don Gagne's avatar
Don Gagne committed
284
    _stopCalibration();
Don Gagne's avatar
Don Gagne committed
285 286
}

Don Gagne's avatar
Don Gagne committed
287
void RadioComponentController::_saveAllTrims(void)
Don Gagne's avatar
Don Gagne committed
288 289 290 291 292 293 294
{
    // 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++) {
Don Gagne's avatar
Don Gagne committed
295
        qCDebug(RadioComponentControllerLog) << "_saveAllTrims trim" << _rcRawValue[i];
Don Gagne's avatar
Don Gagne committed
296 297
        _rgChannelInfo[i].rcTrim = _rcRawValue[i];
    }
Don Gagne's avatar
Don Gagne committed
298
    _advanceState();
Don Gagne's avatar
Don Gagne committed
299 300 301
}

/// @brief Waits for the sticks to be centered, enabling Next when done.
Don Gagne's avatar
Don Gagne committed
302
void RadioComponentController::_inputCenterWaitBegin(enum rcCalFunctions function, int chan, int value)
Don Gagne's avatar
Don Gagne committed
303 304 305 306 307 308 309
{
    Q_UNUSED(function);
    Q_UNUSED(chan);
    Q_UNUSED(value);
    
    // FIXME: Doesn't wait for center
    
Don Gagne's avatar
Don Gagne committed
310
    _nextButton->setEnabled(true);
Don Gagne's avatar
Don Gagne committed
311 312
}

Don Gagne's avatar
Don Gagne committed
313
bool RadioComponentController::_stickSettleComplete(int value)
Don Gagne's avatar
Don Gagne committed
314 315 316 317 318 319
{
    // 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
        
Don Gagne's avatar
Don Gagne committed
320
        qCDebug(RadioComponentControllerLog) << "_stickSettleComplete still moving, _stickDetectValue:value" << _stickDetectValue << value;
Don Gagne's avatar
Don Gagne committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336

        _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
            
Don Gagne's avatar
Don Gagne committed
337
            qCDebug(RadioComponentControllerLog) << "_stickSettleComplete starting settle timer, _stickDetectValue:value" << _stickDetectValue << value;
Don Gagne's avatar
Don Gagne committed
338 339 340 341 342 343 344 345 346
            
            _stickDetectSettleStarted = true;
            _stickDetectSettleElapsed.start();
        }
    }
    
    return false;
}

Don Gagne's avatar
Don Gagne committed
347
void RadioComponentController::_inputStickDetect(enum rcCalFunctions function, int channel, int value)
Don Gagne's avatar
Don Gagne committed
348
{
Don Gagne's avatar
Don Gagne committed
349
    qCDebug(RadioComponentControllerLog) << "_inputStickDetect function:channel:value" << _rgFunctionInfo[function].parameterName << channel << value;
Don Gagne's avatar
Don Gagne committed
350 351 352 353 354
    
    // If this channel is already used in a mapping we can't use it again
    if (_rgChannelInfo[channel].function != rcCalFunctionMax) {
        return;
    }
355
    
Don Gagne's avatar
Don Gagne committed
356 357 358 359 360 361
    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
            
Don Gagne's avatar
Don Gagne committed
362
            qCDebug(RadioComponentControllerLog) << "_inputStickDetect starting settle wait, function:channel:value" << function << channel << value;
Don Gagne's avatar
Don Gagne committed
363 364 365 366 367 368 369 370 371 372
            
            // 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];
            
Don Gagne's avatar
Don Gagne committed
373
            qCDebug(RadioComponentControllerLog) << "_inputStickDetect settle complete, function:channel:value" << function << channel << value;
Don Gagne's avatar
Don Gagne committed
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
            
            // 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) {
                _rgChannelInfo[channel].rcMin = value;
            } else {
                _rgChannelInfo[channel].rcMax = value;
            }
            
Don Gagne's avatar
Don Gagne committed
389 390 391
            _signalAllAttiudeValueChanges();
            
            _advanceState();
Don Gagne's avatar
Don Gagne committed
392 393 394 395
        }
    }
}

Don Gagne's avatar
Don Gagne committed
396
void RadioComponentController::_inputStickMin(enum rcCalFunctions function, int channel, int value)
Don Gagne's avatar
Don Gagne committed
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
{
    // 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) {
                _rgChannelInfo[channel].rcMax = value;
            } else {
                _rgChannelInfo[channel].rcMin = value;
            }
430 431 432 433 434 435 436

            // Check if this is throttle and set trim accordingly
            if (function == rcCalFunctionThrottle) {
                _rgChannelInfo[channel].rcTrim = value;
            }
            // XXX to support configs which can reverse they need to check a reverse
            // flag here and not do this.
Don Gagne's avatar
Don Gagne committed
437
            
Don Gagne's avatar
Don Gagne committed
438
            _advanceState();
Don Gagne's avatar
Don Gagne committed
439 440 441 442
        }
    }
}

Don Gagne's avatar
Don Gagne committed
443
void RadioComponentController::_inputCenterWait(enum rcCalFunctions function, int channel, int value)
Don Gagne's avatar
Don Gagne committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
{
    // 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)) {
Don Gagne's avatar
Don Gagne committed
461
            _advanceState();
Don Gagne's avatar
Don Gagne committed
462 463 464 465 466
        }
    }
}

/// @brief Saves min/max for non-mapped channels
Don Gagne's avatar
Don Gagne committed
467
void RadioComponentController::_inputSwitchMinMax(enum rcCalFunctions function, int channel, int value)
Don Gagne's avatar
Don Gagne committed
468 469 470 471 472 473 474 475 476 477 478 479 480
{
    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);
            
Don Gagne's avatar
Don Gagne committed
481
            qCDebug(RadioComponentControllerLog) << "_inputSwitchMinMax setting min channel:min" << channel << minValue;
Don Gagne's avatar
Don Gagne committed
482 483 484 485 486
            
            _rgChannelInfo[channel].rcMin = minValue;
        } else {
            int maxValue = qMax(_rgChannelInfo[channel].rcMax, value);
            
Don Gagne's avatar
Don Gagne committed
487
            qCDebug(RadioComponentControllerLog) << "_inputSwitchMinMax setting max channel:max" << channel << maxValue;
Don Gagne's avatar
Don Gagne committed
488 489 490 491 492 493
            
            _rgChannelInfo[channel].rcMax = maxValue;
        }
    }
}

Don Gagne's avatar
Don Gagne committed
494
void RadioComponentController::_skipFlaps(void)
Don Gagne's avatar
Don Gagne committed
495 496 497
{
    // Flaps channel may have been identified. Clear it out.
    for (int i=0; i<_chanCount; i++) {
Don Gagne's avatar
Don Gagne committed
498
        if (_rgChannelInfo[i].function == RadioComponentController::rcCalFunctionFlaps) {
Don Gagne's avatar
Don Gagne committed
499 500 501
            _rgChannelInfo[i].function = rcCalFunctionMax;
        }
    }
Don Gagne's avatar
Don Gagne committed
502
    _rgFunctionChannelMapping[RadioComponentController::rcCalFunctionFlaps] = _chanMax;
Don Gagne's avatar
Don Gagne committed
503 504 505 506 507 508

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

Don Gagne's avatar
Don Gagne committed
509
void RadioComponentController::_saveFlapsDown(void)
Don Gagne's avatar
Don Gagne committed
510 511 512 513 514 515 516 517
{
    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
518
            QGCMessageBox::warning(tr("Flaps switch"), tr("Flaps switch has not yet been detected."));
Don Gagne's avatar
Don Gagne committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        }
        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) {
        _rgChannelInfo[channel].rcMin = rcValue;
    } else {
        _rgChannelInfo[channel].rcMax = rcValue;
    }
    
Don Gagne's avatar
Don Gagne committed
539
    _advanceState();
Don Gagne's avatar
Don Gagne committed
540 541
}

Don Gagne's avatar
Don Gagne committed
542
void RadioComponentController::_inputFlapsUp(enum rcCalFunctions function, int channel, int value)
Don Gagne's avatar
Don Gagne committed
543
{
544 545
    Q_UNUSED(function);
    
Don Gagne's avatar
Don Gagne committed
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
    // 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) {
                _rgChannelInfo[channel].rcMax = value;
            } else {
                _rgChannelInfo[channel].rcMin = value;
            }
            
Don Gagne's avatar
Don Gagne committed
583
            _advanceState();
Don Gagne's avatar
Don Gagne committed
584 585 586 587
        }
    }
}

Don Gagne's avatar
Don Gagne committed
588
void RadioComponentController::_switchDetect(enum rcCalFunctions function, int channel, int value, bool moveToNextStep)
Don Gagne's avatar
Don Gagne committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
{
    // 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;
        
Don Gagne's avatar
Don Gagne committed
605
        qCDebug(RadioComponentControllerLog) << "Function:" << function << "mapped to:" << channel;
Don Gagne's avatar
Don Gagne committed
606 607
        
        if (moveToNextStep) {
Don Gagne's avatar
Don Gagne committed
608
            _advanceState();
Don Gagne's avatar
Don Gagne committed
609 610 611 612
        }
    }
}

Don Gagne's avatar
Don Gagne committed
613
void RadioComponentController::_inputSwitchDetect(enum rcCalFunctions function, int channel, int value)
Don Gagne's avatar
Don Gagne committed
614 615 616 617
{
    _switchDetect(function, channel, value, true /* move to next step after detection */);
}

Don Gagne's avatar
Don Gagne committed
618
void RadioComponentController::_inputFlapsDetect(enum rcCalFunctions function, int channel, int value)
Don Gagne's avatar
Don Gagne committed
619 620
{
    _switchDetect(function, channel, value, false /* do not move to next step after detection */);
621 622 623
}

/// @brief Resets internal calibration values to their initial state in preparation for a new calibration sequence.
Don Gagne's avatar
Don Gagne committed
624
void RadioComponentController::_resetInternalCalibrationValues(void)
625 626
{
    // Set all raw channels to not reversed and center point values
627
    for (int i=0; i<_chanMax; i++) {
628 629 630
        struct ChannelInfo* info = &_rgChannelInfo[i];
        info->function = rcCalFunctionMax;
        info->reversed = false;
Don Gagne's avatar
Don Gagne committed
631 632 633
        info->rcMin = RadioComponentController::_rcCalPWMCenterPoint;
        info->rcMax = RadioComponentController::_rcCalPWMCenterPoint;
        info->rcTrim = RadioComponentController::_rcCalPWMCenterPoint;
634 635
    }
    
636
    // Initialize attitude function mapping to function channel not set
637 638 639 640
    for (size_t i=0; i<rcCalFunctionMax; i++) {
        _rgFunctionChannelMapping[i] = _chanMax;
    }
    
641 642 643 644 645 646 647 648 649 650 651 652 653 654
    // 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]);

    for (size_t i=0; i < crgFlightModeFunctions; i++) {
        QVariant value;
        enum rcCalFunctions curFunction = rgFlightModeFunctions[i];
        
        bool ok;
Don Gagne's avatar
Don Gagne committed
655
        int switchChannel = getParameterFact(FactSystem::defaultComponentId, _rgFunctionInfo[curFunction].parameterName)->value().toInt(&ok);
656 657 658 659 660
        Q_ASSERT(ok);
        
        // Parameter: 1-based channel, 0=not mapped
        // _rgFunctionChannelMapping: 0-based channel, _chanMax=not mapped
        
661
        if (switchChannel != 0) {
Don Gagne's avatar
Don Gagne committed
662
            qCDebug(RadioComponentControllerLog) << "Reserving 0-based switch channel" << switchChannel - 1;
663 664
            _rgFunctionChannelMapping[curFunction] = switchChannel - 1;
            _rgChannelInfo[switchChannel - 1].function = curFunction;
665 666
        }
    }
Don Gagne's avatar
Don Gagne committed
667 668
    
    _signalAllAttiudeValueChanges();
Don Gagne's avatar
Don Gagne committed
669 670
}

Don Gagne's avatar
Don Gagne committed
671
/// @brief Sets internal calibration values from the stored parameters
Don Gagne's avatar
Don Gagne committed
672
void RadioComponentController::_setInternalCalibrationValuesFromParameters(void)
Don Gagne's avatar
Don Gagne committed
673
{
674 675
    // Initialize all function mappings to not set
    
676
    for (int i=0; i<_chanMax; i++) {
677 678 679 680 681 682 683 684 685 686 687 688 689 690
        struct ChannelInfo* info = &_rgChannelInfo[i];
        info->function = rcCalFunctionMax;
    }
    
    for (size_t i=0; i<rcCalFunctionMax; i++) {
        _rgFunctionChannelMapping[i] = _chanMax;
    }
    
    // Pull parameters and update
    
    QString minTpl("RC%1_MIN");
    QString maxTpl("RC%1_MAX");
    QString trimTpl("RC%1_TRIM");
    QString revTpl("RC%1_REV");
691
    
692 693 694 695
    bool convertOk;
    
    for (int i = 0; i < _chanMax; ++i) {
        struct ChannelInfo* info = &_rgChannelInfo[i];
Don Gagne's avatar
Don Gagne committed
696
        
Don Gagne's avatar
Don Gagne committed
697
        info->rcTrim = getParameterFact(FactSystem::defaultComponentId, trimTpl.arg(i+1))->value().toInt(&convertOk);
698
        Q_ASSERT(convertOk);
Don Gagne's avatar
Don Gagne committed
699
        
Don Gagne's avatar
Don Gagne committed
700
        info->rcMin = getParameterFact(FactSystem::defaultComponentId, minTpl.arg(i+1))->value().toInt(&convertOk);
701
        Q_ASSERT(convertOk);
Don Gagne's avatar
Don Gagne committed
702

Don Gagne's avatar
Don Gagne committed
703
        info->rcMax = getParameterFact(FactSystem::defaultComponentId, maxTpl.arg(i+1))->value().toInt(&convertOk);
704
        Q_ASSERT(convertOk);
Don Gagne's avatar
Don Gagne committed
705

Don Gagne's avatar
Don Gagne committed
706
        float floatReversed = getParameterFact(FactSystem::defaultComponentId, revTpl.arg(i+1))->value().toFloat(&convertOk);
707 708 709
        Q_ASSERT(convertOk);
        Q_ASSERT(floatReversed == 1.0f || floatReversed == -1.0f);
        info->reversed = floatReversed == -1.0f;
710 711 712 713
    }
    
    for (int i=0; i<rcCalFunctionMax; i++) {
        int32_t paramChannel;
Don Gagne's avatar
Don Gagne committed
714
        
Don Gagne's avatar
Don Gagne committed
715
        paramChannel = getParameterFact(FactSystem::defaultComponentId, _rgFunctionInfo[i].parameterName)->value().toInt(&convertOk);
716 717 718 719 720
        Q_ASSERT(convertOk);
        
        if (paramChannel != 0) {
            _rgFunctionChannelMapping[i] = paramChannel - 1;
            _rgChannelInfo[paramChannel - 1].function = (enum rcCalFunctions)i;
Don Gagne's avatar
Don Gagne committed
721 722
        }
    }
723
    
Don Gagne's avatar
Don Gagne committed
724
    _signalAllAttiudeValueChanges();
725 726
}

Don Gagne's avatar
Don Gagne committed
727
void RadioComponentController::spektrumBindMode(int mode)
Don Gagne's avatar
Don Gagne committed
728
{
Don Gagne's avatar
Don Gagne committed
729
    _uas->pairRX(0, mode);
730 731
}

Don Gagne's avatar
Don Gagne committed
732
/// @brief Validates the current settings against the calibration rules resetting values as necessary.
Don Gagne's avatar
Don Gagne committed
733
void RadioComponentController::_validateCalibration(void)
Don Gagne's avatar
Don Gagne committed
734 735 736 737 738 739 740 741
{
    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) {
Don Gagne's avatar
Don Gagne committed
742
                qCDebug(RadioComponentControllerLog) << "_validateCalibration resetting channel" << chan;
Don Gagne's avatar
Don Gagne committed
743 744
                info->rcMin = _rcCalPWMDefaultMinValue;
                info->rcMax = _rcCalPWMDefaultMaxValue;
Don Gagne's avatar
Don Gagne committed
745 746 747 748 749 750 751
                info->rcTrim = info->rcMin + ((info->rcMax - info->rcMin) / 2);
            } else {
                switch (_rgChannelInfo[chan].function) {
                    case rcCalFunctionThrottle:
                    case rcCalFunctionYaw:
                    case rcCalFunctionRoll:
                    case rcCalFunctionPitch:
752 753 754 755 756 757
                        // 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
758 759 760 761 762 763 764
                        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
765 766 767
            }
        } else {
            // Unavailable channels are set to defaults
Don Gagne's avatar
Don Gagne committed
768
            qCDebug(RadioComponentControllerLog) << "_validateCalibration resetting unavailable channel" << chan;
Don Gagne's avatar
Don Gagne committed
769 770
            info->rcMin = _rcCalPWMDefaultMinValue;
            info->rcMax = _rcCalPWMDefaultMaxValue;
Don Gagne's avatar
Don Gagne committed
771
            info->rcTrim = info->rcMin + ((info->rcMax - info->rcMin) / 2);
Don Gagne's avatar
Don Gagne committed
772 773 774 775 776 777
            info->reversed = false;
        }
    }
}


778
/// @brief Saves the rc calibration values to the board parameters.
Don Gagne's avatar
Don Gagne committed
779
void RadioComponentController::_writeCalibration(void)
780
{
781
    if (!_uas) return;
782
    
783
    _uas->stopCalibration();
784
    
Don Gagne's avatar
Don Gagne committed
785 786
    _validateCalibration();
    
787 788 789 790 791
    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
792
    // 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
793 794
    for (int chan = 0; chan<_chanMax; chan++) {
        struct ChannelInfo* info = &_rgChannelInfo[chan];
795 796
        int                 oneBasedChannel = chan + 1;
        
Don Gagne's avatar
Don Gagne committed
797 798 799 800
        getParameterFact(FactSystem::defaultComponentId, trimTpl.arg(oneBasedChannel))->setValue((float)info->rcTrim);
        getParameterFact(FactSystem::defaultComponentId, minTpl.arg(oneBasedChannel))->setValue((float)info->rcMin);
        getParameterFact(FactSystem::defaultComponentId, maxTpl.arg(oneBasedChannel))->setValue((float)info->rcMax);
        getParameterFact(FactSystem::defaultComponentId, revTpl.arg(oneBasedChannel))->setValue(info->reversed ? -1.0f : 1.0f);
801 802
    }
    
Don Gagne's avatar
Don Gagne committed
803 804 805 806 807 808 809 810 811
    // 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;
812
        }
Don Gagne's avatar
Don Gagne committed
813
        getParameterFact(FactSystem::defaultComponentId, _rgFunctionInfo[i].parameterName)->setValue(paramChannel);
814 815
    }
    
816
    // If the RC_CHAN_COUNT parameter is available write the channel count
Don Gagne's avatar
Don Gagne committed
817 818
    if (parameterExists(FactSystem::defaultComponentId, "RC_CHAN_CNT")) {
        getParameterFact(FactSystem::defaultComponentId, "RC_CHAN_CNT")->setValue(_chanCount);
819
    }
820
    
Don Gagne's avatar
Don Gagne committed
821
    _stopCalibration();
822
    _setInternalCalibrationValuesFromParameters();
823 824
}

Don Gagne's avatar
Don Gagne committed
825
/// @brief Starts the calibration process
Don Gagne's avatar
Don Gagne committed
826
void RadioComponentController::_startCalibration(void)
827 828 829
{
    Q_ASSERT(_chanCount >= _chanMinimum);
    
Don Gagne's avatar
Don Gagne committed
830 831
    _resetInternalCalibrationValues();
    
832
    // Let the mav known we are starting calibration. This should turn off motors and so forth.
833
    _uas->startCalibration(UASInterface::StartCalibrationRadio);
834
    
Don Gagne's avatar
Don Gagne committed
835 836
    _nextButton->setProperty("text", "Next");
    _cancelButton->setEnabled(true);
837
    
Don Gagne's avatar
Don Gagne committed
838 839
    _currentStep = 0;
    _setupCurrentState();
840 841
}

Don Gagne's avatar
Don Gagne committed
842
/// @brief Cancels the calibration process, setting things back to initial state.
Don Gagne's avatar
Don Gagne committed
843
void RadioComponentController::_stopCalibration(void)
844
{
Don Gagne's avatar
Don Gagne committed
845
    _currentStep = -1;
846
    
847 848
    if (_uas) {
        _uas->stopCalibration();
Don Gagne's avatar
Don Gagne committed
849 850 851
        _setInternalCalibrationValuesFromParameters();
    } else {
        _resetInternalCalibrationValues();
852 853
    }
    
Don Gagne's avatar
Don Gagne committed
854
    _statusText->setProperty("text", "");
855

Don Gagne's avatar
Don Gagne committed
856 857 858 859
    _nextButton->setProperty("text", "Calibrate");
    _nextButton->setEnabled(true);
    _cancelButton->setEnabled(false);
    _skipButton->setEnabled(false);
860 861
    
    _setHelpImage(_imageCenter);
862 863
}

Don Gagne's avatar
Don Gagne committed
864
/// @brief Saves the current channel values, so that we can detect when the use moves an input.
Don Gagne's avatar
Don Gagne committed
865
void RadioComponentController::_rcCalSaveCurrentValues(void)
866
{
Don Gagne's avatar
Don Gagne committed
867
	qCDebug(RadioComponentControllerLog) << "_rcCalSaveCurrentValues";
868
    for (int i = 0; i < _chanMax; i++) {
Don Gagne's avatar
Don Gagne committed
869 870
        _rcValueSave[i] = _rcRawValue[i];
    }
871 872 873
}

/// @brief Set up the Save state of calibration.
Don Gagne's avatar
Don Gagne committed
874
void RadioComponentController::_rcCalSave(void)
875 876 877
{
    _rcCalState = rcCalStateSave;
    
Don Gagne's avatar
Don Gagne committed
878 879 880
    _statusText->setProperty("text",
                             "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.");
881

Don Gagne's avatar
Don Gagne committed
882 883 884
    _nextButton->setEnabled(true);
    _skipButton->setEnabled(false);
    _cancelButton->setEnabled(true);
Don Gagne's avatar
Don Gagne committed
885 886 887 888
    
    // 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();
Don Gagne's avatar
Don Gagne committed
889 890
}

Don Gagne's avatar
Don Gagne committed
891
void RadioComponentController::_loadSettings(void)
892 893 894 895 896 897 898 899 900 901 902 903
{
    QSettings settings;
    
    settings.beginGroup(_settingsGroup);
    _transmitterMode = settings.value(_settingsKeyTransmitterMode, 2).toInt();
    settings.endGroup();
    
    if (_transmitterMode != 1 || _transmitterMode != 2) {
        _transmitterMode = 2;
    }
}

Don Gagne's avatar
Don Gagne committed
904
void RadioComponentController::_storeSettings(void)
905 906 907 908 909 910 911 912
{
    QSettings settings;
    
    settings.beginGroup(_settingsGroup);
    settings.setValue(_settingsKeyTransmitterMode, _transmitterMode);
    settings.endGroup();
}

Don Gagne's avatar
Don Gagne committed
913
void RadioComponentController::_setHelpImage(const char* imageFile)
914 915 916 917 918 919 920 921 922 923 924 925
{
    QString file = _imageFilePrefix;
    
    if (_transmitterMode == 1) {
        file += _imageFileMode1Dir;
    } else if (_transmitterMode == 2) {
        file += _imageFileMode2Dir;
    } else {
        Q_ASSERT(false);
    }
    file += imageFile;
    
Don Gagne's avatar
Don Gagne committed
926
    qCDebug(RadioComponentControllerLog) << "_setHelpImage" << file;
927
    
Don Gagne's avatar
Don Gagne committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
    _imageHelp = file;
    emit imageHelpChanged(file);
}

int RadioComponentController::channelCount(void)
{
    return _chanCount;
}

int RadioComponentController::rollChannelRCValue(void)
{    
    if (_rgFunctionChannelMapping[rcCalFunctionRoll] != _chanMax) {
        return _rcRawValue[rcCalFunctionRoll];
    } else {
        return 1500;
    }
}

int RadioComponentController::pitchChannelRCValue(void)
{
    if (_rgFunctionChannelMapping[rcCalFunctionPitch] != _chanMax) {
        return _rcRawValue[rcCalFunctionPitch];
    } else {
        return 1500;
    }
}

int RadioComponentController::yawChannelRCValue(void)
{
    if (_rgFunctionChannelMapping[rcCalFunctionYaw] != _chanMax) {
        return _rcRawValue[rcCalFunctionYaw];
    } else {
        return 1500;
    }
}

int RadioComponentController::throttleChannelRCValue(void)
{
    if (_rgFunctionChannelMapping[rcCalFunctionThrottle] != _chanMax) {
        return _rcRawValue[rcCalFunctionThrottle];
    } else {
        return 1500;
    }
}

bool RadioComponentController::rollChannelMapped(void)
{
    return _rgFunctionChannelMapping[rcCalFunctionRoll] != _chanMax;
}

bool RadioComponentController::pitchChannelMapped(void)
{
    return _rgFunctionChannelMapping[rcCalFunctionPitch] != _chanMax;
}

bool RadioComponentController::yawChannelMapped(void)
{
    return _rgFunctionChannelMapping[rcCalFunctionYaw] != _chanMax;
}

bool RadioComponentController::throttleChannelMapped(void)
{
    return _rgFunctionChannelMapping[rcCalFunctionThrottle] != _chanMax;
}

bool RadioComponentController::rollChannelReversed(void)
{
    if (_rgFunctionChannelMapping[rcCalFunctionRoll] != _chanMax) {
        return _rgChannelInfo[_rgFunctionChannelMapping[rcCalFunctionRoll]].reversed;
    } else {
        return false;
    }
}

bool RadioComponentController::pitchChannelReversed(void)
{
    if (_rgFunctionChannelMapping[rcCalFunctionPitch] != _chanMax) {
        return _rgChannelInfo[_rgFunctionChannelMapping[rcCalFunctionPitch]].reversed;
    } else {
        return false;
    }
}

bool RadioComponentController::yawChannelReversed(void)
{
    if (_rgFunctionChannelMapping[rcCalFunctionYaw] != _chanMax) {
        return _rgChannelInfo[_rgFunctionChannelMapping[rcCalFunctionYaw]].reversed;
    } else {
        return false;
    }
}

bool RadioComponentController::throttleChannelReversed(void)
{
    if (_rgFunctionChannelMapping[rcCalFunctionThrottle] != _chanMax) {
        return _rgChannelInfo[_rgFunctionChannelMapping[rcCalFunctionThrottle]].reversed;
    } else {
        return false;
    }
}

void RadioComponentController::setTransmitterMode(int mode)
{
    if (mode == 1 || mode == 2) {
        _transmitterMode = mode;
        if (_currentStep != -1) {
            const stateMachineEntry* state = _getStateMachineEntry(_currentStep);
            _setHelpImage(state->image);
        }
    }
}

void RadioComponentController::_signalAllAttiudeValueChanges(void)
{
    emit rollChannelMappedChanged(rollChannelMapped());
    emit pitchChannelMappedChanged(pitchChannelMapped());
    emit yawChannelMappedChanged(yawChannelMapped());
    emit throttleChannelMappedChanged(throttleChannelMapped());
    
    emit rollChannelReversedChanged(rollChannelReversed());
    emit pitchChannelReversedChanged(pitchChannelReversed());
    emit yawChannelReversedChanged(yawChannelReversed());
    emit throttleChannelReversedChanged(throttleChannelReversed());
1051
}
Don Gagne's avatar
Don Gagne committed
1052 1053 1054

void RadioComponentController::copyTrims(void)
{
1055
    _uas->startCalibration(UASInterface::StartCalibrationCopyTrims);
Don Gagne's avatar
Don Gagne committed
1056
}