ParameterLoader.cc 25 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/*=====================================================================
 
 QGroundControl Open Source Ground Control Station
 
 (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 
 This file is part of the QGROUNDCONTROL project
 
 QGROUNDCONTROL is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 QGROUNDCONTROL is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
 
 ======================================================================*/

/// @file
///     @author Don Gagne <don@thegagnes.com>

#include "ParameterLoader.h"
#include "QGCApplication.h"
#include "QGCLoggingCategory.h"
30
#include "QGCApplication.h"
31
#include "QGCMessageBox.h"
32 33 34 35 36 37

#include <QFile>
#include <QDebug>

QGC_LOGGING_CATEGORY(ParameterLoaderLog, "ParameterLoaderLog")

38
ParameterLoader::ParameterLoader(AutoPilotPlugin* autopilot, UASInterface* uas, QObject* parent) :
39
    QObject(parent),
40 41 42
    _autopilot(autopilot),
    _uas(uas),
    _mavlink(MAVLinkProtocol::instance()),
43
    _parametersReady(false),
44 45 46
    _defaultComponentId(FactSystem::defaultComponentId),
    _totalParamCount(0),
    _fullRefresh(false)
47
{
48 49 50
    Q_ASSERT(_autopilot);
    Q_ASSERT(_uas);
    Q_ASSERT(_mavlink);
51
    
52 53
    // We signal this to ouselves in order to start timer on our thread
    connect(this, &ParameterLoader::restartWaitingParamTimer, this, &ParameterLoader::_restartWaitingParamTimer);
54
    
55 56 57
    _waitingParamTimeoutTimer.setSingleShot(true);
    _waitingParamTimeoutTimer.setInterval(100);
    connect(&_waitingParamTimeoutTimer, &QTimer::timeout, this, &ParameterLoader::_waitingParamTimeout);
58
    
59 60
    // FIXME: Why not direct connect?
    connect(_uas, SIGNAL(parameterUpdate(int, int, QString, int, int, int, QVariant)), this, SLOT(_parameterUpdate(int, int, QString, int, int, int, QVariant)));
61
    
62 63
    // Request full param list
    refreshAllParameters();
64 65 66 67 68 69 70 71
}

ParameterLoader::~ParameterLoader()
{

}

/// Called whenever a parameter is updated or first seen.
72
void ParameterLoader::_parameterUpdate(int uasId, int componentId, QString parameterName, int parameterCount, int parameterId, int mavType, QVariant value)
73 74 75 76
{
    bool setMetaData = false;
    
    // Is this for our uas?
77
    if (uasId != _uas->getUASID()) {
78 79 80
        return;
    }
    
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    qCDebug(ParameterLoaderLog) << "_parameterUpdate (usaId:" << uasId <<
                                    "componentId:" << componentId <<
                                    "name:" << parameterName <<
                                    "count:" << parameterCount <<
                                    "index:" << parameterId <<
                                    "mavType:" << mavType <<
                                    "value:" << value <<
                                    ")";
    
    _dataMutex.lock();
    
    // Restart our waiting for param timer
    _waitingParamTimeoutTimer.start();
    
    // Update our total parameter counts
    if (!_paramCountMap.contains(componentId)) {
        _paramCountMap[componentId] = parameterCount;
        _totalParamCount += parameterCount;
    }
    
    // If we've never seen this component id before, setup the wait lists.
    if (!_waitingReadParamIndexMap.contains(componentId)) {
        QStringList paramNameList;
        QList<int>  paramIndexList;
        
        // Parameter index is 0-based
        for (int i=0; i<parameterCount; i++) {
            paramIndexList << i;
        }
        
        _waitingReadParamIndexMap[componentId] = paramIndexList;
        _waitingReadParamNameMap[componentId] = paramNameList;
        _waitingWriteParamNameMap[componentId] = paramNameList;
        
        qCDebug(ParameterLoaderLog) << "Seeing component for first time, id:" << componentId << "parameter count:" << parameterCount;
    }
    
    // Remove this parameter from the waiting lists
    _waitingReadParamIndexMap[componentId].removeOne(parameterId);
    _waitingReadParamNameMap[componentId].removeOne(parameterName);
    _waitingWriteParamNameMap[componentId].removeOne(parameterName);
    qCDebug(ParameterLoaderLog) << "_waitingReadParamIndexMap:" << _waitingReadParamIndexMap[componentId];
    qCDebug(ParameterLoaderLog) << "_waitingReadParamNameMap" << _waitingReadParamNameMap[componentId];
    qCDebug(ParameterLoaderLog) << "_waitingWriteParamNameMap" << _waitingWriteParamNameMap[componentId];

    // Track how many parameters we are still waiting for
    
    int waitingReadParamIndexCount = 0;
    int waitingReadParamNameCount = 0;
    int waitingWriteParamNameCount = 0;
	
    foreach(int waitingComponentId, _waitingReadParamIndexMap.keys()) {
        waitingReadParamIndexCount += _waitingReadParamIndexMap[waitingComponentId].count();
    }
    if (waitingReadParamIndexCount) {
        qCDebug(ParameterLoaderLog) << "waitingReadParamIndexCount:" << waitingReadParamIndexCount;
    }

	
    foreach(int waitingComponentId, _waitingReadParamNameMap.keys()) {
        waitingReadParamNameCount += _waitingReadParamNameMap[waitingComponentId].count();
    }
    if (waitingReadParamNameCount) {
        qCDebug(ParameterLoaderLog) << "waitingReadParamNameCount:" << waitingReadParamNameCount;
    }
    
    foreach(int waitingComponentId, _waitingWriteParamNameMap.keys()) {
        waitingWriteParamNameCount += _waitingWriteParamNameMap[waitingComponentId].count();
    }
    if (waitingWriteParamNameCount) {
        qCDebug(ParameterLoaderLog) << "waitingWriteParamNameCount:" << waitingWriteParamNameCount;
    }
    
    int waitingParamCount = waitingReadParamIndexCount + waitingReadParamNameCount + waitingWriteParamNameCount;
    if (waitingParamCount) {
        qCDebug(ParameterLoaderLog) << "waitingParamCount:" << waitingParamCount;
    } else {
        // No more parameters to wait for, stop the timeout
        _waitingParamTimeoutTimer.stop();
    }

    // Update progress bar
    if (waitingParamCount == 0) {
        emit parameterListProgress(0);
    } else {
        emit parameterListProgress((float)(_totalParamCount - waitingParamCount) / (float)_totalParamCount);
    }
    
169 170 171 172 173 174 175 176 177
    // Attempt to determine default component id
    if (_defaultComponentId == FactSystem::defaultComponentId && _defaultComponentIdParam.isEmpty()) {
        _defaultComponentIdParam = getDefaultComponentIdParam();
    }
    if (!_defaultComponentIdParam.isEmpty() && _defaultComponentIdParam == parameterName) {
        _defaultComponentId = componentId;
    }
    
    if (!_mapParameterName2Variant.contains(componentId) || !_mapParameterName2Variant[componentId].contains(parameterName)) {
178
        qCDebug(ParameterLoaderLog) << "Adding new fact";
179 180 181 182 183 184 185
        
        FactMetaData::ValueType_t factType;
        switch (mavType) {
            case MAV_PARAM_TYPE_UINT8:
                factType = FactMetaData::valueTypeUint8;
                break;
            case MAV_PARAM_TYPE_INT8:
186
                factType = FactMetaData::valueTypeInt8;
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
                break;
            case MAV_PARAM_TYPE_UINT16:
                factType = FactMetaData::valueTypeUint16;
                break;
            case MAV_PARAM_TYPE_INT16:
                factType = FactMetaData::valueTypeInt16;
                break;
            case MAV_PARAM_TYPE_UINT32:
                factType = FactMetaData::valueTypeUint32;
                break;
            case MAV_PARAM_TYPE_INT32:
                factType = FactMetaData::valueTypeInt32;
                break;
            case MAV_PARAM_TYPE_REAL32:
                factType = FactMetaData::valueTypeFloat;
                break;
            case MAV_PARAM_TYPE_REAL64:
                factType = FactMetaData::valueTypeDouble;
                break;
            default:
                factType = FactMetaData::valueTypeInt32;
                qCritical() << "Unsupported fact type" << mavType;
                break;
        }
        
        Fact* fact = new Fact(componentId, parameterName, factType, this);
        setMetaData = true;
        
        _mapParameterName2Variant[componentId][parameterName] = QVariant::fromValue(fact);
        
        // We need to know when the fact changes from QML so that we can send the new value to the parameter manager
        connect(fact, &Fact::_containerValueChanged, this, &ParameterLoader::_valueUpdated);
    }
    
    Q_ASSERT(_mapParameterName2Variant[componentId].contains(parameterName));
    
    Fact* fact = _mapParameterName2Variant[componentId][parameterName].value<Fact*>();
    Q_ASSERT(fact);
    fact->_containerSetValue(value);
    
    if (setMetaData) {
        _addMetaDataToFact(fact);
    }
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    
    _dataMutex.unlock();
    
    if (waitingParamCount == 0) {
        // Now that we know vehicle is up to date persist
        _saveToEEPROM();
    }
    
    // Check to see if we have the full param list for the first time
    
    if (_fullRefresh) {
        if (waitingParamCount == 0) {
            if (!_parametersReady) {
                _parametersReady = true;
                _determineDefaultComponentId();
                _setupGroupMap();
                emit parametersReady();
            }
        }
    }
250 251 252 253
}

/// Connected to Fact::valueUpdated
///
254
/// Writes the parameter to mavlink, sets up for write wait
255 256 257 258 259 260
void ParameterLoader::_valueUpdated(const QVariant& value)
{
    Fact* fact = qobject_cast<Fact*>(sender());
    Q_ASSERT(fact);
    
    int componentId = fact->componentId();
261
    QString name = fact->name();
262
    
263
    _dataMutex.lock();
264
    
265 266 267 268
    Q_ASSERT(_waitingWriteParamNameMap.contains(componentId));
    _waitingWriteParamNameMap[componentId].removeOne(name);
    _waitingWriteParamNameMap[componentId] << name;
    _waitingParamTimeoutTimer.start();
269
    
270 271 272 273
    _dataMutex.unlock();
    
    _writeParameterRaw(componentId, fact->name(), value);
    qCDebug(ParameterLoaderLog) << "Set parameter (componentId:" << componentId << "name:" << name << value << ")";
274 275 276 277
}

void ParameterLoader::_addMetaDataToFact(Fact* fact)
{
278 279
    FactMetaData* metaData = new FactMetaData(fact->type(), this);
    fact->setMetaData(metaData);
280 281 282 283
}

void ParameterLoader::refreshAllParameters(void)
{
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    _dataMutex.lock();
    
    _fullRefresh = true;
    
    // Reset index wait lists
    foreach (int componentId, _paramCountMap.keys()) {
        QList<int>  paramIndexList;
        
        // Parameter index is 0-based
        for (int i=0; i<_paramCountMap[componentId]; i++) {
            paramIndexList << i;
        }
        
        _waitingReadParamIndexMap[componentId] = paramIndexList;
    }
    
    _dataMutex.unlock();
    
    MAVLinkProtocol* mavlink = MAVLinkProtocol::instance();
    Q_ASSERT(mavlink);
    
    mavlink_message_t msg;
    mavlink_msg_param_request_list_pack(mavlink->getSystemId(), mavlink->getComponentId(), &msg, _uas->getUASID(), MAV_COMP_ID_ALL);
    _uas->sendMessage(msg);
    
    qCDebug(ParameterLoaderLog) << "Request to refresh all parameters";
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
}

void ParameterLoader::_determineDefaultComponentId(void)
{
    if (_defaultComponentId == FactSystem::defaultComponentId) {
        // We don't have a default component id yet. That means the plugin can't provide
        // the param to trigger off of. Instead we use the most prominent component id in
        // the set of parameters. Better than nothing!
        
        _defaultComponentId = -1;
        foreach(int componentId, _mapParameterName2Variant.keys()) {
            if (_mapParameterName2Variant[componentId].count() > _defaultComponentId) {
                _defaultComponentId = componentId;
            }
        }
        Q_ASSERT(_defaultComponentId != -1);
    }
}

/// Translates FactSystem::defaultComponentId to real component id if needed
int ParameterLoader::_actualComponentId(int componentId)
{
    if (componentId == FactSystem::defaultComponentId) {
        componentId = _defaultComponentId;
        Q_ASSERT(componentId != FactSystem::defaultComponentId);
    }
    
    return componentId;
}

void ParameterLoader::refreshParameter(int componentId, const QString& name)
{
342 343 344 345 346 347 348 349 350 351 352 353
    componentId = _actualComponentId(componentId);
    qCDebug(ParameterLoaderLog) << "refreshParameter (component id:" << componentId << "name:" << name << ")";
    
    _dataMutex.lock();

    Q_ASSERT(_waitingReadParamNameMap.contains(componentId));
    
    if (_waitingReadParamNameMap.contains(componentId)) {
        _waitingReadParamNameMap[componentId].removeOne(name);
        _waitingReadParamNameMap[componentId] << name;
        emit restartWaitingParamTimer();
    }
354
    
355 356 357
    _dataMutex.unlock();

    _readParameterRaw(componentId, name, -1);
358 359 360 361 362
}

void ParameterLoader::refreshParametersPrefix(int componentId, const QString& namePrefix)
{
    componentId = _actualComponentId(componentId);
363 364
    qCDebug(ParameterLoaderLog) << "refreshParametersPrefix (component id:" << componentId << "name:" << namePrefix << ")";

365 366 367 368 369 370 371
    foreach(QString name, _mapParameterName2Variant[componentId].keys()) {
        if (name.startsWith(namePrefix)) {
            refreshParameter(componentId, name);
        }
    }
}

372
bool ParameterLoader::parameterExists(int componentId, const QString&  name)
373
{
374 375
    bool ret = false;
    
376 377
    componentId = _actualComponentId(componentId);
    if (_mapParameterName2Variant.contains(componentId)) {
378
        ret = _mapParameterName2Variant[componentId].contains(name);
379
    }
380 381

    return ret;
382 383 384 385 386
}

Fact* ParameterLoader::getFact(int componentId, const QString& name)
{
    componentId = _actualComponentId(componentId);
387 388
    
    if (!_mapParameterName2Variant.contains(componentId) || !_mapParameterName2Variant[componentId].contains(name)) {
389
        return NULL;
390 391
    }
    
392 393
    Fact* fact = _mapParameterName2Variant[componentId][name].value<Fact*>();
    Q_ASSERT(fact);
394
    
395 396
    return fact;
}
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

QStringList ParameterLoader::parameterNames(void)
{
	QStringList names;
	
	foreach(QString paramName, _mapParameterName2Variant[_defaultComponentId].keys()) {
		names << paramName;
	}
	
	return names;
}

void ParameterLoader::_setupGroupMap(void)
{
    foreach (int componentId, _mapParameterName2Variant.keys()) {
        foreach (QString name, _mapParameterName2Variant[componentId].keys()) {
            Fact* fact = _mapParameterName2Variant[componentId][name].value<Fact*>();
            _mapGroup2ParameterName[componentId][fact->group()] += name;
        }
    }
}

const QMap<int, QMap<QString, QStringList> >& ParameterLoader::getGroupMap(void)
{
    return _mapGroup2ParameterName;
}
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 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 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705

void ParameterLoader::_waitingParamTimeout(void)
{
    bool paramsRequested = false;
    const int maxBatchSize = 10;
    int batchCount = 0;
    
    // We timed out waiting for some parameters from the initial set. Re-request those.
    
    batchCount = 0;
    foreach(int componentId, _waitingReadParamIndexMap.keys()) {
        foreach(int paramIndex, _waitingReadParamIndexMap[componentId]) {
            paramsRequested = true;
            _readParameterRaw(componentId, "", paramIndex);
            qCDebug(ParameterLoaderLog) << "Read re-request for (componentId:" << componentId << "paramIndex:" << paramIndex << ")";
            
            if (++batchCount > maxBatchSize) {
                goto Out;
            }
        }
    }
    
    if (!paramsRequested) {
        foreach(int componentId, _waitingWriteParamNameMap.keys()) {
            foreach(QString paramName, _waitingWriteParamNameMap[componentId]) {
                paramsRequested = true;
                _writeParameterRaw(componentId, paramName, _autopilot->getFact(FactSystem::ParameterProvider, componentId, paramName)->value());
                qCDebug(ParameterLoaderLog) << "Write resend for (componentId:" << componentId << "paramName:" << paramName << ")";
                
                if (++batchCount > maxBatchSize) {
                    goto Out;
                }
            }
        }
    }
    
    if (!paramsRequested) {
        foreach(int componentId, _waitingReadParamNameMap.keys()) {
            foreach(QString paramName, _waitingReadParamNameMap[componentId]) {
                paramsRequested = true;
                _readParameterRaw(componentId, paramName, -1);
                qCDebug(ParameterLoaderLog) << "Read re-request for (componentId:" << componentId << "paramName:" << paramName << ")";
                
                if (++batchCount > maxBatchSize) {
                    goto Out;
                }
            }
        }
    }
	
Out:
    if (paramsRequested) {
        _waitingParamTimeoutTimer.start();
    }
}

void ParameterLoader::_readParameterRaw(int componentId, const QString& paramName, int paramIndex)
{
    mavlink_message_t msg;
    char fixedParamName[MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN];

    strncpy(fixedParamName, paramName.toStdString().c_str(), sizeof(fixedParamName));
    mavlink_msg_param_request_read_pack(_mavlink->getSystemId(),    // Our system id
                                        _mavlink->getComponentId(), // Our component id
                                        &msg,                       // Pack into this mavlink_message_t
                                        _uas->getUASID(),           // Target system id
                                        componentId,                // Target component id
                                        fixedParamName,             // Named parameter being requested
                                        paramIndex);                // Parameter index being requested, -1 for named
    _uas->sendMessage(msg);
}

void ParameterLoader::_writeParameterRaw(int componentId, const QString& paramName, const QVariant& value)
{
    bool floatHack = _uas->getAutopilotType() == MAV_AUTOPILOT_ARDUPILOTMEGA;

    mavlink_param_set_t     p;
    mavlink_param_union_t   union_value;
    
    FactMetaData::ValueType_t factType = _autopilot->getFact(FactSystem::ParameterProvider, componentId, paramName)->type();
    p.param_type = _factTypeToMavType(factType);
    
    switch (factType) {
        case FactMetaData::valueTypeUint8:
            if (floatHack) {
                union_value.param_float = (uint8_t)value.toUInt();
            } else {                
                union_value.param_uint8 = (uint8_t)value.toUInt();
            }
            break;
            
        case FactMetaData::valueTypeInt8:
            if (floatHack) {
                union_value.param_float = (int8_t)value.toInt();
            } else {
                union_value.param_int8 = (int8_t)value.toInt();
            }
            break;
            
        case FactMetaData::valueTypeUint16:
            if (floatHack) {
                union_value.param_float = (uint16_t)value.toUInt();
            } else {
                union_value.param_uint16 = (uint16_t)value.toUInt();
            }
            break;
            
        case FactMetaData::valueTypeInt16:
            if (floatHack) {
                union_value.param_float = (int16_t)value.toInt();
            } else {
                union_value.param_int16 = (int16_t)value.toInt();
            }
            break;
            
        case FactMetaData::valueTypeUint32:
            if (floatHack) {
                union_value.param_float = (uint32_t)value.toUInt();
            } else {
                union_value.param_uint32 = (uint32_t)value.toUInt();
            }
            break;
            
        case FactMetaData::valueTypeFloat:
            union_value.param_float = value.toFloat();
            break;
            
        default:
            qCritical() << "Unsupported fact type" << factType;
            // fall through
            
        case FactMetaData::valueTypeInt32:
            if (floatHack) {
                union_value.param_float = (int32_t)value.toInt();
            } else {
                union_value.param_int32 = (int32_t)value.toInt();
            }
            break;
    }
    
    p.param_value = union_value.param_float;
    p.target_system = (uint8_t)_uas->getUASID();
    p.target_component = (uint8_t)componentId;
        
    strncpy(p.param_id, paramName.toStdString().c_str(), sizeof(p.param_id));
    
    mavlink_message_t msg;
    mavlink_msg_param_set_encode(_mavlink->getSystemId(), _mavlink->getComponentId(), &msg, &p);
    _uas->sendMessage(msg);
}

void ParameterLoader::_saveToEEPROM(void)
{
    mavlink_message_t msg;
    mavlink_msg_command_long_pack(_mavlink->getSystemId(), _mavlink->getComponentId(), &msg, _uas->getUASID(), 0, MAV_CMD_PREFLIGHT_STORAGE, 1, 1, -1, -1, -1, 0, 0, 0);
    _uas->sendMessage(msg);
    qCDebug(ParameterLoaderLog) << "_saveToEEPROM";
}

void ParameterLoader::readParametersFromStream(QTextStream& stream)
{
    bool userWarned = false;
    
    while (!stream.atEnd()) {
        QString line = stream.readLine();
        if (!line.startsWith("#")) {
            QStringList wpParams = line.split("\t");
            int lineMavId = wpParams.at(0).toInt();
            if (wpParams.size() == 5) {
                if (!userWarned && (_uas->getUASID() != lineMavId)) {
                    userWarned = true;
                    QString msg("The parameters in the stream have been saved from System Id %1, but the current vehicle has the System Id %2.");
                    QGCMessageBox::StandardButton button = QGCMessageBox::warning("Parameter Load",
                                                                                  msg.arg(lineMavId).arg(_uas->getUASID()),
                                                                                  QGCMessageBox::Ok | QGCMessageBox::Cancel,
                                                                                  QGCMessageBox::Cancel);
                    if (button == QGCMessageBox::Cancel) {
                        return;
                    }
                }   
                
                int     componentId = wpParams.at(1).toInt();
                QString paramName = wpParams.at(2);
                QString valStr = wpParams.at(3);
                uint    mavType = wpParams.at(4).toUInt();
                
                if (!_autopilot->factExists(FactSystem::ParameterProvider, componentId, paramName)) {
                    continue;
                }
                
                Fact* fact = _autopilot->getFact(FactSystem::ParameterProvider, componentId, paramName);
                if (fact->type() != _mavTypeToFactType((MAV_PARAM_TYPE)mavType)) {
                    continue;
                }
                
                fact->setValue(valStr);
            }
        }
    }
}

void ParameterLoader::writeParametersToStream(QTextStream &stream, const QString& name)
{
    stream << "# Onboard parameters for system " << name << "\n";
    stream << "#\n";
    stream << "# MAV ID  COMPONENT ID  PARAM NAME  VALUE (FLOAT)\n";

    foreach (int componentId, _mapParameterName2Variant.keys()) {
        foreach (QString paramName, _mapParameterName2Variant[componentId].keys()) {
            Fact* fact = _mapParameterName2Variant[componentId][paramName].value<Fact*>();
            Q_ASSERT(fact);
            
            stream << _uas->getUASID() << "\t" << componentId << "\t" << paramName << "\t" << fact->valueString() << "\t" << QString("%1").arg(_factTypeToMavType(fact->type())) << "\n";
        }
    }
    
    stream.flush();
}

MAV_PARAM_TYPE ParameterLoader::_factTypeToMavType(FactMetaData::ValueType_t factType)
{
    switch (factType) {
        case FactMetaData::valueTypeUint8:
            return MAV_PARAM_TYPE_UINT8;
            
        case FactMetaData::valueTypeInt8:
            return MAV_PARAM_TYPE_INT8;
            
        case FactMetaData::valueTypeUint16:
            return MAV_PARAM_TYPE_UINT16;
            
        case FactMetaData::valueTypeInt16:
            return MAV_PARAM_TYPE_INT16;
            
        case FactMetaData::valueTypeUint32:
            return MAV_PARAM_TYPE_UINT32;
            
        case FactMetaData::valueTypeFloat:
            return MAV_PARAM_TYPE_REAL32;
            
        default:
            qWarning() << "Unsupported fact type" << factType;
            // fall through
            
        case FactMetaData::valueTypeInt32:
            return MAV_PARAM_TYPE_INT32;
    }
}

FactMetaData::ValueType_t ParameterLoader::_mavTypeToFactType(MAV_PARAM_TYPE mavType)
{
    switch (mavType) {
        case MAV_PARAM_TYPE_UINT8:
            return FactMetaData::valueTypeUint8;
            
        case MAV_PARAM_TYPE_INT8:
            return FactMetaData::valueTypeInt8;
            
        case MAV_PARAM_TYPE_UINT16:
            return FactMetaData::valueTypeUint16;
            
        case MAV_PARAM_TYPE_INT16:
            return FactMetaData::valueTypeInt16;
            
        case MAV_PARAM_TYPE_UINT32:
            return FactMetaData::valueTypeUint32;
            
        case MAV_PARAM_TYPE_REAL32:
            return FactMetaData::valueTypeFloat;
            
        default:
            qWarning() << "Unsupported mav param type" << mavType;
            // fall through
            
        case MAV_PARAM_TYPE_INT32:
            return FactMetaData::valueTypeInt32;
    }
}

void ParameterLoader::_restartWaitingParamTimer(void)
{
    _waitingParamTimeoutTimer.start();
}