QGCVehicleConfig.cc 62.2 KB
Newer Older
Bryant's avatar
Bryant committed
1 2 3 4 5 6
// On Windows (for VS2010) stdint.h contains the limits normally contained in limits.h
// It also needs the __STDC_LIMIT_MACROS macro defined in order to include them (done
// in qgroundcontrol.pri).
#ifdef WIN32
#include <stdint.h>
#else
7
#include <limits.h>
Bryant's avatar
Bryant committed
8
#endif
9 10

#include <QTimer>
11 12 13
#include <QDir>
#include <QXmlStreamReader>
#include <QMessageBox>
14

15
#include "QGCVehicleConfig.h"
16

17
#include "QGC.h"
18
#include "QGCToolWidget.h"
19 20
#include "UASManager.h"
#include "UASParameterCommsMgr.h"
21 22 23 24
#include "ui_QGCVehicleConfig.h"

QGCVehicleConfig::QGCVehicleConfig(QWidget *parent) :
    QWidget(parent),
25
    mav(NULL),
26
    chanCount(0),
27 28 29 30 31 32 33 34
    rcRoll(0.0f),
    rcPitch(0.0f),
    rcYaw(0.0f),
    rcThrottle(0.0f),
    rcMode(0.0f),
    rcAux1(0.0f),
    rcAux2(0.0f),
    rcAux3(0.0f),
35
    changed(true),
36
    rc_mode(RC_MODE_NONE),
37
    calibrationEnabled(false),
38 39
    ui(new Ui::QGCVehicleConfig)
{
40
    doneLoadingConfig = false;
41

42
    setObjectName("QGC_VEHICLECONFIG");
43
    ui->setupUi(this);
44

45 46 47 48
    ui->rollWidget->setOrientation(Qt::Horizontal);
    ui->rollWidget->setName("Roll");
    ui->yawWidget->setOrientation(Qt::Horizontal);
    ui->yawWidget->setName("Yaw");
49 50
    ui->pitchWidget->setName("Pitch");
    ui->throttleWidget->setName("Throttle");
51 52 53 54 55 56 57 58 59
    ui->radio5Widget->setOrientation(Qt::Horizontal);
    ui->radio5Widget->setName("Radio 5");
    ui->radio6Widget->setOrientation(Qt::Horizontal);
    ui->radio6Widget->setName("Radio 6");
    ui->radio7Widget->setOrientation(Qt::Horizontal);
    ui->radio7Widget->setName("Radio 7");
    ui->radio8Widget->setOrientation(Qt::Horizontal);
    ui->radio8Widget->setName("Radio 8");

60 61 62 63 64
    connect(ui->rcMenuButton,SIGNAL(clicked()),this,SLOT(rcMenuButtonClicked()));
    connect(ui->sensorMenuButton,SIGNAL(clicked()),this,SLOT(sensorMenuButtonClicked()));
    connect(ui->generalMenuButton,SIGNAL(clicked()),this,SLOT(generalMenuButtonClicked()));
    connect(ui->advancedMenuButton,SIGNAL(clicked()),this,SLOT(advancedMenuButtonClicked()));

65 66
    ui->rcModeComboBox->setCurrentIndex((int)rc_mode - 1);

67
    ui->rcCalibrationButton->setCheckable(true);
68
    connect(ui->rcCalibrationButton, SIGNAL(clicked(bool)), this, SLOT(toggleCalibrationRC(bool)));
69
    connect(ui->setButton, SIGNAL(clicked()), this, SLOT(writeParameters()));
70
    connect(ui->rcModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setRCModeIndex(int)));
71
    //connect(ui->setTrimButton, SIGNAL(clicked()), this, SLOT(setTrimPositions()));
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

    /* Connect RC mapping assignments */
    connect(ui->rollSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setRollChan(int)));
    connect(ui->pitchSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setPitchChan(int)));
    connect(ui->yawSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setYawChan(int)));
    connect(ui->throttleSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setThrottleChan(int)));
    connect(ui->modeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setModeChan(int)));
    connect(ui->aux1SpinBox, SIGNAL(valueChanged(int)), this, SLOT(setAux1Chan(int)));
    connect(ui->aux2SpinBox, SIGNAL(valueChanged(int)), this, SLOT(setAux2Chan(int)));
    connect(ui->aux3SpinBox, SIGNAL(valueChanged(int)), this, SLOT(setAux3Chan(int)));

    // Connect RC reverse assignments
    connect(ui->invertCheckBox, SIGNAL(clicked(bool)), this, SLOT(setRollInverted(bool)));
    connect(ui->invertCheckBox_2, SIGNAL(clicked(bool)), this, SLOT(setPitchInverted(bool)));
    connect(ui->invertCheckBox_3, SIGNAL(clicked(bool)), this, SLOT(setYawInverted(bool)));
    connect(ui->invertCheckBox_4, SIGNAL(clicked(bool)), this, SLOT(setThrottleInverted(bool)));
    connect(ui->invertCheckBox_5, SIGNAL(clicked(bool)), this, SLOT(setModeInverted(bool)));
    connect(ui->invertCheckBox_6, SIGNAL(clicked(bool)), this, SLOT(setAux1Inverted(bool)));
    connect(ui->invertCheckBox_7, SIGNAL(clicked(bool)), this, SLOT(setAux2Inverted(bool)));
    connect(ui->invertCheckBox_8, SIGNAL(clicked(bool)), this, SLOT(setAux3Inverted(bool)));
92 93 94 95 96

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

    setActiveUAS(UASManager::instance()->getActiveUAS());

97
    for (unsigned int i = 0; i < chanMax; i++)
98
    {
99
        rcValue[i] = UINT16_MAX;
100
        rcMapping[i] = i;
101 102 103 104 105
    }

    updateTimer.setInterval(150);
    connect(&updateTimer, SIGNAL(timeout()), this, SLOT(updateView()));
    updateTimer.start();
106

107 108 109 110 111 112 113
    // Make sure the advanced features match what the checkbox indicates on startup and listen for
    // future changes.
    if (!ui->advancedCheckBox->isChecked())
    {
        ui->advancedGroupBox->hide();
    }
    connect(ui->advancedCheckBox, SIGNAL(toggled(bool)), ui->advancedGroupBox,SLOT(setVisible(bool)));
114
}
115 116 117 118 119 120 121 122 123 124
void QGCVehicleConfig::rcMenuButtonClicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void QGCVehicleConfig::sensorMenuButtonClicked()
{
    ui->stackedWidget->setCurrentIndex(1);
}

125 126 127 128 129
void QGCVehicleConfig::generalMenuButtonClicked()
{
    ui->stackedWidget->setCurrentIndex(ui->stackedWidget->count()-2);
}

130 131 132 133
void QGCVehicleConfig::advancedMenuButtonClicked()
{
    ui->stackedWidget->setCurrentIndex(ui->stackedWidget->count()-1);
}
134 135 136 137 138

QGCVehicleConfig::~QGCVehicleConfig()
{
    delete ui;
}
139

140 141
void QGCVehicleConfig::setRCModeIndex(int newRcMode)
{
142
    if (newRcMode > 0 && newRcMode < 6)
143
    {
144
        //rc_mode = (enum RC_MODE) (newRcMode+1);
145 146 147
        changed = true;
    }
}
148 149 150 151 152 153 154 155 156 157 158 159 160

void QGCVehicleConfig::toggleCalibrationRC(bool enabled)
{
    if (enabled)
    {
        startCalibrationRC();
    }
    else
    {
        stopCalibrationRC();
    }
}

161 162
void QGCVehicleConfig::setTrimPositions()
{
Lorenz Meier's avatar
Lorenz Meier committed
163 164 165 166 167 168
    // Set trim to min if stick is close to min
    if (abs(rcValue[rcMapping[3]] - rcMin[rcMapping[3]]) < 100)
    {
        rcTrim[rcMapping[3]] = rcMin[rcMapping[3]];   // throttle
    }
    // Set trim to max if stick is close to max
169
    else if (abs(rcValue[rcMapping[3]] - rcMax[rcMapping[3]]) < 100)
Lorenz Meier's avatar
Lorenz Meier committed
170 171 172
    {
        rcTrim[rcMapping[3]] = rcMax[rcMapping[3]];   // throttle
    }
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    else
    {

        // Reject
        QMessageBox msgBox;
        msgBox.setText(tr("Throttle Stick Trim Position Invalid"));
        msgBox.setInformativeText(tr("The throttle stick is not in the min position. Please set it to the minimum value"));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);
        (void)msgBox.exec();
    }

    // Set trim for roll, pitch, yaw, throttle
    rcTrim[rcMapping[0]] = rcValue[rcMapping[0]]; // roll
    rcTrim[rcMapping[1]] = rcValue[rcMapping[1]]; // pitch
    rcTrim[rcMapping[2]] = rcValue[rcMapping[2]]; // yaw

190 191 192 193
    rcTrim[rcMapping[4]] = ((rcMax[rcMapping[4]] - rcMin[rcMapping[4]]) / 2.0f) + rcMin[rcMapping[4]];   // mode sw
    rcTrim[rcMapping[5]] = ((rcMax[rcMapping[5]] - rcMin[rcMapping[5]]) / 2.0f) + rcMin[rcMapping[5]];   // aux 1
    rcTrim[rcMapping[6]] = ((rcMax[rcMapping[6]] - rcMin[rcMapping[6]]) / 2.0f) + rcMin[rcMapping[6]];   // aux 2
    rcTrim[rcMapping[7]] = ((rcMax[rcMapping[7]] - rcMin[rcMapping[7]]) / 2.0f) + rcMin[rcMapping[7]];   // aux 3
194 195 196 197 198 199 200
}

void QGCVehicleConfig::detectChannelInversion()
{

}

201 202
void QGCVehicleConfig::startCalibrationRC()
{
203 204
    QMessageBox::information(0,"Warning!","You are about to start radio calibration.\nPlease ensure all motor power is disconnected AND all props are removed from the vehicle.\nAlso ensure transmitter and reciever are powered and connected\n\nClick OK to confirm");
    QMessageBox::information(0,"Information","Click OK, then move all sticks to their extreme positions, watching the min/max values to ensure you get the most range from your controller. This includes all switches");
205
    ui->rcTypeComboBox->setEnabled(false);
206
    ui->rcCalibrationButton->setText(tr("Stop RC Calibration"));
207
    resetCalibrationRC();
208
    calibrationEnabled = true;
209 210 211 212 213 214 215 216
    ui->rollWidget->showMinMax(true);
    ui->pitchWidget->showMinMax(true);
    ui->yawWidget->showMinMax(true);
    ui->throttleWidget->showMinMax(true);
    ui->radio5Widget->showMinMax(true);
    ui->radio6Widget->showMinMax(true);
    ui->radio7Widget->showMinMax(true);
    ui->radio8Widget->showMinMax(true);
217 218 219 220
}

void QGCVehicleConfig::stopCalibrationRC()
{
221
    QMessageBox::information(0,"Trims","Ensure all sticks are centeres and throttle is in the downmost position, click OK to continue");
222
    calibrationEnabled = false;
223
    ui->rcTypeComboBox->setEnabled(true);
224
    ui->rcCalibrationButton->setText(tr("Start RC Calibration"));
225 226 227 228 229 230 231 232
    ui->rollWidget->showMinMax(false);
    ui->pitchWidget->showMinMax(false);
    ui->yawWidget->showMinMax(false);
    ui->throttleWidget->showMinMax(false);
    ui->radio5Widget->showMinMax(false);
    ui->radio6Widget->showMinMax(false);
    ui->radio7Widget->showMinMax(false);
    ui->radio8Widget->showMinMax(false);
233 234 235 236 237 238 239 240 241 242
    QString statusstr;
    statusstr = "Below you will find the detected radio calibration information that will be sent to the autopilot\n";
    statusstr += "Normal values are around 1100 to 1900, with disconnected channels reading very close to 1500\n\n";
    statusstr += "Channel\tMin\tCenter\tMax\n";
    statusstr += "--------------------\n";
    for (int i=0;i<8;i++)
    {
        statusstr += QString::number(i) + "\t" + QString::number(rcMin[i]) + "\t" + QString::number(rcValue[i]) + "\t" + QString::number(rcMax[i]) + "\n";
    }
    QMessageBox::information(0,"Status",statusstr);
243 244
}

245
void QGCVehicleConfig::loadQgcConfig(bool primary)
246
{
247
    Q_UNUSED(primary);
248 249 250 251 252 253
    QDir autopilotdir(qApp->applicationDirPath() + "/files/" + mav->getAutopilotTypeName().toLower());
    QDir generaldir = QDir(autopilotdir.absolutePath() + "/general/widgets");
    QDir vehicledir = QDir(autopilotdir.absolutePath() + "/" + mav->getSystemTypeName().toLower() + "/widgets");
    if (!autopilotdir.exists("general"))
    {
     //TODO: Throw some kind of error here. There is no general configuration directory
254
        qDebug() << "Invalid general dir. no general configuration will be loaded.";
255 256 257 258
    }
    if (!autopilotdir.exists(mav->getAutopilotTypeName().toLower()))
    {
        //TODO: Throw an error here too, no autopilot specific configuration
259
        qDebug() << "Invalid vehicle dir, no vehicle specific configuration will be loaded.";
260
    }
261 262

    // Generate widgets for the General tab.
263 264
    QGCToolWidget *tool;
    bool left = true;
265 266 267
    foreach (QString file,generaldir.entryList(QDir::Files | QDir::NoDotAndDotDot))
    {
        if (file.toLower().endsWith(".qgw")) {
268
            QWidget* parent = left?ui->generalLeftContents:ui->generalRightContents;
269
            tool = new QGCToolWidget("", "", parent);
270 271 272
            if (tool->loadSettings(generaldir.absoluteFilePath(file), false))
            {
                toolWidgets.append(tool);
273
                QGroupBox *box = new QGroupBox(parent);
274
                box->setTitle(tool->objectName());
275
                box->setLayout(new QVBoxLayout(box));
276
                box->layout()->addWidget(tool);
277
                if (left)
278
                {
279
                    left = false;
280
                    ui->generalLeftLayout->addWidget(box);
281 282 283 284
                }
                else
                {
                    left = true;
285
                    ui->generalRightLayout->addWidget(box);
286
                }
287 288 289 290 291
            } else {
                delete tool;
            }
        }
    }
292 293

    // Generate widgets for the Advanced tab.
294
    left = true;
295 296 297
    foreach (QString file,vehicledir.entryList(QDir::Files | QDir::NoDotAndDotDot))
    {
        if (file.toLower().endsWith(".qgw")) {
298
            QWidget* parent = left?ui->advancedLeftContents:ui->advancedRightContents;
299
            tool = new QGCToolWidget("", "", parent);
300 301 302
            if (tool->loadSettings(vehicledir.absoluteFilePath(file), false))
            {
                toolWidgets.append(tool);
303
                QGroupBox *box = new QGroupBox(parent);
304
                box->setTitle(tool->objectName());
305
                box->setLayout(new QVBoxLayout(box));
306
                box->layout()->addWidget(tool);
307
                if (left)
308
                {
309
                    left = false;
310
                    ui->advancedLeftLayout->addWidget(box);
311 312 313 314
                }
                else
                {
                    left = true;
315
                    ui->advancedRightLayout->addWidget(box);
316
                }
317 318 319 320 321 322
            } else {
                delete tool;
            }
        }
    }

323
    // Load tabs for general configuration
324 325
    foreach (QString dir,generaldir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
    {
326 327 328
        QPushButton *button = new QPushButton(ui->scrollAreaWidgetContents_3);
        connect(button,SIGNAL(clicked()),this,SLOT(menuButtonClicked()));
        ui->navBarLayout->insertWidget(2,button);
329
        button->setMinimumHeight(75);
330 331 332 333 334 335
        button->setMinimumWidth(100);
        button->show();
        button->setText(dir);
        QWidget *tab = new QWidget(ui->stackedWidget);
        ui->stackedWidget->insertWidget(2,tab);
        buttonToWidgetMap[button] = tab;
336
        tab->setLayout(new QVBoxLayout());
337
        tab->show();
338
        QScrollArea *area = new QScrollArea(tab);
339
        tab->layout()->addWidget(area);
340 341
        QWidget *scrollArea = new QWidget(tab);
        scrollArea->setLayout(new QVBoxLayout(tab));
342 343 344 345
        area->setWidget(scrollArea);
        area->setWidgetResizable(true);
        area->show();
        scrollArea->show();
346 347 348 349
        QDir newdir = QDir(generaldir.absoluteFilePath(dir));
        foreach (QString file,newdir.entryList(QDir::Files| QDir::NoDotAndDotDot))
        {
            if (file.toLower().endsWith(".qgw")) {
350
                tool = new QGCToolWidget("", "", tab);
351 352 353 354
                if (tool->loadSettings(newdir.absoluteFilePath(file), false))
                {
                    toolWidgets.append(tool);
                    //ui->sensorLayout->addWidget(tool);
355
                    QGroupBox *box = new QGroupBox(tab);
356
                    box->setTitle(tool->objectName());
357
                    box->setLayout(new QVBoxLayout(tab));
358
                    box->layout()->addWidget(tool);
359
                    scrollArea->layout()->addWidget(box);
360 361 362 363 364 365 366
                } else {
                    delete tool;
                }
            }
        }
    }

367
    // Load additional tabs for vehicle specific configuration
368 369
    foreach (QString dir,vehicledir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
    {
370 371 372 373 374 375 376 377
        QPushButton *button = new QPushButton(ui->scrollAreaWidgetContents_3);
        connect(button,SIGNAL(clicked()),this,SLOT(menuButtonClicked()));
        ui->navBarLayout->insertWidget(2,button);

        QWidget *tab = new QWidget(ui->stackedWidget);
        ui->stackedWidget->insertWidget(2,tab);
        buttonToWidgetMap[button] = tab;

378
        button->setMinimumHeight(75);
379 380 381
        button->setMinimumWidth(100);
        button->show();
        button->setText(dir);
382
        tab->setLayout(new QVBoxLayout());
383
        tab->show();
384
        QScrollArea *area = new QScrollArea(tab);
385
        tab->layout()->addWidget(area);
386 387
        QWidget *scrollArea = new QWidget(tab);
        scrollArea->setLayout(new QVBoxLayout(tab));
388 389 390 391 392
        area->setWidget(scrollArea);
        area->setWidgetResizable(true);
        area->show();
        scrollArea->show();

393 394 395 396
        QDir newdir = QDir(vehicledir.absoluteFilePath(dir));
        foreach (QString file,newdir.entryList(QDir::Files| QDir::NoDotAndDotDot))
        {
            if (file.toLower().endsWith(".qgw")) {
397
                tool = new QGCToolWidget("","", tab);
398 399 400 401 402
                tool->addUAS(mav);
                if (tool->loadSettings(newdir.absoluteFilePath(file), false))
                {
                    toolWidgets.append(tool);
                    //ui->sensorLayout->addWidget(tool);
403
                    QGroupBox *box = new QGroupBox(tab);
404
                    box->setTitle(tool->objectName());
405
                    box->setLayout(new QVBoxLayout(box));
406
                    box->layout()->addWidget(tool);
407 408 409
                    scrollArea->layout()->addWidget(box);
                    box->show();
                    //gbox->layout()->addWidget(box);
410 411 412 413 414 415
                } else {
                    delete tool;
                }
            }
        }
    }
416

417
    // Load general calibration for autopilot
418
    //TODO: Handle this more gracefully, maybe have it scan the directory for multiple calibration entries?
419
    tool = new QGCToolWidget("", "", ui->sensorContents);
420
    tool->addUAS(mav);
421
    if (tool->loadSettings(autopilotdir.absolutePath() + "/general/calibration/calibration.qgw", false))
422 423
    {
        toolWidgets.append(tool);
424
        QGroupBox *box = new QGroupBox(ui->sensorContents);
425
        box->setTitle(tool->objectName());
426
        box->setLayout(new QVBoxLayout(box));
427 428 429 430 431 432
        box->layout()->addWidget(tool);
        ui->sensorLayout->addWidget(box);
    } else {
        delete tool;
    }

433
    // Load vehicle-specific autopilot configuration
434
    tool = new QGCToolWidget("", "", ui->sensorContents);
435 436 437 438
    tool->addUAS(mav);
    if (tool->loadSettings(autopilotdir.absolutePath() + "/" +  mav->getSystemTypeName().toLower() + "/calibration/calibration.qgw", false))
    {
        toolWidgets.append(tool);
439
        QGroupBox *box = new QGroupBox(ui->sensorContents);
440
        box->setTitle(tool->objectName());
441
        box->setLayout(new QVBoxLayout(box));
442 443
        box->layout()->addWidget(tool);
        ui->sensorLayout->addWidget(box);
444 445
    } else {
        delete tool;
446
    }
447

448 449 450 451 452
    //description.txt
    QFile sensortipsfile(autopilotdir.absolutePath() + "/general/calibration/description.txt");
    sensortipsfile.open(QIODevice::ReadOnly);
    ui->sensorTips->setHtml(sensortipsfile.readAll());
    sensortipsfile.close();
453
}
454 455 456 457 458 459 460 461 462 463 464 465 466
void QGCVehicleConfig::menuButtonClicked()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button)
    {
        return;
    }
    if (buttonToWidgetMap.contains(button))
    {
        ui->stackedWidget->setCurrentWidget(buttonToWidgetMap[button]);
    }

}
467

468 469 470 471 472 473 474 475 476 477
void QGCVehicleConfig::loadConfig()
{
    QGCToolWidget* tool;

    QDir autopilotdir(qApp->applicationDirPath() + "/files/" + mav->getAutopilotTypeName().toLower());
    QDir generaldir = QDir(autopilotdir.absolutePath() + "/general/widgets");
    QDir vehicledir = QDir(autopilotdir.absolutePath() + "/" + mav->getSystemTypeName().toLower() + "/widgets");
    if (!autopilotdir.exists("general"))
    {
     //TODO: Throw some kind of error here. There is no general configuration directory
478
        qDebug() << "Invalid general dir. no general configuration will be loaded.";
479 480 481 482
    }
    if (!autopilotdir.exists(mav->getAutopilotTypeName().toLower()))
    {
        //TODO: Throw an error here too, no autopilot specific configuration
483
        qDebug() << "Invalid vehicle dir, no vehicle specific configuration will be loaded.";
484 485 486 487 488
    }
    qDebug() << autopilotdir.absolutePath();
    qDebug() << generaldir.absolutePath();
    qDebug() << vehicledir.absolutePath();
    QFile xmlfile(autopilotdir.absolutePath() + "/arduplane.pdef.xml");
489
    if (xmlfile.exists() && !xmlfile.open(QIODevice::ReadOnly))
490
    {
491
        loadQgcConfig(false);
492
        doneLoadingConfig = true;
493 494
        return;
    }
495
    loadQgcConfig(true);
496 497 498

    QXmlStreamReader xml(xmlfile.readAll());
    xmlfile.close();
499

500
    //TODO: Testing to ensure that incorrectly formatted XML won't break this.
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
    while (!xml.atEnd())
    {
        if (xml.isStartElement() && xml.name() == "paramfile")
        {
            xml.readNext();
            while ((xml.name() != "paramfile") && !xml.atEnd())
            {
                QString valuetype = "";
                if (xml.isStartElement() && (xml.name() == "vehicles" || xml.name() == "libraries")) //Enter into the vehicles loop
                {
                    valuetype = xml.name().toString();
                    xml.readNext();
                    while ((xml.name() != valuetype) && !xml.atEnd())
                    {
                        if (xml.isStartElement() && xml.name() == "parameters") //This is a parameter block
                        {
                            QString parametersname = "";
                            if (xml.attributes().hasAttribute("name"))
                            {
                                    parametersname = xml.attributes().value("name").toString();
                            }
522 523 524
                            QVariantMap genset;
                            QVariantMap advset;

525 526
                            QString setname = parametersname;
                            xml.readNext();
527 528
                            int genarraycount = 0;
                            int advarraycount = 0;
529 530 531 532 533 534
                            while ((xml.name() != "parameters") && !xml.atEnd())
                            {
                                if (xml.isStartElement() && xml.name() == "param")
                                {
                                    QString humanname = xml.attributes().value("humanName").toString();
                                    QString name = xml.attributes().value("name").toString();
535 536 537 538 539 540 541 542 543
                                    QString tab= xml.attributes().value("user").toString();
                                    if (tab == "Advanced")
                                    {
                                        advset["title"] = parametersname;
                                    }
                                    else
                                    {
                                        genset["title"] = parametersname;
                                    }
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
                                    if (name.contains(":"))
                                    {
                                        name = name.split(":")[1];
                                    }
                                    QString docs = xml.attributes().value("documentation").toString();
                                    paramTooltips[name] = name + " - " + docs;

                                    int type = -1; //Type of item
                                    QMap<QString,QString> fieldmap;
                                    xml.readNext();
                                    while ((xml.name() != "param") && !xml.atEnd())
                                    {
                                        if (xml.isStartElement() && xml.name() == "values")
                                        {
                                            type = 1; //1 is a combobox
559 560 561 562 563 564 565 566 567 568 569 570 571 572
                                            if (tab == "Advanced")
                                            {
                                                advset[setname + "\\" + QString::number(advarraycount) + "\\" + "TYPE"] = "COMBO";
                                                advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_COMBOBOX_DESCRIPTION"] = humanname;
                                                advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_COMBOBOX_PARAMID"] = name;
                                                advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_COMBOBOX_COMPONENTID"] = 1;
                                            }
                                            else
                                            {
                                                genset[setname + "\\" + QString::number(genarraycount) + "\\" + "TYPE"] = "COMBO";
                                                genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_COMBOBOX_DESCRIPTION"] = humanname;
                                                genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_COMBOBOX_PARAMID"] = name;
                                                genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_COMBOBOX_COMPONENTID"] = 1;
                                            }
573 574 575 576 577 578 579 580 581
                                            int paramcount = 0;
                                            xml.readNext();
                                            while ((xml.name() != "values") && !xml.atEnd())
                                            {
                                                if (xml.isStartElement() && xml.name() == "value")
                                                {

                                                    QString code = xml.attributes().value("code").toString();
                                                    QString arg = xml.readElementText();
582 583 584 585 586 587 588 589 590 591
                                                    if (tab == "Advanced")
                                                    {
                                                        advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_COMBOBOX_ITEM_" + QString::number(paramcount) + "_TEXT"] = arg;
                                                        advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_COMBOBOX_ITEM_" + QString::number(paramcount) + "_VAL"] = code.toInt();
                                                    }
                                                    else
                                                    {
                                                        genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_COMBOBOX_ITEM_" + QString::number(paramcount) + "_TEXT"] = arg;
                                                        genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_COMBOBOX_ITEM_" + QString::number(paramcount) + "_VAL"] = code.toInt();
                                                    }
592 593 594 595
                                                    paramcount++;
                                                }
                                                xml.readNext();
                                            }
596 597 598 599 600 601 602 603
                                            if (tab == "Advanced")
                                            {
                                                advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_COMBOBOX_COUNT"] = paramcount;
                                            }
                                            else
                                            {
                                                genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_COMBOBOX_COUNT"] = paramcount;
                                            }
604 605 606 607 608 609 610 611 612 613 614 615
                                        }
                                        if (xml.isStartElement() && xml.name() == "field")
                                        {
                                            type = 2; //2 is a slider
                                            QString fieldtype = xml.attributes().value("name").toString();
                                            QString text = xml.readElementText();
                                            fieldmap[fieldtype] = text;
                                        }
                                        xml.readNext();
                                    }
                                    if (type == -1)
                                    {
616
                                        //Nothing inside! Assume it's a value, give it a default range.
617 618
                                        type = 2;
                                        QString fieldtype = "Range";
619
                                        QString text = "0 100"; //TODO: Determine a better way of figuring out default ranges.
620 621 622 623
                                        fieldmap[fieldtype] = text;
                                    }
                                    if (type == 2)
                                    {
624 625 626 627 628 629 630 631 632 633 634 635 636 637
                                        if (tab == "Advanced")
                                        {
                                            advset[setname + "\\" + QString::number(advarraycount) + "\\" + "TYPE"] = "SLIDER";
                                            advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_SLIDER_DESCRIPTION"] = humanname;
                                            advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_SLIDER_PARAMID"] = name;
                                            advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_SLIDER_COMPONENTID"] = 1;
                                        }
                                        else
                                        {
                                            genset[setname + "\\" + QString::number(genarraycount) + "\\" + "TYPE"] = "SLIDER";
                                            genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_SLIDER_DESCRIPTION"] = humanname;
                                            genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_SLIDER_PARAMID"] = name;
                                            genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_SLIDER_COMPONENTID"] = 1;
                                        }
638 639 640 641
                                        if (fieldmap.contains("Range"))
                                        {
                                            float min = 0;
                                            float max = 0;
642
                                            //Some range fields list "0-10" and some list "0 10". Handle both.
643 644 645 646 647 648 649 650 651 652
                                            if (fieldmap["Range"].split(" ").size() > 1)
                                            {
                                                min = fieldmap["Range"].split(" ")[0].trimmed().toFloat();
                                                max = fieldmap["Range"].split(" ")[1].trimmed().toFloat();
                                            }
                                            else if (fieldmap["Range"].split("-").size() > 1)
                                            {
                                                min = fieldmap["Range"].split("-")[0].trimmed().toFloat();
                                                max = fieldmap["Range"].split("-")[1].trimmed().toFloat();
                                            }
653 654 655 656 657 658 659 660 661 662
                                            if (tab == "Advanced")
                                            {
                                                advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_SLIDER_MIN"] = min;
                                                advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_SLIDER_MAX"] = max;
                                            }
                                            else
                                            {
                                                genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_SLIDER_MIN"] = min;
                                                genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_SLIDER_MAX"] = max;
                                            }
663 664
                                        }
                                    }
665 666 667 668 669 670 671 672 673 674
                                    if (tab == "Advanced")
                                    {
                                        advarraycount++;
                                        advset["count"] = advarraycount;
                                    }
                                    else
                                    {
                                        genarraycount++;
                                        genset["count"] = genarraycount;
                                    }
675 676 677
                                }
                                xml.readNext();
                            }
678
                            if (genarraycount > 0)
679
                            {
680 681 682 683 684 685 686 687 688
                                QWidget* parent = this;
                                if (valuetype == "vehicles")
                                {
                                    parent = ui->generalLeftContents;
                                }
                                else if (valuetype == "libraries")
                                {
                                    parent = ui->generalRightContents;
                                }
689
                                tool = new QGCToolWidget(parametersname, parametersname, parent);
690 691 692 693
                                tool->addUAS(mav);
                                tool->setSettings(genset);
                                QList<QString> paramlist = tool->getParamList();
                                for (int i=0;i<paramlist.size();i++)
694
                                {
695 696 697
                                    //Based on the airframe, we add the parameter to different categories.
                                    if (parametersname == "ArduPlane") //MAV_TYPE_FIXED_WING FIXED_WING
                                    {
698
                                        systemTypeToParamMap["FIXED_WING"].insert(paramlist[i],tool);
699 700 701
                                    }
                                    else if (parametersname == "ArduCopter") //MAV_TYPE_QUADROTOR "QUADROTOR
                                    {
702
                                        systemTypeToParamMap["QUADROTOR"].insert(paramlist[i],tool);
703 704 705
                                    }
                                    else if (parametersname == "APMrover2") //MAV_TYPE_GROUND_ROVER GROUND_ROVER
                                    {
706
                                        systemTypeToParamMap["GROUND_ROVER"].insert(paramlist[i],tool);
707 708 709
                                    }
                                    else
                                    {
710
                                        libParamToWidgetMap.insert(paramlist[i],tool);
711
                                    }
712
                                }
713 714

                                toolWidgets.append(tool);
715
                                QGroupBox *box = new QGroupBox(parent);
716
                                box->setTitle(tool->objectName());
717
                                box->setLayout(new QVBoxLayout(box));
718 719
                                box->layout()->addWidget(tool);
                                if (valuetype == "vehicles")
720
                                {
721
                                    ui->generalLeftLayout->addWidget(box);
722
                                }
723
                                else if (valuetype == "libraries")
724
                                {
725
                                    ui->generalRightLayout->addWidget(box);
726
                                }
727 728 729 730 731
                                box->hide();
                                toolToBoxMap[tool] = box;
                            }
                            if (advarraycount > 0)
                            {
732 733 734 735 736 737 738 739 740
                                QWidget* parent = this;
                                if (valuetype == "vehicles")
                                {
                                    parent = ui->generalLeftContents;
                                }
                                else if (valuetype == "libraries")
                                {
                                    parent = ui->generalRightContents;
                                }
741
                                tool = new QGCToolWidget(parametersname, parametersname, parent);
742 743 744 745
                                tool->addUAS(mav);
                                tool->setSettings(advset);
                                QList<QString> paramlist = tool->getParamList();
                                for (int i=0;i<paramlist.size();i++)
746
                                {
747 748 749
                                    //Based on the airframe, we add the parameter to different categories.
                                    if (parametersname == "ArduPlane") //MAV_TYPE_FIXED_WING FIXED_WING
                                    {
750
                                        systemTypeToParamMap["FIXED_WING"].insert(paramlist[i],tool);
751 752 753
                                    }
                                    else if (parametersname == "ArduCopter") //MAV_TYPE_QUADROTOR "QUADROTOR
                                    {
754
                                        systemTypeToParamMap["QUADROTOR"].insert(paramlist[i],tool);
755 756 757
                                    }
                                    else if (parametersname == "APMrover2") //MAV_TYPE_GROUND_ROVER GROUND_ROVER
                                    {
758
                                        systemTypeToParamMap["GROUND_ROVER"].insert(paramlist[i],tool);
759 760 761
                                    }
                                    else
                                    {
762
                                        libParamToWidgetMap.insert(paramlist[i],tool);
763
                                    }
764
                                }
765

766
                                toolWidgets.append(tool);
767
                                QGroupBox *box = new QGroupBox(parent);
768
                                box->setTitle(tool->objectName());
769
                                box->setLayout(new QVBoxLayout(box));
770 771 772
                                box->layout()->addWidget(tool);
                                if (valuetype == "vehicles")
                                {
773
                                    ui->generalLeftLayout->addWidget(box);
774 775 776
                                }
                                else if (valuetype == "libraries")
                                {
777
                                    ui->generalRightLayout->addWidget(box);
778 779 780
                                }
                                box->hide();
                                toolToBoxMap[tool] = box;
781 782 783 784 785 786 787 788 789 790
                            }
                        }
                        xml.readNext();
                    }
                }
                xml.readNext();
            }
        }
        xml.readNext();
    }
791

792 793 794
    if (!paramTooltips.isEmpty()) {
           paramMgr->setParamDescriptions(paramTooltips);
    }
795
    doneLoadingConfig = true;
796
    //Config is finished, lets do a parameter request to ensure none are missed if someone else started requesting before we were finished.
797
    paramMgr->requestParameterListIfEmpty();
798 799 800 801
}

void QGCVehicleConfig::setActiveUAS(UASInterface* active)
{
Lorenz Meier's avatar
Lorenz Meier committed
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
    // Hide items if NULL and abort
    if (!active) {
        ui->setButton->setEnabled(false);
        ui->refreshButton->setEnabled(false);
        ui->readButton->show();
        ui->readButton->setEnabled(false);
        ui->writeButton->show();
        ui->writeButton->setEnabled(false);
        ui->loadFileButton->setEnabled(false);
        ui->saveFileButton->setEnabled(false);

        return;
    }


817
    // Do nothing if system is the same
818
    if (mav == active) return;
819 820 821 822 823 824 825 826

    if (mav)
    {
        // Disconnect old system
        disconnect(mav, SIGNAL(remoteControlChannelRawChanged(int,float)), this,
                   SLOT(remoteControlChannelRawChanged(int,float)));
        disconnect(mav, SIGNAL(parameterChanged(int,int,QString,QVariant)), this,
                   SLOT(parameterChanged(int,int,QString,QVariant)));
Lorenz Meier's avatar
Lorenz Meier committed
827
        disconnect(ui->refreshButton,SIGNAL(clicked()),mav,SLOT(requestParameters()));
828

829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
        // Delete all children from all fixed tabs.
        foreach(QWidget* child, ui->generalLeftContents->findChildren<QWidget*>())
        {
            child->deleteLater();
        }
        foreach(QWidget* child, ui->generalRightContents->findChildren<QWidget*>())
        {
            child->deleteLater();
        }
        foreach(QWidget* child, ui->advancedLeftContents->findChildren<QWidget*>())
        {
            child->deleteLater();
        }
        foreach(QWidget* child, ui->advancedRightContents->findChildren<QWidget*>())
        {
            child->deleteLater();
        }
        foreach(QWidget* child, ui->sensorContents->findChildren<QWidget*>())
        {
            child->deleteLater();
        }

        // And then delete any custom tabs
        foreach(QWidget* child, additionalTabs)
853
        {
854
            child->deleteLater();
855
        }
856 857
        additionalTabs.clear();

858
        toolWidgets.clear();
859
        paramToWidgetMap.clear();
860 861 862 863
        libParamToWidgetMap.clear();
        systemTypeToParamMap.clear();
        toolToBoxMap.clear();
        paramTooltips.clear();
864 865
    }

Lorenz Meier's avatar
Lorenz Meier committed
866 867
    // Connect new system
    mav = active;
868
    paramMgr = mav->getParamManager();
Lorenz Meier's avatar
Lorenz Meier committed
869

870 871 872
    // Reset current state
    resetCalibrationRC();

Lorenz Meier's avatar
Lorenz Meier committed
873 874 875
    requestCalibrationRC();
    mav->requestParameter(0, "RC_TYPE");

876 877
    chanCount = 0;

878
    // Connect new system
879 880 881 882
    connect(active, SIGNAL(remoteControlChannelRawChanged(int,float)), this,
               SLOT(remoteControlChannelRawChanged(int,float)));
    connect(active, SIGNAL(parameterChanged(int,int,QString,QVariant)), this,
               SLOT(parameterChanged(int,int,QString,QVariant)));
Lorenz Meier's avatar
Lorenz Meier committed
883
    connect(ui->refreshButton, SIGNAL(clicked()), active, SLOT(requestParameters()));
884

885
    if (systemTypeToParamMap.contains(mav->getSystemTypeName()))
886
    {
887
        paramToWidgetMap = systemTypeToParamMap[mav->getSystemTypeName()];
888
    }
889
    else
890
    {
891
        //Indication that we have no meta data for this system type.
892
        qDebug() << "No parameters defined for system type:" << mav->getSystemTypeName();
893
        paramToWidgetMap = systemTypeToParamMap[mav->getSystemTypeName()];
894 895
    }

896
    if (!paramTooltips.isEmpty())
897
    {
898
           mav->getParamManager()->setParamDescriptions(paramTooltips);
899 900
    }

901
    qDebug() << "CALIBRATION!! System Type Name:" << mav->getSystemTypeName();
902

903 904 905
    //Load configuration after 1ms. This allows it to go into the event loop, and prevents application hangups due to the
    //amount of time it actually takes to load the configuration windows.
    QTimer::singleShot(1,this,SLOT(loadConfig()));
906 907

    updateStatus(QString("Reading from system %1").arg(mav->getUASName()));
908 909 910 911 912 913 914 915

    // Since a system is now connected, enable the VehicleConfig UI.
    ui->setButton->setEnabled(true);
    ui->refreshButton->setEnabled(true);
    ui->readButton->setEnabled(true);
    ui->writeButton->setEnabled(true);
    ui->loadFileButton->setEnabled(true);
    ui->saveFileButton->setEnabled(true);
916 917 918 919 920
    if (mav->getAutopilotTypeName() == "ARDUPILOTMEGA")
    {
        ui->readButton->hide();
        ui->writeButton->hide();
    }
921
}
922

923 924 925 926
void QGCVehicleConfig::resetCalibrationRC()
{
    for (unsigned int i = 0; i < chanMax; ++i)
    {
927 928
        rcMin[i] = 1500;
        rcMax[i] = 1500;
929 930 931 932 933 934 935 936 937 938
    }
}

/**
 * Sends the RC calibration to the vehicle and stores it in EEPROM
 */
void QGCVehicleConfig::writeCalibrationRC()
{
    if (!mav) return;

939 940
    setTrimPositions();

941 942 943 944 945 946 947 948
    QString minTpl("RC%1_MIN");
    QString maxTpl("RC%1_MAX");
    QString trimTpl("RC%1_TRIM");
    QString revTpl("RC%1_REV");

    // Do not write the RC type, as these values depend on this
    // active onboard parameter

949
    //TODO consolidate RC param sending in the UAS comms mgr
950
    for (unsigned int i = 0; i < chanCount; ++i)
951
    {
952
        //qDebug() << "SENDING" << minTpl.arg(i+1) << rcMin[i];
Lorenz Meier's avatar
Lorenz Meier committed
953
        mav->setParameter(0, minTpl.arg(i+1), rcMin[i]);
954
        QGC::SLEEP::usleep(50000);
Lorenz Meier's avatar
Lorenz Meier committed
955
        mav->setParameter(0, trimTpl.arg(i+1), rcTrim[i]);
956
        QGC::SLEEP::usleep(50000);
Lorenz Meier's avatar
Lorenz Meier committed
957
        mav->setParameter(0, maxTpl.arg(i+1), rcMax[i]);
958 959 960
        QGC::SLEEP::usleep(50000);
        mav->setParameter(0, revTpl.arg(i+1), (rcRev[i]) ? -1.0f : 1.0f);
        QGC::SLEEP::usleep(50000);
961 962 963
    }

    // Write mappings
964 965 966 967
    mav->setParameter(0, "RC_MAP_ROLL", (int32_t)(rcMapping[0]+1));
    QGC::SLEEP::usleep(50000);
    mav->setParameter(0, "RC_MAP_PITCH", (int32_t)(rcMapping[1]+1));
    QGC::SLEEP::usleep(50000);
968
    mav->setParameter(0, "RC_MAP_YAW", (int32_t)(rcMapping[2]+1));
969
    QGC::SLEEP::usleep(50000);
970
    mav->setParameter(0, "RC_MAP_THROTTLE", (int32_t)(rcMapping[3]+1));
971 972 973 974 975 976 977 978 979
    QGC::SLEEP::usleep(50000);
    mav->setParameter(0, "RC_MAP_MODE_SW", (int32_t)(rcMapping[4]+1));
    QGC::SLEEP::usleep(50000);
    mav->setParameter(0, "RC_MAP_AUX1", (int32_t)(rcMapping[5]+1));
    QGC::SLEEP::usleep(50000);
    mav->setParameter(0, "RC_MAP_AUX2", (int32_t)(rcMapping[6]+1));
    QGC::SLEEP::usleep(50000);
    mav->setParameter(0, "RC_MAP_AUX3", (int32_t)(rcMapping[7]+1));
    QGC::SLEEP::usleep(50000);
980 981 982 983
}

void QGCVehicleConfig::requestCalibrationRC()
{
984
    paramMgr->requestRcCalibrationParamsUpdate();
985 986 987 988 989 990
}

void QGCVehicleConfig::writeParameters()
{
    updateStatus(tr("Writing all onboard parameters."));
    writeCalibrationRC();
991

992
    mav->writeParametersToStorage();
993 994 995 996
}

void QGCVehicleConfig::remoteControlChannelRawChanged(int chan, float val)
{
997 998
    // Check if index and values are sane
    if (chan < 0 || static_cast<unsigned int>(chan) >= chanMax || val < 500 || val > 2500)
999 1000
        return;

Bryant's avatar
Bryant committed
1001
    if (chan + 1 > (int)chanCount) {
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        chanCount = chan+1;
    }

    // Update calibration data
    if (calibrationEnabled) {
        if (val < rcMin[chan])
        {
            rcMin[chan] = val;
        }

        if (val > rcMax[chan])
        {
            rcMax[chan] = val;
        }
1016 1017
    }

1018 1019 1020
    // Raw value
    rcValue[chan] = val;

1021 1022 1023
    // Normalized value
    float normalized;

1024
    if (val >= rcTrim[chan]) {
1025
        normalized = (val - rcTrim[chan])/(rcMax[chan] - rcTrim[chan]);
1026
    }
1027
    else {
1028 1029 1030 1031 1032 1033 1034
        normalized = -(rcTrim[chan] - val)/(rcTrim[chan] - rcMin[chan]);
    }

    // Bound
    normalized = qBound(-1.0f, normalized, 1.0f);
    // Invert
    normalized = (rcRev[chan]) ? -1.0f*normalized : normalized;
1035

1036
    if (chan == rcMapping[0]) {
1037
        // ROLL
1038
        rcRoll = normalized;
1039
    }
1040
    if (chan == rcMapping[1]) {
1041
        // PITCH
1042
        rcPitch = normalized;
1043
    }
1044
    if (chan == rcMapping[2]) {
1045
        rcYaw = normalized;
1046
    }
1047
    if (chan == rcMapping[3]) {
1048
        // THROTTLE
1049 1050 1051 1052
        if (rcRev[chan]) {
            rcThrottle = 1.0f + normalized;
        } else {
            rcThrottle = normalized;
1053
        }
1054 1055

        rcThrottle = qBound(0.0f, rcThrottle, 1.0f);
1056
    }
1057
    if (chan == rcMapping[4]) {
1058
        // MODE SWITCH
1059
        rcMode = normalized;
1060
    }
1061
    if (chan == rcMapping[5]) {
1062
        // AUX1
1063
        rcAux1 = normalized;
1064
    }
1065
    if (chan == rcMapping[6]) {
1066
        // AUX2
1067
        rcAux2 = normalized;
1068
    }
1069
    if (chan == rcMapping[7]) {
1070
        // AUX3
1071
        rcAux3 = normalized;
1072 1073 1074 1075
    }

    changed = true;

1076
    //qDebug() << "RC CHAN:" << chan << "PPM:" << val << "NORMALIZED:" << normalized;
1077 1078
}

1079 1080 1081 1082 1083 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
void QGCVehicleConfig::updateInvertedCheckboxes(int index)
{
    unsigned int mapindex = rcMapping[index];

    switch (mapindex)
    {
    case 0:
        ui->invertCheckBox->setChecked(rcRev[index]);
        break;
    case 1:
        ui->invertCheckBox_2->setChecked(rcRev[index]);
        break;
    case 2:
        ui->invertCheckBox_3->setChecked(rcRev[index]);
        break;
    case 3:
        ui->invertCheckBox_4->setChecked(rcRev[index]);
        break;
    case 4:
        ui->invertCheckBox_5->setChecked(rcRev[index]);
        break;
    case 5:
        ui->invertCheckBox_6->setChecked(rcRev[index]);
        break;
    case 6:
        ui->invertCheckBox_7->setChecked(rcRev[index]);
        break;
    case 7:
        ui->invertCheckBox_8->setChecked(rcRev[index]);
        break;
    }
}

1112 1113 1114 1115
void QGCVehicleConfig::parameterChanged(int uas, int component, QString parameterName, QVariant value)
{
    Q_UNUSED(uas);
    Q_UNUSED(component);
1116 1117
    if (!doneLoadingConfig)
    {
1118 1119
        //We do not want to attempt to generate any UI elements until loading of the config file is complete.
        //We should re-request params later if needed, that is not implemented yet.
1120 1121
        return;
    }
1122

1123
    if (paramToWidgetMap.contains(parameterName))
1124
    {
1125
        //Main group of parameters of the selected airframe
1126 1127
        paramToWidgetMap.value(parameterName)->setParameterValue(uas,component,parameterName,value);
        if (toolToBoxMap.contains(paramToWidgetMap.value(parameterName)))
1128
        {
1129
            toolToBoxMap[paramToWidgetMap.value(parameterName)]->show();
1130 1131 1132
        }
        else
        {
1133
            qCritical() << "Widget with no box, possible memory corruption for param:" << parameterName;
1134 1135
        }
    }
1136
    else if (libParamToWidgetMap.contains(parameterName))
1137
    {
1138
        //All the library parameters
1139 1140
        libParamToWidgetMap.value(parameterName)->setParameterValue(uas,component,parameterName,value);
        if (toolToBoxMap.contains(libParamToWidgetMap.value(parameterName)))
1141
        {
1142
            toolToBoxMap[libParamToWidgetMap.value(parameterName)]->show();
1143 1144 1145
        }
        else
        {
1146
            qCritical() << "Widget with no box, possible memory corruption for param:" << parameterName;
1147 1148 1149 1150
        }
    }
    else
    {
1151 1152
        //Param recieved that we have no metadata for. Search to see if it belongs in a
        //group with some other params
1153 1154 1155 1156 1157
        bool found = false;
        for (int i=0;i<toolWidgets.size();i++)
        {
            if (parameterName.startsWith(toolWidgets[i]->objectName()))
            {
1158
                //It should be grouped with this one, add it.
1159
                toolWidgets[i]->addParam(uas,component,parameterName,value);
1160
                libParamToWidgetMap.insert(parameterName,toolWidgets[i]);
1161 1162 1163 1164 1165 1166
                found  = true;
                break;
            }
        }
        if (!found)
        {
1167
            //New param type, create a QGroupBox for it.
1168
            QWidget* parent;
1169
            if (ui->advancedLeftLayout->count() > ui->advancedRightLayout->count())
1170 1171 1172 1173 1174 1175 1176 1177 1178
            {
                parent = ui->advancedRightContents;
            }
            else
            {
                parent = ui->advancedLeftContents;
            }

            // Create the tool, attaching it to the QGroupBox
1179 1180 1181 1182 1183
            QString tooltitle = parameterName;
            if (parameterName.split("_").size() > 1)
            {
                tooltitle = parameterName.split("_")[0] + "_";
            }
1184
            QGCToolWidget *tool = new QGCToolWidget(tooltitle, tooltitle, parent);
1185
            //tool->setSettings(set);
1186
            libParamToWidgetMap.insert(parameterName,tool);
1187
            toolWidgets.append(tool);
1188 1189
            tool->addParam(uas, component, parameterName, value);
            QGroupBox *box = new QGroupBox(parent);
1190
            box->setTitle(tool->objectName());
1191
            box->setLayout(new QVBoxLayout(box));
1192 1193
            box->layout()->addWidget(tool);

1194 1195 1196
            libParamToWidgetMap.insert(parameterName,tool);
            toolWidgets.append(tool);

1197 1198
            // Make sure we have similar number of widgets on each side.
            if (ui->advancedLeftLayout->count() > ui->advancedRightLayout->count())
1199
            {
1200
                ui->advancedRightLayout->addWidget(box);
1201 1202 1203
            }
            else
            {
1204
                ui->advancedLeftLayout->addWidget(box);
1205 1206 1207
            }
            toolToBoxMap[tool] = box;
        }
1208
    }
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224

    // Channel calibration values
    QRegExp minTpl("RC?_MIN");
    minTpl.setPatternSyntax(QRegExp::Wildcard);
    QRegExp maxTpl("RC?_MAX");
    maxTpl.setPatternSyntax(QRegExp::Wildcard);
    QRegExp trimTpl("RC?_TRIM");
    trimTpl.setPatternSyntax(QRegExp::Wildcard);
    QRegExp revTpl("RC?_REV");
    revTpl.setPatternSyntax(QRegExp::Wildcard);

    // Do not write the RC type, as these values depend on this
    // active onboard parameter

    if (minTpl.exactMatch(parameterName)) {
        bool ok;
1225
        unsigned int index = parameterName.mid(2, 1).toInt(&ok) - 1;
1226
        //qDebug() << "PARAM:" << parameterName << "index:" << index;
1227
        if (ok && index < chanMax)
1228 1229
        {
            rcMin[index] = value.toInt();
1230
            updateMinMax();
1231 1232 1233 1234 1235
        }
    }

    if (maxTpl.exactMatch(parameterName)) {
        bool ok;
1236 1237
        unsigned int index = parameterName.mid(2, 1).toInt(&ok) - 1;
        if (ok && index < chanMax)
1238 1239
        {
            rcMax[index] = value.toInt();
1240
            updateMinMax();
1241 1242 1243 1244 1245
        }
    }

    if (trimTpl.exactMatch(parameterName)) {
        bool ok;
1246 1247
        unsigned int index = parameterName.mid(2, 1).toInt(&ok) - 1;
        if (ok && index < chanMax)
1248 1249 1250 1251 1252 1253 1254
        {
            rcTrim[index] = value.toInt();
        }
    }

    if (revTpl.exactMatch(parameterName)) {
        bool ok;
1255 1256
        unsigned int index = parameterName.mid(2, 1).toInt(&ok) - 1;
        if (ok && index < chanMax)
1257 1258
        {
            rcRev[index] = (value.toInt() == -1) ? true : false;
1259
            updateInvertedCheckboxes(index);
1260 1261 1262 1263 1264 1265 1266 1267
        }
    }

//        mav->setParameter(0, trimTpl.arg(i), rcTrim[i]);
//        mav->setParameter(0, maxTpl.arg(i), rcMax[i]);
//        mav->setParameter(0, revTpl.arg(i), (rcRev[i]) ? -1 : 1);
//    }

1268 1269 1270 1271 1272 1273 1274 1275
    if (rcTypeUpdateRequested > 0 && parameterName == QString("RC_TYPE"))
    {
        rcTypeUpdateRequested = 0;
        updateStatus(tr("Received RC type update, setting parameters based on model."));
        rcType = value.toInt();
        // Request all other parameters as well
        requestCalibrationRC();
    }
1276 1277 1278 1279

    // Order is: roll, pitch, yaw, throttle, mode sw, aux 1-3

    if (parameterName.contains("RC_MAP_ROLL")) {
1280 1281
        rcMapping[0] = value.toInt() - 1;
        ui->rollSpinBox->setValue(rcMapping[0]+1);
1282
        ui->rollSpinBox->setEnabled(true);
1283 1284 1285
    }

    if (parameterName.contains("RC_MAP_PITCH")) {
1286 1287
        rcMapping[1] = value.toInt() - 1;
        ui->pitchSpinBox->setValue(rcMapping[1]+1);
1288
        ui->pitchSpinBox->setEnabled(true);
1289 1290 1291
    }

    if (parameterName.contains("RC_MAP_YAW")) {
1292 1293
        rcMapping[2] = value.toInt() - 1;
        ui->yawSpinBox->setValue(rcMapping[2]+1);
1294
        ui->yawSpinBox->setEnabled(true);
1295 1296 1297
    }

    if (parameterName.contains("RC_MAP_THROTTLE")) {
1298 1299
        rcMapping[3] = value.toInt() - 1;
        ui->throttleSpinBox->setValue(rcMapping[3]+1);
1300
        ui->throttleSpinBox->setEnabled(true);
1301 1302 1303
    }

    if (parameterName.contains("RC_MAP_MODE_SW")) {
1304 1305
        rcMapping[4] = value.toInt() - 1;
        ui->modeSpinBox->setValue(rcMapping[4]+1);
1306
        ui->modeSpinBox->setEnabled(true);
1307 1308 1309
    }

    if (parameterName.contains("RC_MAP_AUX1")) {
1310 1311
        rcMapping[5] = value.toInt() - 1;
        ui->aux1SpinBox->setValue(rcMapping[5]+1);
1312
        ui->aux1SpinBox->setEnabled(true);
1313 1314 1315
    }

    if (parameterName.contains("RC_MAP_AUX2")) {
1316
        rcMapping[6] = value.toInt() - 1;
1317
        ui->aux2SpinBox->setValue(rcMapping[6]+1);
1318
        ui->aux2SpinBox->setEnabled(true);
1319 1320 1321
    }

    if (parameterName.contains("RC_MAP_AUX3")) {
1322
        rcMapping[7] = value.toInt() - 1;
1323
        ui->aux3SpinBox->setValue(rcMapping[7]+1);
1324
        ui->aux3SpinBox->setEnabled(true);
1325 1326 1327 1328 1329
    }

    // Scaling

    if (parameterName.contains("RC_SCALE_ROLL")) {
1330
        rcScaling[0] = value.toFloat();
1331 1332 1333
    }

    if (parameterName.contains("RC_SCALE_PITCH")) {
1334
        rcScaling[1] = value.toFloat();
1335 1336 1337
    }

    if (parameterName.contains("RC_SCALE_YAW")) {
1338
        rcScaling[2] = value.toFloat();
1339 1340 1341
    }

    if (parameterName.contains("RC_SCALE_THROTTLE")) {
1342
        rcScaling[3] = value.toFloat();
1343 1344 1345
    }

    if (parameterName.contains("RC_SCALE_MODE_SW")) {
1346
        rcScaling[4] = value.toFloat();
1347 1348 1349
    }

    if (parameterName.contains("RC_SCALE_AUX1")) {
1350
        rcScaling[5] = value.toFloat();
1351 1352 1353
    }

    if (parameterName.contains("RC_SCALE_AUX2")) {
1354
        rcScaling[6] = value.toFloat();
1355 1356 1357
    }

    if (parameterName.contains("RC_SCALE_AUX3")) {
1358
        rcScaling[7] = value.toFloat();
1359
    }
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
}

void QGCVehicleConfig::updateStatus(const QString& str)
{
    ui->statusLabel->setText(str);
    ui->statusLabel->setStyleSheet("");
}

void QGCVehicleConfig::updateError(const QString& str)
{
    ui->statusLabel->setText(str);
    ui->statusLabel->setStyleSheet(QString("QLabel { margin: 0px 2px; font: 14px; color: %1; background-color: %2; }").arg(QGC::colorDarkWhite.name()).arg(QGC::colorMagenta.name()));
}
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
void QGCVehicleConfig::updateMinMax()
{
    // Order is: roll, pitch, yaw, throttle, mode sw, aux 1-3
    /*ui->rollWidget->setMin(rcMin[0]);
    ui->rollWidget->setMax(rcMax[0]);
    ui->pitchWidget->setMin(rcMin[1]);
    ui->pitchWidget->setMax(rcMax[1]);
    ui->yawWidget->setMin(rcMin[2]);
    ui->yawWidget->setMax(rcMax[2]);
    ui->throttleWidget->setMin(rcMin[3]);
    ui->throttleWidget->setMax(rcMax[3]);
    ui->radio5Widget->setMin(rcMin[4]);
    ui->radio5Widget->setMax(rcMax[4]);
    ui->radio6Widget->setMin(rcMin[5]);
    ui->radio6Widget->setMax(rcMax[5]);
    ui->radio7Widget->setMin(rcMin[6]);
    ui->radio7Widget->setMax(rcMax[6]);
    ui->radio8Widget->setMin(rcMin[7]);
    ui->radio8Widget->setMax(rcMax[7]);*/
}
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419

void QGCVehicleConfig::setRCType(int type)
{
    if (!mav) return;

    // XXX TODO Add handling of RC_TYPE vs non-RC_TYPE here

    mav->setParameter(0, "RC_TYPE", type);
    rcTypeUpdateRequested = QGC::groundTimeMilliseconds();
    QTimer::singleShot(rcTypeTimeout+100, this, SLOT(checktimeOuts()));
}

void QGCVehicleConfig::checktimeOuts()
{
    if (rcTypeUpdateRequested > 0)
    {
        if (QGC::groundTimeMilliseconds() - rcTypeUpdateRequested > rcTypeTimeout)
        {
            updateError(tr("Setting remote control timed out - is the system connected?"));
        }
    }
}

void QGCVehicleConfig::updateView()
{
    if (changed)
    {
1420 1421
        if (rc_mode == RC_MODE_1)
        {
1422 1423 1424 1425
            //ui->rollSlider->setValue(rcRoll * 50 + 50);
            //ui->pitchSlider->setValue(rcThrottle * 100);
            //ui->yawSlider->setValue(rcYaw * 50 + 50);
            //ui->throttleSlider->setValue(rcPitch * 50 + 50);
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
            ui->rollWidget->setValue(rcValue[0]);
            ui->throttleWidget->setValue(rcValue[1]);
            ui->yawWidget->setValue(rcValue[2]);
            ui->pitchWidget->setValue(rcValue[3]);

            ui->rollWidget->setMin(rcMin[0]);
            ui->rollWidget->setMax(rcMax[0]);
            ui->throttleWidget->setMin(rcMin[1]);
            ui->throttleWidget->setMax(rcMax[1]);
            ui->yawWidget->setMin(rcMin[2]);
            ui->yawWidget->setMax(rcMax[2]);
            ui->pitchWidget->setMin(rcMin[3]);
            ui->pitchWidget->setMax(rcMax[3]);
1439 1440 1441
        }
        else if (rc_mode == RC_MODE_2)
        {
1442 1443 1444 1445
            //ui->rollSlider->setValue(rcRoll * 50 + 50);
            //ui->pitchSlider->setValue(rcPitch * 50 + 50);
            //ui->yawSlider->setValue(rcYaw * 50 + 50);
            //ui->throttleSlider->setValue(rcThrottle * 100);
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
            ui->rollWidget->setValue(rcValue[0]);
            ui->pitchWidget->setValue(rcValue[1]);
            ui->yawWidget->setValue(rcValue[2]);
            ui->throttleWidget->setValue(rcValue[3]);

            ui->rollWidget->setMin(rcMin[0]);
            ui->rollWidget->setMax(rcMax[0]);
            ui->pitchWidget->setMin(rcMin[1]);
            ui->pitchWidget->setMax(rcMax[1]);
            ui->yawWidget->setMin(rcMin[2]);
            ui->yawWidget->setMax(rcMax[2]);
            ui->throttleWidget->setMin(rcMin[3]);
            ui->throttleWidget->setMax(rcMax[3]);
1459 1460 1461
        }
        else if (rc_mode == RC_MODE_3)
        {
1462 1463 1464 1465
            //ui->rollSlider->setValue(rcYaw * 50 + 50);
            //ui->pitchSlider->setValue(rcThrottle * 100);
            //ui->yawSlider->setValue(rcRoll * 50 + 50);
            //ui->throttleSlider->setValue(rcPitch * 50 + 50);
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
            ui->yawWidget->setValue(rcValue[0]);
            ui->throttleWidget->setValue(rcValue[1]);
            ui->rollWidget->setValue(rcValue[2]);
            ui->pitchWidget->setValue(rcValue[3]);

            ui->yawWidget->setMin(rcMin[0]);
            ui->yawWidget->setMax(rcMax[0]);
            ui->throttleWidget->setMin(rcMin[1]);
            ui->throttleWidget->setMax(rcMax[1]);
            ui->rollWidget->setMin(rcMin[2]);
            ui->rollWidget->setMax(rcMax[2]);
            ui->pitchWidget->setMin(rcMin[3]);
            ui->pitchWidget->setMax(rcMax[3]);
1479 1480 1481
        }
        else if (rc_mode == RC_MODE_4)
        {
1482 1483 1484 1485
            //ui->rollSlider->setValue(rcYaw * 50 + 50);
            //ui->pitchSlider->setValue(rcPitch * 50 + 50);
            //ui->yawSlider->setValue(rcRoll * 50 + 50);
            //ui->throttleSlider->setValue(rcThrottle * 100);
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
            ui->yawWidget->setValue(rcValue[0]);
            ui->pitchWidget->setValue(rcValue[1]);
            ui->rollWidget->setValue(rcValue[2]);
            ui->throttleWidget->setValue(rcValue[3]);

            ui->yawWidget->setMin(rcMin[0]);
            ui->yawWidget->setMax(rcMax[0]);
            ui->pitchWidget->setMin(rcMin[1]);
            ui->pitchWidget->setMax(rcMax[1]);
            ui->rollWidget->setMin(rcMin[2]);
            ui->rollWidget->setMax(rcMax[2]);
            ui->throttleWidget->setMin(rcMin[3]);
            ui->throttleWidget->setMax(rcMax[3]);
        }
        else if (rc_mode == RC_MODE_NONE)
        {
            ui->rollWidget->setValue(rcValue[0]);
            ui->pitchWidget->setValue(rcValue[1]);
            ui->throttleWidget->setValue(rcValue[2]);
            ui->yawWidget->setValue(rcValue[3]);

1507 1508 1509 1510 1511 1512 1513 1514
            ui->rollWidget->setMin(800);
            ui->rollWidget->setMax(2200);
            ui->pitchWidget->setMin(800);
            ui->pitchWidget->setMax(2200);
            ui->throttleWidget->setMin(800);
            ui->throttleWidget->setMax(2200);
            ui->yawWidget->setMin(800);
            ui->yawWidget->setMax(2200);
1515 1516
        }

1517 1518 1519 1520
        ui->chanLabel->setText(QString("%1/%2").arg(rcValue[rcMapping[0]]).arg(rcRoll, 5, 'f', 2, QChar(' ')));
        ui->chanLabel_2->setText(QString("%1/%2").arg(rcValue[rcMapping[1]]).arg(rcPitch, 5, 'f', 2, QChar(' ')));
        ui->chanLabel_3->setText(QString("%1/%2").arg(rcValue[rcMapping[2]]).arg(rcYaw, 5, 'f', 2, QChar(' ')));
        ui->chanLabel_4->setText(QString("%1/%2").arg(rcValue[rcMapping[3]]).arg(rcThrottle, 5, 'f', 2, QChar(' ')));
1521

1522 1523 1524


        //ui->modeSwitchSlider->setValue(rcMode * 50 + 50);
1525
        ui->chanLabel_5->setText(QString("%1/%2").arg(rcValue[rcMapping[4]]).arg(rcMode, 5, 'f', 2, QChar(' ')));
1526

1527 1528 1529 1530 1531 1532 1533
        if (rcValue[rcMapping[4] != UINT16_MAX]) {
            ui->radio5Widget->setValue(rcValue[4]);
            ui->chanLabel_5->setText(QString("%1/%2").arg(rcValue[rcMapping[5]]).arg(rcAux1, 5, 'f', 2, QChar(' ')));
        } else {
            ui->chanLabel_5->setText(tr("---"));
        }

1534
        if (rcValue[rcMapping[5]] != UINT16_MAX) {
1535
            //ui->aux1Slider->setValue(rcAux1 * 50 + 50);
1536
            ui->radio6Widget->setValue(rcValue[5]);
1537
            ui->chanLabel_6->setText(QString("%1/%2").arg(rcValue[rcMapping[5]]).arg(rcAux1, 5, 'f', 2, QChar(' ')));
1538 1539 1540 1541
        } else {
            ui->chanLabel_6->setText(tr("---"));
        }

1542
        if (rcValue[rcMapping[6]] != UINT16_MAX) {
1543
            //ui->aux2Slider->setValue(rcAux2 * 50 + 50);
1544
            ui->radio7Widget->setValue(rcValue[6]);
1545
            ui->chanLabel_7->setText(QString("%1/%2").arg(rcValue[rcMapping[6]]).arg(rcAux2, 5, 'f', 2, QChar(' ')));
1546 1547 1548 1549
        } else {
            ui->chanLabel_7->setText(tr("---"));
        }

1550
        if (rcValue[rcMapping[7]] != UINT16_MAX) {
1551
            //ui->aux3Slider->setValue(rcAux3 * 50 + 50);
1552
            ui->radio8Widget->setValue(rcValue[7]);
1553
            ui->chanLabel_8->setText(QString("%1/%2").arg(rcValue[rcMapping[7]]).arg(rcAux3, 5, 'f', 2, QChar(' ')));
1554 1555
        } else {
            ui->chanLabel_8->setText(tr("---"));
1556 1557
        }

1558 1559 1560
        changed = false;
    }
}