ParameterManager.cc 61.2 KB
Newer Older
1 2 3 4 5 6 7 8
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/
dogmaphobic's avatar
dogmaphobic committed
9

10 11 12 13

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

14
#include "ParameterManager.h"
15 16
#include "QGCApplication.h"
#include "QGCLoggingCategory.h"
17
#include "QGCApplication.h"
18
#include "UASMessageHandler.h"
Don Gagne's avatar
Don Gagne committed
19
#include "FirmwarePlugin.h"
20
#include "UAS.h"
21
#include "JsonHelper.h"
22

23
#include <QEasingCurve>
24 25
#include <QFile>
#include <QDebug>
26
#include <QVariantAnimation>
27
#include <QJsonArray>
28

29 30 31 32 33
/* types for local parameter cache */
typedef QPair<int, QVariant> ParamTypeVal;
typedef QPair<QString, ParamTypeVal> NamedParam;
typedef QMap<int, NamedParam> MapID2NamedParam;

34 35
QGC_LOGGING_CATEGORY(ParameterManagerVerbose1Log, "ParameterManagerVerbose1Log")
QGC_LOGGING_CATEGORY(ParameterManagerVerbose2Log, "ParameterManagerVerbose2Log")
36

37
Fact ParameterManager::_defaultFact;
Don Gagne's avatar
Don Gagne committed
38

39 40 41 42 43
const char* ParameterManager::_cachedMetaDataFilePrefix =   "ParameterFactMetaData";
const char* ParameterManager::_jsonParametersKey =          "parameters";
const char* ParameterManager::_jsonCompIdKey =              "compId";
const char* ParameterManager::_jsonParamNameKey =           "name";
const char* ParameterManager::_jsonParamValueKey =          "value";
44

45
ParameterManager::ParameterManager(Vehicle* vehicle)
46
    : QObject(vehicle)
47
    , _vehicle(vehicle)
48
    , _mavlink(NULL)
49
    , _loadProgress(0.0)
50
    , _parametersReady(false)
51
    , _missingParameters(false)
52
    , _initialLoadComplete(false)
53
    , _waitingForDefaultComponent(false)
54
    , _saveRequired(false)
55
    , _defaultComponentId(MAV_COMP_ID_ALL)
56 57
    , _parameterSetMajorVersion(-1)
    , _parameterMetaData(NULL)
Don Gagne's avatar
Don Gagne committed
58 59 60
    , _prevWaitingReadParamIndexCount(0)
    , _prevWaitingReadParamNameCount(0)
    , _prevWaitingWriteParamNameCount(0)
61
    , _initialRequestRetryCount(0)
62
    , _disableAllRetries(false)
63
    , _totalParamCount(0)
64
{
65 66
    _versionParam = vehicle->firmwarePlugin()->getVersionParam();

67 68 69 70 71 72
    if (_vehicle->isOfflineEditingVehicle()) {
        _loadOfflineEditingParams();
        return;
    }

    _mavlink = qgcApp()->toolbox()->mavlinkProtocol();
dogmaphobic's avatar
dogmaphobic committed
73

74
    _initialRequestTimeoutTimer.setSingleShot(true);
75
    _initialRequestTimeoutTimer.setInterval(20000);
76
    connect(&_initialRequestTimeoutTimer, &QTimer::timeout, this, &ParameterManager::_initialRequestTimeout);
77

78
    _waitingParamTimeoutTimer.setSingleShot(true);
79
    _waitingParamTimeoutTimer.setInterval(3000);
80
    connect(&_waitingParamTimeoutTimer, &QTimer::timeout, this, &ParameterManager::_waitingParamTimeout);
81

82
    connect(_vehicle->uas(), &UASInterface::parameterUpdate, this, &ParameterManager::_parameterUpdate);
83

84
    _defaultComponentIdParam = vehicle->firmwarePlugin()->getDefaultComponentIdParam();
85
    qCDebug(ParameterManagerLog) << _logVehiclePrefix() << "Default component param" << _defaultComponentIdParam;
86

87 88 89
    // Ensure the cache directory exists
    QFileInfo(QSettings().fileName()).dir().mkdir("ParamCache");
    refreshAllParameters();
90 91
}

92
ParameterManager::~ParameterManager()
93
{
94
    delete _parameterMetaData;
95 96 97
}

/// Called whenever a parameter is updated or first seen.
98
void ParameterManager::_parameterUpdate(int vehicleId, int componentId, QString parameterName, int parameterCount, int parameterId, int mavType, QVariant value)
99 100
{
    // Is this for our uas?
101
    if (vehicleId != _vehicle->id()) {
102 103
        return;
    }
dogmaphobic's avatar
dogmaphobic committed
104

105 106 107 108 109 110 111 112
    qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) <<
                                            "_parameterUpdate" <<
                                            "name:" << parameterName <<
                                            "count:" << parameterCount <<
                                            "index:" << parameterId <<
                                            "mavType:" << mavType <<
                                            "value:" << value <<
                                            ")";
113

114
    _initialRequestTimeoutTimer.stop();
dogmaphobic's avatar
dogmaphobic committed
115

116 117 118
#if 0
    // Handy for testing retry logic
    static int counter = 0;
119
    if (counter++ & 0x8) {
120
        qCDebug(ParameterManagerLog) << "Artificial discard" << counter;
121 122 123
        return;
    }
#endif
124

125 126 127 128 129 130 131
#if 0
    // Use this to test missing default component id
    if (componentId == 50) {
        return;
    }
#endif

Don Gagne's avatar
Don Gagne committed
132
    if (_vehicle->px4Firmware() && parameterName == "_HASH_CHECK") {
133
        /* we received a cache hash, potentially load from cache */
134
        _tryCacheHashLoad(vehicleId, componentId, value);
135 136
        return;
    }
137 138 139 140 141 142 143 144

    if (parameterId >= parameterCount) {
        qCDebug(ParameterManagerLog) << _logVehiclePrefix() << "Discarding bogus update name:id:count" << parameterName << parameterId << parameterCount;
        return;
    }

    _initialRequestTimeoutTimer.stop();

145
    _dataMutex.lock();
dogmaphobic's avatar
dogmaphobic committed
146

147 148 149 150 151
    // Update our total parameter counts
    if (!_paramCountMap.contains(componentId)) {
        _paramCountMap[componentId] = parameterCount;
        _totalParamCount += parameterCount;
    }
152 153

    _mapParameterId2Name[componentId][parameterId] = parameterName;
dogmaphobic's avatar
dogmaphobic committed
154

155 156
    // If we've never seen this component id before, setup the wait lists.
    if (!_waitingReadParamIndexMap.contains(componentId)) {
157 158 159 160
        // Add all indices to the wait list, parameter index is 0-based
        for (int waitingIndex=0; waitingIndex<parameterCount; waitingIndex++) {
            // This will add the new component id, as well as the the new waiting index and set the retry count for that index to 0
            _waitingReadParamIndexMap[componentId][waitingIndex] = 0;
161
        }
dogmaphobic's avatar
dogmaphobic committed
162

163 164 165
        // The read and write waiting lists for this component are initialized the empty
        _waitingReadParamNameMap[componentId] = QMap<QString, int>();
        _waitingWriteParamNameMap[componentId] = QMap<QString, int>();
dogmaphobic's avatar
dogmaphobic committed
166

167
        qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Seeing component for first time - paramcount:" << parameterCount;
168
    }
dogmaphobic's avatar
dogmaphobic committed
169

170 171
    // Determine default component id
    if (!_defaultComponentIdParam.isEmpty() && _defaultComponentIdParam == parameterName) {
172
        qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Default component id determined";
173 174 175 176 177 178 179 180 181
        _defaultComponentId = componentId;
    }

    bool componentParamsComplete = false;
    if (_waitingReadParamIndexMap[componentId].count() == 1) {
        // We need to know when we get the last param from a component in order to complete setup
        componentParamsComplete = true;
    }

182 183 184 185 186
    if (_waitingReadParamIndexMap[componentId].contains(parameterId) ||
        _waitingReadParamNameMap[componentId].contains(parameterName) ||
        _waitingWriteParamNameMap[componentId].contains(parameterName)) {
        // We were waiting for this parameter, restart wait timer. Otherwise it is a spurious parameter update which
        // means we should not reset the wait timer.
187
        qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix() << "Restarting _waitingParamTimeoutTimer (valid param received)";
188
        _waitingParamTimeoutTimer.start();
189 190
    } else {
        qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix() << "Unrequested param update" << parameterName;
191 192
    }

193
    // Remove this parameter from the waiting lists
194 195 196
    _waitingReadParamIndexMap[componentId].remove(parameterId);
    _waitingReadParamNameMap[componentId].remove(parameterName);
    _waitingWriteParamNameMap[componentId].remove(parameterName);
197 198 199 200 201 202 203 204 205
    if (_waitingReadParamIndexMap[componentId].count()) {
        qCDebug(ParameterManagerVerbose2Log) << _logVehiclePrefix(componentId) << "_waitingReadParamIndexMap:" << _waitingReadParamIndexMap[componentId];
    }
    if (_waitingReadParamNameMap[componentId].count()) {
        qCDebug(ParameterManagerVerbose2Log) << _logVehiclePrefix(componentId) << "_waitingReadParamNameMap" << _waitingReadParamNameMap[componentId];
    }
    if (_waitingWriteParamNameMap[componentId].count()) {
        qCDebug(ParameterManagerVerbose2Log) << _logVehiclePrefix(componentId) << "_waitingWriteParamNameMap" << _waitingWriteParamNameMap[componentId];
    }
206 207

    // Track how many parameters we are still waiting for
dogmaphobic's avatar
dogmaphobic committed
208

209 210 211
    int waitingReadParamIndexCount = 0;
    int waitingReadParamNameCount = 0;
    int waitingWriteParamNameCount = 0;
dogmaphobic's avatar
dogmaphobic committed
212

213 214 215 216
    foreach(int waitingComponentId, _waitingReadParamIndexMap.keys()) {
        waitingReadParamIndexCount += _waitingReadParamIndexMap[waitingComponentId].count();
    }
    if (waitingReadParamIndexCount) {
217
        qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "waitingReadParamIndexCount:" << waitingReadParamIndexCount;
218 219 220 221 222 223
    }

    foreach(int waitingComponentId, _waitingReadParamNameMap.keys()) {
        waitingReadParamNameCount += _waitingReadParamNameMap[waitingComponentId].count();
    }
    if (waitingReadParamNameCount) {
224
        qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "waitingReadParamNameCount:" << waitingReadParamNameCount;
225
    }
dogmaphobic's avatar
dogmaphobic committed
226

227 228 229 230
    foreach(int waitingComponentId, _waitingWriteParamNameMap.keys()) {
        waitingWriteParamNameCount += _waitingWriteParamNameMap[waitingComponentId].count();
    }
    if (waitingWriteParamNameCount) {
231
        qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "waitingWriteParamNameCount:" << waitingWriteParamNameCount;
232
    }
dogmaphobic's avatar
dogmaphobic committed
233

Don Gagne's avatar
Don Gagne committed
234 235 236
    int readWaitingParamCount = waitingReadParamIndexCount + waitingReadParamNameCount;
    int totalWaitingParamCount = readWaitingParamCount + waitingWriteParamNameCount;
    if (totalWaitingParamCount) {
237
        qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "totalWaitingParamCount:" << totalWaitingParamCount;
238
    } else if (_defaultComponentId != MAV_COMP_ID_ALL || _defaultComponentIdParam.isEmpty()) {
239 240
        // No more parameters to wait for, stop the timeout. Be careful to not stop timer if we don't have the default
        // component yet.
241
        qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix() << "Stopping _waitingParamTimeoutTimer (all requests satisfied)";
242 243 244
        _waitingParamTimeoutTimer.stop();
    }

Don Gagne's avatar
Don Gagne committed
245 246 247 248 249
    // Update progress bar for waiting reads
    if (readWaitingParamCount == 0) {
        // We are no longer waiting for any reads to complete
        if (_prevWaitingReadParamIndexCount + _prevWaitingReadParamNameCount != 0) {
            // Set progress to 0 if not already there
250
            _setLoadProgress(0.0);
Don Gagne's avatar
Don Gagne committed
251
        }
252
    } else {
253
        _setLoadProgress((double)(_totalParamCount - readWaitingParamCount) / (double)_totalParamCount);
254
    }
dogmaphobic's avatar
dogmaphobic committed
255

256 257 258 259 260
    // Get parameter set version
    if (!_versionParam.isEmpty() && _versionParam == parameterName) {
        _parameterSetMajorVersion = value.toInt();
    }

261
    if (!_mapParameterName2Variant.contains(componentId) || !_mapParameterName2Variant[componentId].contains(parameterName)) {
262
        qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "Adding new fact" << parameterName;
dogmaphobic's avatar
dogmaphobic committed
263

264 265 266 267 268 269
        FactMetaData::ValueType_t factType;
        switch (mavType) {
            case MAV_PARAM_TYPE_UINT8:
                factType = FactMetaData::valueTypeUint8;
                break;
            case MAV_PARAM_TYPE_INT8:
270
                factType = FactMetaData::valueTypeInt8;
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
                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;
        }
dogmaphobic's avatar
dogmaphobic committed
295

296
        Fact* fact = new Fact(componentId, parameterName, factType, this);
dogmaphobic's avatar
dogmaphobic committed
297

298
        _mapParameterName2Variant[componentId][parameterName] = QVariant::fromValue(fact);
dogmaphobic's avatar
dogmaphobic committed
299

300
        // We need to know when the fact changes from QML so that we can send the new value to the parameter manager
301
        connect(fact, &Fact::_containerRawValueChanged, this, &ParameterManager::_valueUpdated);
302
    }
dogmaphobic's avatar
dogmaphobic committed
303

Don Gagne's avatar
Don Gagne committed
304 305
    _dataMutex.unlock();

306
    Q_ASSERT(_mapParameterName2Variant[componentId].contains(parameterName));
dogmaphobic's avatar
dogmaphobic committed
307

308 309
    Fact* fact = _mapParameterName2Variant[componentId][parameterName].value<Fact*>();
    Q_ASSERT(fact);
Don Gagne's avatar
Don Gagne committed
310
    fact->_containerSetRawValue(value);
dogmaphobic's avatar
dogmaphobic committed
311

312 313 314 315 316 317 318 319 320 321 322 323 324
    if (componentParamsComplete) {
        if (componentId == _defaultComponentId) {
            // Add meta data to default component. We need to do this before we setup the group map since group
            // map requires meta data.
            _addMetaDataToDefaultComponent();
        }

        // When we are getting the very last component param index, reset the group maps to update for the
        // new params. By handling this here, we can pick up components which finish up later than the default
        // component param set.
        _setupGroupMap();
    }

Don Gagne's avatar
Don Gagne committed
325 326
    if (_prevWaitingWriteParamNameCount != 0 &&  waitingWriteParamNameCount == 0) {
        // If all the writes just finished the vehicle is up to date, so persist.
327 328
        _saveToEEPROM();
    }
dogmaphobic's avatar
dogmaphobic committed
329

Don Gagne's avatar
Don Gagne committed
330 331 332 333 334 335
    // Update param cache. The param cache is only used on PX4 Firmware since ArduPilot and Solo have volatile params
    // which invalidate the cache. The Solo also streams param updates in flight for things like gimbal values
    // which in turn causes a perf problem with all the param cache updates.
    if (_vehicle->px4Firmware()) {
        if (_prevWaitingReadParamIndexCount + _prevWaitingReadParamNameCount != 0 && readWaitingParamCount == 0) {
            // All reads just finished, update the cache
336
            _writeLocalParamCache(vehicleId, componentId);
Don Gagne's avatar
Don Gagne committed
337 338 339 340 341 342 343
        }
    }

    _prevWaitingReadParamIndexCount = waitingReadParamIndexCount;
    _prevWaitingReadParamNameCount = waitingReadParamNameCount;
    _prevWaitingWriteParamNameCount = waitingWriteParamNameCount;

344 345
    // Don't fail initial load complete if default component isn't found yet. That will be handled in wait timeout check.
    _checkInitialLoadComplete(false /* failIfNoDefaultComponent */);
346 347

    qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "_parameterUpdate complete";
348 349 350 351
}

/// Connected to Fact::valueUpdated
///
352
/// Writes the parameter to mavlink, sets up for write wait
353
void ParameterManager::_valueUpdated(const QVariant& value)
354 355 356
{
    Fact* fact = qobject_cast<Fact*>(sender());
    Q_ASSERT(fact);
dogmaphobic's avatar
dogmaphobic committed
357

358
    int componentId = fact->componentId();
359
    QString name = fact->name();
dogmaphobic's avatar
dogmaphobic committed
360

361
    _dataMutex.lock();
dogmaphobic's avatar
dogmaphobic committed
362

363
    Q_ASSERT(_waitingWriteParamNameMap.contains(componentId));
364 365
    _waitingWriteParamNameMap[componentId].remove(name);    // Remove any old entry
    _waitingWriteParamNameMap[componentId][name] = 0;       // Add new entry and set retry count
366
    _waitingParamTimeoutTimer.start();
367
    _saveRequired = true;
dogmaphobic's avatar
dogmaphobic committed
368

369
    _dataMutex.unlock();
dogmaphobic's avatar
dogmaphobic committed
370

371
    _writeParameterRaw(componentId, fact->name(), value);
372
    qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Set parameter - name:" << name << value << "(_waitingParamTimeoutTimer started)";
373

374 375
    if (fact->rebootRequired() && !qgcApp()->runningUnitTests()) {
        qgcApp()->showMessage(QStringLiteral("Change of parameter %1 requires a Vehicle reboot to take effect").arg(name));
376
    }
377 378
}

379
void ParameterManager::refreshAllParameters(uint8_t componentId)
380
{
381
    _dataMutex.lock();
dogmaphobic's avatar
dogmaphobic committed
382

383 384 385 386
    if (!_initialLoadComplete) {
        _initialRequestTimeoutTimer.start();
    }

387
    // Reset index wait lists
dogmaphobic's avatar
dogmaphobic committed
388
    foreach (int cid, _paramCountMap.keys()) {
389
        // Add/Update all indices to the wait list, parameter index is 0-based
390
        if(componentId != MAV_COMP_ID_ALL && componentId != cid)
dogmaphobic's avatar
dogmaphobic committed
391 392
            continue;
        for (int waitingIndex = 0; waitingIndex < _paramCountMap[cid]; waitingIndex++) {
393
            // This will add a new waiting index if needed and set the retry count for that index to 0
dogmaphobic's avatar
dogmaphobic committed
394
            _waitingReadParamIndexMap[cid][waitingIndex] = 0;
395 396
        }
    }
dogmaphobic's avatar
dogmaphobic committed
397

398
    _dataMutex.unlock();
dogmaphobic's avatar
dogmaphobic committed
399

400
    MAVLinkProtocol* mavlink = qgcApp()->toolbox()->mavlinkProtocol();
401
    Q_ASSERT(mavlink);
dogmaphobic's avatar
dogmaphobic committed
402

403
    mavlink_message_t msg;
404 405 406 407 408
    mavlink_msg_param_request_list_pack_chan(mavlink->getSystemId(),
                                             mavlink->getComponentId(),
                                             _vehicle->priorityLink()->mavlinkChannel(),
                                             &msg,
                                             _vehicle->id(),
409
                                             componentId);
410
    _vehicle->sendMessageOnLink(_vehicle->priorityLink(), msg);
dogmaphobic's avatar
dogmaphobic committed
411

412 413
    QString what = (componentId == MAV_COMP_ID_ALL) ? "MAV_COMP_ID_ALL" : QString::number(componentId);
    qCDebug(ParameterManagerLog) << _logVehiclePrefix() << "Request to refresh all parameters for component ID:" << what;
414 415
}

416
void ParameterManager::_determineDefaultComponentId(void)
417
{
418
    if (_defaultComponentId == MAV_COMP_ID_ALL) {
419 420 421
        // 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!
dogmaphobic's avatar
dogmaphobic committed
422

423
        int largestCompParamCount = 0;
424
        foreach(int componentId, _mapParameterName2Variant.keys()) {
425 426 427
            int compParamCount = _mapParameterName2Variant[componentId].count();
            if (compParamCount > largestCompParamCount) {
                largestCompParamCount = compParamCount;
428 429 430
                _defaultComponentId = componentId;
            }
        }
431

432
        if (_defaultComponentId == MAV_COMP_ID_ALL) {
433
            qWarning() << _logVehiclePrefix() << "All parameters missing, unable to determine default component id";
434
        }
435 436 437 438
    }
}

/// Translates FactSystem::defaultComponentId to real component id if needed
439
int ParameterManager::_actualComponentId(int componentId)
440 441 442
{
    if (componentId == FactSystem::defaultComponentId) {
        componentId = _defaultComponentId;
Don Gagne's avatar
Don Gagne committed
443
        if (componentId == FactSystem::defaultComponentId) {
444
            qWarning() << _logVehiclePrefix() << "Default component id not set";
Don Gagne's avatar
Don Gagne committed
445
        }
446
    }
dogmaphobic's avatar
dogmaphobic committed
447

448 449 450
    return componentId;
}

451
void ParameterManager::refreshParameter(int componentId, const QString& name)
452
{
453
    componentId = _actualComponentId(componentId);
454
    qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "refreshParameter - name:" << name << ")";
dogmaphobic's avatar
dogmaphobic committed
455

456 457 458
    _dataMutex.lock();

    Q_ASSERT(_waitingReadParamNameMap.contains(componentId));
dogmaphobic's avatar
dogmaphobic committed
459

460
    if (_waitingReadParamNameMap.contains(componentId)) {
461 462 463 464
        QString mappedParamName = _remapParamNameToVersion(name);

        _waitingReadParamNameMap[componentId].remove(mappedParamName);  // Remove old wait entry if there
        _waitingReadParamNameMap[componentId][mappedParamName] = 0;     // Add new wait entry and update retry count
465 466
        qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "restarting _waitingParamTimeout";
        _waitingParamTimeoutTimer.start();
467
    }
dogmaphobic's avatar
dogmaphobic committed
468

469 470 471
    _dataMutex.unlock();

    _readParameterRaw(componentId, name, -1);
472 473
}

474
void ParameterManager::refreshParametersPrefix(int componentId, const QString& namePrefix)
475 476
{
    componentId = _actualComponentId(componentId);
477
    qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "refreshParametersPrefix - name:" << namePrefix << ")";
478

479
    foreach(const QString &name, _mapParameterName2Variant[componentId].keys()) {
480 481 482 483 484 485
        if (name.startsWith(namePrefix)) {
            refreshParameter(componentId, name);
        }
    }
}

486
bool ParameterManager::parameterExists(int componentId, const QString&  name)
487
{
488
    bool ret = false;
dogmaphobic's avatar
dogmaphobic committed
489

490 491
    componentId = _actualComponentId(componentId);
    if (_mapParameterName2Variant.contains(componentId)) {
492
        ret = _mapParameterName2Variant[componentId].contains(_remapParamNameToVersion(name));
493
    }
494 495

    return ret;
496 497
}

498
Fact* ParameterManager::getParameter(int componentId, const QString& name)
499 500
{
    componentId = _actualComponentId(componentId);
dogmaphobic's avatar
dogmaphobic committed
501

502 503 504
    QString mappedParamName = _remapParamNameToVersion(name);
    if (!_mapParameterName2Variant.contains(componentId) || !_mapParameterName2Variant[componentId].contains(mappedParamName)) {
        qgcApp()->reportMissingParameter(componentId, mappedParamName);
Don Gagne's avatar
Don Gagne committed
505
        return &_defaultFact;
506
    }
dogmaphobic's avatar
dogmaphobic committed
507

508
    return _mapParameterName2Variant[componentId][mappedParamName].value<Fact*>();
509
}
510

511
QStringList ParameterManager::parameterNames(int componentId)
512
{
dogmaphobic's avatar
dogmaphobic committed
513 514
    QStringList names;

515
    foreach(const QString &paramName, _mapParameterName2Variant[_actualComponentId(componentId)].keys()) {
dogmaphobic's avatar
dogmaphobic committed
516 517 518 519
        names << paramName;
    }

    return names;
520 521
}

522
void ParameterManager::_setupGroupMap(void)
523
{
524 525 526
    // Must be able to handle being called multiple times
    _mapGroup2ParameterName.clear();

527
    foreach (int componentId, _mapParameterName2Variant.keys()) {
528
        foreach (const QString &name, _mapParameterName2Variant[componentId].keys()) {
529 530 531 532 533 534
            Fact* fact = _mapParameterName2Variant[componentId][name].value<Fact*>();
            _mapGroup2ParameterName[componentId][fact->group()] += name;
        }
    }
}

535
const QMap<int, QMap<QString, QStringList> >& ParameterManager::getGroupMap(void)
536 537 538
{
    return _mapGroup2ParameterName;
}
539

540
void ParameterManager::_waitingParamTimeout(void)
541 542 543 544
{
    bool paramsRequested = false;
    const int maxBatchSize = 10;
    int batchCount = 0;
dogmaphobic's avatar
dogmaphobic committed
545

546 547
    qCDebug(ParameterManagerLog) << _logVehiclePrefix() << "_waitingParamTimeout";

548
    // First check for any missing parameters from the initial index based load
549

550 551
    batchCount = 0;
    foreach(int componentId, _waitingReadParamIndexMap.keys()) {
552 553 554 555 556 557 558 559 560
        if (_waitingReadParamIndexMap[componentId].count()) {
            qCDebug(ParameterManagerLog) << _logVehiclePrefix() << "_waitingReadParamIndexMap" << _waitingReadParamIndexMap[componentId];
        }

        foreach(int paramIndex, _waitingReadParamIndexMap[componentId].keys()) {            
            if (++batchCount > maxBatchSize) {
                goto Out;
            }

561
            _waitingReadParamIndexMap[componentId][paramIndex]++;   // Bump retry count
562
            if (_disableAllRetries || _waitingReadParamIndexMap[componentId][paramIndex] > _maxInitialLoadRetrySingleParam) {
563 564
                // Give up on this index
                _failedReadParamIndexMap[componentId] << paramIndex;
565
                qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Giving up on (paramIndex:" << paramIndex << "retryCount:" << _waitingReadParamIndexMap[componentId][paramIndex] << ")";
566 567 568 569 570
                _waitingReadParamIndexMap[componentId].remove(paramIndex);
            } else {
                // Retry again
                paramsRequested = true;
                _readParameterRaw(componentId, "", paramIndex);
571
                qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Read re-request for (paramIndex:" << paramIndex << "retryCount:" << _waitingReadParamIndexMap[componentId][paramIndex] << ")";
572 573 574
            }
        }
    }
575

576
    if (!paramsRequested && _defaultComponentId == MAV_COMP_ID_ALL && !_defaultComponentIdParam.isEmpty() && !_waitingForDefaultComponent) {
577 578
        // Initial load is complete but we still don't have default component params. Wait one more cycle to see if the
        // default component finally shows up.
579
        qCDebug(ParameterManagerLog) << _logVehiclePrefix() << "Restarting _waitingParamTimeoutTimer - still don't have default component id";
580 581 582 583 584 585 586 587
        _waitingParamTimeoutTimer.start();
        _waitingForDefaultComponent = true;
        return;
    }
    _waitingForDefaultComponent = false;

    // Check for initial load complete success/failure. Fail load if we don't have a default component at this point.
    _checkInitialLoadComplete(true /* failIfNoDefaultComponent */);
dogmaphobic's avatar
dogmaphobic committed
588

589 590
    if (!paramsRequested) {
        foreach(int componentId, _waitingWriteParamNameMap.keys()) {
591
            foreach(const QString &paramName, _waitingWriteParamNameMap[componentId].keys()) {
592
                paramsRequested = true;
593
                _waitingWriteParamNameMap[componentId][paramName]++;   // Bump retry count
594
                if (_waitingWriteParamNameMap[componentId][paramName] <= _maxReadWriteRetry) {
595
                    _writeParameterRaw(componentId, paramName, getParameter(componentId, paramName)->rawValue());
596
                    qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Write resend for (paramName:" << paramName << "retryCount:" << _waitingWriteParamNameMap[componentId][paramName] << ")";
597 598 599 600 601 602
                    if (++batchCount > maxBatchSize) {
                        goto Out;
                    }
                } else {
                    // Exceeded max retry count, notify user
                    _waitingWriteParamNameMap[componentId].remove(paramName);
603 604 605
                    QString errorMsg = tr("Parameter write failed: veh:%1 comp:%2 param:%3").arg(_vehicle->id()).arg(componentId).arg(paramName);
                    qCDebug(ParameterManagerLog) << errorMsg;
                    qgcApp()->showMessage(errorMsg);
606 607 608 609
                }
            }
        }
    }
dogmaphobic's avatar
dogmaphobic committed
610

611 612
    if (!paramsRequested) {
        foreach(int componentId, _waitingReadParamNameMap.keys()) {
613
            foreach(const QString &paramName, _waitingReadParamNameMap[componentId].keys()) {
614
                paramsRequested = true;
615
                _waitingReadParamNameMap[componentId][paramName]++;   // Bump retry count
616 617
                if (_waitingReadParamNameMap[componentId][paramName] <= _maxReadWriteRetry) {
                    _readParameterRaw(componentId, paramName, -1);
618
                    qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Read re-request for (paramName:" << paramName << "retryCount:" << _waitingReadParamNameMap[componentId][paramName] << ")";
619 620 621 622 623 624
                    if (++batchCount > maxBatchSize) {
                        goto Out;
                    }
                } else {
                    // Exceeded max retry count, notify user
                    _waitingReadParamNameMap[componentId].remove(paramName);
625 626 627
                    QString errorMsg = tr("Parameter read failed: veh:%1 comp:%2 param:%3").arg(_vehicle->id()).arg(componentId).arg(paramName);
                    qCDebug(ParameterManagerLog) << errorMsg;
                    qgcApp()->showMessage(errorMsg);
628 629 630 631
                }
            }
        }
    }
dogmaphobic's avatar
dogmaphobic committed
632

633 634
Out:
    if (paramsRequested) {
635
        qCDebug(ParameterManagerLog) << _logVehiclePrefix() << "Restarting _waitingParamTimeoutTimer - re-request";
636 637 638 639
        _waitingParamTimeoutTimer.start();
    }
}

640
void ParameterManager::_readParameterRaw(int componentId, const QString& paramName, int paramIndex)
641 642 643 644 645
{
    mavlink_message_t msg;
    char fixedParamName[MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN];

    strncpy(fixedParamName, paramName.toStdString().c_str(), sizeof(fixedParamName));
646 647 648 649 650 651 652 653
    mavlink_msg_param_request_read_pack_chan(_mavlink->getSystemId(),   // QGC system id
                                             _mavlink->getComponentId(),     // QGC component id
                                             _vehicle->priorityLink()->mavlinkChannel(),
                                             &msg,                           // Pack into this mavlink_message_t
                                             _vehicle->id(),                 // Target system id
                                             componentId,                    // Target component id
                                             fixedParamName,                 // Named parameter being requested
                                             paramIndex);                    // Parameter index being requested, -1 for named
654
    _vehicle->sendMessageOnLink(_vehicle->priorityLink(), msg);
655 656
}

657
void ParameterManager::_writeParameterRaw(int componentId, const QString& paramName, const QVariant& value)
658 659 660
{
    mavlink_param_set_t     p;
    mavlink_param_union_t   union_value;
dogmaphobic's avatar
dogmaphobic committed
661

662
    FactMetaData::ValueType_t factType = getParameter(componentId, paramName)->type();
663
    p.param_type = _factTypeToMavType(factType);
dogmaphobic's avatar
dogmaphobic committed
664

665 666
    switch (factType) {
        case FactMetaData::valueTypeUint8:
Don Gagne's avatar
Don Gagne committed
667
            union_value.param_uint8 = (uint8_t)value.toUInt();
668
            break;
dogmaphobic's avatar
dogmaphobic committed
669

670
        case FactMetaData::valueTypeInt8:
Don Gagne's avatar
Don Gagne committed
671
            union_value.param_int8 = (int8_t)value.toInt();
672
            break;
dogmaphobic's avatar
dogmaphobic committed
673

674
        case FactMetaData::valueTypeUint16:
Don Gagne's avatar
Don Gagne committed
675
            union_value.param_uint16 = (uint16_t)value.toUInt();
676
            break;
dogmaphobic's avatar
dogmaphobic committed
677

678
        case FactMetaData::valueTypeInt16:
Don Gagne's avatar
Don Gagne committed
679
            union_value.param_int16 = (int16_t)value.toInt();
680
            break;
dogmaphobic's avatar
dogmaphobic committed
681

682
        case FactMetaData::valueTypeUint32:
Don Gagne's avatar
Don Gagne committed
683
            union_value.param_uint32 = (uint32_t)value.toUInt();
684
            break;
dogmaphobic's avatar
dogmaphobic committed
685

686 687 688
        case FactMetaData::valueTypeFloat:
            union_value.param_float = value.toFloat();
            break;
dogmaphobic's avatar
dogmaphobic committed
689

690 691 692
        default:
            qCritical() << "Unsupported fact type" << factType;
            // fall through
dogmaphobic's avatar
dogmaphobic committed
693

694
        case FactMetaData::valueTypeInt32:
Don Gagne's avatar
Don Gagne committed
695
            union_value.param_int32 = (int32_t)value.toInt();
696 697
            break;
    }
dogmaphobic's avatar
dogmaphobic committed
698

699
    p.param_value = union_value.param_float;
700
    p.target_system = (uint8_t)_vehicle->id();
701
    p.target_component = (uint8_t)componentId;
dogmaphobic's avatar
dogmaphobic committed
702

703
    strncpy(p.param_id, paramName.toStdString().c_str(), sizeof(p.param_id));
dogmaphobic's avatar
dogmaphobic committed
704

705
    mavlink_message_t msg;
706 707 708 709 710
    mavlink_msg_param_set_encode_chan(_mavlink->getSystemId(),
                                      _mavlink->getComponentId(),
                                      _vehicle->priorityLink()->mavlinkChannel(),
                                      &msg,
                                      &p);
711
    _vehicle->sendMessageOnLink(_vehicle->priorityLink(), msg);
712 713
}

714
void ParameterManager::_writeLocalParamCache(int vehicleId, int componentId)
715
{
716
    MapID2NamedParam cache_map;
717

718 719 720 721
    foreach(int id, _mapParameterId2Name[componentId].keys()) {
        const QString name(_mapParameterId2Name[componentId][id]);
        const Fact *fact = _mapParameterName2Variant[componentId][name].value<Fact*>();
        cache_map[id] = NamedParam(name, ParamTypeVal(fact->type(), fact->rawValue()));
722 723
    }

724
    QFile cache_file(parameterCacheFile(vehicleId, componentId));
725 726 727 728 729 730
    cache_file.open(QIODevice::WriteOnly | QIODevice::Truncate);

    QDataStream ds(&cache_file);
    ds << cache_map;
}

731
QDir ParameterManager::parameterCacheDir()
732 733 734 735 736
{
    const QString spath(QFileInfo(QSettings().fileName()).dir().absolutePath());
    return spath + QDir::separator() + "ParamCache";
}

737
QString ParameterManager::parameterCacheFile(int vehicleId, int componentId)
738
{
739
    return parameterCacheDir().filePath(QString("%1_%2").arg(vehicleId).arg(componentId));
740 741
}

742
void ParameterManager::_tryCacheHashLoad(int vehicleId, int componentId, QVariant hash_value)
743 744 745
{
    uint32_t crc32_value = 0;
    /* The datastructure of the cache table */
746
    MapID2NamedParam cache_map;
747
    QFile cache_file(parameterCacheFile(vehicleId, componentId));
748
    if (!cache_file.exists()) {
749
        /* no local cache, just wait for them to come in*/
750 751 752 753 754 755 756 757 758
        return;
    }
    cache_file.open(QIODevice::ReadOnly);

    /* Deserialize the parameter cache table */
    QDataStream ds(&cache_file);
    ds >> cache_map;

    /* compute the crc of the local cache to check against the remote */
759 760 761 762 763 764 765

    foreach(int id, cache_map.keys()) {
        const QString name(cache_map[id].first);
        const void *vdat = cache_map[id].second.second.constData();
        const FactMetaData::ValueType_t fact_type = static_cast<FactMetaData::ValueType_t>(cache_map[id].second.first);
        crc32_value = QGC::crc32((const uint8_t *)qPrintable(name), name.length(),  crc32_value);
        crc32_value = QGC::crc32((const uint8_t *)vdat, FactMetaData::typeToSize(fact_type), crc32_value);
766 767 768
    }

    if (crc32_value == hash_value.toUInt()) {
769
        qCInfo(ParameterManagerLog) << "Parameters loaded from cache" << qPrintable(QFileInfo(cache_file).absoluteFilePath());
770
        /* if the two param set hashes match, just load from the disk */
771 772 773 774 775 776
        int count = cache_map.count();
        foreach(int id, cache_map.keys()) {
            const QString &name = cache_map[id].first;
            const QVariant &value = cache_map[id].second.second;
            const FactMetaData::ValueType_t fact_type = static_cast<FactMetaData::ValueType_t>(cache_map[id].second.first);
            const int mavType = _factTypeToMavType(fact_type);
777
            _parameterUpdate(vehicleId, componentId, name, count, id, mavType, value);
778
        }
779 780 781 782 783 784 785 786 787 788
        // Return the hash value to notify we don't want any more updates
        mavlink_param_set_t     p;
        mavlink_param_union_t   union_value;
        p.param_type = MAV_PARAM_TYPE_UINT32;
        strncpy(p.param_id, "_HASH_CHECK", sizeof(p.param_id));
        union_value.param_uint32 = crc32_value;
        p.param_value = union_value.param_float;
        p.target_system = (uint8_t)_vehicle->id();
        p.target_component = (uint8_t)componentId;
        mavlink_message_t msg;
789 790 791 792 793
        mavlink_msg_param_set_encode_chan(_mavlink->getSystemId(),
                                          _mavlink->getComponentId(),
                                          _vehicle->priorityLink()->mavlinkChannel(),
                                          &msg,
                                          &p);
794
        _vehicle->sendMessageOnLink(_vehicle->priorityLink(), msg);
795 796 797 798 799 800 801 802 803

        // Give the user some feedback things loaded properly
        QVariantAnimation *ani = new QVariantAnimation(this);
        ani->setEasingCurve(QEasingCurve::OutCubic);
        ani->setStartValue(0.0);
        ani->setEndValue(1.0);
        ani->setDuration(750);

        connect(ani, &QVariantAnimation::valueChanged, [this](const QVariant &value) {
804
            _setLoadProgress(value.toDouble());
805 806 807 808 809
        });

        // Hide 500ms after animation finishes
        connect(ani, &QVariantAnimation::finished, [this](){
            QTimer::singleShot(500, [this]() {
810
                _setLoadProgress(0);
811 812 813 814
            });
        });

        ani->start(QAbstractAnimation::DeleteWhenStopped);
815 816 817
    }
}

818
void ParameterManager::_saveToEEPROM(void)
819
{
820 821
    if (_saveRequired) {
        _saveRequired = false;
822
        if (_vehicle->firmwarePlugin()->isCapable(_vehicle, FirmwarePlugin::MavCmdPreflightStorageCapability)) {
823
            mavlink_message_t msg;
824 825 826 827 828 829 830
            mavlink_msg_command_long_pack_chan(_mavlink->getSystemId(),
                                               _mavlink->getComponentId(),
                                               _vehicle->priorityLink()->mavlinkChannel(),
                                               &msg,
                                               _vehicle->id(),
                                               0,
                                               MAV_CMD_PREFLIGHT_STORAGE, 1, 1, -1, -1, -1, 0, 0, 0);
831
            _vehicle->sendMessageOnLink(_vehicle->priorityLink(), msg);
832
            qCDebug(ParameterManagerLog) << _logVehiclePrefix() << "_saveToEEPROM";
833
        } else {
834
            qCDebug(ParameterManagerLog) << _logVehiclePrefix() << "_saveToEEPROM skipped due to FirmwarePlugin::isCapable";
835
        }
Don Gagne's avatar
Don Gagne committed
836
    }
837 838
}

839
QString ParameterManager::readParametersFromStream(QTextStream& stream)
840
{
841
    QString errors;
dogmaphobic's avatar
dogmaphobic committed
842

843 844 845 846 847 848
    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) {
Don Gagne's avatar
Don Gagne committed
849 850
                if (_vehicle->id() != lineMavId) {
                    return QString("The parameters in the stream have been saved from System Id %1, but the current vehicle has the System Id %2.").arg(lineMavId).arg(_vehicle->id());
dogmaphobic's avatar
dogmaphobic committed
851 852
                }

853 854 855 856
                int     componentId = wpParams.at(1).toInt();
                QString paramName = wpParams.at(2);
                QString valStr = wpParams.at(3);
                uint    mavType = wpParams.at(4).toUInt();
dogmaphobic's avatar
dogmaphobic committed
857

858
                if (!parameterExists(componentId, paramName)) {
859 860 861
                    QString error;
                    error = QString("Skipped parameter %1:%2 - does not exist on this vehicle\n").arg(componentId).arg(paramName);
                    errors += error;
862
                    qCDebug(ParameterManagerLog) << error;
863 864
                    continue;
                }
dogmaphobic's avatar
dogmaphobic committed
865

866
                Fact* fact = getParameter(componentId, paramName);
867
                if (fact->type() != _mavTypeToFactType((MAV_PARAM_TYPE)mavType)) {
868 869 870
                    QString error;
                    error  = QString("Skipped parameter %1:%2 - type mismatch %3:%4\n").arg(componentId).arg(paramName).arg(fact->type()).arg(_mavTypeToFactType((MAV_PARAM_TYPE)mavType));
                    errors += error;
871
                    qCDebug(ParameterManagerLog) << error;
872 873
                    continue;
                }
dogmaphobic's avatar
dogmaphobic committed
874

875
                qCDebug(ParameterManagerLog) << "Updating parameter" << componentId << paramName << valStr;
Don Gagne's avatar
Don Gagne committed
876
                fact->setRawValue(valStr);
877 878 879
            }
        }
    }
dogmaphobic's avatar
dogmaphobic committed
880

881
    return errors;
882 883
}

884
void ParameterManager::writeParametersToStream(QTextStream &stream)
885
{
886
    stream << "# Onboard parameters for vehicle " << _vehicle->id() << "\n";
887 888 889 890
    stream << "#\n";
    stream << "# MAV ID  COMPONENT ID  PARAM NAME  VALUE (FLOAT)\n";

    foreach (int componentId, _mapParameterName2Variant.keys()) {
891
        foreach (const QString &paramName, _mapParameterName2Variant[componentId].keys()) {
892
            Fact* fact = _mapParameterName2Variant[componentId][paramName].value<Fact*>();
893 894 895 896 897
            if (fact) {
                stream << _vehicle->id() << "\t" << componentId << "\t" << paramName << "\t" << fact->rawValueStringFullPrecision() << "\t" << QString("%1").arg(_factTypeToMavType(fact->type())) << "\n";
            } else {
                qWarning() << "Internal error: missing fact";
            }
898 899
        }
    }
dogmaphobic's avatar
dogmaphobic committed
900

901 902 903
    stream.flush();
}

904
MAV_PARAM_TYPE ParameterManager::_factTypeToMavType(FactMetaData::ValueType_t factType)
905 906 907 908
{
    switch (factType) {
        case FactMetaData::valueTypeUint8:
            return MAV_PARAM_TYPE_UINT8;
dogmaphobic's avatar
dogmaphobic committed
909

910 911
        case FactMetaData::valueTypeInt8:
            return MAV_PARAM_TYPE_INT8;
dogmaphobic's avatar
dogmaphobic committed
912

913 914
        case FactMetaData::valueTypeUint16:
            return MAV_PARAM_TYPE_UINT16;
dogmaphobic's avatar
dogmaphobic committed
915

916 917
        case FactMetaData::valueTypeInt16:
            return MAV_PARAM_TYPE_INT16;
dogmaphobic's avatar
dogmaphobic committed
918

919 920
        case FactMetaData::valueTypeUint32:
            return MAV_PARAM_TYPE_UINT32;
dogmaphobic's avatar
dogmaphobic committed
921

922 923
        case FactMetaData::valueTypeFloat:
            return MAV_PARAM_TYPE_REAL32;
dogmaphobic's avatar
dogmaphobic committed
924

925 926 927
        default:
            qWarning() << "Unsupported fact type" << factType;
            // fall through
dogmaphobic's avatar
dogmaphobic committed
928

929 930 931 932 933
        case FactMetaData::valueTypeInt32:
            return MAV_PARAM_TYPE_INT32;
    }
}

934
FactMetaData::ValueType_t ParameterManager::_mavTypeToFactType(MAV_PARAM_TYPE mavType)
935 936 937 938
{
    switch (mavType) {
        case MAV_PARAM_TYPE_UINT8:
            return FactMetaData::valueTypeUint8;
dogmaphobic's avatar
dogmaphobic committed
939

940 941
        case MAV_PARAM_TYPE_INT8:
            return FactMetaData::valueTypeInt8;
dogmaphobic's avatar
dogmaphobic committed
942

943 944
        case MAV_PARAM_TYPE_UINT16:
            return FactMetaData::valueTypeUint16;
dogmaphobic's avatar
dogmaphobic committed
945

946 947
        case MAV_PARAM_TYPE_INT16:
            return FactMetaData::valueTypeInt16;
dogmaphobic's avatar
dogmaphobic committed
948

949 950
        case MAV_PARAM_TYPE_UINT32:
            return FactMetaData::valueTypeUint32;
dogmaphobic's avatar
dogmaphobic committed
951

952 953
        case MAV_PARAM_TYPE_REAL32:
            return FactMetaData::valueTypeFloat;
dogmaphobic's avatar
dogmaphobic committed
954

955 956 957
        default:
            qWarning() << "Unsupported mav param type" << mavType;
            // fall through
dogmaphobic's avatar
dogmaphobic committed
958

959 960 961 962 963
        case MAV_PARAM_TYPE_INT32:
            return FactMetaData::valueTypeInt32;
    }
}

964
void ParameterManager::_addMetaDataToDefaultComponent(void)
965
{
966
     if (_defaultComponentId == MAV_COMP_ID_ALL) {
967 968 969 970 971 972 973 974
         // We don't know what the default component is so we can't support meta data
         return;
     }

     if (_parameterMetaData) {
         return;
     }

Don Gagne's avatar
Don Gagne committed
975
     QString metaDataFile;
976
     int majorVersion, minorVersion;
977 978 979 980

     // Load best parameter meta data set
     metaDataFile = parameterMetaDataFile(_vehicle, _vehicle->firmwareType(), _parameterSetMajorVersion, majorVersion, minorVersion);
     qCDebug(ParameterManagerLog) << "Adding meta data to Vehicle file:major:minor" << metaDataFile << majorVersion << minorVersion;
Don Gagne's avatar
Don Gagne committed
981

982 983 984 985 986 987 988 989 990
     _parameterMetaData = _vehicle->firmwarePlugin()->loadParameterMetaData(metaDataFile);

    // Loop over all parameters in default component adding meta data
    QVariantMap& factMap = _mapParameterName2Variant[_defaultComponentId];
    foreach (const QString& key, factMap.keys()) {
        _vehicle->firmwarePlugin()->addMetaDataToFact(_parameterMetaData, factMap[key].value<Fact*>(), _vehicle->vehicleType());
    }
}

991
/// @param failIfNoDefaultComponent true: Fails parameter load if no default component but we should have one
992
void ParameterManager::_checkInitialLoadComplete(bool failIfNoDefaultComponent)
993 994 995 996 997
{
    // Already processed?
    if (_initialLoadComplete) {
        return;
    }
dogmaphobic's avatar
dogmaphobic committed
998

999 1000 1001 1002 1003 1004
    foreach (int componentId, _waitingReadParamIndexMap.keys()) {
        if (_waitingReadParamIndexMap[componentId].count()) {
            // We are still waiting on some parameters, not done yet
            return;
        }
    }
dogmaphobic's avatar
dogmaphobic committed
1005

1006
    if (!failIfNoDefaultComponent && _defaultComponentId == MAV_COMP_ID_ALL  && !_defaultComponentIdParam.isEmpty()) {
1007 1008 1009 1010
        // We are still waiting for default component to show up
        return;
    }

1011 1012
    // We aren't waiting for any more initial parameter updates, initial parameter loading is complete
    _initialLoadComplete = true;
dogmaphobic's avatar
dogmaphobic committed
1013

1014 1015
    qCDebug(ParameterManagerLog) << _logVehiclePrefix() << "Initial load complete";

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    // Check for index based load failures
    QString indexList;
    bool initialLoadFailures = false;
    foreach (int componentId, _failedReadParamIndexMap.keys()) {
        foreach (int paramIndex, _failedReadParamIndexMap[componentId]) {
            if (initialLoadFailures) {
                indexList += ", ";
            }
            indexList += QString("%1").arg(paramIndex);
            initialLoadFailures = true;
1026
            qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Gave up on initial load after max retries (paramIndex:" << paramIndex << ")";
1027 1028
        }
    }
1029 1030

    _missingParameters = false;
1031
    if (initialLoadFailures) {
1032
        _missingParameters = true;
1033
        QString errorMsg = tr("QGroundControl was unable to retrieve the full set of parameters from vehicle %1. "
dogmaphobic's avatar
dogmaphobic committed
1034
                              "This will cause QGroundControl to be unable to display its full user interface. "
1035
                              "If you are using modified firmware, you may need to resolve any vehicle startup errors to resolve the issue. "
1036 1037 1038
                              "If you are using standard firmware, you may need to upgrade to a newer version to resolve the issue.").arg(_vehicle->id());
        qCDebug(ParameterManagerLog) << errorMsg;
        qgcApp()->showMessage(errorMsg);
Don Gagne's avatar
Don Gagne committed
1039
        if (!qgcApp()->runningUnitTests()) {
1040
            qCWarning(ParameterManagerLog) << _logVehiclePrefix() << "The following parameter indices could not be loaded after the maximum number of retries: " << indexList;
Don Gagne's avatar
Don Gagne committed
1041
        }
1042
    } else if (_defaultComponentId == MAV_COMP_ID_ALL && !_defaultComponentIdParam.isEmpty()) {
1043 1044
        // Missing default component when we should have one
        _missingParameters = true;
1045
        QString errorMsg = tr("QGroundControl did not receive parameters from the default component for vehicle %1. "
1046 1047
                              "This will cause QGroundControl to be unable to display its full user interface. "
                              "If you are using modified firmware, you may need to resolve any vehicle startup errors to resolve the issue. "
1048 1049 1050
                              "If you are using standard firmware, you may need to upgrade to a newer version to resolve the issue.").arg(_vehicle->id());
        qCDebug(ParameterManagerLog) << errorMsg;
        qgcApp()->showMessage(errorMsg);
Don Gagne's avatar
Don Gagne committed
1051
        if (!qgcApp()->runningUnitTests()) {
1052
            qCWarning(ParameterManagerLog) << _logVehiclePrefix() << "Default component was never found, param:" << _defaultComponentIdParam;
Don Gagne's avatar
Don Gagne committed
1053
        }
1054 1055
    }

1056
    // Signal load complete
1057 1058
    _parametersReady = true;
    _determineDefaultComponentId();
1059 1060 1061
    _vehicle->autopilotPlugin()->parametersReadyPreChecks();
    emit parametersReadyChanged(true);
    emit missingParametersChanged(_missingParameters);
1062
}
1063

1064
void ParameterManager::_initialRequestTimeout(void)
1065
{
1066
    if (!_disableAllRetries && ++_initialRequestRetryCount <= _maxInitialRequestListRetry) {
1067 1068
        refreshAllParameters();
        _initialRequestTimeoutTimer.start();
1069 1070 1071
    } else {
        if (!_vehicle->genericFirmware()) {
            // Generic vehicles (like BeBop) may not have any parameters, so don't annoy the user
1072 1073
            QString errorMsg = tr("Vehicle %1 did not respond to request for parameters"
                                  "This will cause QGroundControl to be unable to display its full user interface.").arg(_vehicle->id());
1074 1075 1076
            qCDebug(ParameterManagerLog) << errorMsg;
            qgcApp()->showMessage(errorMsg);
        }
1077
    }
1078
}
1079

1080
QString ParameterManager::parameterMetaDataFile(Vehicle* vehicle, MAV_AUTOPILOT firmwareType, int wantedMajorVersion, int& majorVersion, int& minorVersion)
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
{
    bool            cacheHit = false;
    FirmwarePlugin* plugin = qgcApp()->toolbox()->firmwarePluginManager()->firmwarePluginForAutopilot(firmwareType, MAV_TYPE_QUADROTOR);

    // Cached files are stored in settings location
    QSettings settings;
    QDir cacheDir = QFileInfo(settings.fileName()).dir();

    // First look for a direct cache hit
    int cacheMinorVersion, cacheMajorVersion;
    QFile cacheFile(cacheDir.filePath(QString("%1.%2.%3.xml").arg(_cachedMetaDataFilePrefix).arg(firmwareType).arg(wantedMajorVersion)));
    if (cacheFile.exists()) {
        plugin->getParameterMetaDataVersionInfo(cacheFile.fileName(), cacheMajorVersion, cacheMinorVersion);
        if (wantedMajorVersion != cacheMajorVersion) {
            qWarning() << "Parameter meta data cache corruption:" << cacheFile.fileName() << "major version does not match file name" << "actual:excepted" << cacheMajorVersion << wantedMajorVersion;
        } else {
1097
            qCDebug(ParameterManagerLog) << "Direct cache hit on file:major:minor" << cacheFile.fileName() << cacheMajorVersion << cacheMinorVersion;
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
            cacheHit = true;
        }
    }

    if (!cacheHit) {
        // No direct hit, look for lower param set version
        QString wildcard = QString("%1.%2.*.xml").arg(_cachedMetaDataFilePrefix).arg(firmwareType);
        QStringList cacheHits = cacheDir.entryList(QStringList(wildcard), QDir::Files, QDir::Name);

        // Find the highest major version number which is below the vehicles major version number
        int cacheHitIndex = -1;
        cacheMajorVersion = -1;
        QRegExp regExp(QString("%1\\.%2\\.(\\d*)\\.xml").arg(_cachedMetaDataFilePrefix).arg(firmwareType));
        for (int i=0; i< cacheHits.count(); i++) {
            if (regExp.exactMatch(cacheHits[i]) && regExp.captureCount() == 1) {
                int majorVersion = regExp.capturedTexts()[0].toInt();
                if (majorVersion > cacheMajorVersion && majorVersion < wantedMajorVersion) {
                    cacheMajorVersion = majorVersion;
                    cacheHitIndex = i;
                }
            }
        }

        if (cacheHitIndex != -1) {
            // We have a cache hit on a lower major version, read minor version as well
            int majorVersion;
            cacheFile.setFileName(cacheDir.filePath(cacheHits[cacheHitIndex]));
            plugin->getParameterMetaDataVersionInfo(cacheFile.fileName(), majorVersion, cacheMinorVersion);
            if (majorVersion != cacheMajorVersion) {
                qWarning() << "Parameter meta data cache corruption:" << cacheFile.fileName() << "major version does not match file name" << "actual:excepted" << majorVersion << cacheMajorVersion;
                cacheHit = false;
            } else {
1130
                qCDebug(ParameterManagerLog) << "Indirect cache hit on file:major:minor:want" << cacheFile.fileName() << cacheMajorVersion << cacheMinorVersion << wantedMajorVersion;
1131 1132 1133 1134 1135 1136
                cacheHit = true;
            }
        }
    }

    int internalMinorVersion, internalMajorVersion;
1137
    QString internalMetaDataFile = plugin->internalParameterMetaDataFile(vehicle);
1138
    plugin->getParameterMetaDataVersionInfo(internalMetaDataFile, internalMajorVersion, internalMinorVersion);
1139
    qCDebug(ParameterManagerLog) << "Internal meta data file:major:minor" << internalMetaDataFile << internalMajorVersion << internalMinorVersion;
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    if (cacheHit) {
        // Cache hit is available, we need to check if internal meta data is a better match, if so use internal version
        if (internalMajorVersion == wantedMajorVersion) {
            if (cacheMajorVersion == wantedMajorVersion) {
                // Both internal and cache are direct hit on major version, Use higher minor version number
                cacheHit = cacheMinorVersion > internalMinorVersion;
            } else {
                // Direct internal hit, but not direct hit in cache, use internal
                cacheHit = false;
            }
        } else {
            if (cacheMajorVersion == wantedMajorVersion) {
                // Direct hit on cache, no direct hit on internal, use cache
                cacheHit = true;
            } else {
                // No direct hit anywhere, use internal
                cacheHit = false;
            }
        }
    }

    QString metaDataFile;
    if (cacheHit && !qgcApp()->runningUnitTests()) {
        majorVersion = cacheMajorVersion;
        minorVersion = cacheMinorVersion;
        metaDataFile = cacheFile.fileName();
    } else {
        majorVersion = internalMajorVersion;
        minorVersion = internalMinorVersion;
        metaDataFile = internalMetaDataFile;
    }
1171
    qCDebug(ParameterManagerLog) << "ParameterManager::parameterMetaDataFile file:major:minor" << metaDataFile << majorVersion << minorVersion;
1172 1173 1174 1175

    return metaDataFile;
}

1176
void ParameterManager::cacheMetaDataFile(const QString& metaDataFile, MAV_AUTOPILOT firmwareType)
1177 1178 1179 1180 1181
{
    FirmwarePlugin* plugin = qgcApp()->toolbox()->firmwarePluginManager()->firmwarePluginForAutopilot(firmwareType, MAV_TYPE_QUADROTOR);

    int newMajorVersion, newMinorVersion;
    plugin->getParameterMetaDataVersionInfo(metaDataFile, newMajorVersion, newMinorVersion);
1182
    qCDebug(ParameterManagerLog) << "ParameterManager::cacheMetaDataFile file:firmware:major;minor" << metaDataFile << firmwareType << newMajorVersion << newMinorVersion;
1183 1184 1185

    // Find the cache hit closest to this new file
    int cacheMajorVersion, cacheMinorVersion;
1186
    QString cacheHit = ParameterManager::parameterMetaDataFile(NULL, firmwareType, newMajorVersion, cacheMajorVersion, cacheMinorVersion);
1187
    qCDebug(ParameterManagerLog) << "ParameterManager::cacheMetaDataFile cacheHit file:firmware:major;minor" << cacheHit << cacheMajorVersion << cacheMinorVersion;
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

    bool cacheNewFile = false;
    if (cacheHit.isEmpty()) {
        // No cache hits, store the new file
        cacheNewFile = true;
    } else if (cacheMajorVersion == newMajorVersion) {
        // Direct hit on major version in cache:
        //      Cache new file if newer minor version
        //      Also delete older cache file
        if (newMinorVersion > cacheMinorVersion) {
            cacheNewFile = true;
            QFile::remove(cacheHit);
        }
    } else {
        // Indirect hit in cache, store new file
        cacheNewFile = true;
    }

    if (cacheNewFile) {
        // Cached files are stored in settings location. Copy from current file to cache naming.

        QSettings settings;
        QDir cacheDir = QFileInfo(settings.fileName()).dir();
        QFile cacheFile(cacheDir.filePath(QString("%1.%2.%3.xml").arg(_cachedMetaDataFilePrefix).arg(firmwareType).arg(newMajorVersion)));
1212
        qCDebug(ParameterManagerLog) << "ParameterManager::cacheMetaDataFile caching file:" << cacheFile.fileName();
1213 1214 1215 1216
        QFile newFile(metaDataFile);
        newFile.copy(cacheFile.fileName());
    }
}
1217 1218

/// Remap a parameter from one firmware version to another
1219
QString ParameterManager::_remapParamNameToVersion(const QString& paramName)
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
{
    QString mappedParamName;

    if (!paramName.startsWith(QStringLiteral("r."))) {
        // No version mapping wanted
        return paramName;
    }

    int majorVersion = _vehicle->firmwareMajorVersion();
    int minorVersion = _vehicle->firmwareMinorVersion();

1231
    qCDebug(ParameterManagerLog) << "_remapParamNameToVersion" << paramName << majorVersion << minorVersion;
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243

    mappedParamName = paramName.right(paramName.count() - 2);

    if (majorVersion == Vehicle::versionNotSetValue) {
        // Vehicle version unknown
        return mappedParamName;
    }

    const FirmwarePlugin::remapParamNameMajorVersionMap_t& majorVersionRemap = _vehicle->firmwarePlugin()->paramNameRemapMajorVersionMap();

    if (!majorVersionRemap.contains(majorVersion)) {
        // No mapping for this major version
1244
        qCDebug(ParameterManagerLog) << "_remapParamNameToVersion: no major version mapping";
1245 1246 1247 1248 1249
        return mappedParamName;
    }

    const FirmwarePlugin::remapParamNameMinorVersionRemapMap_t& remapMinorVersion = majorVersionRemap[majorVersion];

1250
    // We must map backwards from the highest known minor version to one above the vehicle's minor version
1251 1252 1253 1254 1255 1256 1257

    for (int currentMinorVersion=_vehicle->firmwarePlugin()->remapParamNameHigestMinorVersionNumber(majorVersion); currentMinorVersion>minorVersion; currentMinorVersion--) {
        if (remapMinorVersion.contains(currentMinorVersion)) {
            const FirmwarePlugin::remapParamNameMap_t& remap = remapMinorVersion[currentMinorVersion];

            if (remap.contains(mappedParamName)) {
                QString toParamName = remap[mappedParamName];
1258
                qCDebug(ParameterManagerLog) << "_remapParamNameToVersion: remapped currentMinor:from:to"<< currentMinorVersion << mappedParamName << toParamName;
1259 1260 1261 1262 1263 1264 1265
                mappedParamName = toParamName;
            }
        }
    }

    return mappedParamName;
}
1266 1267

/// The offline editing vehicle can have custom loaded params bolted into it.
1268
void ParameterManager::_loadOfflineEditingParams(void)
1269 1270 1271 1272 1273 1274 1275 1276
{    
    QString paramFilename = _vehicle->firmwarePlugin()->offlineEditingParamFile(_vehicle);
    if (paramFilename.isEmpty()) {
        return;
    }

    QFile paramFile(paramFilename);
    if (!paramFile.open(QFile::ReadOnly)) {
1277
        qCWarning(ParameterManagerLog) << "Unable to open offline editing params file" << paramFilename;
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    }

    QTextStream paramStream(&paramFile);

    while (!paramStream.atEnd()) {
        QString line = paramStream.readLine();

        if (line.startsWith("#")) {
            continue;
        }

        QStringList paramData = line.split("\t");
        Q_ASSERT(paramData.count() == 5);

        _defaultComponentId = paramData.at(1).toInt();
        QString paramName = paramData.at(2);
        QString valStr = paramData.at(3);
        MAV_PARAM_TYPE paramType = static_cast<MAV_PARAM_TYPE>(paramData.at(4).toUInt());

        QVariant paramValue;
        switch (paramType) {
        case MAV_PARAM_TYPE_REAL32:
            paramValue = QVariant(valStr.toFloat());
            break;
        case MAV_PARAM_TYPE_UINT32:
            paramValue = QVariant(valStr.toUInt());
            break;
        case MAV_PARAM_TYPE_INT32:
            paramValue = QVariant(valStr.toInt());
            break;
        case MAV_PARAM_TYPE_UINT16:
            paramValue = QVariant((quint16)valStr.toUInt());
            break;
        case MAV_PARAM_TYPE_INT16:
            paramValue = QVariant((qint16)valStr.toInt());
            break;
        case MAV_PARAM_TYPE_UINT8:
            paramValue = QVariant((quint8)valStr.toUInt());
            break;
        case MAV_PARAM_TYPE_INT8:
            paramValue = QVariant((qint8)valStr.toUInt());
            break;
        default:
            qCritical() << "Unknown type" << paramType;
            paramValue = QVariant(valStr.toInt());
            break;
        }

1326 1327 1328 1329 1330
        // Get parameter set version
        if (!_versionParam.isEmpty() && _versionParam == paramName) {
            _parameterSetMajorVersion = paramValue.toInt();
        }

1331 1332 1333 1334 1335
        Fact* fact = new Fact(_defaultComponentId, paramName, _mavTypeToFactType(paramType), this);
        _mapParameterName2Variant[_defaultComponentId][paramName] = QVariant::fromValue(fact);
    }

    _addMetaDataToDefaultComponent();
1336
    _setupGroupMap();
1337 1338 1339
    _parametersReady = true;
    _initialLoadComplete = true;
}
1340 1341 1342 1343 1344 1345 1346 1347 1348 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 1376 1377 1378 1379

void ParameterManager::saveToJson(int componentId, const QStringList& paramsToSave, QJsonObject& saveObject)
{
    QList<int>  rgCompIds;
    QStringList rgParamNames;

    if (componentId == MAV_COMP_ID_ALL) {
        rgCompIds = _mapParameterName2Variant.keys();
    } else {
        rgCompIds.append(_actualComponentId(componentId));
    }

    QJsonArray rgParams;

    // Loop over all requested component ids
    for (int i=0; i<rgCompIds.count(); i++) {
        int compId = rgCompIds[i];

        if (!_mapParameterName2Variant.contains(compId)) {
            qCDebug(ParameterManagerLog) << "ParameterManager::saveToJson no params for compId" << compId;
            continue;
        }

        // Build list of parameter names if not specified
        if (paramsToSave.count() == 0) {
            rgParamNames = 	parameterNames(compId);
        } else {
            rgParamNames = paramsToSave;
        }

        // Loop over parameter names adding each to json array
        for (int j=0; j<rgParamNames.count(); j++) {
            QString paramName = rgParamNames[j];

            if (!parameterExists(compId, paramName)) {
                qCDebug(ParameterManagerLog) << "ParameterManager::saveToJson param not found compId:param" << compId << paramName;
                continue;
            }

            QJsonObject paramJson;
1380
            Fact* fact = getParameter(compId, paramName);
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
            paramJson.insert(_jsonCompIdKey, QJsonValue(compId));
            paramJson.insert(_jsonParamNameKey, QJsonValue(fact->name()));
            paramJson.insert(_jsonParamValueKey, QJsonValue(fact->rawValue().toDouble()));

            rgParams.append(QJsonValue(paramJson));
        }
    }

    saveObject.insert(_jsonParametersKey, QJsonValue(rgParams));
}

bool ParameterManager::loadFromJson(const QJsonObject& json, bool required, QString& errorString)
{
    QList<QJsonValue::Type> keyTypes;

    errorString.clear();

    if (required) {
        if (!JsonHelper::validateRequiredKeys(json, QStringList(_jsonParametersKey), errorString)) {
            return false;
        }
    } else if (!json.contains(_jsonParametersKey)) {
        return true;
    }

    keyTypes = { QJsonValue::Array };
    if (!JsonHelper::validateKeyTypes(json, QStringList(_jsonParametersKey), keyTypes, errorString)) {
        return false;
    }

    QJsonArray rgParams = json[_jsonParametersKey].toArray();
    for (int i=0; i<rgParams.count(); i++) {
        QJsonValueRef paramValue = rgParams[i];

        if (!paramValue.isObject()) {
            errorString = tr("%1 key is not a json object").arg(_jsonParametersKey);
            return false;
        }
        QJsonObject param = paramValue.toObject();

        QStringList requiredKeys = { _jsonCompIdKey, _jsonParamNameKey, _jsonParamValueKey };
        if (!JsonHelper::validateRequiredKeys(param, requiredKeys, errorString)) {
            return false;
        }
        keyTypes = { QJsonValue::Double, QJsonValue::String, QJsonValue::Double };
        if (!JsonHelper::validateKeyTypes(param, requiredKeys, keyTypes, errorString)) {
            return false;
        }

        int compId = param[_jsonCompIdKey].toInt();
        QString name = param[_jsonParamNameKey].toString();
        double value = param[_jsonParamValueKey].toDouble();

        if (!parameterExists(compId, name)) {
            qCDebug(ParameterManagerLog) << "ParameterManager::loadFromJson param not found compId:param" << compId << name;
            continue;
        }

1439
        Fact* fact = getParameter(compId, name);
1440 1441 1442 1443 1444 1445
        fact->setRawValue(value);
    }

    return true;
}

1446 1447 1448 1449 1450
void ParameterManager::resetAllParametersToDefaults(void)
{
    mavlink_message_t msg;
    MAVLinkProtocol* mavlink = qgcApp()->toolbox()->mavlinkProtocol();

1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
    mavlink_msg_command_long_pack_chan(mavlink->getSystemId(),
                                       mavlink->getComponentId(),
                                       _vehicle->priorityLink()->mavlinkChannel(),
                                       &msg,
                                       _vehicle->id(),                   // Target systeem
                                       _vehicle->defaultComponentId(),   // Target component
                                       MAV_CMD_PREFLIGHT_STORAGE,
                                       0,                                // Confirmation
                                       2,                                // 2 = Reset params to default
                                       -1,                               // -1 = No change to mission storage
                                       0,                                // 0 = Ignore
                                       0, 0, 0, 0);                      // Unused
    _vehicle->sendMessageOnLink(_vehicle->priorityLink(), msg);
1464 1465
}

1466 1467 1468 1469 1470 1471 1472 1473
QString ParameterManager::_logVehiclePrefix(int componentId)
{
    if (componentId == -1) {
        return QString("V:%1").arg(_vehicle->id());
    } else {
        return QString("V:%1 C:%2").arg(_vehicle->id()).arg(componentId);
    }
}
1474 1475 1476 1477 1478 1479

void ParameterManager::_setLoadProgress(double loadProgress)
{
    _loadProgress = loadProgress;
    emit loadProgressChanged(loadProgress);
}