QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
SensorsComponentController.cc
Go to the documentation of this file.
2
3#include "AppMessages.h"
4#include "MAVLinkLib.h"
5#include "PX4SensorDevice.h"
6#include "ParameterManager.h"
8#include "Vehicle.h"
10
11QGC_LOGGING_CATEGORY(SensorsComponentControllerLog, "AutoPilotPlugins.SensorsComponentController")
12
13namespace {
14
15// PX4 acks a calibration cancel twice: the commander answers TEMPORARILY_REJECTED because a calibration is running
16// while the calibration itself takes the cancel and answers ACCEPTED. Either can arrive first, so neither is an error.
17// The "calibration cancelled" status text is what ends the calibration.
18// https://github.com/PX4/PX4-Autopilot/issues/29424
19void px4SensorsCancelCalibrationResultHandler(void* /*resultHandlerData*/, int /*compId*/,
20 const mavlink_command_ack_t& ack,
22{
24 QGC::showAppMessage(SensorsComponentController::tr("Vehicle did not respond to the calibration cancel"));
25 return;
26 }
27 if (ack.result == MAV_RESULT_ACCEPTED || ack.result == MAV_RESULT_TEMPORARILY_REJECTED) {
28 return;
29 }
31}
32
33} // namespace
34
36 : _showOrientationCalArea(false)
37 , _gyroCalInProgress(false)
38 , _magCalInProgress(false)
39 , _accelCalInProgress(false)
40 , _airspeedCalInProgress(false)
41 , _levelCalInProgress(false)
42 , _baroCalInProgress(false)
43 , _orientationCalDownSideVisible(false)
44 , _orientationCalUpsideDownSideVisible(false)
45 , _orientationCalLeftSideVisible(false)
46 , _orientationCalRightSideVisible(false)
47 , _orientationCalNoseDownSideVisible(false)
48 , _orientationCalTailDownSideVisible(false)
49 , _orientationCalDownSideState(SideCalStateIdle)
50 , _orientationCalUpsideDownSideState(SideCalStateIdle)
51 , _orientationCalLeftSideState(SideCalStateIdle)
52 , _orientationCalRightSideState(SideCalStateIdle)
53 , _orientationCalNoseDownSideState(SideCalStateIdle)
54 , _orientationCalTailDownSideState(SideCalStateIdle)
55 , _unknownFirmwareVersion(false)
56 , _waitingForCancel(false)
57{
58 connect(_vehicle, &Vehicle::sensorsParametersResetAck, this, &SensorsComponentController::_handleParametersReset);
59
60 _largeVehicleCalibrationTimer.setSingleShot(true);
61 _largeVehicleCalibrationTimer.setInterval(_largeVehicleCalibrationTimeoutMs);
62 connect(&_largeVehicleCalibrationTimer, &QTimer::timeout, this,
63 &SensorsComponentController::_largeVehicleCalibrationTimedOut);
64}
65
67{
68 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
69 if (sharedLink) {
70 return sharedLink->linkConfiguration()->type() == LinkConfiguration::TypeUdp;
71 } else {
72 return false;
73 }
74}
75
77void SensorsComponentController::_appendStatusLog(const QString& text)
78{
79 if (!_calibrationLog.isEmpty()) {
80 _calibrationLog += QLatin1Char('\n');
81 }
82 _calibrationLog += text;
84}
85
86void SensorsComponentController::_setCalibrationResult(CalibrationResult result)
87{
88 _calibrationResult = result;
90}
91
92void SensorsComponentController::_startLogCalibration(void)
93{
94 _unknownFirmwareVersion = false;
95 _calibrationFailureText.clear();
96 _calibrationDetail.clear();
97 _calibrationLog.clear();
98 _sideAlreadyDone = false;
100 _setCalibrationResult(CalibrationResultNone);
101 _setCalibrationProgress(0);
102 _hideAllCalAreas();
103
104 connect(_vehicle, &Vehicle::textMessageReceived, this, &SensorsComponentController::_handleUASTextMessage,
105 Qt::UniqueConnection);
106}
107
108void SensorsComponentController::_setCalibrationProgress(double progress)
109{
110 if (!qFuzzyIsNull(_calibrationProgress - progress)) {
111 _calibrationProgress = progress;
113 }
114}
115
116void SensorsComponentController::_startVisualCalibration(void)
117{
118 _setAllSidesState(SideCalStateIncomplete);
119 _setCalibrationProgress(0);
120}
121
122void SensorsComponentController::_setAllSidesState(SideCalState state)
123{
124 _orientationCalDownSideState = state;
125 _orientationCalUpsideDownSideState = state;
126 _orientationCalLeftSideState = state;
127 _orientationCalRightSideState = state;
128 _orientationCalTailDownSideState = state;
129 _orientationCalNoseDownSideState = state;
130
132}
133
134void SensorsComponentController::_stopCalibration(SensorsComponentController::StopCalibrationCode code)
135{
136 disconnect(_vehicle, &Vehicle::textMessageReceived, this, &SensorsComponentController::_handleUASTextMessage);
137
138 // The page shows every calibration in its row or in its panel, so a failure needs no message box
139 const bool inlineCalibration = _baroCalInProgress || _levelCalInProgress || _gyroCalInProgress;
140
141 if (code == StopCalibrationSuccess) {
142 _setAllSidesState(SideCalStateCompleted);
143 _setCalibrationProgress(1);
144 } else {
145 // Calibration results are discarded: return any partially completed sides
146 // to the neutral idle preview state
147 _setAllSidesState(SideCalStateIdle);
148 _setCalibrationProgress(0);
149 }
150
151 _waitingForCancel = false;
153
154 _refreshParams();
155
156 switch (code) {
157 case StopCalibrationSuccess:
158 _setCalibrationResult(CalibrationResultSuccess);
159 if (_magCalInProgress) {
160 _vehicle->setRebootRequired();
161 emit magCalComplete();
162 }
163 break;
164
165 case StopCalibrationCancelled:
166 _hideAllCalAreas();
167 break;
168
169 default:
170 // Assume failed
171 _hideAllCalAreas();
172 _setCalibrationResult(CalibrationResultFailed);
173 break;
174 }
175
176 if (inlineCalibration) {
177 emit inlineCalibrationFinished(code == StopCalibrationSuccess, _calibrationFailureText);
178 }
179
180 _magCalInProgress = false;
181 _accelCalInProgress = false;
182 _gyroCalInProgress = false;
183 _airspeedCalInProgress = false;
184 _levelCalInProgress = false;
185 _baroCalInProgress = false;
186
188}
189
191{
192 _startLogCalibration();
193 _vehicle->startCalibration(QGCMAVLink::CalibrationGyro);
194}
195
197{
198 _startLogCalibration();
199 _vehicle->startCalibration(QGCMAVLink::CalibrationMag);
200}
201
203{
204 _startLogCalibration();
205 _vehicle->startCalibration(QGCMAVLink::CalibrationAccel);
206}
207
209{
210 _startLogCalibration();
211 _vehicle->startCalibration(QGCMAVLink::CalibrationLevel);
212}
213
215{
216 _startLogCalibration();
218}
219
221{
222 _startLogCalibration();
224}
225
227{
228 // Watch first: a command which cannot be sent at all reports its failure before sendMavCommand returns.
229 // The result of a command which the vehicle refuses is reported here instead of as an error box.
230 _watchLargeVehicleCalibration();
231
232 // The firmware takes the vehicle's GPS position when the latitude and longitude are not set
233 _vehicle->sendMavCommand(_vehicle->defaultComponentId(), MAV_CMD_FIXED_MAG_CAL_YAW,
234 false, // showError
235 static_cast<float>(headingDegrees),
236 0, // Unused by PX4
237 0, // Latitude, unset
238 0); // Longitude, unset
239}
240
242 const QString& text)
243{
244 // Texts from the firmware's do_mag_calibration_quick() and the worker thread
245 if (text.contains(QStringLiteral("Mag quick calibration finished"), Qt::CaseInsensitive)) {
247 }
248
249 static const QStringList failureTexts = {
250 QStringLiteral("mag quick cal"),
251 QStringLiteral("calibration failed"),
252 QStringLiteral("calibration save failed"),
253 QStringLiteral("cannot open calibration storage"),
254 };
255 for (const QString& failureText : failureTexts) {
256 if (text.contains(failureText, Qt::CaseInsensitive)) {
258 }
259 }
260
262}
263
264void SensorsComponentController::_watchLargeVehicleCalibration(void)
265{
267 &SensorsComponentController::_handleLargeVehicleCalibrationMessage, Qt::UniqueConnection);
268 connect(_vehicle, &Vehicle::mavCommandResult, this, &SensorsComponentController::_handleLargeVehicleCommandResult,
269 Qt::UniqueConnection);
270 _largeVehicleCalibrationTimer.start();
271 _setLargeVehicleCalibrationPending(true);
272}
273
274void SensorsComponentController::_stopWatchingLargeVehicleCalibration(void)
275{
276 _largeVehicleCalibrationTimer.stop();
277 disconnect(_vehicle, &Vehicle::textMessageReceived, this,
278 &SensorsComponentController::_handleLargeVehicleCalibrationMessage);
279 disconnect(_vehicle, &Vehicle::mavCommandResult, this,
280 &SensorsComponentController::_handleLargeVehicleCommandResult);
281 _setLargeVehicleCalibrationPending(false);
282}
283
284void SensorsComponentController::_setLargeVehicleCalibrationPending(bool pending)
285{
286 if (_largeVehicleCalibrationPending != pending) {
287 _largeVehicleCalibrationPending = pending;
289 }
290}
291
293{
294 switch (failureCode) {
296 return tr("The vehicle did not respond.");
298 return tr("A calibration request is already waiting for the vehicle.");
299 default:
300 break;
301 }
302
303 return tr(
304 "The vehicle did not accept the calibration. It may be armed or busy, or its firmware may not support it.");
305}
306
307void SensorsComponentController::_handleLargeVehicleCommandResult(quint32 vehicleId, int targetComponent, int command,
308 int ackResult, int failureCode)
309{
310 Q_UNUSED(targetComponent);
311
312 if (vehicleId != _vehicle->id() || command != MAV_CMD_FIXED_MAG_CAL_YAW) {
313 return;
314 }
315
316 if (ackResult == MAV_RESULT_ACCEPTED || ackResult == MAV_RESULT_IN_PROGRESS) {
317 return;
318 }
319
320 _stopWatchingLargeVehicleCalibration();
322}
323
324void SensorsComponentController::_handleLargeVehicleCalibrationMessage(quint32 uasId, int compId, int severity,
325 QString text, const QString& description)
326{
327 Q_UNUSED(compId);
328 Q_UNUSED(severity);
329 Q_UNUSED(description);
330
331 if (uasId != _vehicle->id()) {
332 return;
333 }
334
337 return;
338 }
339
340 _stopWatchingLargeVehicleCalibration();
341 _refreshParams();
343}
344
345void SensorsComponentController::_largeVehicleCalibrationTimedOut(void)
346{
347 // The firmware may have saved offsets without saying so, so refresh anyway
348 _stopWatchingLargeVehicleCalibration();
349 _refreshParams();
351 tr("No result from the vehicle. Check the compass offsets, or try again."));
352}
353
355{
356 return PX4SensorDevice::description(static_cast<quint32>(deviceId));
357}
358
360{
361 if (_magCalInProgress) {
363 }
364 if (_gyroCalInProgress) {
366 }
367 if (_accelCalInProgress) {
369 }
370 if (_levelCalInProgress) {
372 }
373 if (_airspeedCalInProgress) {
375 }
376 if (_baroCalInProgress) {
378 }
380}
381
382void SensorsComponentController::_handleUASTextMessage(quint32 uasId, int compId, int severity, QString text,
383 const QString& description)
384{
385 Q_UNUSED(compId);
386 Q_UNUSED(severity);
387 Q_UNUSED(description);
388
389 if (uasId != _vehicle->id()) {
390 return;
391 }
392
393 // Needed for level horizon calibration
394 text.replace("&lt;", "<");
395 text.replace("&gt;", ">");
396
397 if (text.contains("progress <")) {
398 QString percent = text.split("<").last().split(">").first();
399 bool ok;
400 int p = percent.toInt(&ok);
401 if (ok) {
402 _setCalibrationProgress(p / 100.0);
403 }
404 return;
405 }
406
407 _appendStatusLog(text);
408 qCDebug(SensorsComponentControllerLog) << text;
409
410 if (_unknownFirmwareVersion) {
411 // We don't know how to do visual cal with the version of firwmare
412 return;
413 }
414
415 // All calibration messages start with [cal]
416 QString calPrefix("[cal] ");
417 if (!text.startsWith(calPrefix)) {
418 // The firmware logs the reason a calibration failed, such as "motion during calibration", just before it
419 // reports the failure
420 _calibrationDetail = text;
421 return;
422 }
423 text = text.right(text.length() - calPrefix.length());
424
425 QString calStartPrefix("calibration started: ");
426 if (text.startsWith(calStartPrefix)) {
427 text = text.right(text.length() - calStartPrefix.length());
428
429 // Split version number and cal type
430 QStringList parts = text.split(" ");
431 if (parts.count() != 2 && parts[0].toInt() != _supportedFirmwareCalVersion) {
432 _unknownFirmwareVersion = true;
433 QString msg = tr("Unsupported calibration firmware version, using log");
434 _appendStatusLog(msg);
435 qDebug() << msg;
436 return;
437 }
438
439 _startVisualCalibration();
440
441 text = parts[1];
442 if (text == "accel" || text == "mag" || text == "gyro") {
443 // _startVisualCalibration() above reset all side indicators to Incomplete
444
445 // Reset all visibility
446 _orientationCalDownSideVisible = false;
447 _orientationCalUpsideDownSideVisible = false;
448 _orientationCalLeftSideVisible = false;
449 _orientationCalRightSideVisible = false;
450 _orientationCalTailDownSideVisible = false;
451 _orientationCalNoseDownSideVisible = false;
452
453 if (text == "accel") {
454 _accelCalInProgress = true;
455 _orientationCalDownSideVisible = true;
456 _orientationCalUpsideDownSideVisible = true;
457 _orientationCalLeftSideVisible = true;
458 _orientationCalRightSideVisible = true;
459 _orientationCalTailDownSideVisible = true;
460 _orientationCalNoseDownSideVisible = true;
461 } else if (text == "mag") {
462 // Work out what the autopilot is configured to. CAL_MAG_SIDES is the legacy name of SENS_MAG_SIDES.
463 int sides = 0;
464
465 const QString sidesParamName = _vehicle->parameterManager()->parameterExists(
466 ParameterManager::defaultComponentId, "SENS_MAG_SIDES")
467 ? QStringLiteral("SENS_MAG_SIDES")
468 : QStringLiteral("CAL_MAG_SIDES");
469
470 if (_vehicle->parameterManager()->parameterExists(ParameterManager::defaultComponentId,
471 sidesParamName)) {
472 // Read the requested calibration directions off the system
473 Fact* const calMagSides = _vehicle->parameterManager()->getParameter(
474 ParameterManager::defaultComponentId, sidesParamName);
475 if (calMagSides) {
476 sides = calMagSides->rawValue().toFloat();
477 } else {
478 qCWarning(SensorsComponentControllerLog)
479 << sidesParamName << "disappeared while starting calibration";
480 sides = (1 << 5) | (1 << 4) | (1 << 3) | (1 << 2) | (1 << 1) | (1 << 0);
481 }
482 } else {
483 // There is no valid setting, default to all six sides
484 sides = (1 << 5) | (1 << 4) | (1 << 3) | (1 << 2) | (1 << 1) | (1 << 0);
485 }
486
487 _magCalInProgress = true;
488 _orientationCalTailDownSideVisible = ((sides & (1 << 0)) > 0);
489 _orientationCalNoseDownSideVisible = ((sides & (1 << 1)) > 0);
490 _orientationCalLeftSideVisible = ((sides & (1 << 2)) > 0);
491 _orientationCalRightSideVisible = ((sides & (1 << 3)) > 0);
492 _orientationCalUpsideDownSideVisible = ((sides & (1 << 4)) > 0);
493 _orientationCalDownSideVisible = ((sides & (1 << 5)) > 0);
494 } else if (text == "gyro") {
495 _gyroCalInProgress = true;
496 _orientationCalDownSideVisible = true;
497 } else {
498 qWarning() << "Unknown calibration message type" << text;
499 }
501 _updateAndEmitShowOrientationCalArea(true);
502 } else if (text == "airspeed") {
503 _airspeedCalInProgress = true;
504 } else if (text == "level") {
505 _levelCalInProgress = true;
506 } else if (text == "baro") {
507 _baroCalInProgress = true;
508 }
510 return;
511 }
512
513 if (text.endsWith("orientation detected")) {
514 QString side = text.section(" ", 0, 0);
515 qCDebug(SensorsComponentControllerLog) << "Side started" << side;
516
517 if (side == "down") {
518 _orientationCalDownSideState = SideCalStateInProgress;
519 } else if (side == "up") {
520 _orientationCalUpsideDownSideState = SideCalStateInProgress;
521 } else if (side == "left") {
522 _orientationCalLeftSideState = SideCalStateInProgress;
523 } else if (side == "right") {
524 _orientationCalRightSideState = SideCalStateInProgress;
525 } else if (side == "front") {
526 _orientationCalNoseDownSideState = SideCalStateInProgress;
527 } else if (side == "back") {
528 _orientationCalTailDownSideState = SideCalStateInProgress;
529 }
530
531 _sideAlreadyDone = false;
532
533 emit orientationCalSidesStateChanged();
534 return;
535 }
536
537 if (text.endsWith("side done, rotate to a different side")) {
538 QString side = text.section(" ", 0, 0);
539 qCDebug(SensorsComponentControllerLog) << "Side finished" << side;
540
541 if (side == "down") {
542 _orientationCalDownSideState = SideCalStateCompleted;
543 } else if (side == "up") {
544 _orientationCalUpsideDownSideState = SideCalStateCompleted;
545 } else if (side == "left") {
546 _orientationCalLeftSideState = SideCalStateCompleted;
547 } else if (side == "right") {
548 _orientationCalRightSideState = SideCalStateCompleted;
549 } else if (side == "front") {
550 _orientationCalNoseDownSideState = SideCalStateCompleted;
551 } else if (side == "back") {
552 _orientationCalTailDownSideState = SideCalStateCompleted;
553 }
554
555 _sideAlreadyDone = false;
556
557 emit orientationCalSidesStateChanged();
558 return;
559 }
560
561 if (text.endsWith("side already completed")) {
562 _sideAlreadyDone = true;
563 emit orientationCalSidesStateChanged();
564 return;
565 }
566
567 QString calCompletePrefix("calibration done:");
568 if (text.startsWith(calCompletePrefix)) {
569 _stopCalibration(StopCalibrationSuccess);
570 return;
571 }
572
573 if (text.startsWith("calibration cancelled")) {
574 _stopCalibration(_waitingForCancel ? StopCalibrationCancelled : StopCalibrationFailed);
575 return;
576 }
577
578 if (text.startsWith("calibration failed")) {
579 _calibrationFailureText =
580 _calibrationDetail.isEmpty() ? text : _calibrationDetail + QStringLiteral(": ") + text;
581 _stopCalibration(StopCalibrationFailed);
582 return;
583 }
584}
585
586void SensorsComponentController::_refreshParams(void)
587{
588 _vehicle->parameterManager()->bulkRefresh(ParameterManager::defaultComponentId, {
589 QStringLiteral("CAL_MAG0_ID"), QStringLiteral("CAL_MAG1_ID"), QStringLiteral("CAL_MAG2_ID"),
590 QStringLiteral("CAL_MAG0_ROT"), QStringLiteral("CAL_MAG1_ROT"), QStringLiteral("CAL_MAG2_ROT"),
591 QStringLiteral("CAL_*"),
592 QStringLiteral("SENS_*"),
593 }, false /* notifyFailure */);
594}
595
596void SensorsComponentController::_updateAndEmitShowOrientationCalArea(bool show)
597{
598 _showOrientationCalArea = show;
600}
601
602void SensorsComponentController::_hideAllCalAreas(void)
603{
604 _updateAndEmitShowOrientationCalArea(false);
605}
606
608{
609 _waitingForCancel = true;
611
612 const Vehicle::MavCmdAckHandlerInfo_t handlerInfo{
613 .resultHandler = px4SensorsCancelCalibrationResultHandler,
614 .resultHandlerData = nullptr,
615 .progressHandler = nullptr,
616 .progressHandlerData = nullptr,
617 };
618 // All zero params cancel the running calibration
619 _vehicle->sendMavCommandWithHandler(&handlerInfo, _vehicle->defaultComponentId(), MAV_CMD_PREFLIGHT_CALIBRATION);
620}
621
622void SensorsComponentController::_handleParametersReset(bool success)
623{
624 if (success) {
625 QGC::showAppMessage(tr("Reset successful"));
626
627 QTimer::singleShot(1000, this, [this]() {
628 _refreshParams();
629 });
630 }
631 else {
632 QGC::showAppMessage(tr("Reset failed"));
633 }
634}
635
637{
638 auto compId = _vehicle->defaultComponentId();
639
640 _vehicle->sendMavCommand(compId,
641 MAV_CMD_PREFLIGHT_STORAGE,
642 true, // showError
643 3, // Reset factory parameters
644 -1); // Don't do anything with mission storage
645}
std::shared_ptr< LinkInterface > SharedLinkInterfacePtr
#define QGC_LOGGING_CATEGORY(name, categoryStr)
struct __mavlink_command_ack_t mavlink_command_ack_t
static QString description(quint32 deviceId)
Chip name and bus for display, such as "ICM42688P ยท SPI". Empty for the unset device ID 0.
static constexpr int defaultComponentId
Q_INVOKABLE void calibrateCompassLargeVehicle(double headingDegrees)
void orientationCalSidesVisibleChanged(void)
ActiveCalibration
Calibration which is running through the firmware's [cal] message protocol.
static QString largeVehicleCommandFailureText(int failureCode)
Why the large vehicle compass calibration command failed, from the failureCode of Vehicle::mavCommand...
void calibrationProgressChanged(void)
@ CalibrationResultNone
Running, cancelled, or none has run.
void inlineCalibrationFinished(bool success, const QString &message)
void waitingForCancelChanged(void)
ActiveCalibration activeCalibration() const
static LargeVehicleCalibrationResult largeVehicleCalibrationResult(const QString &text)
What a status text from the vehicle says about the outcome of a large vehicle compass calibration.
@ SideCalStateIncomplete
Calibration running, side not yet calibrated.
@ SideCalStateIdle
No calibration data to show (neutral preview).
@ SideCalStateCompleted
Side calibration complete.
void largeVehicleCalibrationPendingChanged(void)
void orientationCalSidesStateChanged(void)
Q_INVOKABLE QString deviceDescription(int deviceId) const
Chip and bus of a CAL_*_ID device ID parameter value, empty when the ID is not set.
void largeVehicleCalibrationFinished(bool success, const QString &message)
success is false when the firmware reported a failure, message is its text
Q_INVOKABLE void calibrateCompass(void)
What the firmware has logged during the calibration, one message per line.
void calibrationResultChanged(void)
void calibrationActiveChanged(void)
void showOrientationCalAreaChanged(void)
static void showCommandAckError(const mavlink_command_ack_t &ack)
Definition Vehicle.cc:2255
void sensorsParametersResetAck(bool success)
void textMessageReceived(quint32 sysid, int componentid, int severity, QString text, QString description)
void mavCommandResult(quint32 vehicleId, int targetComponent, int command, int ackResult, int failureCode)
quint32 id() const
Definition Vehicle.h:446
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.
Definition AppMessages.cc:9
Result of timestamp-based calibration/matching.
struct VehicleTypes::MavCmdAckHandlerInfo_s MavCmdAckHandlerInfo_t
Callback info bundle for sendMavCommandWithHandler.
@ MavCmdResultFailureDuplicateCommand
Unable to send command since duplicate is already being waited on for response.
@ MavCmdResultFailureNoResponseToCommand
No response from vehicle to command.