QGCVehicleConfig.cc 40.7 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
#include <QDir>
12
#include <QXmlStreamReader>
13

14
#include "QGCVehicleConfig.h"
15
#include "UASManager.h"
16
#include "QGC.h"
17
#include "QGCToolWidget.h"
18 19 20 21
#include "ui_QGCVehicleConfig.h"

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

    requestCalibrationRC();
    if (mav) mav->requestParameter(0, "RC_TYPE");

48 49
    ui->rcModeComboBox->setCurrentIndex((int)rc_mode - 1);

50
    ui->rcCalibrationButton->setCheckable(true);
51 52
    connect(ui->rcCalibrationButton, SIGNAL(clicked(bool)), this, SLOT(toggleCalibrationRC(bool)));
    connect(ui->storeButton, SIGNAL(clicked()), this, SLOT(writeParameters()));
53
    connect(ui->rcModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setRCModeIndex(int)));
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    connect(ui->setTrimButton, SIGNAL(clicked()), this, SLOT(setTrimPositions()));

    /* 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)));
75 76 77 78 79

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

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

80
    for (unsigned int i = 0; i < chanMax; i++)
81
    {
82
        rcValue[i] = UINT16_MAX;
83
        rcMapping[i] = i;
84 85 86 87 88
    }

    updateTimer.setInterval(150);
    connect(&updateTimer, SIGNAL(timeout()), this, SLOT(updateView()));
    updateTimer.start();
89 90 91 92 93 94
}

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

96 97 98 99 100 101 102 103
void QGCVehicleConfig::setRCModeIndex(int newRcMode)
{
    if (newRcMode > 0 && newRcMode < 5)
    {
        rc_mode = (enum RC_MODE) (newRcMode+1);
        changed = true;
    }
}
104 105 106 107 108 109 110 111 112 113 114 115 116

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

117 118 119
void QGCVehicleConfig::setTrimPositions()
{
    // Set trim for roll, pitch, yaw, throttle
120 121 122
    rcTrim[rcMapping[0]] = rcValue[rcMapping[0]]; // roll
    rcTrim[rcMapping[1]] = rcValue[rcMapping[1]]; // pitch
    rcTrim[rcMapping[2]] = rcValue[rcMapping[2]]; // yaw
Lorenz Meier's avatar
Lorenz Meier committed
123 124 125 126 127 128 129 130 131 132
    // 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
    if (abs(rcValue[rcMapping[3]] - rcMax[rcMapping[3]]) < 100)
    {
        rcTrim[rcMapping[3]] = rcMax[rcMapping[3]];   // throttle
    }
133 134 135 136
    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
137 138 139 140 141 142 143
}

void QGCVehicleConfig::detectChannelInversion()
{

}

144 145 146
void QGCVehicleConfig::startCalibrationRC()
{
    ui->rcTypeComboBox->setEnabled(false);
147
    ui->rcCalibrationButton->setText(tr("Stop RC Calibration"));
148
    resetCalibrationRC();
149
    calibrationEnabled = true;
150 151 152 153
}

void QGCVehicleConfig::stopCalibrationRC()
{
154
    calibrationEnabled = false;
155
    ui->rcTypeComboBox->setEnabled(true);
156
    ui->rcCalibrationButton->setText(tr("Start RC Calibration"));
157
}
158
void QGCVehicleConfig::loadQgcConfig()
159
{
160 161 162 163 164 165 166 167 168 169 170 171 172
    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
        qDebug() << "invalid general dir";
    }
    if (!autopilotdir.exists(mav->getAutopilotTypeName().toLower()))
    {
        //TODO: Throw an error here too, no autopilot specific configuration
        qDebug() << "invalid vehicle dir";
    }
173 174
    QGCToolWidget *tool;
    bool left = true;
175 176 177 178 179 180 181 182 183 184 185 186
    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);
187 188 189 190 191 192 193 194 195 196
                if (left)
                {
                    left = false;
                    ui->leftGeneralLayout->addWidget(box);
                }
                else
                {
                    left = true;
                    ui->rightGeneralLayout->addWidget(box);
                }
197 198 199 200 201
            } else {
                delete tool;
            }
        }
    }
202
    left = true;
203 204 205 206 207 208 209 210 211 212 213 214
    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);
215 216 217 218 219 220 221 222 223 224 225
                if (left)
                {
                    left = false;
                    ui->leftHWSpecificLayout->addWidget(box);
                }
                else
                {
                    left = true;
                    ui->rightHWSpecificLayout->addWidget(box);
                }

226 227 228 229 230 231 232 233
            } else {
                delete tool;
            }
        }
    }



234 235
    // Load calibration
    tool = new QGCToolWidget("", this);
236
    if (tool->loadSettings(autopilotdir.absolutePath() + "/general/calibration/calibration.qgw", false))
237 238 239
    {
        toolWidgets.append(tool);
        ui->sensorLayout->addWidget(tool);
240 241
    } else {
        delete tool;
242
    }
243

244
    // Load multirotor attitude pid
245
    /*
246 247 248 249
    tool = new QGCToolWidget("", this);
    if (tool->loadSettings(defaultsDir + "px4_mc_attitude_pid_params.qgw", false))
    {
        toolWidgets.append(tool);
250 251 252 253 254 255
    QGroupBox *box = new QGroupBox(this);
    box->setTitle(tool->objectName());
    box->setLayout(new QVBoxLayout());
    box->layout()->addWidget(tool);
    ui->multiRotorAttitudeLayout->addWidget(box);
    //ui->multiRotorAttitudeLayout->addWidget(tool);
256 257
    } else {
        delete tool;
258 259 260 261 262 263 264
    }

    // Load multirotor position pid
    tool = new QGCToolWidget("", this);
    if (tool->loadSettings(defaultsDir + "px4_mc_position_pid_params.qgw", false))
    {
        toolWidgets.append(tool);
265 266 267 268 269 270
    QGroupBox *box = new QGroupBox(this);
    box->setTitle(tool->objectName());
    box->setLayout(new QVBoxLayout());
    box->layout()->addWidget(tool);
    ui->multiRotorAttitudeLayout->addWidget(box);
    //ui->multiRotorPositionLayout->addWidget(tool);
271 272
    } else {
        delete tool;
273 274 275 276 277 278 279
    }

    // Load fixed wing attitude pid
    tool = new QGCToolWidget("", this);
    if (tool->loadSettings(defaultsDir + "px4_fw_attitude_pid_params.qgw", false))
    {
        toolWidgets.append(tool);
280 281 282 283 284 285
    QGroupBox *box = new QGroupBox(this);
    box->setTitle(tool->objectName());
    box->setLayout(new QVBoxLayout());
    box->layout()->addWidget(tool);
    ui->multiRotorAttitudeLayout->addWidget(box);
    //ui->fixedWingAttitudeLayout->addWidget(tool);
286 287
    } else {
        delete tool;
288 289 290 291 292 293 294
    }

    // Load fixed wing position pid
    tool = new QGCToolWidget("", this);
    if (tool->loadSettings(defaultsDir + "px4_fw_position_pid_params.qgw", false))
    {
        toolWidgets.append(tool);
295 296 297 298 299 300
    QGroupBox *box = new QGroupBox(this);
    box->setTitle(tool->objectName());
    box->setLayout(new QVBoxLayout());
    box->layout()->addWidget(tool);
    ui->multiRotorAttitudeLayout->addWidget(box);
    //ui->fixedWingPositionLayout->addWidget(tool);
301 302
    } else {
        delete tool;
303
    }*/
304
}
305

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
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
        qDebug() << "invalid general dir";
    }
    if (!autopilotdir.exists(mav->getAutopilotTypeName().toLower()))
    {
        //TODO: Throw an error here too, no autopilot specific configuration
        qDebug() << "invalid vehicle dir";
    }
    qDebug() << autopilotdir.absolutePath();
    qDebug() << generaldir.absolutePath();
    qDebug() << vehicledir.absolutePath();
    QFile xmlfile(autopilotdir.absolutePath() + "/arduplane.pdef.xml");
    if (!xmlfile.open(QIODevice::ReadOnly))
    {
        loadQgcConfig();
330
        doneLoadingConfig = true;
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        return;
    }

    QXmlStreamReader xml(xmlfile.readAll());
    xmlfile.close();
    while (!xml.atEnd())
    {
        if (xml.isStartElement() && xml.name() == "paramfile")
        {
            //Beginning of the file
            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();
                            }
                            QVariantMap set;
                            set["title"] = parametersname;
                            QString setname = parametersname;
                            xml.readNext();
                            int arraycount = 0;
                            while ((xml.name() != "parameters") && !xml.atEnd())
                            {
                                if (xml.isStartElement() && xml.name() == "param")
                                {
                                    //set.setArrayIndex(arraycount++);
                                    QString humanname = xml.attributes().value("humanName").toString();
                                    QString name = xml.attributes().value("name").toString();
                                    if (name.contains(":"))
                                    {
                                        name = name.split(":")[1];
                                    }
                                    QString docs = xml.attributes().value("documentation").toString();
                                    paramTooltips[name] = name + " - " + docs;
                                   // qDebug() << "Found param:" << name << humanname;

                                    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
                                            set[setname + "\\" + QString::number(arraycount) + "\\" + "TYPE"] = "COMBO";
                                            set[setname + "\\" + QString::number(arraycount) + "\\" + "QGC_PARAM_COMBOBOX_DESCRIPTION"] = humanname;
                                            set[setname + "\\" + QString::number(arraycount) + "\\" + "QGC_PARAM_COMBOBOX_PARAMID"] = name;
                                            set[setname + "\\" + QString::number(arraycount) + "\\" + "QGC_PARAM_COMBOBOX_COMPONENTID"] = 1;
                                            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();
                                                    set[setname + "\\" + QString::number(arraycount) + "\\" + "QGC_PARAM_COMBOBOX_ITEM_" + QString::number(paramcount) + "_TEXT"] = arg;
                                                    set[setname + "\\" + QString::number(arraycount) + "\\" + "QGC_PARAM_COMBOBOX_ITEM_" + QString::number(paramcount) + "_VAL"] = code.toInt();
                                                    paramcount++;
                                                    //qDebug() << "Code:" << code << "Arg:" << arg;
                                                }
                                                xml.readNext();
                                            }
                                            set[setname + "\\" + QString::number(arraycount) + "\\" + "QGC_PARAM_COMBOBOX_COUNT"] = paramcount;
                                        }
                                        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;
                                           // qDebug() << "Field:" << fieldtype << "Text:" << text;
                                        }
                                        xml.readNext();
                                    }
                                    if (type == -1)
                                    {
                                        //Nothing inside! Assume it's a value
                                        type = 2;
                                        QString fieldtype = "Range";
                                        QString text = "0 100";
                                        fieldmap[fieldtype] = text;
                                    }
                                    if (type == 2)
                                    {
                                        set[setname + "\\" + QString::number(arraycount) + "\\" + "TYPE"] = "SLIDER";
                                        set[setname + "\\" + QString::number(arraycount) + "\\" + "QGC_PARAM_SLIDER_DESCRIPTION"] = humanname;
                                        set[setname + "\\" + QString::number(arraycount) + "\\" + "QGC_PARAM_SLIDER_PARAMID"] = name;
                                        set[setname + "\\" + QString::number(arraycount) + "\\" + "QGC_PARAM_SLIDER_COMPONENTID"] = 1;
                                        if (fieldmap.contains("Range"))
                                        {
                                            float min = 0;
                                            float max = 0;
                                            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();
                                            }

                                            set[setname + "\\" + QString::number(arraycount) + "\\" + "QGC_PARAM_SLIDER_MIN"] = min;
                                            set[setname + "\\" + QString::number(arraycount) + "\\" + "QGC_PARAM_SLIDER_MAX"] = max;
                                        }
                                    }
                                    arraycount++;
                                }
                                xml.readNext();
                            }
                            set["count"] = arraycount;

                            tool = new QGCToolWidget("", this);
                            tool->setTitle(parametersname);
                            tool->setObjectName(parametersname);
                            tool->setSettings(set);
                            QList<QString> paramlist = tool->getParamList();
                            for (int i=0;i<paramlist.size();i++)
                            {
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
                                qDebug() << "Adding:" << paramlist[i] << parametersname;
                                if (parametersname == "ArduPlane") //MAV_TYPE_FIXED_WING FIXED_WING
                                {
                                    systemTypeToParamMap["FIXED_WING"]->insert(paramlist[i],tool);
                                }
                                else if (parametersname == "ArduCoptor") //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);
                                }
                                //paramToWidgetMap[paramlist[i]] = tool;
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
                            }

                            toolWidgets.append(tool);
                            QGroupBox *box = new QGroupBox(this);
                            box->setTitle(tool->objectName());
                            box->setLayout(new QVBoxLayout());
                            box->layout()->addWidget(tool);
                            if (valuetype == "vehicles")
                            {
                                ui->leftGeneralLayout->addWidget(box);
                            }
                            else if (valuetype == "libraries")
                            {
                                ui->rightGeneralLayout->addWidget(box);
                            }
                            box->hide();
                            toolToBoxMap[tool] = box;


                        }
                        xml.readNext();
                    }

                }

                xml.readNext();
            }
        }
        xml.readNext();
    }
    if (mav)
    {
           mav->getParamManager()->setParamInfo(paramTooltips);
    }
    emit configReady();
517 518
    doneLoadingConfig = true;
    mav->requestParameters();
519 520
}

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
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)));

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

    // Reset current state
    resetCalibrationRC();

    chanCount = 0;

    // Connect new system
    mav = active;
    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)));

553 554 555 556 557 558 559 560 561
    if (systemTypeToParamMap.contains(mav->getSystemTypeName()))
    {
        paramToWidgetMap = systemTypeToParamMap[mav->getSystemTypeName()];
    }
    else
    {
        qDebug() << "No parameters defined for system type:" << mav->getSystemTypeName();
    }

562 563 564 565 566
    if (!paramTooltips.isEmpty())
    {
           mav->getParamManager()->setParamInfo(paramTooltips);
    }

567
   //    mav->requestParameters();
568 569 570 571 572 573 574 575 576 577 578

    QString defaultsDir = qApp->applicationDirPath() + "/files/" + mav->getAutopilotTypeName().toLower() + "/widgets/";
    qDebug() << "CALIBRATION!! System Type Name:" << mav->getSystemTypeName();


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

    updateStatus(QString("Reading from system %1").arg(mav->getUASName()));
}
579 580 581 582
void QGCVehicleConfig::resetCalibrationRC()
{
    for (unsigned int i = 0; i < chanMax; ++i)
    {
583 584
        rcMin[i] = 1200;
        rcMax[i] = 1800;
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
    }
}

/**
 * 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

603
    for (unsigned int i = 0; i < chanCount; ++i)
604
    {
605
        //qDebug() << "SENDING" << minTpl.arg(i+1) << rcMin[i];
Lorenz Meier's avatar
Lorenz Meier committed
606
        mav->setParameter(0, minTpl.arg(i+1), rcMin[i]);
607
        QGC::SLEEP::usleep(50000);
Lorenz Meier's avatar
Lorenz Meier committed
608
        mav->setParameter(0, trimTpl.arg(i+1), rcTrim[i]);
609
        QGC::SLEEP::usleep(50000);
Lorenz Meier's avatar
Lorenz Meier committed
610
        mav->setParameter(0, maxTpl.arg(i+1), rcMax[i]);
611 612 613
        QGC::SLEEP::usleep(50000);
        mav->setParameter(0, revTpl.arg(i+1), (rcRev[i]) ? -1.0f : 1.0f);
        QGC::SLEEP::usleep(50000);
614 615 616
    }

    // Write mappings
617 618 619 620
    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);
621
    mav->setParameter(0, "RC_MAP_YAW", (int32_t)(rcMapping[2]+1));
622
    QGC::SLEEP::usleep(50000);
623
    mav->setParameter(0, "RC_MAP_THROTTLE", (int32_t)(rcMapping[3]+1));
624 625 626 627 628 629 630 631 632
    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);
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
}

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
649
        mav->requestParameter(0, minTpl.arg(i+1));
Lorenz Meier's avatar
Lorenz Meier committed
650
        QGC::SLEEP::usleep(5000);
Lorenz Meier's avatar
Lorenz Meier committed
651
        mav->requestParameter(0, trimTpl.arg(i+1));
Lorenz Meier's avatar
Lorenz Meier committed
652
        QGC::SLEEP::usleep(5000);
Lorenz Meier's avatar
Lorenz Meier committed
653
        mav->requestParameter(0, maxTpl.arg(i+1));
Lorenz Meier's avatar
Lorenz Meier committed
654
        QGC::SLEEP::usleep(5000);
Lorenz Meier's avatar
Lorenz Meier committed
655
        mav->requestParameter(0, revTpl.arg(i+1));
Lorenz Meier's avatar
Lorenz Meier committed
656
        QGC::SLEEP::usleep(5000);
657 658 659 660 661 662 663
    }
}

void QGCVehicleConfig::writeParameters()
{
    updateStatus(tr("Writing all onboard parameters."));
    writeCalibrationRC();
664
    mav->writeParametersToStorage();
665 666 667 668
}

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

Bryant's avatar
Bryant committed
673
    if (chan + 1 > (int)chanCount) {
674 675 676 677 678 679 680 681 682 683 684 685 686 687
        chanCount = chan+1;
    }

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

        if (val > rcMax[chan])
        {
            rcMax[chan] = val;
        }
688 689
    }

690 691 692
    // Raw value
    rcValue[chan] = val;

693 694 695 696
    // Normalized value
    float normalized;

    if (val >= rcTrim[chan])
697
    {
698
        normalized = (val - rcTrim[chan])/(rcMax[chan] - rcTrim[chan]);
699
    }
700 701 702 703 704 705 706 707 708
    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;
709

710 711 712
    if (chan == rcMapping[0])
    {
        // ROLL
713
        rcRoll = normalized;
714
    }
715
    if (chan == rcMapping[1])
716 717
    {
        // PITCH
718
        rcPitch = normalized;
719
    }
720
    if (chan == rcMapping[2])
721
    {
722
        rcYaw = normalized;
723
    }
724
    if (chan == rcMapping[3])
725 726
    {
        // THROTTLE
727 728 729 730
        if (rcRev[chan]) {
            rcThrottle = 1.0f + normalized;
        } else {
            rcThrottle = normalized;
731
        }
732 733

        rcThrottle = qBound(0.0f, rcThrottle, 1.0f);
734
    }
735
    if (chan == rcMapping[4])
736 737
    {
        // MODE SWITCH
738
        rcMode = normalized;
739
    }
740
    if (chan == rcMapping[5])
741 742
    {
        // AUX1
743
        rcAux1 = normalized;
744
    }
745
    if (chan == rcMapping[6])
746 747
    {
        // AUX2
748
        rcAux2 = normalized;
749
    }
750
    if (chan == rcMapping[7])
751 752
    {
        // AUX3
753
        rcAux3 = normalized;
754 755 756 757
    }

    changed = true;

758
    //qDebug() << "RC CHAN:" << chan << "PPM:" << val << "NORMALIZED:" << normalized;
759 760
}

761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
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;
    }
}

794 795 796 797
void QGCVehicleConfig::parameterChanged(int uas, int component, QString parameterName, QVariant value)
{
    Q_UNUSED(uas);
    Q_UNUSED(component);
798 799 800 801
    if (!doneLoadingConfig)
    {
        return;
    }
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    if (paramToWidgetMap->contains(parameterName))
    {
        paramToWidgetMap->value(parameterName)->setParameterValue(uas,component,parameterName,value);
        if (toolToBoxMap.contains(paramToWidgetMap->value(parameterName)))
        {
            if (value.type() == QVariant::Char)
            {
                //qDebug() << "Parameter update (char):" << parameterName << QVariant(value.toUInt());
            }
            else
            {
                //qDebug() << "Parameter update:" << parameterName << value;
            }
            toolToBoxMap[paramToWidgetMap->value(parameterName)]->show();
        }
        else
        {
            qDebug() << "ERROR!!!!!!!!!! widget with no box:" << parameterName;
        }
    }
    else if (libParamToWidgetMap->contains(parameterName))
823
    {
824 825 826
        //It's a lib param
        libParamToWidgetMap->value(parameterName)->setParameterValue(uas,component,parameterName,value);
        if (toolToBoxMap.contains(libParamToWidgetMap->value(parameterName)))
827
        {
828 829
            if (value.type() == QVariant::Char)
            {
830
                //qDebug() << "Parameter update (char):" << parameterName << QVariant(value.toUInt());
831 832 833
            }
            else
            {
834
                //qDebug() << "Parameter update:" << parameterName << value;
835
            }
836
            toolToBoxMap[libParamToWidgetMap->value(parameterName)]->show();
837 838 839 840 841 842 843 844
        }
        else
        {
            qDebug() << "ERROR!!!!!!!!!! widget with no box:" << parameterName;
        }
    }
    else
    {
845
        bool found = false;
846
        qDebug() << "Param with no widget:" << parameterName;
847 848 849 850 851 852 853
        for (int i=0;i<toolWidgets.size();i++)
        {
            if (parameterName.startsWith(toolWidgets[i]->objectName()))
            {
                //It should be grouped with this one.
                qDebug() << parameterName << toolWidgets[i]->objectName();
                toolWidgets[i]->addParam(uas,component,parameterName,value);
854
                libParamToWidgetMap->insert(parameterName,toolWidgets[i]);
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
                found  = true;
                break;
            }
        }
        if (!found)
        {
            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);
871
            libParamToWidgetMap->insert(parameterName,tool);
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
            toolWidgets.append(tool);
            QGroupBox *box = new QGroupBox(this);
            box->setTitle(tool->objectName());
            box->setLayout(new QVBoxLayout());
            box->layout()->addWidget(tool);

            if (ui->leftHWSpecificLayout->count() > ui->rightHWSpecificLayout->count())
            {
                ui->rightHWSpecificLayout->addWidget(box);
            }
            else
            {
                ui->leftHWSpecificLayout->addWidget(box);
            }
            toolToBoxMap[tool] = box;
        }
888 889
    }

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
    // 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;
Lorenz Meier's avatar
Lorenz Meier committed
905
        int index = parameterName.mid(2, 1).toInt(&ok) - 1;
906
        //qDebug() << "PARAM:" << parameterName << "index:" << index;
907
        if (ok && (index >= 0) && (index < chanMax))
908 909 910 911 912 913 914
        {
            rcMin[index] = value.toInt();
        }
    }

    if (maxTpl.exactMatch(parameterName)) {
        bool ok;
Lorenz Meier's avatar
Lorenz Meier committed
915
        int index = parameterName.mid(2, 1).toInt(&ok) - 1;
916
        if (ok && (index >= 0) && (index < chanMax))
917 918 919 920 921 922 923
        {
            rcMax[index] = value.toInt();
        }
    }

    if (trimTpl.exactMatch(parameterName)) {
        bool ok;
Lorenz Meier's avatar
Lorenz Meier committed
924
        int index = parameterName.mid(2, 1).toInt(&ok) - 1;
925
        if (ok && (index >= 0) && (index < chanMax))
926 927 928 929 930 931 932
        {
            rcTrim[index] = value.toInt();
        }
    }

    if (revTpl.exactMatch(parameterName)) {
        bool ok;
Lorenz Meier's avatar
Lorenz Meier committed
933
        int index = parameterName.mid(2, 1).toInt(&ok) - 1;
934
        if (ok && (index >= 0) && (index < chanMax))
935 936
        {
            rcRev[index] = (value.toInt() == -1) ? true : false;
937
            updateInvertedCheckboxes(index);
938 939 940 941 942 943 944 945
        }
    }

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

946 947 948 949 950 951 952 953
    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();
    }
954 955 956 957

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

    if (parameterName.contains("RC_MAP_ROLL")) {
958 959
        rcMapping[0] = value.toInt() - 1;
        ui->rollSpinBox->setValue(rcMapping[0]+1);
960 961 962
    }

    if (parameterName.contains("RC_MAP_PITCH")) {
963 964
        rcMapping[1] = value.toInt() - 1;
        ui->pitchSpinBox->setValue(rcMapping[1]+1);
965 966 967
    }

    if (parameterName.contains("RC_MAP_YAW")) {
968 969
        rcMapping[2] = value.toInt() - 1;
        ui->yawSpinBox->setValue(rcMapping[2]+1);
970 971 972
    }

    if (parameterName.contains("RC_MAP_THROTTLE")) {
973 974
        rcMapping[3] = value.toInt() - 1;
        ui->throttleSpinBox->setValue(rcMapping[3]+1);
975 976 977
    }

    if (parameterName.contains("RC_MAP_MODE_SW")) {
978 979
        rcMapping[4] = value.toInt() - 1;
        ui->modeSpinBox->setValue(rcMapping[4]+1);
980 981 982
    }

    if (parameterName.contains("RC_MAP_AUX1")) {
983 984
        rcMapping[5] = value.toInt() - 1;
        ui->aux1SpinBox->setValue(rcMapping[5]+1);
985 986 987
    }

    if (parameterName.contains("RC_MAP_AUX2")) {
988
        rcMapping[6] = value.toInt() - 1;
989
        ui->aux2SpinBox->setValue(rcMapping[6]+1);
990 991 992
    }

    if (parameterName.contains("RC_MAP_AUX3")) {
993
        rcMapping[7] = value.toInt() - 1;
994
        ui->aux3SpinBox->setValue(rcMapping[7]+1);
995 996 997 998 999
    }

    // Scaling

    if (parameterName.contains("RC_SCALE_ROLL")) {
1000
        rcScaling[0] = value.toFloat();
1001 1002 1003
    }

    if (parameterName.contains("RC_SCALE_PITCH")) {
1004
        rcScaling[1] = value.toFloat();
1005 1006 1007
    }

    if (parameterName.contains("RC_SCALE_YAW")) {
1008
        rcScaling[2] = value.toFloat();
1009 1010 1011
    }

    if (parameterName.contains("RC_SCALE_THROTTLE")) {
1012
        rcScaling[3] = value.toFloat();
1013 1014 1015
    }

    if (parameterName.contains("RC_SCALE_MODE_SW")) {
1016
        rcScaling[4] = value.toFloat();
1017 1018 1019
    }

    if (parameterName.contains("RC_SCALE_AUX1")) {
1020
        rcScaling[5] = value.toFloat();
1021 1022 1023
    }

    if (parameterName.contains("RC_SCALE_AUX2")) {
1024
        rcScaling[6] = value.toFloat();
1025 1026 1027
    }

    if (parameterName.contains("RC_SCALE_AUX3")) {
1028
        rcScaling[7] = value.toFloat();
1029
    }
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 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
}

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

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)
    {
1070 1071
        if (rc_mode == RC_MODE_1)
        {
1072 1073 1074 1075
            ui->rollSlider->setValue(rcRoll * 50 + 50);
            ui->pitchSlider->setValue(rcThrottle * 100);
            ui->yawSlider->setValue(rcYaw * 50 + 50);
            ui->throttleSlider->setValue(rcPitch * 50 + 50);
1076 1077 1078
        }
        else if (rc_mode == RC_MODE_2)
        {
1079 1080 1081 1082
            ui->rollSlider->setValue(rcRoll * 50 + 50);
            ui->pitchSlider->setValue(rcPitch * 50 + 50);
            ui->yawSlider->setValue(rcYaw * 50 + 50);
            ui->throttleSlider->setValue(rcThrottle * 100);
1083 1084 1085
        }
        else if (rc_mode == RC_MODE_3)
        {
1086 1087 1088 1089
            ui->rollSlider->setValue(rcYaw * 50 + 50);
            ui->pitchSlider->setValue(rcThrottle * 100);
            ui->yawSlider->setValue(rcRoll * 50 + 50);
            ui->throttleSlider->setValue(rcPitch * 50 + 50);
1090 1091 1092
        }
        else if (rc_mode == RC_MODE_4)
        {
1093 1094 1095 1096 1097 1098
            ui->rollSlider->setValue(rcYaw * 50 + 50);
            ui->pitchSlider->setValue(rcPitch * 50 + 50);
            ui->yawSlider->setValue(rcRoll * 50 + 50);
            ui->throttleSlider->setValue(rcThrottle * 100);
        }

1099 1100 1101 1102
        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(' ')));
1103 1104

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

1107
        if (rcValue[rcMapping[5]] != UINT16_MAX) {
1108
            ui->aux1Slider->setValue(rcAux1 * 50 + 50);
1109
            ui->chanLabel_6->setText(QString("%1/%2").arg(rcValue[rcMapping[5]]).arg(rcAux1, 5, 'f', 2, QChar(' ')));
1110 1111 1112 1113
        } else {
            ui->chanLabel_6->setText(tr("---"));
        }

1114
        if (rcValue[rcMapping[6]] != UINT16_MAX) {
1115
            ui->aux2Slider->setValue(rcAux2 * 50 + 50);
1116
            ui->chanLabel_7->setText(QString("%1/%2").arg(rcValue[rcMapping[6]]).arg(rcAux2, 5, 'f', 2, QChar(' ')));
1117 1118 1119 1120
        } else {
            ui->chanLabel_7->setText(tr("---"));
        }

1121
        if (rcValue[rcMapping[7]] != UINT16_MAX) {
1122
            ui->aux3Slider->setValue(rcAux3 * 50 + 50);
1123
            ui->chanLabel_8->setText(QString("%1/%2").arg(rcValue[rcMapping[7]]).arg(rcAux3, 5, 'f', 2, QChar(' ')));
1124 1125
        } else {
            ui->chanLabel_8->setText(tr("---"));
1126 1127
        }

1128 1129 1130
        changed = false;
    }
}