9#include <QtCore/QTextStream>
28#include <QtCore/QEasingCurve>
29#include <QtCore/QFile>
30#include <QtCore/QStandardPaths>
31#include <QtCore/QVariantAnimation>
36QGC_LOGGING_CATEGORY(ParameterManagerDebugCacheFailureLog,
"FactSystem.ParameterManager:debugCacheFailure")
41 , _logReplay(!
vehicle->vehicleLinkManager()->primaryLink().expired() &&
vehicle->vehicleLinkManager()->primaryLink().lock()->isLogReplay())
42 , _disableAllRetries(_logReplay)
46 qCDebug(ParameterManagerLog) <<
this;
48 if (_vehicle->isOfflineEditingVehicle()) {
49 _loadOfflineEditingParams();
54 qCDebug(ParameterManagerLog) <<
this <<
"In log replay mode";
57 _hashCheckTimer.setSingleShot(
true);
59 (void) connect(&_hashCheckTimer, &QTimer::timeout,
this, &ParameterManager::_hashCheckTimeout);
61 _paramRequestListTimer.setSingleShot(
true);
63 (void) connect(&_paramRequestListTimer, &QTimer::timeout,
this, &ParameterManager::_paramRequestListTimeout);
65 _waitingParamTimeoutTimer.setSingleShot(
true);
68 (void) connect(&_waitingParamTimeoutTimer, &QTimer::timeout,
this, &ParameterManager::_waitingParamTimeout);
77 qCDebug(ParameterManagerLog) <<
this;
80void ParameterManager::_updateProgressBar()
83 if (_initialLoadComplete && !_refreshAllProgressActive) {
87 int waitingReadParamIndexCount = 0;
89 for (
const int compId: _waitingReadParamIndexMap.keys()) {
90 waitingReadParamIndexCount += _waitingReadParamIndexMap[compId].count();
93 if (waitingReadParamIndexCount == 0) {
94 _refreshAllProgressActive =
false;
95 if (_readParamIndexProgressActive) {
96 _readParamIndexProgressActive =
false;
97 _setLoadProgress(0.0);
101 _readParamIndexProgressActive =
true;
102 _setLoadProgress(
static_cast<double>(_totalParamCount - waitingReadParamIndexCount) /
static_cast<double>(_totalParamCount));
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, ¶m_value);
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);
122 if (_tryftp && (message.compid == MAV_COMP_ID_AUTOPILOT1) && !_initialLoadComplete
123 && (parameterName != QStringLiteral(
"_HASH_CHECK"))) {
128 paramUnion.param_float = param_value.param_value;
129 paramUnion.type = param_value.param_type;
131 QVariant parameterValue;
132 if (!_mavlinkParamUnionToVariant(paramUnion, parameterValue)) {
136 _handleParamValue(message.compid, parameterName, param_value.param_count, param_value.param_index,
static_cast<MAV_PARAM_TYPE
>(param_value.param_type), parameterValue);
140void ParameterManager::_handleParamValue(
int componentId,
const QString ¶meterName,
int parameterCount,
int parameterIndex, MAV_PARAM_TYPE mavParamType,
const QVariant ¶meterValue)
143 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) <<
144 "_parameterUpdate" <<
145 "name:" << parameterName <<
146 "count:" << parameterCount <<
147 "index:" << parameterIndex <<
148 "mavType:" << mavParamType <<
149 "value:" << parameterValue <<
154 if ((parameterIndex == 65535) && (parameterName != QStringLiteral(
"_HASH_CHECK")) && _paramRequestListTimer.isActive()) {
155 qCDebug(ParameterManagerLog) <<
"Disregarding unrequested param prior to initial list response" << parameterName;
159 if (_vehicle->px4Firmware() && (parameterName ==
"_HASH_CHECK")) {
160 _hashCheckTimer.stop();
161 if (!_initialLoadComplete && !_logReplay) {
163 _tryCacheHashLoad(_vehicle->id(), componentId, parameterValue);
168 _paramRequestListTimer.stop();
171 if (!_initialLoadComplete && !_logReplay && _debugCacheCRC.contains(componentId) && _debugCacheCRC[componentId]) {
172 if (_debugCacheMap[componentId].contains(parameterName)) {
173 const ParamTypeVal &cacheParamTypeVal = _debugCacheMap[componentId][parameterName];
175 const void *
const cacheData = cacheParamTypeVal.second.constData();
176 const void *
const vehicleData = parameterValue.constData();
178 if (memcmp(cacheData, vehicleData, dataSize) != 0) {
179 qCDebug(ParameterManagerVerbose1Log) <<
"Cache/Vehicle values differ for name:cache:actual" << parameterName << parameterValue << cacheParamTypeVal.second;
181 _debugCacheParamSeen[componentId][parameterName] =
true;
183 qCDebug(ParameterManagerVerbose1Log) <<
"Parameter missing from cache" << parameterName;
187 _waitingParamTimeoutTimer.stop();
189 _paramValuesReceivedThisCycle[componentId]++;
190 _silentCycleCount.remove(componentId);
193 if (!_paramCountMap.contains(componentId)) {
194 _paramCountMap[componentId] = parameterCount;
195 _totalParamCount += parameterCount;
199 if (!_waitingReadParamIndexMap.contains(componentId)) {
201 for (
int waitingIndex = 0; waitingIndex < parameterCount; waitingIndex++) {
203 _waitingReadParamIndexMap[componentId][waitingIndex] = 0;
206 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) <<
"Seeing component for first time - paramcount:" << parameterCount;
209 if (!_waitingReadParamIndexMap[componentId].contains(parameterIndex)) {
210 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) <<
"Unrequested param update" << parameterName;
214 if (_waitingReadParamIndexMap[componentId].contains(parameterIndex)) {
215 _waitingReadParamIndexMap[componentId].remove(parameterIndex);
216 (void) _indexBatchQueue.removeOne(qMakePair(componentId, parameterIndex));
217 _fillIndexBatchQueue(
false );
221 int waitingReadParamIndexCount = 0;
223 for (
const int waitingComponentId: _waitingReadParamIndexMap.keys()) {
224 waitingReadParamIndexCount += _waitingReadParamIndexMap[waitingComponentId].count();
226 if (waitingReadParamIndexCount) {
227 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) <<
"waitingReadParamIndexCount:" << waitingReadParamIndexCount;
230 const int readWaitingParamCount = waitingReadParamIndexCount;
231 const int totalWaitingParamCount = readWaitingParamCount;
232 if (totalWaitingParamCount) {
234 _waitingParamTimeoutTimer.start();
235 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(-1) <<
"Restarting _waitingParamTimeoutTimer: totalWaitingParamCount:" << totalWaitingParamCount;
236 }
else if (!_mapCompId2FactMap.contains(_vehicle->defaultComponentId())) {
238 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"Restarting _waitingParamTimeoutTimer (still waiting for default component params)";
239 _waitingParamTimeoutTimer.start();
241 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(-1) <<
"Not restarting _waitingParamTimeoutTimer (all requests satisfied)";
244 _updateProgressBar();
246 Fact *fact =
nullptr;
247 if (_mapCompId2FactMap.contains(componentId) && _mapCompId2FactMap[componentId].contains(parameterName)) {
248 fact = _mapCompId2FactMap[componentId][parameterName];
250 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) <<
"Adding new fact" << parameterName;
252 fact =
new Fact(componentId, parameterName,
mavTypeToFactType(mavParamType),
this);
253 FactMetaData *
const factMetaData = _vehicle->compInfoManager()->compInfoParam(componentId)->factMetaDataForName(parameterName, fact->
type());
256 _mapCompId2FactMap[componentId][parameterName] = fact;
269 if (!_logReplay && _vehicle->px4Firmware()) {
270 if (_prevWaitingReadParamIndexCount != 0 && readWaitingParamCount == 0) {
272 _writeLocalParamCache(_vehicle->id(), componentId);
276 _prevWaitingReadParamIndexCount = waitingReadParamIndexCount;
278 _checkInitialLoadComplete();
280 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) <<
"_handleParamValue complete";
283QString ParameterManager::_vehicleAndComponentString(
int componentId)
const
286 QString vehicleIdStr;
288 vehicleIdStr = QStringLiteral(
"veh: %1").arg(_vehicle->id());
292 QString componentIdStr;
293 if (_mapCompId2FactMap.keys().count() > 1) {
294 componentIdStr = QStringLiteral(
"comp: %1").arg(componentId);
297 if (!vehicleIdStr.isEmpty() && !componentIdStr.isEmpty()) {
298 return vehicleIdStr + QStringLiteral(
" ") + componentIdStr;
299 }
else if (!vehicleIdStr.isEmpty()) {
301 }
else if (!componentIdStr.isEmpty()) {
302 return componentIdStr;
308void ParameterManager::_mavlinkParamSet(
int componentId,
const QString ¶mName,
FactMetaData::ValueType_t valueType,
const QVariant &rawValue)
310 auto paramSetEncoder = [
this, componentId, paramName, valueType, rawValue](quint32 , uint8_t channel,
315 if (!_fillMavlinkParamUnion(valueType, rawValue, union_value)) {
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);
324 static_cast<uint8_t
>(componentId), paramId, union_value.param_float,
325 static_cast<uint8_t
>(paramType));
328 auto checkForCorrectParamValue = [
this, componentId, paramName, rawValue](
const mavlink_message_t &message) ->
bool {
329 if (message.compid != componentId) {
333 mavlink_param_value_t param_value{};
334 mavlink_msg_param_value_decode(&message, ¶m_value);
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);
341 if (parameterName != paramName) {
346 QVariant receivedValue;
348 param_union.param_float = param_value.param_value;
349 param_union.type = param_value.param_type;
350 if (!_mavlinkParamUnionToVariant(param_union, receivedValue)) {
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();
357 if (param_value.param_type == MAV_PARAM_TYPE_REAL32) {
361 return receivedValue == rawValue;
365 auto checkForParamError = [componentId, paramName](
const mavlink_message_t &message) ->
bool {
366 if (message.compid != componentId) {
370 mavlink_param_error_t paramError{};
371 mavlink_msg_param_error_decode(&message, ¶mError);
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);
376 return QString(paramId) == paramName;
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();
399 auto decPendingWriteCountState =
new FunctionState(QStringLiteral(
"ParameterManager decrement pending write count"), stateMachine, [
this]() {
400 _decrementPendingWriteCount();
402 auto retryDecPendingWriteCountState =
new FunctionState(QStringLiteral(
"ParameterManager retry decrement pending write count"), stateMachine, [
this]() {
403 _decrementPendingWriteCount();
405 auto errorDecPendingWriteCountState =
new FunctionState(QStringLiteral(
"ParameterManager error decrement pending write count"), stateMachine, [
this]() {
406 _decrementPendingWriteCount();
408 auto waitAckState =
new WaitForParamResponseState(stateMachine, _waitForParamValueAckMs, checkForCorrectParamValue, checkForParamError);
409 auto paramRefreshState =
new FunctionState(QStringLiteral(
"ParameterManager param refresh"), stateMachine, [
this, waitAckState, componentId, paramName]() {
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);
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);
425 auto logSuccessState =
new FunctionState(QStringLiteral(
"ParameterManager log success"), stateMachine, [
this, componentId, paramName]() {
426 qCDebug(ParameterManagerLog) <<
"Parameter write succeeded: param:" << paramName << _vehicleAndComponentString(componentId);
429 auto logFailureState =
new FunctionState(QStringLiteral(
"ParameterManager log failure"), stateMachine, [
this, componentId, paramName]() {
430 qCDebug(ParameterManagerLog) <<
"Parameter write failed: param:" << paramName << _vehicleAndComponentString(componentId);
433 auto finalState =
new QGCFinalState(stateMachine);
436 stateMachine->setInitialState(sendParamSetState);
437 sendParamSetState->addThisTransition (&
QGCState::advance, incPendingWriteCountState);
452 sendParamSetState->addThisTransition(&
QGCState::error, logFailureState);
459 qCDebug(ParameterManagerLog) <<
"Starting state machine for PARAM_SET on: " << paramName << _vehicleAndComponentString(componentId);
460 stateMachine->start();
469 paramUnion.param_uint8 =
static_cast<uint8_t
>(rawValue.toUInt(&ok));
472 paramUnion.param_int8 =
static_cast<int8_t
>(rawValue.toInt(&ok));
475 paramUnion.param_uint16 =
static_cast<uint16_t
>(rawValue.toUInt(&ok));
478 paramUnion.param_int16 =
static_cast<int16_t
>(rawValue.toInt(&ok));
481 paramUnion.param_uint32 =
static_cast<uint32_t
>(rawValue.toUInt(&ok));
484 paramUnion.param_float = rawValue.toFloat(&ok);
487 paramUnion.param_int32 =
static_cast<int32_t
>(rawValue.toInt(&ok));
490 qCCritical(ParameterManagerLog) <<
"Internal Error: Unsupported fact value type" << valueType;
491 paramUnion.param_int32 =
static_cast<int32_t
>(rawValue.toInt(&ok));
496 qCCritical(ParameterManagerLog) <<
"Fact Failed to Convert to Param Type:" << valueType;
503bool ParameterManager::_mavlinkParamUnionToVariant(
const mavlink_param_union_t ¶mUnion, QVariant &outValue)
const
505 switch (paramUnion.type) {
506 case MAV_PARAM_TYPE_REAL32:
507 outValue = QVariant(paramUnion.param_float);
509 case MAV_PARAM_TYPE_UINT8:
510 outValue = QVariant(
static_cast<quint32
>(paramUnion.param_uint8));
512 case MAV_PARAM_TYPE_INT8:
513 outValue = QVariant(
static_cast<qint32
>(paramUnion.param_int8));
515 case MAV_PARAM_TYPE_UINT16:
516 outValue = QVariant(
static_cast<quint32
>(paramUnion.param_uint16));
518 case MAV_PARAM_TYPE_INT16:
519 outValue = QVariant(
static_cast<qint32
>(paramUnion.param_int16));
521 case MAV_PARAM_TYPE_UINT32:
522 outValue = QVariant(paramUnion.param_uint32);
524 case MAV_PARAM_TYPE_INT32:
525 outValue = QVariant(paramUnion.param_int32);
528 qCCritical(ParameterManagerLog) <<
"ParameterManager::_mavlinkParamUnionToVariant - unsupported MAV_PARAM_TYPE" << paramUnion.type;
533void ParameterManager::_factRawValueUpdated(
const QVariant &rawValue)
535 Fact *
const fact = qobject_cast<Fact*>(sender());
537 qCWarning(ParameterManagerLog) <<
"Internal error";
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."));
553void ParameterManager::_ftpDownloadComplete(
const QString &fileName,
const QString &errorMsg)
555 bool continueWithDefaultParameterdownload =
true;
556 bool immediateRetry =
false;
558 _ftpDownloadInProgress =
false;
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));
572 qCDebug(ParameterManagerLog) <<
"ParameterManager::_ftpDownloadComplete : Error in parameter file";
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;
580 }
else if ((_loadProgress > 0.0001) && (_loadProgress < 0.01)) {
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";
585 qCDebug(ParameterManagerLog) <<
"ParameterManager-ftp Retry:" << _initialRequestRetryCount;
586 continueWithDefaultParameterdownload =
false;
589 if (continueWithDefaultParameterdownload) {
591 _initialRequestRetryCount = 0;
596 if (immediateRetry) {
597 _paramRequestListTimeout();
599 _paramRequestListTimer.start();
602 _paramRequestListTimer.start();
606void ParameterManager::_handleHeartbeat(
int componentId)
608 if ((componentId == MAV_COMP_ID_ALL) || (componentId == MAV_COMP_ID_AUTOPILOT1) ||
609 _heartbeatComponentIds.contains(componentId)) {
612 _heartbeatComponentIds.insert(componentId);
615 if (_ftpParamsLoaded) {
616 _sendParamRequestList(
static_cast<uint8_t
>(componentId));
620void ParameterManager::_sendParamRequestList(uint8_t componentId)
627 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) <<
"Sending PARAM_REQUEST_LIST";
632 _vehicle->id(), componentId);
633 (void) _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg);
636void ParameterManager::_ftpDownloadProgress(
float progress)
638 qCDebug(ParameterManagerVerbose1Log) <<
"ParameterManager::_ftpDownloadProgress:" << progress;
639 _setLoadProgress(
static_cast<double>(progress));
640 if (progress > 0.001) {
641 _paramRequestListTimer.stop();
645void ParameterManager::_resetHashCheck()
647 _hashCheckTimer.stop();
648 _hashCheckDone =
false;
655 _refreshAllProgressActive =
true;
656 _startParameterDownload(componentId);
662 _cacheOnlyHashCheck =
true;
670 if (sharedLink->linkConfiguration()->isHighLatency() || _logReplay) {
671 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"Cache-only hash check: high latency or log replay link, signalling failure";
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);
681 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"Cache-only hash check: not available, signalling failure";
686void ParameterManager::_startParameterDownload(uint8_t componentId)
693 if (sharedLink->linkConfiguration()->isHighLatency() || _logReplay) {
695 _parametersReady =
true;
696 _missingParameters =
true;
697 _initialLoadComplete =
true;
698 _waitingForDefaultComponent =
false;
704 if (_vehicle->px4Firmware() && !_initialLoadComplete && !_hashCheckDone) {
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)
712 _requestHashCheck(hashCheckCompId);
713 }
else if (_tryftp && ((componentId == MAV_COMP_ID_ALL) || (componentId == MAV_COMP_ID_AUTOPILOT1))) {
714 if (_ftpDownloadInProgress) {
716 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"Parameter file download already in progress";
717 _refreshAllProgressActive =
false;
720 if (!_initialLoadComplete) {
721 _paramRequestListTimer.start();
723 FTPManager *
const ftpManager = _vehicle->ftpManager();
726 if (!_anyComponentWaiting()) {
727 _waitingParamTimeoutTimer.stop();
729 if (ftpManager->
download(MAV_COMP_ID_AUTOPILOT1,
730 QStringLiteral(
"@PARAM/param.pck?withdefaults=1"),
731 QStandardPaths::writableLocation(QStandardPaths::TempLocation),
732 QStringLiteral(
"param.pck"),
734 _ftpDownloadInProgress =
true;
737 qCWarning(ParameterManagerLog) <<
"ParameterManager::_startParameterDownload FTPManager::download returned failure";
739 _refreshAllProgressActive =
false;
742 if (!_initialLoadComplete) {
743 _paramRequestListTimer.start();
747 for (
int cid: _paramCountMap.keys()) {
749 if ((componentId != MAV_COMP_ID_ALL) && (componentId != cid)) {
752 for (
int waitingIndex = 0; waitingIndex < _paramCountMap[cid]; waitingIndex++) {
754 _waitingReadParamIndexMap[cid][waitingIndex] = 0;
758 _sendParamRequestList(componentId);
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;
765int ParameterManager::_actualComponentId(
int componentId)
const
768 componentId = _vehicle->defaultComponentId();
770 qCWarning(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"Default component id not set";
779 componentId = _actualComponentId(componentId);
781 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) <<
"refreshParameter - name:" << paramName;
783 _mavlinkParamRequestRead(componentId, paramName, -1, notifyFailure);
788 _rebootMessageSuppressCount++;
793 if (_rebootMessageSuppressCount == 0) {
794 qCWarning(ParameterManagerLog) <<
"unsuppressRebootMessage without matching suppressRebootMessage";
797 _rebootMessageSuppressCount--;
802 componentId = _actualComponentId(componentId);
803 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) <<
"refreshParametersPrefix - name:" << namePrefix;
805 if (!_mapCompId2FactMap.contains(componentId)) {
808 for (
const QString ¶mName: _mapCompId2FactMap[componentId].keys()) {
809 if (paramName.startsWith(namePrefix)) {
817 componentId = _actualComponentId(componentId);
819 if (!_mapCompId2FactMap.contains(componentId)) {
822 const QMap<QString, Fact *> &factMap = _mapCompId2FactMap[componentId];
823 QStringList resolved;
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";
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());
838 }
else if (factMap.contains(entry)) {
839 if (!seen.contains(entry)) {
841 resolved.append(entry);
844 qCWarning(ParameterManagerLog) <<
"bulkRefresh: unknown param name (skipped):" << entry;
848 if (resolved.isEmpty()) {
852 qCDebug(ParameterManagerLog) <<
"bulkRefresh: resolved" << resolved.count() <<
"params";
854 this, componentId, resolved, notifyFailure,
855 [
this, componentId](
const QString &name) {
856 _mavlinkParamRequestRead(componentId, name, -1,
false );
865 componentId = _actualComponentId(componentId);
866 if (_mapCompId2FactMap.contains(componentId)) {
867 ret = _mapCompId2FactMap[componentId].contains(_remapParamNameToVersion(paramName));
875 componentId = _actualComponentId(componentId);
877 const QString mappedParamName = _remapParamNameToVersion(paramName);
878 if (!_mapCompId2FactMap.contains(componentId) || !_mapCompId2FactMap[componentId].contains(mappedParamName)) {
879 qgcApp()->reportMissingParameter(componentId, mappedParamName);
880 return &_defaultFact;
883 return _mapCompId2FactMap[componentId][mappedParamName];
890 const int compId = _actualComponentId(componentId);
891 const QMap<QString, Fact*> &factMap = _mapCompId2FactMap[compId];
892 for (
const QString ¶mName: factMap.keys()) {
899bool ParameterManager::_fillIndexBatchQueue(
bool waitingParamTimeout)
901 if (!_indexBatchQueueActive) {
905 if (waitingParamTimeout) {
907 qCDebug(ParameterManagerLog) <<
"Refilling index based batch queue due to timeout";
908 _indexBatchQueue.clear();
910 qCDebug(ParameterManagerLog) <<
"Refilling index based batch queue due to received parameter";
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];
919 for (
const int paramIndex: _waitingReadParamIndexMap[componentId].keys()) {
920 if (_indexBatchQueue.contains(qMakePair(componentId, paramIndex))) {
929 _waitingReadParamIndexMap[componentId][paramIndex]++;
930 if (_disableAllRetries || (_waitingReadParamIndexMap[componentId][paramIndex] > _maxInitialLoadRetrySingleParam)) {
932 _failedReadParamIndexMap[componentId] << paramIndex;
933 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) <<
"Giving up on (paramIndex:" << paramIndex <<
"retryCount:" << _waitingReadParamIndexMap[componentId][paramIndex] <<
")";
934 (void) _waitingReadParamIndexMap[componentId].remove(paramIndex);
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] <<
")";
944 return (!_indexBatchQueue.isEmpty());
947void ParameterManager::_waitingParamTimeout()
953 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"_waitingParamTimeout after" << _waitingParamTimeoutTimer.interval() <<
"ms";
956 _indexBatchQueueActive =
true;
958 _giveUpOnUnresponsiveComponents();
961 bool paramsRequested = _fillIndexBatchQueue(
true );
962 if (!paramsRequested && !_waitingForDefaultComponent && !_mapCompId2FactMap.contains(_vehicle->defaultComponentId())) {
965 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"Restarting _waitingParamTimeoutTimer - still don't have default component params" << _vehicle->defaultComponentId();
966 _waitingParamTimeoutTimer.start();
967 _waitingForDefaultComponent =
true;
970 _waitingForDefaultComponent =
false;
972 _checkInitialLoadComplete();
974 _updateProgressBar();
976 if (paramsRequested) {
977 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"Restarting _waitingParamTimeoutTimer - re-request";
978 _waitingParamTimeoutTimer.start();
982void ParameterManager::_giveUpOnUnresponsiveComponents()
984 const int defaultCompId = _vehicle->defaultComponentId();
986 for (
const int componentId: _waitingReadParamIndexMap.keys()) {
987 if (componentId == defaultCompId) {
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; }));
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; });
1009 _paramValuesReceivedThisCycle.clear();
1012void ParameterManager::_requestHashCheck(uint8_t componentId)
1019 qCDebug(ParameterManagerLog) << _logVehiclePrefix(componentId) <<
"Sending PARAM_REQUEST_READ for _HASH_CHECK";
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);
1027 &msg, _vehicle->id(), componentId, paramId, -1);
1029 (void) _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg);
1032void ParameterManager::_sendParamRequestReadIndex(
int componentId,
int paramIndex)
1040 char paramId[MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN + 1] = {};
1042 (void) mavlink_msg_param_request_read_pack_chan(
1044 &msg, _vehicle->id(),
static_cast<uint8_t
>(componentId), paramId,
static_cast<int16_t
>(paramIndex));
1045 (void) _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg);
1048void ParameterManager::_mavlinkParamRequestRead(
int componentId,
const QString ¶mName,
int paramIndex,
bool notifyFailure)
1050 auto paramRequestReadEncoder = [
this, componentId, paramName, paramIndex](quint32 , uint8_t channel,
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);
1057 channel, message, _vehicle->id(),
1058 static_cast<uint8_t
>(componentId), paramId,
1059 static_cast<int16_t
>(paramIndex));
1062 auto checkForCorrectParamValue = [componentId, paramName, paramIndex](
const mavlink_message_t &message) ->
bool {
1063 if (message.compid != componentId) {
1067 mavlink_param_value_t param_value{};
1068 mavlink_msg_param_value_decode(&message, ¶m_value);
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);
1076 if (paramIndex != -1) {
1078 if (param_value.param_index != paramIndex) {
1083 if (parameterName != paramName) {
1091 auto checkForParamError = [componentId, paramName, paramIndex](
const mavlink_message_t &message) ->
bool {
1092 if (message.compid != componentId) {
1096 mavlink_param_error_t paramError{};
1097 mavlink_msg_param_error_decode(&message, ¶mError);
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);
1102 if (paramIndex != -1) {
1103 return paramError.param_index == paramIndex;
1105 return QString(paramId) == paramName;
1120 auto stateMachine =
new QGCStateMachine(QStringLiteral(
"PARAM_REQUEST_READ"),
vehicle(),
this);
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);
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);
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);
1138 auto finalState =
new QGCFinalState(stateMachine);
1141 stateMachine->setInitialState(sendParamRequestReadState);
1153 sendParamRequestReadState->addThisTransition(&
QGCState::error, logFailureState);
1156 if (notifyFailure) {
1163 qCDebug(ParameterManagerLog) <<
"Starting state machine for PARAM_REQUEST_READ on: " << paramName << _vehicleAndComponentString(componentId);
1164 stateMachine->start();
1167void ParameterManager::_writeLocalParamCache(quint32 vehicleId,
int componentId)
1169 CacheMapName2ParamTypeVal cacheMap;
1171 for (
const QString ¶mName: _mapCompId2FactMap[componentId].keys()) {
1172 const Fact *
const fact = _mapCompId2FactMap[componentId][paramName];
1173 cacheMap[paramName] = ParamTypeVal(fact->
type(), fact->
rawValue());
1177 if (cacheFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
1178 QDataStream ds(&cacheFile);
1180 qCDebug(ParameterManagerLog) <<
"Parameter cache written" << cacheFile.fileName() <<
"paramCount:" << cacheMap.count();
1182 qCWarning(ParameterManagerLog) <<
"Failed to open cache file for writing" << cacheFile.fileName();
1188 return QDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral(
"/ParamCache"));
1193 return parameterCacheDir().filePath(QStringLiteral(
"%1_%2.v2").arg(vehicleId).arg(componentId));
1196void ParameterManager::_tryCacheHashLoad(quint32 vehicleId,
int componentId,
const QVariant& hashValue)
1198 qCDebug(ParameterManagerLog) <<
"Attemping load from cache";
1201 CacheMapName2ParamTypeVal cacheMap;
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";
1213 _startParameterDownload(MAV_COMP_ID_ALL);
1218 (void) cacheFile.open(QIODevice::ReadOnly);
1221 QDataStream ds(&cacheFile);
1225 uint32_t crc32_value = 0;
1226 for (
const QString &name: cacheMap.keys()) {
1227 const ParamTypeVal ¶mTypeVal = cacheMap[name];
1230 if (_vehicle->compInfoManager()->compInfoParam(MAV_COMP_ID_AUTOPILOT1)->factMetaDataForName(name, factType)->volatileValue()) {
1232 qCDebug(ParameterManagerLog) <<
"Volatile parameter" << name;
1234 const void *
const vdat = paramTypeVal.second.constData();
1236 crc32_value =
QGC::crc32(
reinterpret_cast<const uint8_t *
>(qPrintable(name)), name.length(), crc32_value);
1242 if (crc32_value == hashValue.toUInt()) {
1243 _hashCheckDone =
true;
1244 _paramRequestListTimer.stop();
1245 qCDebug(ParameterManagerLog) <<
"Parameters loaded from cache" << qPrintable(QFileInfo(cacheFile).absoluteFilePath());
1247 const int count = cacheMap.count();
1249 for (
const QString &name: cacheMap.keys()) {
1250 const ParamTypeVal ¶mTypeVal = cacheMap[name];
1253 _handleParamValue(componentId, name, count, index++, mavParamType, paramTypeVal.second);
1258 mavlink_param_set_t p{};
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);
1271 &msg, _vehicle->id(), p.target_component, p.param_id, p.param_value,
1273 (void) _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg);
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);
1283 (void) connect(ani, &QVariantAnimation::valueChanged,
this, [
this](
const QVariant &value) {
1284 _setLoadProgress(value.toDouble());
1288 connect(ani, &QVariantAnimation::finished,
this, [
this] {
1289 QTimer::singleShot(500,
this, [
this] {
1290 _setLoadProgress(0);
1294 ani->start(QAbstractAnimation::DeleteWhenStopped);
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;
1305 if (!_hashCheckDone) {
1306 _hashCheckDone =
true;
1307 if (_cacheOnlyHashCheck) {
1308 qCDebug(ParameterManagerLog) <<
"Cache-only hash check: CRC mismatch, signalling failure";
1313 _startParameterDownload(MAV_COMP_ID_ALL);
1321 stream <<
"# Onboard parameters for Vehicle " << _vehicle->id() <<
"\n";
1326 stream <<
"# Version: "
1327 << _vehicle->firmwareMajorVersion() <<
"."
1328 << _vehicle->firmwareMinorVersion() <<
"."
1329 << _vehicle->firmwarePatchVersion() <<
" "
1330 << _vehicle->firmwareVersionTypeString() <<
"\n";
1331 stream <<
"# Git Revision: " << _vehicle->gitHash() <<
"\n";
1334 stream <<
"# Vehicle-Id Component-Id Name Value Type\n";
1336 for (
const int componentId: _mapCompId2FactMap.keys()) {
1337 for (
const QString ¶mName: _mapCompId2FactMap[componentId].keys()) {
1338 const Fact *
const fact = _mapCompId2FactMap[componentId][paramName];
1342 qCWarning(ParameterManagerLog) <<
"Internal error: missing fact";
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;
1372 qCWarning(ParameterManagerLog) <<
"Unsupported fact type" << factType;
1375 return MAV_PARAM_TYPE_INT32;
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:
1401 qCWarning(ParameterManagerLog) <<
"Unsupported mav param type" << mavType;
1403 case MAV_PARAM_TYPE_INT32:
1408void ParameterManager::_checkInitialLoadComplete()
1410 if (_initialLoadComplete) {
1411 _checkOtherComponentsLoadComplete();
1417 const int defaultCompId = _vehicle->defaultComponentId();
1418 if (_waitingReadParamIndexMap.contains(defaultCompId) && !_waitingReadParamIndexMap[defaultCompId].isEmpty()) {
1422 if (!_mapCompId2FactMap.contains(defaultCompId)) {
1428 _initialLoadComplete =
true;
1429 _refreshAllProgressActive =
false;
1430 _setLoadProgress(0.0);
1433 for (
const int componentId: _debugCacheParamSeen.keys()) {
1434 if (!_logReplay && _debugCacheCRC.contains(componentId) && _debugCacheCRC[componentId]) {
1435 for (
const QString ¶mName: _debugCacheParamSeen[componentId].keys()) {
1436 if (!_debugCacheParamSeen[componentId][paramName]) {
1437 qCDebug(ParameterManagerLog) <<
"Parameter in cache but not on vehicle componentId:Name" << componentId << paramName;
1442 _debugCacheCRC.clear();
1444 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"Initial load complete";
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));
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;
1462 _parametersReady =
true;
1463 _vehicle->autopilotPlugin()->parametersReadyPreChecks();
1467 _checkOtherComponentsLoadComplete();
1470bool ParameterManager::_anyComponentWaiting()
const
1472 for (
auto it = _waitingReadParamIndexMap.cbegin(); it != _waitingReadParamIndexMap.cend(); ++it) {
1473 if (!it.value().isEmpty()) {
1480void ParameterManager::_checkOtherComponentsLoadComplete()
1482 if (_otherComponentsReported) {
1486 if (_anyComponentWaiting()) {
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()) {
1497 failedComponentIds.append(QString::number(componentId));
1498 for (
const int paramIndex: _failedReadParamIndexMap[componentId]) {
1499 failedIndices.append(QStringLiteral(
"%1:%2").arg(componentId).arg(paramIndex));
1502 if (failedComponentIds.isEmpty()) {
1505 _otherComponentsReported =
true;
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;
1510 vehicleIdPrefix = tr(
"Vehicle %1: ").arg(_vehicle->id());
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;
1517void ParameterManager::_hashCheckTimeout()
1519 _hashCheckDone =
true;
1520 if (_cacheOnlyHashCheck) {
1521 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"_HASH_CHECK timed out in cache-only mode, signalling failure";
1525 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"_HASH_CHECK timed out, falling back to parameter download";
1526 _startParameterDownload(MAV_COMP_ID_ALL);
1529void ParameterManager::_paramRequestListTimeout()
1533 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"_paramRequestListTimeout (log replay): Signalling load complete";
1534 _initialLoadComplete =
true;
1535 _missingParameters =
false;
1536 _parametersReady =
true;
1537 _vehicle->autopilotPlugin()->parametersReadyPreChecks();
1543 if (!_disableAllRetries && (++_initialRequestRetryCount <= _maxInitialRequestListRetry)) {
1544 qCDebug(ParameterManagerLog) << _logVehiclePrefix(-1) <<
"Retrying initial parameter request list";
1545 _startParameterDownload(MAV_COMP_ID_ALL);
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;
1559QString ParameterManager::_remapParamNameToVersion(
const QString ¶mName)
const
1561 static const QString noRemapPrefix = QStringLiteral(
"noremap.");
1562 if (paramName.startsWith(noRemapPrefix)) {
1563 return paramName.mid(noRemapPrefix.length());
1566 const int majorVersion = _vehicle->firmwareMajorVersion();
1567 const int minorVersion = _vehicle->firmwareMinorVersion();
1575 if (!majorVersionRemap.contains(majorVersion)) {
1577 qCDebug(ParameterManagerVerbose1Log) <<
"_remapParamNameToVersion: no major version mapping";
1583 QString mappedParamName = paramName;
1584 for (
int currentMinorVersion = _vehicle->firmwarePlugin()->remapParamNameHigestMinorVersionNumber(majorVersion); currentMinorVersion>minorVersion; currentMinorVersion--) {
1585 if (remapMinorVersion.contains(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;
1595 return mappedParamName;
1598void ParameterManager::_loadOfflineEditingParams()
1600 const QString paramFilename = _vehicle->firmwarePlugin()->offlineEditingParamFile(_vehicle);
1601 if (paramFilename.isEmpty()) {
1605 QFile paramFile(paramFilename);
1606 if (!paramFile.open(QFile::ReadOnly)) {
1607 qCWarning(ParameterManagerLog) <<
"Unable to open offline editing params file" << paramFilename;
1611 QTextStream paramStream(¶mFile);
1612 while (!paramStream.atEnd()) {
1613 const QString
line = paramStream.readLine();
1614 if (
line.trimmed().isEmpty() ||
line.startsWith(
"#")) {
1618 const QStringList paramData =
line.split(
"\t");
1619 if (paramData.count() != 5) {
1620 qCWarning(ParameterManagerLog) <<
"Skipping malformed offline editing param line" <<
line;
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());
1630 QVariant paramValue;
1631 switch (paramType) {
1632 case MAV_PARAM_TYPE_REAL32:
1633 paramValue = QVariant(valStr.toFloat());
1635 case MAV_PARAM_TYPE_UINT32:
1636 paramValue = QVariant(valStr.toUInt());
1638 case MAV_PARAM_TYPE_UINT16:
1639 paramValue = QVariant((quint16)valStr.toUInt());
1641 case MAV_PARAM_TYPE_INT16:
1642 paramValue = QVariant((qint16)valStr.toInt());
1644 case MAV_PARAM_TYPE_UINT8:
1645 paramValue = QVariant((quint8)valStr.toUInt());
1647 case MAV_PARAM_TYPE_INT8:
1648 paramValue = QVariant((qint8)valStr.toUInt());
1651 qCCritical(ParameterManagerLog) <<
"Unknown type" << paramType;
1653 case MAV_PARAM_TYPE_INT32:
1654 paramValue = QVariant(valStr.toInt());
1658 CompInfoParam*
const compInfoParam = _vehicle->compInfoManager()->compInfoParam(offlineDefaultComponentId);
1659 if (!compInfoParam) {
1660 qCWarning(ParameterManagerLog) <<
"No parameter metadata for component" << offlineDefaultComponentId;
1664 Fact*
const fact =
new Fact(offlineDefaultComponentId, paramName,
mavTypeToFactType(paramType),
this);
1670 _parametersReady =
true;
1671 _initialLoadComplete =
true;
1672 _debugCacheCRC.clear();
1677 _vehicle->sendMavCommand(MAV_COMP_ID_AUTOPILOT1,
1678 MAV_CMD_PREFLIGHT_STORAGE,
1688 if (sysAutoConfigFact) {
1693QString ParameterManager::_logVehiclePrefix(
int componentId)
const
1695 if (componentId == -1) {
1696 return QStringLiteral(
"V:%1").arg(_vehicle->
id());
1698 return QStringLiteral(
"V:%1 C:%2").arg(_vehicle->id()).arg(componentId);
1702void ParameterManager::_setLoadProgress(
double loadProgress)
1712 if (_parameterDownloadSkipped != skipped) {
1713 _parameterDownloadSkipped = skipped;
1720 return _paramCountMap.keys();
1725 return _pendingWritesCount > 0;
1728#ifdef QGC_UNITTEST_BUILD
1729void ParameterManager::setPendingWritesForTest(
bool pending)
1731 const bool wasPending = (_pendingWritesCount > 0);
1732 _pendingWritesCount = pending ? 1 : 0;
1733 if (wasPending != pending) {
1745bool ParameterManager::_parseParamFile(
const QString& filename)
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;
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.";
1768 QDataStream in(&file);
1769 in.setByteOrder(QDataStream::LittleEndian);
1771 quint16 magic, num_params, total_params;
1776 if (in.status() != QDataStream::Ok) {
1777 qCDebug(ParameterManagerLog) <<
"_parseParamFile: Error: Could not read Header";
1781 qCDebug(ParameterManagerVerbose2Log) <<
"_parseParamFile: magic: 0x" << Qt::hex << magic;
1782 qCDebug(ParameterManagerVerbose2Log) <<
"_parseParamFile: num_params:" << num_params
1783 <<
"total_params:" << total_params;
1785 if ((magic != magic_standard) && (magic != magic_withdefaults)) {
1786 qCDebug(ParameterManagerLog) <<
"_parseParamFile: Error: File does not start with Magic";
1789 if (num_params > total_params) {
1790 qCDebug(ParameterManagerLog) <<
"_parseParamFile: Error: total_params > num_params";
1793 if (num_params != total_params) {
1795 qCDebug(ParameterManagerLog) <<
"_parseParamFile: Error: total_params != num_params";
1799 while (in.status() == QDataStream::Ok) {
1803 quint8 name_len = 0;
1804 quint8 common_len = 0;
1805 bool withdefault =
false;
1807 char name_buffer[17];
1809 while (
byte == 0x0) {
1811 if (in.status() != QDataStream::Ok) {
1812 if (no_of_parameters_found == num_params) {
1815 qCDebug(ParameterManagerLog) <<
"_parseParamFile: Error: unexpected EOF"
1816 <<
"number of parameters expected:" << num_params
1817 <<
"actual:" << no_of_parameters_found;
1822 ptype =
byte & 0x0F;
1823 flags = (
byte >> 4) & 0x0F;
1824 withdefault = (flags & 0x01) == 0x01;
1826 if (in.status() != QDataStream::Ok) {
1827 qCCritical(ParameterManagerLog) <<
"_parseParamFile: Error: Unexpected EOF while reading flags";
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;
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;
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
1851 <<
"flags" << flags;
1853 QVariant parameterValue = 0;
1854 QVariant defaultValue;
1855 switch (
static_cast<ap_var_type
>(ptype)) {
1862 parameterValue = data8;
1865 defaultValue = data8;
1868 case AP_PARAM_INT16:
1870 parameterValue = data16;
1873 defaultValue = data16;
1876 case AP_PARAM_INT32:
1878 parameterValue = data32;
1881 defaultValue = data32;
1884 case AP_PARAM_FLOAT:
1886 (void) memcpy(&dfloat, &data32, 4);
1887 parameterValue = dfloat;
1891 (void) memcpy(&ddefault, &data32, 4);
1892 defaultValue = ddefault;
1896 qCDebug(ParameterManagerLog) <<
"_parseParamFile: Error: type is out of range" << ptype;
1900 qCDebug(ParameterManagerVerbose2Log) <<
"paramValue" << parameterValue;
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;
1914 Fact *fact =
nullptr;
1915 if (_mapCompId2FactMap.contains(componentId) && _mapCompId2FactMap[componentId].contains(parameterName)) {
1916 fact = _mapCompId2FactMap[componentId][parameterName];
1917 if (withdefault && defaultValue.isValid()) {
1924 qCDebug(ParameterManagerVerbose1Log) << _logVehiclePrefix(componentId) <<
"Adding new fact" << parameterName;
1926 fact =
new Fact(componentId, parameterName, factType,
this);
1927 FactMetaData *
const factMetaData = _vehicle->compInfoManager()->compInfoParam(componentId)->factMetaDataForName(parameterName, fact->
type());
1930 _mapCompId2FactMap[componentId][parameterName] = fact;
1936 if (withdefault && defaultValue.isValid()) {
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);
1954 _checkInitialLoadComplete();
1955 _refreshAllProgressActive =
false;
1956 _setLoadProgress(0.0);
1964void ParameterManager::_incrementPendingWriteCount()
1966 _pendingWritesCount++;
1967 if (_pendingWritesCount == 1) {
1972void ParameterManager::_decrementPendingWriteCount()
1974 if (_pendingWritesCount == 0) {
1975 qCWarning(ParameterManagerLog) <<
"Internal Error: _pendingWriteCount == 0";
1979 _pendingWritesCount--;
1980 if (_pendingWritesCount == 0) {
std::shared_ptr< LinkInterface > SharedLinkInterfacePtr
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)
A Fact is used to hold a single value within the system.
void setMetaData(FactMetaData *metaData, bool setDefaultFromMetaData=false)
void containerSetRawValue(const QVariant &value)
Value coming from Vehicle. This does NOT send a _containerRawValueChanged signal.
FactMetaData * metaData()
FactMetaData::ValueType_t type() const
void setRawValue(const QVariant &value)
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.
bool vehicleRebootRequired() const
QVariant rawValue() const
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 ¶mName) 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 ¶mName)
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 ¶mName, 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)
void tryHashCheckCacheLoad()
bool pendingWrites() const
static QDir parameterCacheDir()
void unsuppressRebootMessage()
static constexpr int kHashCheckTimeoutMs
Timeout for standalone _HASH_CHECK request.
void missingParametersChanged(bool missingParameters)
static constexpr int defaultComponentId
void resetAllParametersToDefaults()
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 ¶mName, int paramIndex)
void _paramRequestReadSuccess(int componentId, const QString ¶mName, 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 ¶mName)
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 suppressRebootMessage()
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 ¶mName)
static VehicleClass_t vehicleClass(MAV_TYPE mavType)
static const char * vehicleClassToCanonicalString(VehicleClass_t vehicleClass)
static FirmwareClass_t firmwareClass(MAV_AUTOPILOT autopilot)
static const char * firmwareClassToCanonicalString(FirmwareClass_t firmwareClass)
QSignalTransition * addThisTransition(PointerToMemberFunction signal, QAbstractState *target)
Simpler version of QState::addTransition which assumes the sender is this.
WeakLinkInterfacePtr primaryLink() const
VehicleLinkManager * vehicleLinkManager()
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)
bool fuzzyCompare(double value1, double value2)
Returns true if the two values are equal or close. Correctly handles 0 and NaN values.
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.
static const int versionNotSetValue