QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
ParameterManager.cc
Go to the documentation of this file.
2#include "ParameterManager.h"
3#include "BulkRefreshJob.h"
4
5#include <algorithm>
6
7#include <QtCore/QDir>
8#include <QtCore/QSet>
9#include <QtCore/QTextStream>
10
11#include "AutoPilotPlugin.h"
12#include "CompInfoParam.h"
14#include "FactGroup.h"
15#include "FirmwarePlugin.h"
16#include "FTPManager.h"
17#include "MAVLinkProtocol.h"
18#include "AppMessages.h"
19#include "QGCMath.h"
20#include "QGCApplication.h"
21#include "QGCLoggingCategory.h"
22#include "QGCMAVLink.h"
23#include "Vehicle.h"
24#include "VehicleLinkManager.h"
25#include "QGCStateMachine.h"
26#include "MultiVehicleManager.h"
27
28#include <QtCore/QEasingCurve>
29#include <QtCore/QFile>
30#include <QtCore/QStandardPaths>
31#include <QtCore/QVariantAnimation>
32
33QGC_LOGGING_CATEGORY(ParameterManagerLog, "FactSystem.ParameterManager")
34QGC_LOGGING_CATEGORY(ParameterManagerVerbose1Log, "FactSystem.ParameterManager:verbose1")
35QGC_LOGGING_CATEGORY(ParameterManagerVerbose2Log, "FactSystem.ParameterManager:verbose2")
36QGC_LOGGING_CATEGORY(ParameterManagerDebugCacheFailureLog, "FactSystem.ParameterManager:debugCacheFailure") // Turn on to debug parameter cache crc misses
37
39 : QObject(vehicle)
40 , _vehicle(vehicle)
41 , _logReplay(!vehicle->vehicleLinkManager()->primaryLink().expired() && vehicle->vehicleLinkManager()->primaryLink().lock()->isLogReplay())
42 , _disableAllRetries(_logReplay)
43 , _waitForParamValueAckMs(QGC::runningUnitTests() ? 50 : kWaitForParamValueAckMs)
44 , _tryftp(vehicle->apmFirmware() || vehicle->px4Firmware())
45{
46 qCDebug(ParameterManagerLog) << this;
47
48 if (_vehicle->isOfflineEditingVehicle()) {
49 _loadOfflineEditingParams();
50 return;
51 }
52
53 if (_logReplay) {
54 qCDebug(ParameterManagerLog) << this << "In log replay mode";
55 }
56
57 _hashCheckTimer.setSingleShot(true);
58 _hashCheckTimer.setInterval(QGC::runningUnitTests() ? kTestHashCheckTimeoutMs : kHashCheckTimeoutMs);
59 (void) connect(&_hashCheckTimer, &QTimer::timeout, this, &ParameterManager::_hashCheckTimeout);
60
61 _paramRequestListTimer.setSingleShot(true);
63 (void) connect(&_paramRequestListTimer, &QTimer::timeout, this, &ParameterManager::_paramRequestListTimeout);
64
65 _waitingParamTimeoutTimer.setSingleShot(true);
66 _waitingParamTimeoutTimer.setInterval(QGC::runningUnitTests() ? 500 : 3000);
67 if (!_logReplay) {
68 (void) connect(&_waitingParamTimeoutTimer, &QTimer::timeout, this, &ParameterManager::_waitingParamTimeout);
69 }
70
71 // Ensure the cache directory exists
72 (void) QDir().mkpath(parameterCacheDir().absolutePath());
73}
74
76{
77 qCDebug(ParameterManagerLog) << this;
78}
79
80void ParameterManager::_updateProgressBar()
81{
82 // The bar is initial-load and user-refresh UI; components still loading in the background must not revive it
83 if (_initialLoadComplete && !_refreshAllProgressActive) {
84 return;
85 }
86
87 int waitingReadParamIndexCount = 0;
88
89 for (const int compId: _waitingReadParamIndexMap.keys()) {
90 waitingReadParamIndexCount += _waitingReadParamIndexMap[compId].count();
91 }
92
93 if (waitingReadParamIndexCount == 0) {
94 _refreshAllProgressActive = false;
95 if (_readParamIndexProgressActive) {
96 _readParamIndexProgressActive = false;
97 _setLoadProgress(0.0);
98 return;
99 }
100 } else {
101 _readParamIndexProgressActive = true;
102 _setLoadProgress(static_cast<double>(_totalParamCount - waitingReadParamIndexCount) / static_cast<double>(_totalParamCount));
103 return;
104 }
105}
106
108{
109 if (message.msgid == MAVLINK_MSG_ID_HEARTBEAT) {
110 _handleHeartbeat(message.compid);
111 } else if (message.msgid == MAVLINK_MSG_ID_PARAM_VALUE) {
112 mavlink_param_value_t param_value{};
113 mavlink_msg_param_value_decode(&message, &param_value);
114
115 // This will null terminate the name string
116 char parameterNameWithNull[MAVLINK_MSG_PARAM_VALUE_FIELD_PARAM_ID_LEN + 1] = {};
117 (void) strncpy(parameterNameWithNull, param_value.param_id, MAVLINK_MSG_PARAM_VALUE_FIELD_PARAM_ID_LEN);
118 const QString parameterName(parameterNameWithNull);
119
120 // FTP download ignores the PARAM_VALUE stream, but PX4 _HASH_CHECK is a PARAM_VALUE
121 // and must still be handled so the cache can skip the download.
122 if (_tryftp && (message.compid == MAV_COMP_ID_AUTOPILOT1) && !_initialLoadComplete
123 && (parameterName != QStringLiteral("_HASH_CHECK"))) {
124 return;
125 }
126
127 mavlink_param_union_t paramUnion{};
128 paramUnion.param_float = param_value.param_value;
129 paramUnion.type = param_value.param_type;
130
131 QVariant parameterValue;
132 if (!_mavlinkParamUnionToVariant(paramUnion, parameterValue)) {
133 return;
134 }
135
136 _handleParamValue(message.compid, parameterName, param_value.param_count, param_value.param_index, static_cast<MAV_PARAM_TYPE>(param_value.param_type), parameterValue);
137 }
138}
139
140void ParameterManager::_handleParamValue(int componentId, const QString &parameterName, int parameterCount, int parameterIndex, MAV_PARAM_TYPE mavParamType, const QVariant &parameterValue)
141{
142
143 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) <<
144 "_parameterUpdate" <<
145 "name:" << parameterName <<
146 "count:" << parameterCount <<
147 "index:" << parameterIndex <<
148 "mavType:" << mavParamType <<
149 "value:" << parameterValue <<
150 ")";
151
152 // ArduPilot has this strange behavior of streaming parameters that we didn't ask for. This even happens before it responds to the
153 // PARAM_REQUEST_LIST. We disregard any of this until the initial request is responded to.
154 if ((parameterIndex == 65535) && (parameterName != QStringLiteral("_HASH_CHECK")) && _paramRequestListTimer.isActive()) {
155 qCDebug(ParameterManagerLog) << "Disregarding unrequested param prior to initial list response" << parameterName;
156 return;
157 }
158
159 if (_vehicle->px4Firmware() && (parameterName == "_HASH_CHECK")) {
160 _hashCheckTimer.stop();
161 if (!_initialLoadComplete && !_logReplay) {
162 /* we received a cache hash, potentially load from cache */
163 _tryCacheHashLoad(_vehicle->id(), componentId, parameterValue);
164 }
165 return;
166 }
167
168 _paramRequestListTimer.stop();
169
170 // Used to debug cache crc misses (turn on ParameterManagerDebugCacheFailureLog)
171 if (!_initialLoadComplete && !_logReplay && _debugCacheCRC.contains(componentId) && _debugCacheCRC[componentId]) {
172 if (_debugCacheMap[componentId].contains(parameterName)) {
173 const ParamTypeVal &cacheParamTypeVal = _debugCacheMap[componentId][parameterName];
174 const size_t dataSize = FactMetaData::typeToSize(static_cast<FactMetaData::ValueType_t>(cacheParamTypeVal.first));
175 const void *const cacheData = cacheParamTypeVal.second.constData();
176 const void *const vehicleData = parameterValue.constData();
177
178 if (memcmp(cacheData, vehicleData, dataSize) != 0) {
179 qCDebug(ParameterManagerVerbose1Log) << "Cache/Vehicle values differ for name:cache:actual" << parameterName << parameterValue << cacheParamTypeVal.second;
180 }
181 _debugCacheParamSeen[componentId][parameterName] = true;
182 } else {
183 qCDebug(ParameterManagerVerbose1Log) << "Parameter missing from cache" << parameterName;
184 }
185 }
186
187 _waitingParamTimeoutTimer.stop();
188
189 _paramValuesReceivedThisCycle[componentId]++;
190 _silentCycleCount.remove(componentId);
191
192 // Update our total parameter counts
193 if (!_paramCountMap.contains(componentId)) {
194 _paramCountMap[componentId] = parameterCount;
195 _totalParamCount += parameterCount;
196 }
197
198 // If we've never seen this component id before, setup the index wait lists.
199 if (!_waitingReadParamIndexMap.contains(componentId)) {
200 // Add all indices to the wait list, parameter index is 0-based
201 for (int waitingIndex = 0; waitingIndex < parameterCount; waitingIndex++) {
202 // 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
203 _waitingReadParamIndexMap[componentId][waitingIndex] = 0;
204 }
205
206 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Seeing component for first time - paramcount:" << parameterCount;
207 }
208
209 if (!_waitingReadParamIndexMap[componentId].contains(parameterIndex)) {
210 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "Unrequested param update" << parameterName;
211 }
212
213 // Remove this parameter from the waiting lists
214 if (_waitingReadParamIndexMap[componentId].contains(parameterIndex)) {
215 _waitingReadParamIndexMap[componentId].remove(parameterIndex);
216 (void) _indexBatchQueue.removeOne(qMakePair(componentId, parameterIndex));
217 _fillIndexBatchQueue(false /* waitingParamTimeout */);
218 }
219
220 // Track how many parameters we are still waiting for
221 int waitingReadParamIndexCount = 0;
222
223 for (const int waitingComponentId: _waitingReadParamIndexMap.keys()) {
224 waitingReadParamIndexCount += _waitingReadParamIndexMap[waitingComponentId].count();
225 }
226 if (waitingReadParamIndexCount) {
227 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "waitingReadParamIndexCount:" << waitingReadParamIndexCount;
228 }
229
230 const int readWaitingParamCount = waitingReadParamIndexCount;
231 const int totalWaitingParamCount = readWaitingParamCount;
232 if (totalWaitingParamCount) {
233 // More params to wait for, restart timer
234 _waitingParamTimeoutTimer.start();
235 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(-1) << "Restarting _waitingParamTimeoutTimer: totalWaitingParamCount:" << totalWaitingParamCount;
236 } else if (!_mapCompId2FactMap.contains(_vehicle->defaultComponentId())) {
237 // Still waiting for parameters from default component
238 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Restarting _waitingParamTimeoutTimer (still waiting for default component params)";
239 _waitingParamTimeoutTimer.start();
240 } else {
241 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(-1) << "Not restarting _waitingParamTimeoutTimer (all requests satisfied)";
242 }
243
244 _updateProgressBar();
245
246 Fact *fact = nullptr;
247 if (_mapCompId2FactMap.contains(componentId) && _mapCompId2FactMap[componentId].contains(parameterName)) {
248 fact = _mapCompId2FactMap[componentId][parameterName];
249 } else {
250 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "Adding new fact" << parameterName;
251
252 fact = new Fact(componentId, parameterName, mavTypeToFactType(mavParamType), this);
253 FactMetaData *const factMetaData = _vehicle->compInfoManager()->compInfoParam(componentId)->factMetaDataForName(parameterName, fact->type());
254 fact->setMetaData(factMetaData);
255
256 _mapCompId2FactMap[componentId][parameterName] = fact;
257
258 // We need to know when the fact value changes so we can update the vehicle
259 (void) connect(fact, &Fact::containerRawValueChanged, this, &ParameterManager::_factRawValueUpdated);
260
261 emit factAdded(componentId, fact);
262 }
263
264 fact->containerSetRawValue(parameterValue);
265
266 // Update param cache. The param cache is only used on PX4 Firmware since ArduPilot and Solo have volatile params
267 // which invalidate the cache. The Solo also streams param updates in flight for things like gimbal values
268 // which in turn causes a perf problem with all the param cache updates.
269 if (!_logReplay && _vehicle->px4Firmware()) {
270 if (_prevWaitingReadParamIndexCount != 0 && readWaitingParamCount == 0) {
271 // All reads just finished, update the cache
272 _writeLocalParamCache(_vehicle->id(), componentId);
273 }
274 }
275
276 _prevWaitingReadParamIndexCount = waitingReadParamIndexCount;
277
278 _checkInitialLoadComplete();
279
280 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "_handleParamValue complete";
281}
282
283QString ParameterManager::_vehicleAndComponentString(int componentId) const
284{
285 // If there are multiple vehicles include the vehicle id for disambiguation
286 QString vehicleIdStr;
287 if (MultiVehicleManager::instance()->vehicles()->count() > 1) {
288 vehicleIdStr = QStringLiteral("veh: %1").arg(_vehicle->id());
289 }
290
291 // IF we have parameters for multiple components include the component id for disambiguation
292 QString componentIdStr;
293 if (_mapCompId2FactMap.keys().count() > 1) {
294 componentIdStr = QStringLiteral("comp: %1").arg(componentId);
295 }
296
297 if (!vehicleIdStr.isEmpty() && !componentIdStr.isEmpty()) {
298 return vehicleIdStr + QStringLiteral(" ") + componentIdStr;
299 } else if (!vehicleIdStr.isEmpty()) {
300 return vehicleIdStr;
301 } else if (!componentIdStr.isEmpty()) {
302 return componentIdStr;
303 } else {
304 return QString();
305 }
306}
307
308void ParameterManager::_mavlinkParamSet(int componentId, const QString &paramName, FactMetaData::ValueType_t valueType, const QVariant &rawValue)
309{
310 auto paramSetEncoder = [this, componentId, paramName, valueType, rawValue](quint32 /*systemId*/, uint8_t channel,
311 mavlink_message_t* message) -> void {
312 const MAV_PARAM_TYPE paramType = factTypeToMavType(valueType);
313
314 mavlink_param_union_t union_value{};
315 if (!_fillMavlinkParamUnion(valueType, rawValue, union_value)) {
316 return;
317 }
318
319 char paramId[MAVLINK_MSG_PARAM_SET_FIELD_PARAM_ID_LEN + 1] = {};
320 (void) strncpy(paramId, paramName.toLocal8Bit().constData(), MAVLINK_MSG_PARAM_SET_FIELD_PARAM_ID_LEN);
321
322 (void) mavlink_msg_param_set_pack_chan(MAVLinkProtocol::instance()->getSystemId(),
323 MAVLinkProtocol::getComponentId(), channel, message, _vehicle->id(),
324 static_cast<uint8_t>(componentId), paramId, union_value.param_float,
325 static_cast<uint8_t>(paramType));
326 };
327
328 auto checkForCorrectParamValue = [this, componentId, paramName, rawValue](const mavlink_message_t &message) -> bool {
329 if (message.compid != componentId) {
330 return false;
331 }
332
333 mavlink_param_value_t param_value{};
334 mavlink_msg_param_value_decode(&message, &param_value);
335
336 // This will null terminate the name string
337 char parameterNameWithNull[MAVLINK_MSG_PARAM_VALUE_FIELD_PARAM_ID_LEN + 1] = {};
338 (void) strncpy(parameterNameWithNull, param_value.param_id, MAVLINK_MSG_PARAM_VALUE_FIELD_PARAM_ID_LEN);
339 const QString parameterName(parameterNameWithNull);
340
341 if (parameterName != paramName) {
342 return false;
343 }
344
345 // Check that the value matches what we expect within tolerance, if it doesn't match then this message is not for us
346 QVariant receivedValue;
347 mavlink_param_union_t param_union;
348 param_union.param_float = param_value.param_value;
349 param_union.type = param_value.param_type;
350 if (!_mavlinkParamUnionToVariant(param_union, receivedValue)) {
351 return false;
352 }
353 if (rawValue.typeId() != receivedValue.typeId()) {
354 qCWarning(ParameterManagerLog) << "QVariant type mismatch on PARAM_VALUE ack for" << paramName << ": expected type" << rawValue.typeId() << "got type" << receivedValue.typeId();
355 return false;
356 }
357 if (param_value.param_type == MAV_PARAM_TYPE_REAL32) {
358 // Float comparison must be fuzzy
359 return QGC::fuzzyCompare(rawValue.toFloat(), receivedValue.toFloat());
360 } else {
361 return receivedValue == rawValue;
362 }
363 };
364
365 auto checkForParamError = [componentId, paramName](const mavlink_message_t &message) -> bool {
366 if (message.compid != componentId) {
367 return false;
368 }
369
370 mavlink_param_error_t paramError{};
371 mavlink_msg_param_error_decode(&message, &paramError);
372
373 char paramId[MAVLINK_MSG_PARAM_ERROR_FIELD_PARAM_ID_LEN + 1] = {};
374 (void) strncpy(paramId, paramError.param_id, MAVLINK_MSG_PARAM_ERROR_FIELD_PARAM_ID_LEN);
375
376 return QString(paramId) == paramName;
377 };
378
379 // State Machine:
380 // Send PARAM_SET - 2 retries after initial attempt
381 // Increment pending write count
382 // Wait for PARAM_VALUE ack or PARAM_ERROR rejection
383 // Decrement pending write count
384 //
385 // timeout:
386 // Decrement pending write count
387 // Back up to PARAM_SET for retries
388 //
389 // error (PARAM_ERROR or retries exhausted):
390 // Refresh parameter from vehicle
391 // Notify user of failure
392
393 // Create states
394 auto stateMachine = new QGCStateMachine(QStringLiteral("ParameterManager PARAM_SET"), vehicle(), this);
395 auto sendParamSetState = new SendMavlinkMessageState(stateMachine, paramSetEncoder, kParamSetRetryCount);
396 auto incPendingWriteCountState = new FunctionState(QStringLiteral("ParameterManager increment pending write count"), stateMachine, [this]() {
397 _incrementPendingWriteCount();
398 });
399 auto decPendingWriteCountState = new FunctionState(QStringLiteral("ParameterManager decrement pending write count"), stateMachine, [this]() {
400 _decrementPendingWriteCount();
401 });
402 auto retryDecPendingWriteCountState = new FunctionState(QStringLiteral("ParameterManager retry decrement pending write count"), stateMachine, [this]() {
403 _decrementPendingWriteCount();
404 });
405 auto errorDecPendingWriteCountState = new FunctionState(QStringLiteral("ParameterManager error decrement pending write count"), stateMachine, [this]() {
406 _decrementPendingWriteCount();
407 });
408 auto waitAckState = new WaitForParamResponseState(stateMachine, _waitForParamValueAckMs, checkForCorrectParamValue, checkForParamError);
409 auto paramRefreshState = new FunctionState(QStringLiteral("ParameterManager param refresh"), stateMachine, [this, waitAckState, componentId, paramName]() {
410 // A definitive "does not exist" rejection means there is nothing on the vehicle
411 // to refresh - stop here rather than generating a redundant read failure.
412 if (waitAckState->lastParamError() == MAV_PARAM_ERROR_DOES_NOT_EXIST) {
413 qCDebug(ParameterManagerLog) << "Skipping post-write-failure refresh, param does not exist on vehicle:" << paramName << _vehicleAndComponentString(componentId);
414 return;
415 }
416 refreshParameter(componentId, paramName);
417 });
418 auto userNotifyState = new FunctionState(QStringLiteral("ParameterManager user notify"), stateMachine, [waitAckState, paramName, this, componentId]() {
419 const QString errorDetail = waitAckState->lastParamErrorString();
420 const QString msg = errorDetail.isEmpty()
421 ? QStringLiteral("Parameter write failed: param: %1 %2").arg(paramName, _vehicleAndComponentString(componentId))
422 : QStringLiteral("Parameter write failed: param: %1 %2 - %3").arg(paramName, _vehicleAndComponentString(componentId), errorDetail);
424 });
425 auto logSuccessState = new FunctionState(QStringLiteral("ParameterManager log success"), stateMachine, [this, componentId, paramName]() {
426 qCDebug(ParameterManagerLog) << "Parameter write succeeded: param:" << paramName << _vehicleAndComponentString(componentId);
427 emit _paramSetSuccess(componentId, paramName);
428 });
429 auto logFailureState = new FunctionState(QStringLiteral("ParameterManager log failure"), stateMachine, [this, componentId, paramName]() {
430 qCDebug(ParameterManagerLog) << "Parameter write failed: param:" << paramName << _vehicleAndComponentString(componentId);
431 emit _paramSetFailure(componentId, paramName);
432 });
433 auto finalState = new QGCFinalState(stateMachine);
434
435 // Successful state machine transitions
436 stateMachine->setInitialState(sendParamSetState);
437 sendParamSetState->addThisTransition (&QGCState::advance, incPendingWriteCountState);
438 incPendingWriteCountState->addThisTransition(&QGCState::advance, waitAckState);
439 waitAckState->addThisTransition (&QGCState::advance, decPendingWriteCountState);
440 decPendingWriteCountState->addThisTransition(&QGCState::advance, logSuccessState);
441 logSuccessState->addThisTransition (&QGCState::advance, finalState);
442
443 // Retry transitions (timeout path)
444 waitAckState->addTransition(waitAckState, &WaitStateBase::timeout, retryDecPendingWriteCountState);
445 retryDecPendingWriteCountState->addThisTransition(&QGCState::advance, sendParamSetState);
446
447 // PARAM_ERROR path (definitive rejection - no retries)
448 waitAckState->addThisTransition (&QGCState::error, errorDecPendingWriteCountState);
449 errorDecPendingWriteCountState->addThisTransition (&QGCState::advance, logFailureState);
450
451 // Error transitions (retries exhausted)
452 sendParamSetState->addThisTransition(&QGCState::error, logFailureState);
453
454 // Error state branching transitions
455 logFailureState->addThisTransition (&QGCState::advance, userNotifyState);
456 userNotifyState->addThisTransition (&QGCState::advance, paramRefreshState);
457 paramRefreshState->addThisTransition(&QGCState::advance, finalState);
458
459 qCDebug(ParameterManagerLog) << "Starting state machine for PARAM_SET on: " << paramName << _vehicleAndComponentString(componentId);
460 stateMachine->start();
461}
462
463bool ParameterManager::_fillMavlinkParamUnion(FactMetaData::ValueType_t valueType, const QVariant &rawValue, mavlink_param_union_t &paramUnion) const
464{
465 bool ok = false;
466
467 switch (valueType) {
469 paramUnion.param_uint8 = static_cast<uint8_t>(rawValue.toUInt(&ok));
470 break;
472 paramUnion.param_int8 = static_cast<int8_t>(rawValue.toInt(&ok));
473 break;
475 paramUnion.param_uint16 = static_cast<uint16_t>(rawValue.toUInt(&ok));
476 break;
478 paramUnion.param_int16 = static_cast<int16_t>(rawValue.toInt(&ok));
479 break;
481 paramUnion.param_uint32 = static_cast<uint32_t>(rawValue.toUInt(&ok));
482 break;
484 paramUnion.param_float = rawValue.toFloat(&ok);
485 break;
487 paramUnion.param_int32 = static_cast<int32_t>(rawValue.toInt(&ok));
488 break;
489 default:
490 qCCritical(ParameterManagerLog) << "Internal Error: Unsupported fact value type" << valueType;
491 paramUnion.param_int32 = static_cast<int32_t>(rawValue.toInt(&ok));
492 break;
493 }
494
495 if (!ok) {
496 qCCritical(ParameterManagerLog) << "Fact Failed to Convert to Param Type:" << valueType;
497 return false;
498 }
499
500 return true;
501}
502
503bool ParameterManager::_mavlinkParamUnionToVariant(const mavlink_param_union_t &paramUnion, QVariant &outValue) const
504{
505 switch (paramUnion.type) {
506 case MAV_PARAM_TYPE_REAL32:
507 outValue = QVariant(paramUnion.param_float);
508 return true;
509 case MAV_PARAM_TYPE_UINT8:
510 outValue = QVariant(static_cast<quint32>(paramUnion.param_uint8));
511 return true;
512 case MAV_PARAM_TYPE_INT8:
513 outValue = QVariant(static_cast<qint32>(paramUnion.param_int8));
514 return true;
515 case MAV_PARAM_TYPE_UINT16:
516 outValue = QVariant(static_cast<quint32>(paramUnion.param_uint16));
517 return true;
518 case MAV_PARAM_TYPE_INT16:
519 outValue = QVariant(static_cast<qint32>(paramUnion.param_int16));
520 return true;
521 case MAV_PARAM_TYPE_UINT32:
522 outValue = QVariant(paramUnion.param_uint32);
523 return true;
524 case MAV_PARAM_TYPE_INT32:
525 outValue = QVariant(paramUnion.param_int32);
526 return true;
527 default:
528 qCCritical(ParameterManagerLog) << "ParameterManager::_mavlinkParamUnionToVariant - unsupported MAV_PARAM_TYPE" << paramUnion.type;
529 return false;
530 }
531}
532
533void ParameterManager::_factRawValueUpdated(const QVariant &rawValue)
534{
535 Fact *const fact = qobject_cast<Fact*>(sender());
536 if (!fact) {
537 qCWarning(ParameterManagerLog) << "Internal error";
538 return;
539 }
540
541 if (fact->vehicleRebootRequired()) {
542 _vehicle->setRebootRequired();
543 if (_rebootMessageSuppressCount == 0) {
545 tr("Vehicle reboot required for changes to take effect. "
546 "Use the main status indicator in the toolbar to reboot."));
547 }
548 }
549
550 _mavlinkParamSet(fact->componentId(), fact->name(), fact->type(), rawValue);
551}
552
553void ParameterManager::_ftpDownloadComplete(const QString &fileName, const QString &errorMsg)
554{
555 bool continueWithDefaultParameterdownload = true;
556 bool immediateRetry = false;
557
558 _ftpDownloadInProgress = false;
559 (void) disconnect(_vehicle->ftpManager(), &FTPManager::downloadComplete, this, &ParameterManager::_ftpDownloadComplete);
560 (void) disconnect(_vehicle->ftpManager(), &FTPManager::commandProgress, this, &ParameterManager::_ftpDownloadProgress);
561
562 if (errorMsg.isEmpty()) {
563 qCDebug(ParameterManagerLog) << "ParameterManager::_ftpDownloadComplete : Parameter file received:" << fileName;
564 if (_parseParamFile(fileName)) {
565 qCDebug(ParameterManagerLog) << "ParameterManager::_ftpDownloadComplete : Parsed!";
566 _ftpParamsLoaded = true;
567 for (const int componentId : _heartbeatComponentIds) {
568 _sendParamRequestList(static_cast<uint8_t>(componentId));
569 }
570 return;
571 } else {
572 qCDebug(ParameterManagerLog) << "ParameterManager::_ftpDownloadComplete : Error in parameter file";
573 /* This should not happen... */
574 }
575 } else if (errorMsg.contains("File Not Found")) {
576 qCDebug(ParameterManagerLog) << "ParameterManager-ftp: No Parameterfile on vehicle - Start Conventional Parameter Download";
577 if (_initialRequestRetryCount == 0) {
578 immediateRetry = true;
579 }
580 } else if ((_loadProgress > 0.0001) && (_loadProgress < 0.01)) { /* FTP supported but too slow */
581 qCDebug(ParameterManagerLog) << "ParameterManager-ftp progress too slow - Start Conventional Parameter Download";
582 } else if (_initialRequestRetryCount == 1) {
583 qCDebug(ParameterManagerLog) << "ParameterManager-ftp: Too many retries - Start Conventional Parameter Download";
584 } else {
585 qCDebug(ParameterManagerLog) << "ParameterManager-ftp Retry:" << _initialRequestRetryCount;
586 continueWithDefaultParameterdownload = false;
587 }
588
589 if (continueWithDefaultParameterdownload) {
590 _tryftp = false;
591 _initialRequestRetryCount = 0;
592 /* If we receive "File not Found" this indicates that the vehicle does not support
593 * the parameter download via ftp. If we received this without retry, then we
594 * can immediately response with the conventional parameter download request, because
595 * we have no indication of communication link congestion.*/
596 if (immediateRetry) {
597 _paramRequestListTimeout();
598 } else {
599 _paramRequestListTimer.start();
600 }
601 } else {
602 _paramRequestListTimer.start();
603 }
604}
605
606void ParameterManager::_handleHeartbeat(int componentId)
607{
608 if ((componentId == MAV_COMP_ID_ALL) || (componentId == MAV_COMP_ID_AUTOPILOT1) ||
609 _heartbeatComponentIds.contains(componentId)) {
610 return;
611 }
612 _heartbeatComponentIds.insert(componentId);
613
614 // Components first heard after the param.pck load missed the requests sent when it completed
615 if (_ftpParamsLoaded) {
616 _sendParamRequestList(static_cast<uint8_t>(componentId));
617 }
618}
619
620void ParameterManager::_sendParamRequestList(uint8_t componentId)
621{
622 const SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
623 if (!sharedLink) {
624 return;
625 }
626
627 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Sending PARAM_REQUEST_LIST";
628
629 mavlink_message_t msg{};
630 mavlink_msg_param_request_list_pack_chan(MAVLinkProtocol::instance()->getSystemId(),
631 MAVLinkProtocol::getComponentId(), sharedLink->mavlinkChannel(), &msg,
632 _vehicle->id(), componentId);
633 (void) _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg);
634}
635
636void ParameterManager::_ftpDownloadProgress(float progress)
637{
638 qCDebug(ParameterManagerVerbose1Log) << "ParameterManager::_ftpDownloadProgress:" << progress;
639 _setLoadProgress(static_cast<double>(progress));
640 if (progress > 0.001) {
641 _paramRequestListTimer.stop();
642 }
643}
644
645void ParameterManager::_resetHashCheck()
646{
647 _hashCheckTimer.stop();
648 _hashCheckDone = false;
649}
650
652{
653 _resetHashCheck();
655 _refreshAllProgressActive = true;
656 _startParameterDownload(componentId);
657}
658
660{
661 _resetHashCheck();
662 _cacheOnlyHashCheck = true;
663
664 const SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
665 if (!sharedLink) {
667 return;
668 }
669
670 if (sharedLink->linkConfiguration()->isHighLatency() || _logReplay) {
671 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Cache-only hash check: high latency or log replay link, signalling failure";
673 return;
674 }
675
676 if (_vehicle->px4Firmware() && !_initialLoadComplete) {
677 _hashCheckTimer.start();
678 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Cache-only hash check: requesting _HASH_CHECK";
679 _requestHashCheck(MAV_COMP_ID_AUTOPILOT1);
680 } else {
681 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Cache-only hash check: not available, signalling failure";
683 }
684}
685
686void ParameterManager::_startParameterDownload(uint8_t componentId)
687{
688 const SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
689 if (!sharedLink) {
690 return;
691 }
692
693 if (sharedLink->linkConfiguration()->isHighLatency() || _logReplay) {
694 // These links don't load params
695 _parametersReady = true;
696 _missingParameters = true;
697 _initialLoadComplete = true;
698 _waitingForDefaultComponent = false;
699 emit parametersReadyChanged(_parametersReady);
700 emit missingParametersChanged(_missingParameters);
701 return;
702 }
703
704 if (_vehicle->px4Firmware() && !_initialLoadComplete && !_hashCheckDone) {
705 // PX4: Try _HASH_CHECK first to see if we can load from cache without a full parameter stream
706 _cacheOnlyHashCheck = false;
707 _hashCheckTimer.start();
708 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Requesting _HASH_CHECK before full parameter list";
709 const uint8_t hashCheckCompId = (componentId == MAV_COMP_ID_ALL)
710 ? static_cast<uint8_t>(MAV_COMP_ID_AUTOPILOT1)
711 : componentId;
712 _requestHashCheck(hashCheckCompId);
713 } else if (_tryftp && ((componentId == MAV_COMP_ID_ALL) || (componentId == MAV_COMP_ID_AUTOPILOT1))) {
714 if (_ftpDownloadInProgress) {
715 // A retry while the file is still transferring would disconnect the completion handler below
716 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Parameter file download already in progress";
717 _refreshAllProgressActive = false;
718 return;
719 }
720 if (!_initialLoadComplete) {
721 _paramRequestListTimer.start();
722 }
723 FTPManager *const ftpManager = _vehicle->ftpManager();
724 (void) connect(ftpManager, &FTPManager::downloadComplete, this, &ParameterManager::_ftpDownloadComplete);
725 // Other components may still be re-reading over the stream path; only their timer keeps them going
726 if (!_anyComponentWaiting()) {
727 _waitingParamTimeoutTimer.stop();
728 }
729 if (ftpManager->download(MAV_COMP_ID_AUTOPILOT1,
730 QStringLiteral("@PARAM/param.pck?withdefaults=1"),
731 QStandardPaths::writableLocation(QStandardPaths::TempLocation),
732 QStringLiteral("param.pck"),
733 false /* No filesize check */)) {
734 _ftpDownloadInProgress = true;
735 (void) connect(ftpManager, &FTPManager::commandProgress, this, &ParameterManager::_ftpDownloadProgress);
736 } else {
737 qCWarning(ParameterManagerLog) << "ParameterManager::_startParameterDownload FTPManager::download returned failure";
738 (void) disconnect(ftpManager, &FTPManager::downloadComplete, this, &ParameterManager::_ftpDownloadComplete);
739 _refreshAllProgressActive = false;
740 }
741 } else {
742 if (!_initialLoadComplete) {
743 _paramRequestListTimer.start();
744 }
745
746 // Reset index wait lists
747 for (int cid: _paramCountMap.keys()) {
748 // Add/Update all indices to the wait list, parameter index is 0-based
749 if ((componentId != MAV_COMP_ID_ALL) && (componentId != cid)) {
750 continue;
751 }
752 for (int waitingIndex = 0; waitingIndex < _paramCountMap[cid]; waitingIndex++) {
753 // This will add a new waiting index if needed and set the retry count for that index to 0
754 _waitingReadParamIndexMap[cid][waitingIndex] = 0;
755 }
756 }
757
758 _sendParamRequestList(componentId);
759 }
760
761 const QString what = (componentId == MAV_COMP_ID_ALL) ? "MAV_COMP_ID_ALL" : QString::number(componentId);
762 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Request to refresh all parameters for component ID:" << what;
763}
764
765int ParameterManager::_actualComponentId(int componentId) const
766{
767 if (componentId == defaultComponentId) {
768 componentId = _vehicle->defaultComponentId();
769 if (componentId == defaultComponentId) {
770 qCWarning(ParameterManagerLog) << _logVehiclePrefix(-1) << "Default component id not set";
771 }
772 }
773
774 return componentId;
775}
776
777void ParameterManager::refreshParameter(int componentId, const QString& paramName, bool notifyFailure)
778{
779 componentId = _actualComponentId(componentId);
780
781 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "refreshParameter - name:" << paramName;
782
783 _mavlinkParamRequestRead(componentId, paramName, -1, notifyFailure);
784}
785
787{
788 _rebootMessageSuppressCount++;
789}
790
792{
793 if (_rebootMessageSuppressCount == 0) {
794 qCWarning(ParameterManagerLog) << "unsuppressRebootMessage without matching suppressRebootMessage";
795 return;
796 }
797 _rebootMessageSuppressCount--;
798}
799
800void ParameterManager::refreshParametersPrefix(int componentId, const QString &namePrefix)
801{
802 componentId = _actualComponentId(componentId);
803 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "refreshParametersPrefix - name:" << namePrefix;
804
805 if (!_mapCompId2FactMap.contains(componentId)) {
806 return;
807 }
808 for (const QString &paramName: _mapCompId2FactMap[componentId].keys()) {
809 if (paramName.startsWith(namePrefix)) {
810 refreshParameter(componentId, paramName);
811 }
812 }
813}
814
815void ParameterManager::bulkRefresh(int componentId, const QStringList &names, bool notifyFailure)
816{
817 componentId = _actualComponentId(componentId);
818
819 if (!_mapCompId2FactMap.contains(componentId)) {
820 return;
821 }
822 const QMap<QString, Fact *> &factMap = _mapCompId2FactMap[componentId];
823 QStringList resolved;
824 QSet<QString> seen;
825 for (const QString &entry : names) {
826 if (entry.endsWith(QLatin1Char('*'))) {
827 const QString prefix = entry.chopped(1);
828 if (prefix.isEmpty()) {
829 qCWarning(ParameterManagerLog) << "bulkRefresh: ignoring bare '*' entry";
830 continue;
831 }
832 for (auto it = factMap.cbegin(); it != factMap.cend(); ++it) {
833 if (it.key().startsWith(prefix) && !seen.contains(it.key())) {
834 seen.insert(it.key());
835 resolved.append(it.key());
836 }
837 }
838 } else if (factMap.contains(entry)) {
839 if (!seen.contains(entry)) {
840 seen.insert(entry);
841 resolved.append(entry);
842 }
843 } else {
844 qCWarning(ParameterManagerLog) << "bulkRefresh: unknown param name (skipped):" << entry;
845 }
846 }
847
848 if (resolved.isEmpty()) {
849 return;
850 }
851
852 qCDebug(ParameterManagerLog) << "bulkRefresh: resolved" << resolved.count() << "params";
853 new BulkRefreshJob(
854 this, componentId, resolved, notifyFailure,
855 [this, componentId](const QString &name) {
856 _mavlinkParamRequestRead(componentId, name, -1, false /* notifyFailure */);
857 },
858 this);
859}
860
861bool ParameterManager::parameterExists(int componentId, const QString &paramName) const
862{
863 bool ret = false;
864
865 componentId = _actualComponentId(componentId);
866 if (_mapCompId2FactMap.contains(componentId)) {
867 ret = _mapCompId2FactMap[componentId].contains(_remapParamNameToVersion(paramName));
868 }
869
870 return ret;
871}
872
873Fact *ParameterManager::getParameter(int componentId, const QString &paramName)
874{
875 componentId = _actualComponentId(componentId);
876
877 const QString mappedParamName = _remapParamNameToVersion(paramName);
878 if (!_mapCompId2FactMap.contains(componentId) || !_mapCompId2FactMap[componentId].contains(mappedParamName)) {
879 qgcApp()->reportMissingParameter(componentId, mappedParamName);
880 return &_defaultFact;
881 }
882
883 return _mapCompId2FactMap[componentId][mappedParamName];
884}
885
886QStringList ParameterManager::parameterNames(int componentId) const
887{
888 QStringList names;
889
890 const int compId = _actualComponentId(componentId);
891 const QMap<QString, Fact*> &factMap = _mapCompId2FactMap[compId];
892 for (const QString &paramName: factMap.keys()) {
893 names << paramName;
894 }
895
896 return names;
897}
898
899bool ParameterManager::_fillIndexBatchQueue(bool waitingParamTimeout)
900{
901 if (!_indexBatchQueueActive) {
902 return false;
903 }
904
905 if (waitingParamTimeout) {
906 // We timed out, clear the queue and try again
907 qCDebug(ParameterManagerLog) << "Refilling index based batch queue due to timeout";
908 _indexBatchQueue.clear();
909 } else {
910 qCDebug(ParameterManagerLog) << "Refilling index based batch queue due to received parameter";
911 }
912
913 for (const int componentId: _waitingReadParamIndexMap.keys()) {
914 if (_waitingReadParamIndexMap[componentId].count()) {
915 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "_waitingReadParamIndexMap count" << _waitingReadParamIndexMap[componentId].count();
916 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "_waitingReadParamIndexMap (index, retry count)" << _waitingReadParamIndexMap[componentId];
917 }
918
919 for (const int paramIndex: _waitingReadParamIndexMap[componentId].keys()) {
920 if (_indexBatchQueue.contains(qMakePair(componentId, paramIndex))) {
921 // Don't add more than once
922 continue;
923 }
924
925 if (_indexBatchQueue.count() >= kIndexBatchMaxOutstanding) {
926 break;
927 }
928
929 _waitingReadParamIndexMap[componentId][paramIndex]++; // Bump retry count
930 if (_disableAllRetries || (_waitingReadParamIndexMap[componentId][paramIndex] > _maxInitialLoadRetrySingleParam)) {
931 // Give up on this index
932 _failedReadParamIndexMap[componentId] << paramIndex;
933 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Giving up on (paramIndex:" << paramIndex << "retryCount:" << _waitingReadParamIndexMap[componentId][paramIndex] << ")";
934 (void) _waitingReadParamIndexMap[componentId].remove(paramIndex);
935 } else {
936 // Retry again
937 _indexBatchQueue.append(qMakePair(componentId, paramIndex));
938 _sendParamRequestReadIndex(componentId, paramIndex);
939 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Read re-request for (paramIndex:" << paramIndex << "retryCount:" << _waitingReadParamIndexMap[componentId][paramIndex] << ")";
940 }
941 }
942 }
943
944 return (!_indexBatchQueue.isEmpty());
945}
946
947void ParameterManager::_waitingParamTimeout()
948{
949 if (_logReplay) {
950 return;
951 }
952
953 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "_waitingParamTimeout after" << _waitingParamTimeoutTimer.interval() << "ms";
954
955 // Now that we have timed out for possibly the first time we can activate the index batch queue
956 _indexBatchQueueActive = true;
957
958 _giveUpOnUnresponsiveComponents();
959
960 // First check for any missing parameters from the initial index based load
961 bool paramsRequested = _fillIndexBatchQueue(true /* waitingParamTimeout */);
962 if (!paramsRequested && !_waitingForDefaultComponent && !_mapCompId2FactMap.contains(_vehicle->defaultComponentId())) {
963 // Initial load is complete but we still don't have any default component params. Wait one more cycle to see if the
964 // any show up.
965 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Restarting _waitingParamTimeoutTimer - still don't have default component params" << _vehicle->defaultComponentId();
966 _waitingParamTimeoutTimer.start();
967 _waitingForDefaultComponent = true;
968 return;
969 }
970 _waitingForDefaultComponent = false;
971
972 _checkInitialLoadComplete();
973 // Giving up on the last waiting index produces no PARAM_VALUE, so the bar must be recomputed here too
974 _updateProgressBar();
975
976 if (paramsRequested) {
977 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Restarting _waitingParamTimeoutTimer - re-request";
978 _waitingParamTimeoutTimer.start();
979 }
980}
981
982void ParameterManager::_giveUpOnUnresponsiveComponents()
983{
984 const int defaultCompId = _vehicle->defaultComponentId();
985
986 for (const int componentId: _waitingReadParamIndexMap.keys()) {
987 if (componentId == defaultCompId) {
988 continue;
989 }
990
991 const int outstanding = static_cast<int>(std::count_if(_indexBatchQueue.cbegin(), _indexBatchQueue.cend(),
992 [componentId](const QPair<int, int> &entry) { return entry.first == componentId; }));
993 if ((outstanding < kUnresponsiveMinOutstanding) || (_paramValuesReceivedThisCycle.value(componentId, 0) != 0)) {
994 continue;
995 }
996
997 if (++_silentCycleCount[componentId] < kUnresponsiveSilentCycles) {
998 continue;
999 }
1000
1001 const QList<int> remaining = _waitingReadParamIndexMap[componentId].keys();
1002 qCWarning(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Component unresponsive for" << kUnresponsiveSilentCycles
1003 << "cycles, giving up on remaining parameters:" << remaining.count();
1004 _failedReadParamIndexMap[componentId] << remaining;
1005 _waitingReadParamIndexMap[componentId].clear();
1006 (void) _indexBatchQueue.removeIf([componentId](const QPair<int, int> &entry) { return entry.first == componentId; });
1007 }
1008
1009 _paramValuesReceivedThisCycle.clear();
1010}
1011
1012void ParameterManager::_requestHashCheck(uint8_t componentId)
1013{
1014 const SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
1015 if (!sharedLink) {
1016 return;
1017 }
1018
1019 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) << "Sending PARAM_REQUEST_READ for _HASH_CHECK";
1020
1021 char paramId[MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN + 1] = {};
1022 (void) strncpy(paramId, "_HASH_CHECK", MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN);
1023
1024 mavlink_message_t msg{};
1025 (void) mavlink_msg_param_request_read_pack_chan(MAVLinkProtocol::instance()->getSystemId(),
1026 MAVLinkProtocol::getComponentId(), sharedLink->mavlinkChannel(),
1027 &msg, _vehicle->id(), componentId, paramId, -1);
1028
1029 (void) _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg);
1030}
1031
1032void ParameterManager::_sendParamRequestReadIndex(int componentId, int paramIndex)
1033{
1034 const SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
1035 if (!sharedLink) {
1036 return;
1037 }
1038
1039 // Packer copies the full fixed-width field, so a short literal would read out of bounds
1040 char paramId[MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN + 1] = {};
1041 mavlink_message_t msg{};
1042 (void) mavlink_msg_param_request_read_pack_chan(
1043 MAVLinkProtocol::instance()->getSystemId(), MAVLinkProtocol::getComponentId(), sharedLink->mavlinkChannel(),
1044 &msg, _vehicle->id(), static_cast<uint8_t>(componentId), paramId, static_cast<int16_t>(paramIndex));
1045 (void) _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg);
1046}
1047
1048void ParameterManager::_mavlinkParamRequestRead(int componentId, const QString &paramName, int paramIndex, bool notifyFailure)
1049{
1050 auto paramRequestReadEncoder = [this, componentId, paramName, paramIndex](quint32 /*systemId*/, uint8_t channel,
1051 mavlink_message_t* message) -> void {
1052 char paramId[MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN + 1] = {};
1053 (void) strncpy(paramId, paramName.toLocal8Bit().constData(), MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN);
1054
1055 (void) mavlink_msg_param_request_read_pack_chan(MAVLinkProtocol::instance()->getSystemId(), // QGC system id
1056 MAVLinkProtocol::getComponentId(), // QGC component id
1057 channel, message, _vehicle->id(),
1058 static_cast<uint8_t>(componentId), paramId,
1059 static_cast<int16_t>(paramIndex));
1060 };
1061
1062 auto checkForCorrectParamValue = [componentId, paramName, paramIndex](const mavlink_message_t &message) -> bool {
1063 if (message.compid != componentId) {
1064 return false;
1065 }
1066
1067 mavlink_param_value_t param_value{};
1068 mavlink_msg_param_value_decode(&message, &param_value);
1069
1070 // This will null terminate the name string
1071 char parameterNameWithNull[MAVLINK_MSG_PARAM_VALUE_FIELD_PARAM_ID_LEN + 1] = {};
1072 (void) strncpy(parameterNameWithNull, param_value.param_id, MAVLINK_MSG_PARAM_VALUE_FIELD_PARAM_ID_LEN);
1073 const QString parameterName(parameterNameWithNull);
1074
1075 // Check that this is for the parameter we requested
1076 if (paramIndex != -1) {
1077 // Index based request
1078 if (param_value.param_index != paramIndex) {
1079 return false;
1080 }
1081 } else {
1082 // Name based request
1083 if (parameterName != paramName) {
1084 return false;
1085 }
1086 }
1087
1088 return true;
1089 };
1090
1091 auto checkForParamError = [componentId, paramName, paramIndex](const mavlink_message_t &message) -> bool {
1092 if (message.compid != componentId) {
1093 return false;
1094 }
1095
1096 mavlink_param_error_t paramError{};
1097 mavlink_msg_param_error_decode(&message, &paramError);
1098
1099 char paramId[MAVLINK_MSG_PARAM_ERROR_FIELD_PARAM_ID_LEN + 1] = {};
1100 (void) strncpy(paramId, paramError.param_id, MAVLINK_MSG_PARAM_ERROR_FIELD_PARAM_ID_LEN);
1101
1102 if (paramIndex != -1) {
1103 return paramError.param_index == paramIndex;
1104 } else {
1105 return QString(paramId) == paramName;
1106 }
1107 };
1108
1109 // State Machine:
1110 // Send PARAM_REQUEST_READ - 2 retries after initial attempt
1111 // Wait for PARAM_VALUE ack or PARAM_ERROR rejection
1112 //
1113 // timeout:
1114 // Back up to PARAM_REQUEST_READ for retries
1115 //
1116 // error (PARAM_ERROR or retries exhausted):
1117 // Notify user of failure
1118
1119 // Create states
1120 auto stateMachine = new QGCStateMachine(QStringLiteral("PARAM_REQUEST_READ"), vehicle(), this);
1121 auto sendParamRequestReadState = new SendMavlinkMessageState(stateMachine, paramRequestReadEncoder, kParamRequestReadRetryCount);
1122 auto waitAckState = new WaitForParamResponseState(stateMachine, _waitForParamValueAckMs, checkForCorrectParamValue, checkForParamError);
1123 auto userNotifyState = new FunctionState(QStringLiteral("User notify"), stateMachine, [waitAckState, paramName, this, componentId]() {
1124 const QString errorDetail = waitAckState->lastParamErrorString();
1125 const QString msg = errorDetail.isEmpty()
1126 ? QStringLiteral("Parameter read failed: param: %1 %2").arg(paramName, _vehicleAndComponentString(componentId))
1127 : QStringLiteral("Parameter read failed: param: %1 %2 - %3").arg(paramName, _vehicleAndComponentString(componentId), errorDetail);
1129 });
1130 auto logSuccessState = new FunctionState(QStringLiteral("Log success"), stateMachine, [this, componentId, paramName, paramIndex]() {
1131 qCDebug(ParameterManagerLog) << "PARAM_REQUEST_READ succeeded: name:" << paramName << "index" << paramIndex << _vehicleAndComponentString(componentId);
1132 emit _paramRequestReadSuccess(componentId, paramName, paramIndex);
1133 });
1134 auto logFailureState = new FunctionState(QStringLiteral("Log failure"), stateMachine, [this, componentId, paramName, paramIndex]() {
1135 qCDebug(ParameterManagerLog) << "PARAM_REQUEST_READ failed: param:" << paramName << "index" << paramIndex << _vehicleAndComponentString(componentId);
1136 emit _paramRequestReadFailure(componentId, paramName, paramIndex);
1137 });
1138 auto finalState = new QGCFinalState(stateMachine);
1139
1140 // Successful state machine transitions
1141 stateMachine->setInitialState(sendParamRequestReadState);
1142 sendParamRequestReadState->addThisTransition(&QGCState::advance, waitAckState);
1143 waitAckState->addThisTransition (&QGCState::advance, logSuccessState);
1144 logSuccessState->addThisTransition (&QGCState::advance, finalState);
1145
1146 // Retry transitions (timeout path)
1147 waitAckState->addTransition(waitAckState, &WaitStateBase::timeout, sendParamRequestReadState);
1148
1149 // PARAM_ERROR path (definitive rejection - no retries)
1150 waitAckState->addThisTransition(&QGCState::error, logFailureState);
1151
1152 // Error transitions (retries exhausted)
1153 sendParamRequestReadState->addThisTransition(&QGCState::error, logFailureState);
1154
1155 // Error state branching transitions
1156 if (notifyFailure) {
1157 logFailureState->addThisTransition (&QGCState::advance, userNotifyState);
1158 } else {
1159 logFailureState->addThisTransition (&QGCState::advance, finalState);
1160 }
1161 userNotifyState->addThisTransition (&QGCState::advance, finalState);
1162
1163 qCDebug(ParameterManagerLog) << "Starting state machine for PARAM_REQUEST_READ on: " << paramName << _vehicleAndComponentString(componentId);
1164 stateMachine->start();
1165}
1166
1167void ParameterManager::_writeLocalParamCache(quint32 vehicleId, int componentId)
1168{
1169 CacheMapName2ParamTypeVal cacheMap;
1170
1171 for (const QString &paramName: _mapCompId2FactMap[componentId].keys()) {
1172 const Fact *const fact = _mapCompId2FactMap[componentId][paramName];
1173 cacheMap[paramName] = ParamTypeVal(fact->type(), fact->rawValue());
1174 }
1175
1176 QFile cacheFile(parameterCacheFile(vehicleId, componentId));
1177 if (cacheFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
1178 QDataStream ds(&cacheFile);
1179 ds << cacheMap;
1180 qCDebug(ParameterManagerLog) << "Parameter cache written" << cacheFile.fileName() << "paramCount:" << cacheMap.count();
1181 } else {
1182 qCWarning(ParameterManagerLog) << "Failed to open cache file for writing" << cacheFile.fileName();
1183 }
1184}
1185
1187{
1188 return QDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/ParamCache"));
1189}
1190
1191QString ParameterManager::parameterCacheFile(quint32 vehicleId, int componentId)
1192{
1193 return parameterCacheDir().filePath(QStringLiteral("%1_%2.v2").arg(vehicleId).arg(componentId));
1194}
1195
1196void ParameterManager::_tryCacheHashLoad(quint32 vehicleId, int componentId, const QVariant& hashValue)
1197{
1198 qCDebug(ParameterManagerLog) << "Attemping load from cache";
1199
1200 /* The datastructure of the cache table */
1201 CacheMapName2ParamTypeVal cacheMap;
1202 QFile cacheFile(parameterCacheFile(vehicleId, componentId));
1203 if (!cacheFile.exists()) {
1204 qCDebug(ParameterManagerLog) << "Parameter cache usage failed - No parameter cache file";
1205 if (!_hashCheckDone) {
1206 _hashCheckDone = true;
1207 if (_cacheOnlyHashCheck) {
1208 qCDebug(ParameterManagerLog) << "Cache-only hash check: no cache file, signalling failure";
1209 emit cacheCheckOnlyFailed();
1210 return;
1211 }
1212 // Standalone hash check path — fall back to FTP / PARAM_REQUEST_LIST
1213 _startParameterDownload(MAV_COMP_ID_ALL);
1214 }
1215 // If already in PARAM_REQUEST_LIST flow, just let the stream continue
1216 return;
1217 }
1218 (void) cacheFile.open(QIODevice::ReadOnly);
1219
1220 /* Deserialize the parameter cache table */
1221 QDataStream ds(&cacheFile);
1222 ds >> cacheMap;
1223
1224 /* compute the crc of the local cache to check against the remote */
1225 uint32_t crc32_value = 0;
1226 for (const QString &name: cacheMap.keys()) {
1227 const ParamTypeVal &paramTypeVal = cacheMap[name];
1228 const FactMetaData::ValueType_t factType = static_cast<FactMetaData::ValueType_t>(paramTypeVal.first);
1229
1230 if (_vehicle->compInfoManager()->compInfoParam(MAV_COMP_ID_AUTOPILOT1)->factMetaDataForName(name, factType)->volatileValue()) {
1231 // Does not take part in CRC
1232 qCDebug(ParameterManagerLog) << "Volatile parameter" << name;
1233 } else {
1234 const void *const vdat = paramTypeVal.second.constData();
1235 const FactMetaData::ValueType_t cacheFactType = static_cast<FactMetaData::ValueType_t>(paramTypeVal.first);
1236 crc32_value = QGC::crc32(reinterpret_cast<const uint8_t *>(qPrintable(name)), name.length(), crc32_value);
1237 crc32_value = QGC::crc32(static_cast<const uint8_t *>(vdat), FactMetaData::typeToSize(cacheFactType), crc32_value);
1238 }
1239 }
1240
1241 /* if the two param set hashes match, just load from the disk */
1242 if (crc32_value == hashValue.toUInt()) {
1243 _hashCheckDone = true;
1244 _paramRequestListTimer.stop();
1245 qCDebug(ParameterManagerLog) << "Parameters loaded from cache" << qPrintable(QFileInfo(cacheFile).absoluteFilePath());
1246
1247 const int count = cacheMap.count();
1248 int index = 0;
1249 for (const QString &name: cacheMap.keys()) {
1250 const ParamTypeVal &paramTypeVal = cacheMap[name];
1251 const FactMetaData::ValueType_t factType = static_cast<FactMetaData::ValueType_t>(paramTypeVal.first);
1252 const MAV_PARAM_TYPE mavParamType = factTypeToMavType(factType);
1253 _handleParamValue(componentId, name, count, index++, mavParamType, paramTypeVal.second);
1254 }
1255
1256 const SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
1257 if (sharedLink) {
1258 mavlink_param_set_t p{};
1259 mavlink_param_union_t union_value{};
1260
1261 // Return the hash value to notify we don't want any more updates
1262 p.param_type = MAV_PARAM_TYPE_UINT32;
1263 (void) strncpy(p.param_id, "_HASH_CHECK", sizeof(p.param_id));
1264 union_value.param_uint32 = crc32_value;
1265 p.param_value = union_value.param_float;
1266 p.target_component = static_cast<uint8_t>(componentId);
1267
1268 mavlink_message_t msg{};
1269 (void) mavlink_msg_param_set_pack_chan(MAVLinkProtocol::instance()->getSystemId(),
1270 MAVLinkProtocol::getComponentId(), sharedLink->mavlinkChannel(),
1271 &msg, _vehicle->id(), p.target_component, p.param_id, p.param_value,
1272 p.param_type);
1273 (void) _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg);
1274 }
1275
1276 // Give the user some feedback things loaded properly
1277 QVariantAnimation *const ani = new QVariantAnimation(this);
1278 ani->setEasingCurve(QEasingCurve::OutCubic);
1279 ani->setStartValue(0.0);
1280 ani->setEndValue(1.0);
1281 ani->setDuration(750);
1282
1283 (void) connect(ani, &QVariantAnimation::valueChanged, this, [this](const QVariant &value) {
1284 _setLoadProgress(value.toDouble());
1285 });
1286
1287 // Hide 500ms after animation finishes
1288 connect(ani, &QVariantAnimation::finished, this, [this] {
1289 QTimer::singleShot(500, this, [this] {
1290 _setLoadProgress(0);
1291 });
1292 });
1293
1294 ani->start(QAbstractAnimation::DeleteWhenStopped);
1295 } else {
1296 qCDebug(ParameterManagerLog) << "Parameters cache match failed" << qPrintable(QFileInfo(cacheFile).absoluteFilePath());
1297 if (ParameterManagerDebugCacheFailureLog().isDebugEnabled()) {
1298 _debugCacheCRC[componentId] = true;
1299 _debugCacheMap[componentId] = cacheMap;
1300 for (const QString &name: cacheMap.keys()) {
1301 _debugCacheParamSeen[componentId][name] = false;
1302 }
1303 QGC::showAppMessage(tr("Parameter cache CRC match failed"));
1304 }
1305 if (!_hashCheckDone) {
1306 _hashCheckDone = true;
1307 if (_cacheOnlyHashCheck) {
1308 qCDebug(ParameterManagerLog) << "Cache-only hash check: CRC mismatch, signalling failure";
1309 emit cacheCheckOnlyFailed();
1310 return;
1311 }
1312 // Standalone hash check path — fall back to FTP / PARAM_REQUEST_LIST
1313 _startParameterDownload(MAV_COMP_ID_ALL);
1314 }
1315 // If already in PARAM_REQUEST_LIST flow, just let the stream continue
1316 }
1317}
1318
1319void ParameterManager::writeParametersToStream(QTextStream &stream) const
1320{
1321 stream << "# Onboard parameters for Vehicle " << _vehicle->id() << "\n";
1322 stream << "#\n";
1323
1324 stream << "# Stack: " << QGCMAVLink::firmwareClassToCanonicalString(QGCMAVLink::firmwareClass(_vehicle->firmwareType())) << "\n";
1325 stream << "# Vehicle: " << QGCMAVLink::vehicleClassToCanonicalString(QGCMAVLink::vehicleClass(_vehicle->vehicleType())) << "\n";
1326 stream << "# Version: "
1327 << _vehicle->firmwareMajorVersion() << "."
1328 << _vehicle->firmwareMinorVersion() << "."
1329 << _vehicle->firmwarePatchVersion() << " "
1330 << _vehicle->firmwareVersionTypeString() << "\n";
1331 stream << "# Git Revision: " << _vehicle->gitHash() << "\n";
1332
1333 stream << "#\n";
1334 stream << "# Vehicle-Id Component-Id Name Value Type\n";
1335
1336 for (const int componentId: _mapCompId2FactMap.keys()) {
1337 for (const QString &paramName: _mapCompId2FactMap[componentId].keys()) {
1338 const Fact *const fact = _mapCompId2FactMap[componentId][paramName];
1339 if (fact) {
1340 stream << _vehicle->id() << "\t" << componentId << "\t" << paramName << "\t" << fact->rawValueStringFullPrecision() << "\t" << QStringLiteral("%1").arg(factTypeToMavType(fact->type())) << "\n";
1341 } else {
1342 qCWarning(ParameterManagerLog) << "Internal error: missing fact";
1343 }
1344 }
1345 }
1346
1347 stream.flush();
1348}
1349
1351{
1352 switch (factType) {
1354 return MAV_PARAM_TYPE_UINT8;
1356 return MAV_PARAM_TYPE_INT8;
1358 return MAV_PARAM_TYPE_UINT16;
1360 return MAV_PARAM_TYPE_INT16;
1362 return MAV_PARAM_TYPE_UINT32;
1364 return MAV_PARAM_TYPE_UINT64;
1366 return MAV_PARAM_TYPE_INT64;
1368 return MAV_PARAM_TYPE_REAL32;
1370 return MAV_PARAM_TYPE_REAL64;
1371 default:
1372 qCWarning(ParameterManagerLog) << "Unsupported fact type" << factType;
1373 [[fallthrough]];
1375 return MAV_PARAM_TYPE_INT32;
1376 }
1377}
1378
1380{
1381 switch (mavType) {
1382 case MAV_PARAM_TYPE_UINT8:
1384 case MAV_PARAM_TYPE_INT8:
1386 case MAV_PARAM_TYPE_UINT16:
1388 case MAV_PARAM_TYPE_INT16:
1390 case MAV_PARAM_TYPE_UINT32:
1392 case MAV_PARAM_TYPE_UINT64:
1394 case MAV_PARAM_TYPE_INT64:
1396 case MAV_PARAM_TYPE_REAL32:
1398 case MAV_PARAM_TYPE_REAL64:
1400 default:
1401 qCWarning(ParameterManagerLog) << "Unsupported mav param type" << mavType;
1402 [[fallthrough]];
1403 case MAV_PARAM_TYPE_INT32:
1405 }
1406}
1407
1408void ParameterManager::_checkInitialLoadComplete()
1409{
1410 if (_initialLoadComplete) {
1411 _checkOtherComponentsLoadComplete();
1412 return;
1413 }
1414
1415 // Only the default component gates readiness. Other components (e.g. DroneCAN nodes bridged by PX4) keep
1416 // loading in the background and are reported by _checkOtherComponentsLoadComplete when they finish.
1417 const int defaultCompId = _vehicle->defaultComponentId();
1418 if (_waitingReadParamIndexMap.contains(defaultCompId) && !_waitingReadParamIndexMap[defaultCompId].isEmpty()) {
1419 return;
1420 }
1421
1422 if (!_mapCompId2FactMap.contains(defaultCompId)) {
1423 // No default component params yet, not done yet
1424 return;
1425 }
1426
1427 // We aren't waiting for any more initial parameter updates, initial parameter loading is complete
1428 _initialLoadComplete = true;
1429 _refreshAllProgressActive = false;
1430 _setLoadProgress(0.0);
1431
1432 // Parameter cache crc failure debugging
1433 for (const int componentId: _debugCacheParamSeen.keys()) {
1434 if (!_logReplay && _debugCacheCRC.contains(componentId) && _debugCacheCRC[componentId]) {
1435 for (const QString &paramName: _debugCacheParamSeen[componentId].keys()) {
1436 if (!_debugCacheParamSeen[componentId][paramName]) {
1437 qCDebug(ParameterManagerLog) << "Parameter in cache but not on vehicle componentId:Name" << componentId << paramName;
1438 }
1439 }
1440 }
1441 }
1442 _debugCacheCRC.clear();
1443
1444 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Initial load complete";
1445
1446 _missingParameters = !_failedReadParamIndexMap.value(defaultCompId).isEmpty();
1447 if (_missingParameters) {
1448 QStringList failedIndices;
1449 for (const int paramIndex: _failedReadParamIndexMap[defaultCompId]) {
1450 failedIndices.append(QString::number(paramIndex));
1451 }
1452 qCWarning(ParameterManagerLog) << _logVehiclePrefix(defaultCompId) << "The following parameter indices could not be loaded after the maximum number of retries:" << failedIndices.join(QStringLiteral(", "));
1453 const QString errorMsg = tr("%1 was unable to retrieve the full set of parameters from vehicle %2. "
1454 "This will cause %1 to be unable to display its full user interface. "
1455 "If you are using modified firmware, you may need to resolve any vehicle startup errors to resolve the issue. "
1456 "If you are using standard firmware, you may need to upgrade to a newer version to resolve the issue.").arg(QCoreApplication::applicationName()).arg(_vehicle->id());
1457 qCDebug(ParameterManagerLog) << errorMsg;
1458 QGC::showAppMessage(errorMsg);
1459 }
1460
1461 // Signal load complete
1462 _parametersReady = true;
1463 _vehicle->autopilotPlugin()->parametersReadyPreChecks();
1464 emit parametersReadyChanged(true);
1465 emit missingParametersChanged(_missingParameters);
1466
1467 _checkOtherComponentsLoadComplete();
1468}
1469
1470bool ParameterManager::_anyComponentWaiting() const
1471{
1472 for (auto it = _waitingReadParamIndexMap.cbegin(); it != _waitingReadParamIndexMap.cend(); ++it) {
1473 if (!it.value().isEmpty()) {
1474 return true;
1475 }
1476 }
1477 return false;
1478}
1479
1480void ParameterManager::_checkOtherComponentsLoadComplete()
1481{
1482 if (_otherComponentsReported) {
1483 return;
1484 }
1485
1486 if (_anyComponentWaiting()) {
1487 return;
1488 }
1489
1490 const int defaultCompId = _vehicle->defaultComponentId();
1491 QStringList failedIndices;
1492 QStringList failedComponentIds;
1493 for (const int componentId: _failedReadParamIndexMap.keys()) {
1494 if ((componentId == defaultCompId) || _failedReadParamIndexMap[componentId].isEmpty()) {
1495 continue;
1496 }
1497 failedComponentIds.append(QString::number(componentId));
1498 for (const int paramIndex: _failedReadParamIndexMap[componentId]) {
1499 failedIndices.append(QStringLiteral("%1:%2").arg(componentId).arg(paramIndex));
1500 }
1501 }
1502 if (failedComponentIds.isEmpty()) {
1503 return;
1504 }
1505 _otherComponentsReported = true;
1506
1507 qCWarning(ParameterManagerLog) << _logVehiclePrefix(-1) << "The following parameter indices could not be loaded after the maximum number of retries:" << failedIndices.join(QStringLiteral(", "));
1508 QString vehicleIdPrefix;
1509 if (MultiVehicleManager::instance()->vehicles()->count() > 1) {
1510 vehicleIdPrefix = tr("Vehicle %1: ").arg(_vehicle->id());
1511 }
1512 const QString errorMsg = vehicleIdPrefix + tr("%1 was unable to retrieve the full set of parameters from component(s) %2.").arg(QCoreApplication::applicationName(), failedComponentIds.join(QStringLiteral(", ")));
1513 qCDebug(ParameterManagerLog) << errorMsg;
1514 QGC::showAppMessage(errorMsg);
1515}
1516
1517void ParameterManager::_hashCheckTimeout()
1518{
1519 _hashCheckDone = true;
1520 if (_cacheOnlyHashCheck) {
1521 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "_HASH_CHECK timed out in cache-only mode, signalling failure";
1522 emit cacheCheckOnlyFailed();
1523 return;
1524 }
1525 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "_HASH_CHECK timed out, falling back to parameter download";
1526 _startParameterDownload(MAV_COMP_ID_ALL);
1527}
1528
1529void ParameterManager::_paramRequestListTimeout()
1530{
1531 if (_logReplay) {
1532 // Signal load complete
1533 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "_paramRequestListTimeout (log replay): Signalling load complete";
1534 _initialLoadComplete = true;
1535 _missingParameters = false;
1536 _parametersReady = true;
1537 _vehicle->autopilotPlugin()->parametersReadyPreChecks();
1538 emit parametersReadyChanged(true);
1539 emit missingParametersChanged(_missingParameters);
1540 return;
1541 }
1542
1543 if (!_disableAllRetries && (++_initialRequestRetryCount <= _maxInitialRequestListRetry)) {
1544 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Retrying initial parameter request list";
1545 _startParameterDownload(MAV_COMP_ID_ALL);
1546 return;
1547 }
1548
1549 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) << "Initial parameter request list retries exhausted, giving up";
1550 if (!_vehicle->genericFirmware()) {
1551 const QString errorMsg = tr("Vehicle %1 did not respond to request for parameters. "
1552 "This will cause %2 to be unable to display its full user interface.").arg(_vehicle->id()).arg(QCoreApplication::applicationName());
1553 qCWarning(ParameterManagerLog) << errorMsg;
1554 QGC::showAppMessage(errorMsg);
1555 }
1557}
1558
1559QString ParameterManager::_remapParamNameToVersion(const QString &paramName) const
1560{
1561 static const QString noRemapPrefix = QStringLiteral("noremap.");
1562 if (paramName.startsWith(noRemapPrefix)) {
1563 return paramName.mid(noRemapPrefix.length());
1564 }
1565
1566 const int majorVersion = _vehicle->firmwareMajorVersion();
1567 const int minorVersion = _vehicle->firmwareMinorVersion();
1568
1569 if (majorVersion == Vehicle::versionNotSetValue) {
1570 // Vehicle version unknown
1571 return paramName;
1572 }
1573
1574 const FirmwarePlugin::remapParamNameMajorVersionMap_t &majorVersionRemap = _vehicle->firmwarePlugin()->paramNameRemapMajorVersionMap();
1575 if (!majorVersionRemap.contains(majorVersion)) {
1576 // No mapping for this major version
1577 qCDebug(ParameterManagerVerbose1Log) << "_remapParamNameToVersion: no major version mapping";
1578 return paramName;
1579 }
1580
1581 const FirmwarePlugin::remapParamNameMinorVersionRemapMap_t &remapMinorVersion = majorVersionRemap[majorVersion];
1582 // We must map backwards from the highest known minor version to one above the vehicle's minor version
1583 QString mappedParamName = paramName;
1584 for (int currentMinorVersion = _vehicle->firmwarePlugin()->remapParamNameHigestMinorVersionNumber(majorVersion); currentMinorVersion>minorVersion; currentMinorVersion--) {
1585 if (remapMinorVersion.contains(currentMinorVersion)) {
1586 const FirmwarePlugin::remapParamNameMap_t &remap = remapMinorVersion[currentMinorVersion];
1587 if (remap.contains(mappedParamName)) {
1588 const QString toParamName = remap[mappedParamName];
1589 qCDebug(ParameterManagerLog) << "_remapParamNameToVersion: remapped currentMinor:from:to" << currentMinorVersion << mappedParamName << toParamName;
1590 mappedParamName = toParamName;
1591 }
1592 }
1593 }
1594
1595 return mappedParamName;
1596}
1597
1598void ParameterManager::_loadOfflineEditingParams()
1599{
1600 const QString paramFilename = _vehicle->firmwarePlugin()->offlineEditingParamFile(_vehicle);
1601 if (paramFilename.isEmpty()) {
1602 return;
1603 }
1604
1605 QFile paramFile(paramFilename);
1606 if (!paramFile.open(QFile::ReadOnly)) {
1607 qCWarning(ParameterManagerLog) << "Unable to open offline editing params file" << paramFilename;
1608 return;
1609 }
1610
1611 QTextStream paramStream(&paramFile);
1612 while (!paramStream.atEnd()) {
1613 const QString line = paramStream.readLine();
1614 if (line.trimmed().isEmpty() || line.startsWith("#")) {
1615 continue;
1616 }
1617
1618 const QStringList paramData = line.split("\t");
1619 if (paramData.count() != 5) {
1620 qCWarning(ParameterManagerLog) << "Skipping malformed offline editing param line" << line;
1621 continue;
1622 }
1623
1624 const int offlineDefaultComponentId = paramData.at(1).toInt();
1625 _vehicle->setOfflineEditingDefaultComponentId(offlineDefaultComponentId);
1626 const QString paramName = paramData.at(2);
1627 const QString valStr = paramData.at(3);
1628 const MAV_PARAM_TYPE paramType = static_cast<MAV_PARAM_TYPE>(paramData.at(4).toUInt());
1629
1630 QVariant paramValue;
1631 switch (paramType) {
1632 case MAV_PARAM_TYPE_REAL32:
1633 paramValue = QVariant(valStr.toFloat());
1634 break;
1635 case MAV_PARAM_TYPE_UINT32:
1636 paramValue = QVariant(valStr.toUInt());
1637 break;
1638 case MAV_PARAM_TYPE_UINT16:
1639 paramValue = QVariant((quint16)valStr.toUInt());
1640 break;
1641 case MAV_PARAM_TYPE_INT16:
1642 paramValue = QVariant((qint16)valStr.toInt());
1643 break;
1644 case MAV_PARAM_TYPE_UINT8:
1645 paramValue = QVariant((quint8)valStr.toUInt());
1646 break;
1647 case MAV_PARAM_TYPE_INT8:
1648 paramValue = QVariant((qint8)valStr.toUInt());
1649 break;
1650 default:
1651 qCCritical(ParameterManagerLog) << "Unknown type" << paramType;
1652 [[fallthrough]];
1653 case MAV_PARAM_TYPE_INT32:
1654 paramValue = QVariant(valStr.toInt());
1655 break;
1656 }
1657
1658 CompInfoParam* const compInfoParam = _vehicle->compInfoManager()->compInfoParam(offlineDefaultComponentId);
1659 if (!compInfoParam) {
1660 qCWarning(ParameterManagerLog) << "No parameter metadata for component" << offlineDefaultComponentId;
1661 continue;
1662 }
1663
1664 Fact* const fact = new Fact(offlineDefaultComponentId, paramName, mavTypeToFactType(paramType), this);
1665 fact->setMetaData(compInfoParam->factMetaDataForName(paramName, fact->type()));
1666
1667 _mapCompId2FactMap[defaultComponentId][paramName] = fact;
1668 }
1669
1670 _parametersReady = true;
1671 _initialLoadComplete = true;
1672 _debugCacheCRC.clear();
1673}
1674
1676{
1677 _vehicle->sendMavCommand(MAV_COMP_ID_AUTOPILOT1,
1678 MAV_CMD_PREFLIGHT_STORAGE,
1679 true, // showError
1680 2, // Reset params to default
1681 -1); // Don't do anything with mission storage
1682}
1683
1685{
1686 //-- https://github.com/PX4/Firmware/pull/11760
1687 Fact *const sysAutoConfigFact = getParameter(defaultComponentId, "SYS_AUTOCONFIG");
1688 if (sysAutoConfigFact) {
1689 sysAutoConfigFact->setRawValue(2);
1690 }
1691}
1692
1693QString ParameterManager::_logVehiclePrefix(int componentId) const
1694{
1695 if (componentId == -1) {
1696 return QStringLiteral("V:%1").arg(_vehicle->id());
1697 } else {
1698 return QStringLiteral("V:%1 C:%2").arg(_vehicle->id()).arg(componentId);
1699 }
1700}
1701
1702void ParameterManager::_setLoadProgress(double loadProgress)
1703{
1704 if (_loadProgress != loadProgress) {
1705 _loadProgress = loadProgress;
1706 emit loadProgressChanged(static_cast<float>(loadProgress));
1707 }
1708}
1709
1711{
1712 if (_parameterDownloadSkipped != skipped) {
1713 _parameterDownloadSkipped = skipped;
1715 }
1716}
1717
1719{
1720 return _paramCountMap.keys();
1721}
1722
1724{
1725 return _pendingWritesCount > 0;
1726}
1727
1728#ifdef QGC_UNITTEST_BUILD
1729void ParameterManager::setPendingWritesForTest(bool pending)
1730{
1731 const bool wasPending = (_pendingWritesCount > 0);
1732 _pendingWritesCount = pending ? 1 : 0;
1733 if (wasPending != pending) {
1734 emit pendingWritesChanged(pending);
1735 }
1736}
1737#endif
1738
1740{
1741 return _vehicle;
1742}
1743
1744
1745bool ParameterManager::_parseParamFile(const QString& filename)
1746{
1747 constexpr quint16 magic_standard = 0x671B;
1748 constexpr quint16 magic_withdefaults = 0x671C;
1749 quint32 no_of_parameters_found = 0;
1750 constexpr int componentId = MAV_COMP_ID_AUTOPILOT1;
1751 enum ap_var_type {
1752 AP_PARAM_NONE = 0,
1753 AP_PARAM_INT8,
1754 AP_PARAM_INT16,
1755 AP_PARAM_INT32,
1756 AP_PARAM_FLOAT,
1757 AP_PARAM_VECTOR3F,
1758 AP_PARAM_GROUP
1759 };
1760
1761 qCDebug(ParameterManagerLog) << "_parseParamFile:" << filename;
1762 QFile file(filename);
1763 if (!file.open(QIODevice::ReadOnly)) {
1764 qCDebug(ParameterManagerLog) << "_parseParamFile: Error: Could not open downloaded parameter file.";
1765 return false;
1766 }
1767
1768 QDataStream in(&file);
1769 in.setByteOrder(QDataStream::LittleEndian);
1770
1771 quint16 magic, num_params, total_params;
1772 in >> magic;
1773 in >> num_params;
1774 in >> total_params;
1775
1776 if (in.status() != QDataStream::Ok) {
1777 qCDebug(ParameterManagerLog) << "_parseParamFile: Error: Could not read Header";
1778 goto Error;
1779 }
1780
1781 qCDebug(ParameterManagerVerbose2Log) << "_parseParamFile: magic: 0x" << Qt::hex << magic;
1782 qCDebug(ParameterManagerVerbose2Log) << "_parseParamFile: num_params:" << num_params
1783 << "total_params:" << total_params;
1784
1785 if ((magic != magic_standard) && (magic != magic_withdefaults)) {
1786 qCDebug(ParameterManagerLog) << "_parseParamFile: Error: File does not start with Magic";
1787 goto Error;
1788 }
1789 if (num_params > total_params) {
1790 qCDebug(ParameterManagerLog) << "_parseParamFile: Error: total_params > num_params";
1791 goto Error;
1792 }
1793 if (num_params != total_params) {
1794 /* We requested all parameters, so this is an error here */
1795 qCDebug(ParameterManagerLog) << "_parseParamFile: Error: total_params != num_params";
1796 goto Error;
1797 }
1798
1799 while (in.status() == QDataStream::Ok) {
1800 quint8 byte = 0;
1801 quint8 flags = 0;
1802 quint8 ptype = 0;
1803 quint8 name_len = 0;
1804 quint8 common_len = 0;
1805 bool withdefault = false;
1806 int no_read = 0;
1807 char name_buffer[17];
1808
1809 while (byte == 0x0) { // Eat padding bytes
1810 in >> byte;
1811 if (in.status() != QDataStream::Ok) {
1812 if (no_of_parameters_found == num_params) {
1813 goto Success;
1814 } else {
1815 qCDebug(ParameterManagerLog) << "_parseParamFile: Error: unexpected EOF"
1816 << "number of parameters expected:" << num_params
1817 << "actual:" << no_of_parameters_found;
1818 goto Error;
1819 }
1820 }
1821 }
1822 ptype = byte & 0x0F;
1823 flags = (byte >> 4) & 0x0F;
1824 withdefault = (flags & 0x01) == 0x01;
1825 in >> byte;
1826 if (in.status() != QDataStream::Ok) {
1827 qCCritical(ParameterManagerLog) << "_parseParamFile: Error: Unexpected EOF while reading flags";
1828 goto Error;
1829 }
1830 name_len = ((byte >> 4) & 0x0F) + 1;
1831 common_len = byte & 0x0F;
1832 if ((name_len + common_len) > 16) {
1833 qCCritical(ParameterManagerLog) << "_parseParamFile: Error: common_len + name_len > 16"
1834 << "name_len" << name_len
1835 << "common_len" << common_len;
1836 goto Error;
1837 }
1838 no_read = in.readRawData(&name_buffer[common_len], static_cast<int>(name_len));
1839 if (no_read != name_len) {
1840 qCCritical(ParameterManagerLog) << "_parseParamFile: Error: Unexpected EOF while reading parameterName"
1841 << "Expected:" << name_len
1842 << "Actual:" << no_read;
1843 goto Error;
1844 }
1845 name_buffer[common_len + name_len] = '\0';
1846 const QString parameterName(name_buffer);
1847 qCDebug(ParameterManagerVerbose2Log) << "_parseParamFile: parameter" << parameterName
1848 << "name_len" << name_len
1849 << "common_len" << common_len
1850 << "ptype" << ptype
1851 << "flags" << flags;
1852
1853 QVariant parameterValue = 0;
1854 QVariant defaultValue;
1855 switch (static_cast<ap_var_type>(ptype)) {
1856 qint8 data8;
1857 qint16 data16;
1858 qint32 data32;
1859 float dfloat;
1860 case AP_PARAM_INT8:
1861 in >> data8;
1862 parameterValue = data8;
1863 if (withdefault) {
1864 in >> data8;
1865 defaultValue = data8;
1866 }
1867 break;
1868 case AP_PARAM_INT16:
1869 in >> data16;
1870 parameterValue = data16;
1871 if (withdefault) {
1872 in >> data16;
1873 defaultValue = data16;
1874 }
1875 break;
1876 case AP_PARAM_INT32:
1877 in >> data32;
1878 parameterValue = data32;
1879 if (withdefault) {
1880 in >> data32;
1881 defaultValue = data32;
1882 }
1883 break;
1884 case AP_PARAM_FLOAT:
1885 in >> data32;
1886 (void) memcpy(&dfloat, &data32, 4);
1887 parameterValue = dfloat;
1888 if (withdefault) {
1889 in >> data32;
1890 float ddefault;
1891 (void) memcpy(&ddefault, &data32, 4);
1892 defaultValue = ddefault;
1893 }
1894 break;
1895 default:
1896 qCDebug(ParameterManagerLog) << "_parseParamFile: Error: type is out of range" << ptype;
1897 goto Error;
1898 break;
1899 }
1900 qCDebug(ParameterManagerVerbose2Log) << "paramValue" << parameterValue;
1901
1902 if (++no_of_parameters_found > num_params) {
1903 qCDebug(ParameterManagerLog) << "_parseParamFile: Error: more parameters in file than expected."
1904 << "Expected:" << num_params
1905 << "Actual:" << no_of_parameters_found;
1906 goto Error;
1907 }
1908
1909 const FactMetaData::ValueType_t factType = ((ptype == AP_PARAM_INT8) ? FactMetaData::valueTypeInt8 :
1910 (ptype == AP_PARAM_INT16) ? FactMetaData::valueTypeInt16 :
1911 (ptype == AP_PARAM_INT32) ? FactMetaData::valueTypeInt32 :
1913
1914 Fact *fact = nullptr;
1915 if (_mapCompId2FactMap.contains(componentId) && _mapCompId2FactMap[componentId].contains(parameterName)) {
1916 fact = _mapCompId2FactMap[componentId][parameterName];
1917 if (withdefault && defaultValue.isValid()) {
1918 // Firmware-provided defaults are authoritative: use the unchecked
1919 // setter so parameters that legitimately default to 0 ("disabled")
1920 // but have a metadata min > 0 don't produce false warnings.
1921 fact->metaData()->setRawDefaultValueFirmwareForce(defaultValue);
1922 }
1923 } else {
1924 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) << "Adding new fact" << parameterName;
1925
1926 fact = new Fact(componentId, parameterName, factType, this);
1927 FactMetaData *const factMetaData = _vehicle->compInfoManager()->compInfoParam(componentId)->factMetaDataForName(parameterName, fact->type());
1928 fact->setMetaData(factMetaData);
1929
1930 _mapCompId2FactMap[componentId][parameterName] = fact;
1931
1932 // We need to know when the fact value changes so we can update the vehicle
1933 (void) connect(fact, &Fact::containerRawValueChanged, this, &ParameterManager::_factRawValueUpdated);
1934
1935 // Set default before emitting factAdded so QML sees defaultValueAvailable from the start
1936 if (withdefault && defaultValue.isValid()) {
1937 fact->metaData()->setRawDefaultValueFirmwareForce(defaultValue);
1938 }
1939
1940 emit factAdded(componentId, fact);
1941 }
1942 fact->containerSetRawValue(parameterValue);
1943 }
1944
1945Success:
1946 file.close();
1947 /* Create empty waiting lists as we have all parameters */
1948 _paramCountMap[componentId] = num_params;
1949 _totalParamCount += num_params;
1950 _waitingReadParamIndexMap[componentId] = QMap<int, int>();
1951 if (!_logReplay && _vehicle->px4Firmware()) {
1952 _writeLocalParamCache(_vehicle->id(), componentId);
1953 }
1954 _checkInitialLoadComplete();
1955 _refreshAllProgressActive = false;
1956 _setLoadProgress(0.0);
1957 return true;
1958
1959Error:
1960 file.close();
1961 return false;
1962}
1963
1964void ParameterManager::_incrementPendingWriteCount()
1965{
1966 _pendingWritesCount++;
1967 if (_pendingWritesCount == 1) {
1968 emit pendingWritesChanged(true);
1969 }
1970}
1971
1972void ParameterManager::_decrementPendingWriteCount()
1973{
1974 if (_pendingWritesCount == 0) {
1975 qCWarning(ParameterManagerLog) << "Internal Error: _pendingWriteCount == 0";
1976 return;
1977 }
1978
1979 _pendingWritesCount--;
1980 if (_pendingWritesCount == 0) {
1981 emit pendingWritesChanged(false);
1982 }
1983}
std::shared_ptr< LinkInterface > SharedLinkInterfacePtr
#define qgcApp()
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
struct param_union mavlink_param_union_t
FactMetaData * factMetaDataForName(const QString &name, FactMetaData::ValueType_t valueType)
void commandProgress(float value)
void downloadComplete(const QString &file, const QString &errorMsg)
bool download(uint8_t fromCompId, const QString &fromURI, const QString &toDir, const QString &fileName="", bool checksize=true)
Definition FTPManager.cc:32
void setRawDefaultValueFirmwareForce(const QVariant &rawDefaultValue)
static size_t typeToSize(ValueType_t type)
A Fact is used to hold a single value within the system.
Definition Fact.h:15
void setMetaData(FactMetaData *metaData, bool setDefaultFromMetaData=false)
Definition Fact.cc:742
void containerSetRawValue(const QVariant &value)
Value coming from Vehicle. This does NOT send a _containerRawValueChanged signal.
Definition Fact.cc:199
FactMetaData * metaData()
Definition Fact.h:172
int componentId() const
Definition Fact.h:92
FactMetaData::ValueType_t type() const
Definition Fact.h:127
void setRawValue(const QVariant &value)
Definition Fact.cc:135
QString name() const
Definition Fact.h:124
void containerRawValueChanged(const QVariant &value)
This signal is meant for use by Fact container implementations. Used to send changed values to vehicl...
QString rawValueStringFullPrecision() const
Returns the values as a string with full 18 digit precision if float/double.
Definition Fact.cc:446
bool vehicleRebootRequired() const
Definition Fact.cc:819
QVariant rawValue() const
Definition Fact.h:87
QMap< int, remapParamNameMap_t > remapParamNameMinorVersionRemapMap_t
QMap< QString, QString > remapParamNameMap_t
QMap< int, remapParamNameMinorVersionRemapMap_t > remapParamNameMajorVersionMap_t
static int getComponentId()
static MAVLinkProtocol * instance()
static MultiVehicleManager * instance()
bool parameterExists(int componentId, const QString &paramName) const
void parameterDownloadSkippedChanged()
static constexpr int kWaitForParamValueAckMs
Time to wait for param value ack after set param.
void mavlinkMessageReceived(const mavlink_message_t &message)
static constexpr int kParamRequestListTimeoutMs
Timeout for PARAM_REQUEST_LIST response.
Fact * getParameter(int componentId, const QString &paramName)
static QString parameterCacheFile(quint32 vehicleId, int componentId)
static constexpr int kTestInitialRequestIntervalMs
void factAdded(int componentId, Fact *fact)
static FactMetaData::ValueType_t mavTypeToFactType(MAV_PARAM_TYPE mavType)
void refreshParameter(int componentId, const QString &paramName, bool notifyFailure=true)
void setParameterDownloadSkipped(bool skipped)
QList< int > componentIds() const
void refreshParametersPrefix(int componentId, const QString &namePrefix)
Request a refresh on all parameters that begin with the specified prefix.
void initialParametersRequestFailed()
Vehicle never responded to PARAM_REQUEST_LIST, all retries exhausted.
void parametersReadyChanged(bool parametersReady)
ParameterManager(Vehicle *vehicle)
double loadProgress() const
void bulkRefresh(int componentId, const QStringList &names, bool notifyFailure=true)
bool pendingWrites() const
static QDir parameterCacheDir()
static constexpr int kHashCheckTimeoutMs
Timeout for standalone _HASH_CHECK request.
void missingParametersChanged(bool missingParameters)
static constexpr int defaultComponentId
static constexpr int kTestHashCheckTimeoutMs
Shortened _HASH_CHECK timeout in unit tests (MockLink responds instantly).
QStringList parameterNames(int componentId) const
Returns all parameter names.
void _paramRequestReadFailure(int componentId, const QString &paramName, int paramIndex)
void _paramRequestReadSuccess(int componentId, const QString &paramName, int paramIndex)
static constexpr int kIndexBatchMaxOutstanding
Maximum index re-reads in flight at once.
static constexpr int kParamSetRetryCount
Number of retries for PARAM_SET.
void _paramSetSuccess(int componentId, const QString &paramName)
static constexpr int kUnresponsiveMinOutstanding
Minimum in-flight re-reads to a component before a silent cycle counts against it.
void loadProgressChanged(float value)
void cacheCheckOnlyFailed()
void pendingWritesChanged(bool pendingWrites)
static MAV_PARAM_TYPE factTypeToMavType(FactMetaData::ValueType_t factType)
static constexpr int kParamRequestReadRetryCount
Number of retries for PARAM_REQUEST_READ.
void resetAllToVehicleConfiguration()
Q_INVOKABLE void refreshAllParameters()
void writeParametersToStream(QTextStream &stream) const
static constexpr int kUnresponsiveSilentCycles
Consecutive silent cycles before a non-default component is given up on.
void _paramSetFailure(int componentId, const QString &paramName)
QSignalTransition * addThisTransition(PointerToMemberFunction signal, QAbstractState *target)
Simpler version of QState::addTransition which assumes the sender is this.
Definition QGCState.h:31
WeakLinkInterfacePtr primaryLink() const
VehicleLinkManager * vehicleLinkManager()
Definition Vehicle.h:602
quint32 id() const
Definition Vehicle.h:446
QByteArray line(std::string_view command)
command as one CR/LF-terminated line.
constexpr std::chrono::microseconds remaining(uint64_t timestampUs, uint64_t nowUs, std::chrono::microseconds lifetime)
Time left before a receipt reaches lifetime; zero for a missing, future or expired one.
std::optional< T > number(std::string_view field, int base=DECIMAL_BASE)
quint32 crc32(const quint8 *src, unsigned len, unsigned state)
Definition QGCMath.cc:66
bool runningUnitTests()
bool fuzzyCompare(double value1, double value2)
Returns true if the two values are equal or close. Correctly handles 0 and NaN values.
Definition QGCMath.cc:71
void showRebootAppMessage(const QString &message, const QString &title)
Modal reboot-required message. Debounced within 2 minutes.
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.
Definition AppMessages.cc:9
static const int versionNotSetValue