QGCVehicleConfig.cc 60.3 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
#include "UASManager.h"
17
#include "QGC.h"
18
#include "QGCToolWidget.h"
19 20 21 22
#include "ui_QGCVehicleConfig.h"

QGCVehicleConfig::QGCVehicleConfig(QWidget *parent) :
    QWidget(parent),
23
    mav(NULL),
24
    chanCount(0),
25 26 27 28 29 30 31 32
    rcRoll(0.0f),
    rcPitch(0.0f),
    rcYaw(0.0f),
    rcThrottle(0.0f),
    rcMode(0.0f),
    rcAux1(0.0f),
    rcAux2(0.0f),
    rcAux3(0.0f),
33
    changed(true),
34
    rc_mode(RC_MODE_NONE),
35
    calibrationEnabled(false),
36 37
    ui(new Ui::QGCVehicleConfig)
{
38
    doneLoadingConfig = false;
39 40 41
    systemTypeToParamMap["FIXED_WING"] = new QMap<QString,QGCToolWidget*>();
    systemTypeToParamMap["QUADROTOR"] = new QMap<QString,QGCToolWidget*>();
    systemTypeToParamMap["GROUND_ROVER"] = new QMap<QString,QGCToolWidget*>();
42
    systemTypeToParamMap["BOAT"] = new QMap<QString,QGCToolWidget*>();
43
    libParamToWidgetMap = new QMap<QString,QGCToolWidget*>();
44

45
    setObjectName("QGC_VEHICLECONFIG");
46
    ui->setupUi(this);
47

48 49 50 51
    ui->rollWidget->setOrientation(Qt::Horizontal);
    ui->rollWidget->setName("Roll");
    ui->yawWidget->setOrientation(Qt::Horizontal);
    ui->yawWidget->setName("Yaw");
52 53
    ui->pitchWidget->setName("Pitch");
    ui->throttleWidget->setName("Throttle");
54 55 56 57 58 59 60 61 62
    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");

63 64 65 66 67
    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()));

68 69
    ui->rcModeComboBox->setCurrentIndex((int)rc_mode - 1);

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

    /* 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)));
95 96 97 98 99

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

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

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

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

    ui->advancedGroupBox->hide();
    connect(ui->advancedCheckBox,SIGNAL(toggled(bool)),ui->advancedGroupBox,SLOT(setShown(bool)));
112
}
113 114 115 116 117 118 119 120 121 122
void QGCVehicleConfig::rcMenuButtonClicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

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

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

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

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

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

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

159 160
void QGCVehicleConfig::setTrimPositions()
{
Lorenz Meier's avatar
Lorenz Meier committed
161 162 163 164 165 166
    // 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
167
    else if (abs(rcValue[rcMapping[3]] - rcMax[rcMapping[3]]) < 100)
Lorenz Meier's avatar
Lorenz Meier committed
168 169 170
    {
        rcTrim[rcMapping[3]] = rcMax[rcMapping[3]];   // throttle
    }
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    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

188 189 190 191
    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
192 193 194 195 196 197 198
}

void QGCVehicleConfig::detectChannelInversion()
{

}

199 200
void QGCVehicleConfig::startCalibrationRC()
{
201 202
    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");
203
    ui->rcTypeComboBox->setEnabled(false);
204
    ui->rcCalibrationButton->setText(tr("Stop RC Calibration"));
205
    resetCalibrationRC();
206
    calibrationEnabled = true;
207 208 209 210 211 212 213 214
    ui->rollWidget->showMinMax();
    ui->pitchWidget->showMinMax();
    ui->yawWidget->showMinMax();
    ui->throttleWidget->showMinMax();
    ui->radio5Widget->showMinMax();
    ui->radio6Widget->showMinMax();
    ui->radio7Widget->showMinMax();
    ui->radio8Widget->showMinMax();
215 216 217 218
}

void QGCVehicleConfig::stopCalibrationRC()
{
219
    QMessageBox::information(0,"Trims","Ensure all sticks are centeres and throttle is in the downmost position, click OK to continue");
220
    calibrationEnabled = false;
221
    ui->rcTypeComboBox->setEnabled(true);
222
    ui->rcCalibrationButton->setText(tr("Start RC Calibration"));
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    ui->rollWidget->hideMinMax();
    ui->pitchWidget->hideMinMax();
    ui->yawWidget->hideMinMax();
    ui->throttleWidget->hideMinMax();
    ui->radio5Widget->hideMinMax();
    ui->radio6Widget->hideMinMax();
    ui->radio7Widget->hideMinMax();
    ui->radio8Widget->hideMinMax();
    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);
241 242
}

243
void QGCVehicleConfig::loadQgcConfig(bool primary)
244
{
245
    Q_UNUSED(primary);
246 247 248 249 250 251
    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
252
        qWarning() << "Invalid general dir. no general configuration will be loaded.";
253 254 255 256
    }
    if (!autopilotdir.exists(mav->getAutopilotTypeName().toLower()))
    {
        //TODO: Throw an error here too, no autopilot specific configuration
257
        qWarning() << "Invalid vehicle dir, no vehicle specific configuration will be loaded.";
258
    }
259 260
    QGCToolWidget *tool;
    bool left = true;
261 262 263 264 265 266 267 268 269 270 271 272
    foreach (QString file,generaldir.entryList(QDir::Files | QDir::NoDotAndDotDot))
    {
        if (file.toLower().endsWith(".qgw")) {
            tool = new QGCToolWidget("", this);
            if (tool->loadSettings(generaldir.absoluteFilePath(file), false))
            {
                toolWidgets.append(tool);
                //ui->sensorLayout->addWidget(tool);
                QGroupBox *box = new QGroupBox(this);
                box->setTitle(tool->objectName());
                box->setLayout(new QVBoxLayout());
                box->layout()->addWidget(tool);
273
                if (left)
274
                {
275 276 277 278 279 280 281
                    left = false;
                    ui->leftGeneralLayout->addWidget(box);
                }
                else
                {
                    left = true;
                    ui->rightGeneralLayout->addWidget(box);
282
                }
283 284 285 286 287
            } else {
                delete tool;
            }
        }
    }
288
    left = true;
289 290 291 292 293 294 295 296 297 298 299 300
    foreach (QString file,vehicledir.entryList(QDir::Files | QDir::NoDotAndDotDot))
    {
        if (file.toLower().endsWith(".qgw")) {
            tool = new QGCToolWidget("", this);
            if (tool->loadSettings(vehicledir.absoluteFilePath(file), false))
            {
                toolWidgets.append(tool);
                //ui->sensorLayout->addWidget(tool);
                QGroupBox *box = new QGroupBox(this);
                box->setTitle(tool->objectName());
                box->setLayout(new QVBoxLayout());
                box->layout()->addWidget(tool);
301
                if (left)
302
                {
303 304 305 306 307 308 309
                    left = false;
                    ui->leftAdvancedLayout->addWidget(box);
                }
                else
                {
                    left = true;
                    ui->rightAdvancedLayout->addWidget(box);
310
                }
311 312 313 314 315 316
            } else {
                delete tool;
            }
        }
    }

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

    //Load tabs for vehicle specific configuration
    foreach (QString dir,vehicledir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
    {
366 367 368 369 370 371 372 373 374 375
        //QWidget *tab = new QWidget(ui->tabWidget);
        //ui->tabWidget->insertTab(2,tab,dir);
        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;

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

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

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

    tool = new QGCToolWidget("", this);
    tool->addUAS(mav);
    if (tool->loadSettings(autopilotdir.absolutePath() + "/" +  mav->getSystemTypeName().toLower() + "/calibration/calibration.qgw", false))
    {
        toolWidgets.append(tool);
        QGroupBox *box = new QGroupBox(this);
        box->setTitle(tool->objectName());
        box->setLayout(new QVBoxLayout());
        box->layout()->addWidget(tool);
        ui->sensorLayout->addWidget(box);
441 442
    } else {
        delete tool;
443
    }
444

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

}
464

465 466 467 468 469 470 471 472 473 474
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
475
        qWarning() << "Invalid general dir. no general configuration will be loaded.";
476 477 478 479
    }
    if (!autopilotdir.exists(mav->getAutopilotTypeName().toLower()))
    {
        //TODO: Throw an error here too, no autopilot specific configuration
480
        qWarning() << "Invalid vehicle dir, no vehicle specific configuration will be loaded.";
481 482 483 484 485
    }
    qDebug() << autopilotdir.absolutePath();
    qDebug() << generaldir.absolutePath();
    qDebug() << vehicledir.absolutePath();
    QFile xmlfile(autopilotdir.absolutePath() + "/arduplane.pdef.xml");
486
    if (xmlfile.exists() && !xmlfile.open(QIODevice::ReadOnly))
487
    {
488
        loadQgcConfig(false);
489
        doneLoadingConfig = true;
490 491
        return;
    }
492
    loadQgcConfig(true);
493 494 495

    QXmlStreamReader xml(xmlfile.readAll());
    xmlfile.close();
496 497

    //TODO: Testing to ensure that incorrectly formated XML won't break this.
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    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();
                            }
519 520 521
                            QVariantMap genset;
                            QVariantMap advset;

522 523
                            QString setname = parametersname;
                            xml.readNext();
524 525
                            int genarraycount = 0;
                            int advarraycount = 0;
526 527 528 529 530 531
                            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();
532 533 534 535 536 537 538 539 540
                                    QString tab= xml.attributes().value("user").toString();
                                    if (tab == "Advanced")
                                    {
                                        advset["title"] = parametersname;
                                    }
                                    else
                                    {
                                        genset["title"] = parametersname;
                                    }
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
                                    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
556 557 558 559 560 561 562 563 564 565 566 567 568 569
                                            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;
                                            }
570 571 572 573 574 575 576 577 578
                                            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();
579 580 581 582 583 584 585 586 587 588
                                                    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();
                                                    }
589 590 591 592
                                                    paramcount++;
                                                }
                                                xml.readNext();
                                            }
593 594 595 596 597 598 599 600
                                            if (tab == "Advanced")
                                            {
                                                advset[setname + "\\" + QString::number(advarraycount) + "\\" + "QGC_PARAM_COMBOBOX_COUNT"] = paramcount;
                                            }
                                            else
                                            {
                                                genset[setname + "\\" + QString::number(genarraycount) + "\\" + "QGC_PARAM_COMBOBOX_COUNT"] = paramcount;
                                            }
601 602 603 604 605 606 607 608 609 610 611 612
                                        }
                                        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)
                                    {
613
                                        //Nothing inside! Assume it's a value, give it a default range.
614 615
                                        type = 2;
                                        QString fieldtype = "Range";
616
                                        QString text = "0 100"; //TODO: Determine a better way of figuring out default ranges.
617 618 619 620
                                        fieldmap[fieldtype] = text;
                                    }
                                    if (type == 2)
                                    {
621 622 623 624 625 626 627 628 629 630 631 632 633 634
                                        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;
                                        }
635 636 637 638
                                        if (fieldmap.contains("Range"))
                                        {
                                            float min = 0;
                                            float max = 0;
639
                                            //Some range fields list "0-10" and some list "0 10". Handle both.
640 641 642 643 644 645 646 647 648 649
                                            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();
                                            }
650 651 652 653 654 655 656 657 658 659
                                            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;
                                            }
660 661
                                        }
                                    }
662 663 664 665 666 667 668 669 670 671
                                    if (tab == "Advanced")
                                    {
                                        advarraycount++;
                                        advset["count"] = advarraycount;
                                    }
                                    else
                                    {
                                        genarraycount++;
                                        genset["count"] = genarraycount;
                                    }
672 673 674
                                }
                                xml.readNext();
                            }
675
                            if (genarraycount > 0)
676
                            {
677 678 679 680 681 682 683
                                tool = new QGCToolWidget("", this);
                                tool->addUAS(mav);
                                tool->setTitle(parametersname);
                                tool->setObjectName(parametersname);
                                tool->setSettings(genset);
                                QList<QString> paramlist = tool->getParamList();
                                for (int i=0;i<paramlist.size();i++)
684
                                {
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
                                    //Based on the airframe, we add the parameter to different categories.
                                    if (parametersname == "ArduPlane") //MAV_TYPE_FIXED_WING FIXED_WING
                                    {
                                        systemTypeToParamMap["FIXED_WING"]->insert(paramlist[i],tool);
                                    }
                                    else if (parametersname == "ArduCopter") //MAV_TYPE_QUADROTOR "QUADROTOR
                                    {
                                        systemTypeToParamMap["QUADROTOR"]->insert(paramlist[i],tool);
                                    }
                                    else if (parametersname == "APMrover2") //MAV_TYPE_GROUND_ROVER GROUND_ROVER
                                    {
                                        systemTypeToParamMap["GROUND_ROVER"]->insert(paramlist[i],tool);
                                    }
                                    else
                                    {
                                        libParamToWidgetMap->insert(paramlist[i],tool);
                                    }
702
                                }
703 704 705 706 707 708 709

                                toolWidgets.append(tool);
                                QGroupBox *box = new QGroupBox(this);
                                box->setTitle(tool->objectName());
                                box->setLayout(new QVBoxLayout());
                                box->layout()->addWidget(tool);
                                if (valuetype == "vehicles")
710
                                {
711
                                    ui->leftGeneralLayout->addWidget(box);
712
                                }
713
                                else if (valuetype == "libraries")
714
                                {
715
                                    ui->rightGeneralLayout->addWidget(box);
716
                                }
717 718 719 720 721 722 723 724 725 726 727 728
                                box->hide();
                                toolToBoxMap[tool] = box;
                            }
                            if (advarraycount > 0)
                            {
                                tool = new QGCToolWidget("", this);
                                tool->addUAS(mav);
                                tool->setTitle(parametersname);
                                tool->setObjectName(parametersname);
                                tool->setSettings(advset);
                                QList<QString> paramlist = tool->getParamList();
                                for (int i=0;i<paramlist.size();i++)
729
                                {
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
                                    //Based on the airframe, we add the parameter to different categories.
                                    if (parametersname == "ArduPlane") //MAV_TYPE_FIXED_WING FIXED_WING
                                    {
                                        systemTypeToParamMap["FIXED_WING"]->insert(paramlist[i],tool);
                                    }
                                    else if (parametersname == "ArduCopter") //MAV_TYPE_QUADROTOR "QUADROTOR
                                    {
                                        systemTypeToParamMap["QUADROTOR"]->insert(paramlist[i],tool);
                                    }
                                    else if (parametersname == "APMrover2") //MAV_TYPE_GROUND_ROVER GROUND_ROVER
                                    {
                                        systemTypeToParamMap["GROUND_ROVER"]->insert(paramlist[i],tool);
                                    }
                                    else
                                    {
                                        libParamToWidgetMap->insert(paramlist[i],tool);
                                    }
747
                                }
748

749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
                                toolWidgets.append(tool);
                                QGroupBox *box = new QGroupBox(this);
                                box->setTitle(tool->objectName());
                                box->setLayout(new QVBoxLayout());
                                box->layout()->addWidget(tool);
                                if (valuetype == "vehicles")
                                {
                                    ui->leftAdvancedLayout->addWidget(box);
                                }
                                else if (valuetype == "libraries")
                                {
                                    ui->rightAdvancedLayout->addWidget(box);
                                }
                                box->hide();
                                toolToBoxMap[tool] = box;
764
                            }
765 766


767 768 769 770 771 772 773 774 775 776 777 778 779


                        }
                        xml.readNext();
                    }

                }

                xml.readNext();
            }
        }
        xml.readNext();
    }
780 781

    mav->getParamManager()->setParamInfo(paramTooltips);
782
    doneLoadingConfig = true;
783
    mav->requestParameters(); //Config is finished, lets do a parameter request to ensure none are missed if someone else started requesting before we were finished.
784 785 786 787 788 789 790 791 792 793 794 795 796 797
}

void QGCVehicleConfig::setActiveUAS(UASInterface* active)
{
    // Do nothing if system is the same or NULL
    if ((active == NULL) || mav == active) return;

    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
798
        disconnect(ui->refreshButton,SIGNAL(clicked()),mav,SLOT(requestParameters()));
799 800 801 802 803

        foreach (QGCToolWidget* tool, toolWidgets)
        {
            delete tool;
        }
804
        toolWidgets.clear();
805 806
    }

Lorenz Meier's avatar
Lorenz Meier committed
807 808 809
    // Connect new system
    mav = active;

810 811 812
    // Reset current state
    resetCalibrationRC();

Lorenz Meier's avatar
Lorenz Meier committed
813 814 815
    requestCalibrationRC();
    mav->requestParameter(0, "RC_TYPE");

816 817
    chanCount = 0;

818 819 820 821
    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
822
    connect(ui->refreshButton, SIGNAL(clicked()), active, SLOT(requestParameters()));
823

824
    if (systemTypeToParamMap.contains(mav->getSystemTypeName()))
825
    {
826
        paramToWidgetMap = systemTypeToParamMap[mav->getSystemTypeName()];
827
    }
828
    else
829
    {
830
        //Indication that we have no meta data for this system type.
831
        qDebug() << "No parameters defined for system type:" << mav->getSystemTypeName();
832 833
        systemTypeToParamMap[mav->getSystemTypeName()] = new QMap<QString,QGCToolWidget*>();
        paramToWidgetMap = systemTypeToParamMap[mav->getSystemTypeName()];
834 835
    }

836
    if (!paramTooltips.isEmpty())
837
    {
838
           mav->getParamManager()->setParamInfo(paramTooltips);
839 840
    }

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

843 844 845
    //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()));
846 847

    updateStatus(QString("Reading from system %1").arg(mav->getUASName()));
848 849

    // Since a system is now connected, enable the VehicleConfig UI.
850
    //ui->tabWidget->setEnabled(true);
851 852 853 854 855 856
    ui->setButton->setEnabled(true);
    ui->refreshButton->setEnabled(true);
    ui->readButton->setEnabled(true);
    ui->writeButton->setEnabled(true);
    ui->loadFileButton->setEnabled(true);
    ui->saveFileButton->setEnabled(true);
857 858 859 860 861
    if (mav->getAutopilotTypeName() == "ARDUPILOTMEGA")
    {
        ui->readButton->hide();
        ui->writeButton->hide();
    }
862
}
863

864 865 866 867
void QGCVehicleConfig::resetCalibrationRC()
{
    for (unsigned int i = 0; i < chanMax; ++i)
    {
868 869
        rcMin[i] = 1500;
        rcMax[i] = 1500;
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
    }
}

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

    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

888
    for (unsigned int i = 0; i < chanCount; ++i)
889
    {
890
        //qDebug() << "SENDING" << minTpl.arg(i+1) << rcMin[i];
Lorenz Meier's avatar
Lorenz Meier committed
891
        mav->setParameter(0, minTpl.arg(i+1), rcMin[i]);
892
        QGC::SLEEP::usleep(50000);
Lorenz Meier's avatar
Lorenz Meier committed
893
        mav->setParameter(0, trimTpl.arg(i+1), rcTrim[i]);
894
        QGC::SLEEP::usleep(50000);
Lorenz Meier's avatar
Lorenz Meier committed
895
        mav->setParameter(0, maxTpl.arg(i+1), rcMax[i]);
896 897 898
        QGC::SLEEP::usleep(50000);
        mav->setParameter(0, revTpl.arg(i+1), (rcRev[i]) ? -1.0f : 1.0f);
        QGC::SLEEP::usleep(50000);
899 900 901
    }

    // Write mappings
902 903 904 905
    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);
906
    mav->setParameter(0, "RC_MAP_YAW", (int32_t)(rcMapping[2]+1));
907
    QGC::SLEEP::usleep(50000);
908
    mav->setParameter(0, "RC_MAP_THROTTLE", (int32_t)(rcMapping[3]+1));
909 910 911 912 913 914 915 916 917
    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);
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
}

void QGCVehicleConfig::requestCalibrationRC()
{
    if (!mav) return;

    QString minTpl("RC%1_MIN");
    QString maxTpl("RC%1_MAX");
    QString trimTpl("RC%1_TRIM");
    QString revTpl("RC%1_REV");

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

    for (unsigned int i = 0; i < chanMax; ++i)
    {
Lorenz Meier's avatar
Lorenz Meier committed
934
        mav->requestParameter(0, minTpl.arg(i+1));
Lorenz Meier's avatar
Lorenz Meier committed
935
        QGC::SLEEP::usleep(5000);
Lorenz Meier's avatar
Lorenz Meier committed
936
        mav->requestParameter(0, trimTpl.arg(i+1));
Lorenz Meier's avatar
Lorenz Meier committed
937
        QGC::SLEEP::usleep(5000);
Lorenz Meier's avatar
Lorenz Meier committed
938
        mav->requestParameter(0, maxTpl.arg(i+1));
Lorenz Meier's avatar
Lorenz Meier committed
939
        QGC::SLEEP::usleep(5000);
Lorenz Meier's avatar
Lorenz Meier committed
940
        mav->requestParameter(0, revTpl.arg(i+1));
Lorenz Meier's avatar
Lorenz Meier committed
941
        QGC::SLEEP::usleep(5000);
942 943 944 945 946 947 948
    }
}

void QGCVehicleConfig::writeParameters()
{
    updateStatus(tr("Writing all onboard parameters."));
    writeCalibrationRC();
949
    mav->writeParametersToStorage();
950 951 952 953
}

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

Bryant's avatar
Bryant committed
958
    if (chan + 1 > (int)chanCount) {
959 960 961 962 963 964 965 966 967 968 969 970 971 972
        chanCount = chan+1;
    }

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

        if (val > rcMax[chan])
        {
            rcMax[chan] = val;
        }
973 974
    }

975 976 977
    // Raw value
    rcValue[chan] = val;

978 979 980 981
    // Normalized value
    float normalized;

    if (val >= rcTrim[chan])
982
    {
983
        normalized = (val - rcTrim[chan])/(rcMax[chan] - rcTrim[chan]);
984
    }
985 986 987 988 989 990 991 992 993
    else
    {
        normalized = -(rcTrim[chan] - val)/(rcTrim[chan] - rcMin[chan]);
    }

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

995 996 997
    if (chan == rcMapping[0])
    {
        // ROLL
998
        rcRoll = normalized;
999
    }
1000
    if (chan == rcMapping[1])
1001 1002
    {
        // PITCH
1003
        rcPitch = normalized;
1004
    }
1005
    if (chan == rcMapping[2])
1006
    {
1007
        rcYaw = normalized;
1008
    }
1009
    if (chan == rcMapping[3])
1010 1011
    {
        // THROTTLE
1012 1013 1014 1015
        if (rcRev[chan]) {
            rcThrottle = 1.0f + normalized;
        } else {
            rcThrottle = normalized;
1016
        }
1017 1018

        rcThrottle = qBound(0.0f, rcThrottle, 1.0f);
1019
    }
1020
    if (chan == rcMapping[4])
1021 1022
    {
        // MODE SWITCH
1023
        rcMode = normalized;
1024
    }
1025
    if (chan == rcMapping[5])
1026 1027
    {
        // AUX1
1028
        rcAux1 = normalized;
1029
    }
1030
    if (chan == rcMapping[6])
1031 1032
    {
        // AUX2
1033
        rcAux2 = normalized;
1034
    }
1035
    if (chan == rcMapping[7])
1036 1037
    {
        // AUX3
1038
        rcAux3 = normalized;
1039 1040 1041 1042
    }

    changed = true;

1043
    //qDebug() << "RC CHAN:" << chan << "PPM:" << val << "NORMALIZED:" << normalized;
1044 1045
}

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
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;
    }
}

1079 1080 1081 1082
void QGCVehicleConfig::parameterChanged(int uas, int component, QString parameterName, QVariant value)
{
    Q_UNUSED(uas);
    Q_UNUSED(component);
1083 1084
    if (!doneLoadingConfig)
    {
1085 1086
        //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.
1087 1088
        return;
    }
1089

1090 1091
    if (paramToWidgetMap->contains(parameterName))
    {
1092
        //Main group of parameters of the selected airframe
1093 1094 1095 1096 1097 1098 1099
        paramToWidgetMap->value(parameterName)->setParameterValue(uas,component,parameterName,value);
        if (toolToBoxMap.contains(paramToWidgetMap->value(parameterName)))
        {
            toolToBoxMap[paramToWidgetMap->value(parameterName)]->show();
        }
        else
        {
1100
            qCritical() << "Widget with no box, possible memory corruption for param:" << parameterName;
1101 1102 1103
        }
    }
    else if (libParamToWidgetMap->contains(parameterName))
1104
    {
1105
        //All the library parameters
1106 1107
        libParamToWidgetMap->value(parameterName)->setParameterValue(uas,component,parameterName,value);
        if (toolToBoxMap.contains(libParamToWidgetMap->value(parameterName)))
1108
        {
1109
            toolToBoxMap[libParamToWidgetMap->value(parameterName)]->show();
1110 1111 1112
        }
        else
        {
1113
            qCritical() << "Widget with no box, possible memory corruption for param:" << parameterName;
1114 1115 1116 1117
        }
    }
    else
    {
1118 1119
        //Param recieved that we have no metadata for. Search to see if it belongs in a
        //group with some other params
1120 1121 1122 1123 1124
        bool found = false;
        for (int i=0;i<toolWidgets.size();i++)
        {
            if (parameterName.startsWith(toolWidgets[i]->objectName()))
            {
1125
                //It should be grouped with this one, add it.
1126
                toolWidgets[i]->addParam(uas,component,parameterName,value);
1127
                libParamToWidgetMap->insert(parameterName,toolWidgets[i]);
1128 1129 1130 1131 1132 1133
                found  = true;
                break;
            }
        }
        if (!found)
        {
1134
            //New param type, create a QGroupBox for it.
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
            QGCToolWidget *tool = new QGCToolWidget("", this);
            QString tooltitle = parameterName;
            if (parameterName.split("_").size() > 1)
            {
                tooltitle = parameterName.split("_")[0] + "_";
            }
            tool->setTitle(tooltitle);
            tool->setObjectName(tooltitle);
            //tool->setSettings(set);
            tool->addParam(uas,component,parameterName,value);
1145
            libParamToWidgetMap->insert(parameterName,tool);
1146 1147 1148 1149 1150 1151
            toolWidgets.append(tool);
            QGroupBox *box = new QGroupBox(this);
            box->setTitle(tool->objectName());
            box->setLayout(new QVBoxLayout());
            box->layout()->addWidget(tool);

1152 1153 1154

            //Make sure we have similar number of widgets on each side.
            if (ui->leftAdvancedLayout->count() > ui->rightAdvancedLayout->count())
1155
            {
1156
                ui->rightAdvancedLayout->addWidget(box);
1157 1158 1159
            }
            else
            {
1160
                ui->leftAdvancedLayout->addWidget(box);
1161 1162 1163
            }
            toolToBoxMap[tool] = box;
        }
1164
    }
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180

    // 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;
1181
        unsigned int index = parameterName.mid(2, 1).toInt(&ok) - 1;
1182
        //qDebug() << "PARAM:" << parameterName << "index:" << index;
1183
        if (ok && index < chanMax)
1184 1185
        {
            rcMin[index] = value.toInt();
1186
            updateMinMax();
1187 1188 1189 1190 1191
        }
    }

    if (maxTpl.exactMatch(parameterName)) {
        bool ok;
1192 1193
        unsigned int index = parameterName.mid(2, 1).toInt(&ok) - 1;
        if (ok && index < chanMax)
1194 1195
        {
            rcMax[index] = value.toInt();
1196
            updateMinMax();
1197 1198 1199 1200 1201
        }
    }

    if (trimTpl.exactMatch(parameterName)) {
        bool ok;
1202 1203
        unsigned int index = parameterName.mid(2, 1).toInt(&ok) - 1;
        if (ok && index < chanMax)
1204 1205 1206 1207 1208 1209 1210
        {
            rcTrim[index] = value.toInt();
        }
    }

    if (revTpl.exactMatch(parameterName)) {
        bool ok;
1211 1212
        unsigned int index = parameterName.mid(2, 1).toInt(&ok) - 1;
        if (ok && index < chanMax)
1213 1214
        {
            rcRev[index] = (value.toInt() == -1) ? true : false;
1215
            updateInvertedCheckboxes(index);
1216 1217 1218 1219 1220 1221 1222 1223
        }
    }

//        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);
//    }

1224 1225 1226 1227 1228 1229 1230 1231
    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();
    }
1232 1233 1234 1235

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

    if (parameterName.contains("RC_MAP_ROLL")) {
1236 1237
        rcMapping[0] = value.toInt() - 1;
        ui->rollSpinBox->setValue(rcMapping[0]+1);
1238
        ui->rollSpinBox->setEnabled(true);
1239 1240 1241
    }

    if (parameterName.contains("RC_MAP_PITCH")) {
1242 1243
        rcMapping[1] = value.toInt() - 1;
        ui->pitchSpinBox->setValue(rcMapping[1]+1);
1244
        ui->pitchSpinBox->setEnabled(true);
1245 1246 1247
    }

    if (parameterName.contains("RC_MAP_YAW")) {
1248 1249
        rcMapping[2] = value.toInt() - 1;
        ui->yawSpinBox->setValue(rcMapping[2]+1);
1250
        ui->yawSpinBox->setEnabled(true);
1251 1252 1253
    }

    if (parameterName.contains("RC_MAP_THROTTLE")) {
1254 1255
        rcMapping[3] = value.toInt() - 1;
        ui->throttleSpinBox->setValue(rcMapping[3]+1);
1256
        ui->throttleSpinBox->setEnabled(true);
1257 1258 1259
    }

    if (parameterName.contains("RC_MAP_MODE_SW")) {
1260 1261
        rcMapping[4] = value.toInt() - 1;
        ui->modeSpinBox->setValue(rcMapping[4]+1);
1262
        ui->modeSpinBox->setEnabled(true);
1263 1264 1265
    }

    if (parameterName.contains("RC_MAP_AUX1")) {
1266 1267
        rcMapping[5] = value.toInt() - 1;
        ui->aux1SpinBox->setValue(rcMapping[5]+1);
1268
        ui->aux1SpinBox->setEnabled(true);
1269 1270 1271
    }

    if (parameterName.contains("RC_MAP_AUX2")) {
1272
        rcMapping[6] = value.toInt() - 1;
1273
        ui->aux2SpinBox->setValue(rcMapping[6]+1);
1274
        ui->aux2SpinBox->setEnabled(true);
1275 1276 1277
    }

    if (parameterName.contains("RC_MAP_AUX3")) {
1278
        rcMapping[7] = value.toInt() - 1;
1279
        ui->aux3SpinBox->setValue(rcMapping[7]+1);
1280
        ui->aux3SpinBox->setEnabled(true);
1281 1282 1283 1284 1285
    }

    // Scaling

    if (parameterName.contains("RC_SCALE_ROLL")) {
1286
        rcScaling[0] = value.toFloat();
1287 1288 1289
    }

    if (parameterName.contains("RC_SCALE_PITCH")) {
1290
        rcScaling[1] = value.toFloat();
1291 1292 1293
    }

    if (parameterName.contains("RC_SCALE_YAW")) {
1294
        rcScaling[2] = value.toFloat();
1295 1296 1297
    }

    if (parameterName.contains("RC_SCALE_THROTTLE")) {
1298
        rcScaling[3] = value.toFloat();
1299 1300 1301
    }

    if (parameterName.contains("RC_SCALE_MODE_SW")) {
1302
        rcScaling[4] = value.toFloat();
1303 1304 1305
    }

    if (parameterName.contains("RC_SCALE_AUX1")) {
1306
        rcScaling[5] = value.toFloat();
1307 1308 1309
    }

    if (parameterName.contains("RC_SCALE_AUX2")) {
1310
        rcScaling[6] = value.toFloat();
1311 1312 1313
    }

    if (parameterName.contains("RC_SCALE_AUX3")) {
1314
        rcScaling[7] = value.toFloat();
1315
    }
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
}

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()));
}
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
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]);*/
}
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375

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)
    {
1376 1377
        if (rc_mode == RC_MODE_1)
        {
1378 1379 1380 1381
            //ui->rollSlider->setValue(rcRoll * 50 + 50);
            //ui->pitchSlider->setValue(rcThrottle * 100);
            //ui->yawSlider->setValue(rcYaw * 50 + 50);
            //ui->throttleSlider->setValue(rcPitch * 50 + 50);
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
            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]);
1395 1396 1397
        }
        else if (rc_mode == RC_MODE_2)
        {
1398 1399 1400 1401
            //ui->rollSlider->setValue(rcRoll * 50 + 50);
            //ui->pitchSlider->setValue(rcPitch * 50 + 50);
            //ui->yawSlider->setValue(rcYaw * 50 + 50);
            //ui->throttleSlider->setValue(rcThrottle * 100);
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
            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]);
1415 1416 1417
        }
        else if (rc_mode == RC_MODE_3)
        {
1418 1419 1420 1421
            //ui->rollSlider->setValue(rcYaw * 50 + 50);
            //ui->pitchSlider->setValue(rcThrottle * 100);
            //ui->yawSlider->setValue(rcRoll * 50 + 50);
            //ui->throttleSlider->setValue(rcPitch * 50 + 50);
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
            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]);
1435 1436 1437
        }
        else if (rc_mode == RC_MODE_4)
        {
1438 1439 1440 1441
            //ui->rollSlider->setValue(rcYaw * 50 + 50);
            //ui->pitchSlider->setValue(rcPitch * 50 + 50);
            //ui->yawSlider->setValue(rcRoll * 50 + 50);
            //ui->throttleSlider->setValue(rcThrottle * 100);
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
            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]);

1463 1464 1465 1466 1467 1468 1469 1470
            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);
1471 1472
        }

1473 1474 1475 1476
        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(' ')));
1477

1478 1479 1480


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

1483 1484 1485 1486 1487 1488 1489
        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("---"));
        }

1490
        if (rcValue[rcMapping[5]] != UINT16_MAX) {
1491
            //ui->aux1Slider->setValue(rcAux1 * 50 + 50);
1492
            ui->radio6Widget->setValue(rcValue[5]);
1493
            ui->chanLabel_6->setText(QString("%1/%2").arg(rcValue[rcMapping[5]]).arg(rcAux1, 5, 'f', 2, QChar(' ')));
1494 1495 1496 1497
        } else {
            ui->chanLabel_6->setText(tr("---"));
        }

1498
        if (rcValue[rcMapping[6]] != UINT16_MAX) {
1499
            //ui->aux2Slider->setValue(rcAux2 * 50 + 50);
1500
            ui->radio7Widget->setValue(rcValue[6]);
1501
            ui->chanLabel_7->setText(QString("%1/%2").arg(rcValue[rcMapping[6]]).arg(rcAux2, 5, 'f', 2, QChar(' ')));
1502 1503 1504 1505
        } else {
            ui->chanLabel_7->setText(tr("---"));
        }

1506
        if (rcValue[rcMapping[7]] != UINT16_MAX) {
1507
            //ui->aux3Slider->setValue(rcAux3 * 50 + 50);
1508
            ui->radio8Widget->setValue(rcValue[7]);
1509
            ui->chanLabel_8->setText(QString("%1/%2").arg(rcValue[rcMapping[7]]).arg(rcAux3, 5, 'f', 2, QChar(' ')));
1510 1511
        } else {
            ui->chanLabel_8->setText(tr("---"));
1512 1513
        }

1514 1515 1516
        changed = false;
    }
}