QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
MockLink.cc
Go to the documentation of this file.
1#include "MockLink.h"
2#include "MAVLinkLib.h"
3#include "LinkManager.h"
4#include "MAVLinkProtocol.h"
5#include "MAVLinkSigning.h"
6#include "SecureMemory.h"
7#include "MockLinkCamera.h"
8#include "MockLinkFTP.h"
9#include "MockLinkGimbal.h"
10#include "MockLinkWorker.h"
11#include "QGCLoggingCategory.h"
12#include "FirmwarePlugin.h"
13#include "FactMetaData.h"
14#include "ParameterManager.h"
15#include "AppMessages.h"
16#include "QGCMath.h"
17
19
20#include <QtCore/QFile>
21#include <QtCore/QJsonArray>
22#include <QtCore/QJsonDocument>
23#include <QtCore/QJsonObject>
24#include <QtCore/QLatin1StringView>
25#include <QtCore/QMutexLocker>
26#include <QtCore/QSet>
27#include <QtCore/QRandomGenerator>
28#include <QtCore/QTemporaryFile>
29#include <QtCore/QThread>
30#include <QtCore/QTimer>
31
32#include <cmath>
33#include <cstring>
34
35QGC_LOGGING_CATEGORY(MockLinkLog, "Comms.MockLink.MockLink")
36QGC_LOGGING_CATEGORY(MockLinkVerboseLog, "Comms.MockLink.MockLink:verbose")
37
38std::atomic<int> MockLink::_nextVehicleSystemId{128};
39
40namespace {
41
42// Parameters PX4 hasn't looked up because nothing uses them: serial port settings no function uses (see
43// PX4MockLink.params for the ones in use) and a second battery the board has no power input for
44constexpr std::pair<const char*, int32_t> kPX4UnusedParams[] = {
45 {"BAT2_SOURCE", 1}, {"GPS_2_PROTOCOL", 1}, {"MAV_0_BROADCAST", 1}, {"MAV_0_REMOTE_PRT", 14550},
46 {"MAV_0_UDP_PRT", 14556}, {"MAV_1_BROADCAST", 0}, {"MAV_1_FLOW_CTRL", 2}, {"MAV_1_FORWARD", 0},
47 {"MAV_1_MODE", 2}, {"MAV_1_RADIO_CTL", 1}, {"MAV_1_RATE", 0}, {"MAV_1_REMOTE_PRT", 0},
48 {"MAV_1_UDP_PRT", 0}, {"SER_EXT2_BAUD", 57600}, {"SER_GPS2_BAUD", 0}, {"SER_GPS3_BAUD", 0},
49 {"SER_RC_BAUD", 0}, {"SER_TEL2_BAUD", 921600}, {"SER_TEL3_BAUD", 57600}, {"SER_TEL4_BAUD", 57600},
50 {"SER_URT6_BAUD", 57600}, {"SER_WIFI_BAUD", 1},
51};
52
53} // namespace
54
55QList<MockLink::FlightMode_t> MockLink::_availableFlightModes = {
56 // Mode Name Standard Mode Custom Mode CanBeSet adv
57 { "Manual", 0, PX4CustomMode::MANUAL, true, true },
58 { "Stabilized", 0, PX4CustomMode::STABILIZED, true, true },
59 { "Acro", 0, PX4CustomMode::ACRO, true, true },
60 { "Altitude", 0, PX4CustomMode::ALTCTL, true, false},
61 { "Offboard", 0, PX4CustomMode::OFFBOARD, true, true },
62 { "Position", 0, PX4CustomMode::POSCTL_POSCTL, true, false},
63 { "Orbit", 0, PX4CustomMode::POSCTL_ORBIT, false, true },
64 { "Hold", 0, PX4CustomMode::AUTO_LOITER, true, true },
65 { "Mission", 0, PX4CustomMode::AUTO_MISSION, true, true },
66 { "Return", 0, PX4CustomMode::AUTO_RTL, true, true },
67 { "Land", MAV_STANDARD_MODE_LAND, PX4CustomMode::AUTO_LAND, false, true },
68 { "Precision Landing", 0, PX4CustomMode::AUTO_PRECLAND, true, true },
69 { "Takeoff", MAV_STANDARD_MODE_TAKEOFF, PX4CustomMode::AUTO_TAKEOFF, false, false},
70 { "MockLink Mode", 0, PX4CustomMode::RATTITUDE, true, false},
71 // Deliberately uses the reserved (deleted RTGS) AUTO sub-mode so QGC has no name for it
72 { "(Mode not available)", 0, static_cast<uint32_t>(PX4_CUSTOM_MAIN_MODE_AUTO << 16 | (PX4_CUSTOM_SUB_MODE_AUTO_RESERVED_DO_NOT_USE << 24)), false, false},
73 { "MockLink Mode (delayed)",0, PX4CustomMode::AUTO_FOLLOW_TARGET, true, false},
74};
75
76// The ArduPilot lists below mirror the availableFlightModes lists in the corresponding
77// firmware plugins (names and custom mode values must match) so that StandardModes streaming
78// results in the same mode names the plugins use.
79QList<MockLink::FlightMode_t> MockLink::_apmCopterAvailableFlightModes = {
80 // Mode Name Standard Mode Custom Mode CanBeSet adv
81 { "Stabilize", 0, 0, true, true },
82 { "Acro", 0, 1, true, true },
83 { "Altitude Hold", 0, 2, true, true },
84 { "Auto", 0, 3, true, true },
85 { "Guided", 0, 4, true, true },
86 { "Loiter", 0, 5, true, true },
87 { "RTL", 0, 6, true, true },
88 { "Circle", 0, 7, true, true },
89 { "Land", 0, 9, true, true },
90 { "Drift", 0, 11, true, true },
91 { "Sport", 0, 13, true, true },
92 { "Flip", 0, 14, true, true },
93 { "Autotune", 0, 15, true, true },
94 { "Position Hold", 0, 16, true, true },
95 { "Brake", 0, 17, true, true },
96 { "Throw", 0, 18, true, true },
97 { "Avoid ADSB", 0, 19, true, true },
98 { "Guided No GPS", 0, 20, true, true },
99 { "Smart RTL", 0, 21, true, true },
100 { "Flow Hold", 0, 22, true, true },
101 { "Follow", 0, 23, true, true },
102 { "ZigZag", 0, 24, true, true },
103 { "SystemID", 0, 25, true, true },
104 { "AutoRotate", 0, 26, true, true },
105 { "AutoRTL", 0, 27, true, true },
106 { "Turtle", 0, 28, true, true },
107};
108
109QList<MockLink::FlightMode_t> MockLink::_apmPlaneAvailableFlightModes = {
110 // Mode Name Standard Mode Custom Mode CanBeSet adv
111 { "Manual", 0, 0, true, true },
112 { "Circle", 0, 1, true, true },
113 { "Stabilize", 0, 2, true, true },
114 { "Training", 0, 3, true, true },
115 { "Acro", 0, 4, true, true },
116 { "FBW A", 0, 5, true, true },
117 { "FBW B", 0, 6, true, true },
118 { "Cruise", 0, 7, true, true },
119 { "Autotune", 0, 8, true, true },
120 { "Auto", 0, 10, true, true },
121 { "RTL", 0, 11, true, true },
122 { "Loiter", 0, 12, true, true },
123 { "Takeoff", 0, 13, true, true },
124 { "Avoid ADSB", 0, 14, true, true },
125 { "Guided", 0, 15, true, true },
126 { "Initializing", 0, 16, false, true },
127 { "QuadPlane Stabilize", 0, 17, true, true },
128 { "QuadPlane Hover", 0, 18, true, true },
129 { "QuadPlane Loiter", 0, 19, true, true },
130 { "QuadPlane Land", 0, 20, true, true },
131 { "QuadPlane RTL", 0, 21, true, true },
132 { "QuadPlane AutoTune", 0, 22, true, true },
133 { "QuadPlane Acro", 0, 23, true, true },
134 { "Thermal", 0, 24, true, true },
135 { "Loiter to QLand", 0, 25, true, true },
136 { "Autoland", 0, 26, true, true },
137};
138
139QList<MockLink::FlightMode_t> MockLink::_apmRoverAvailableFlightModes = {
140 // Mode Name Standard Mode Custom Mode CanBeSet adv
141 { "Manual", 0, 0, true, true },
142 { "Acro", 0, 1, true, true },
143 { "Learning", 0, 2, false, true },
144 { "Steering", 0, 3, true, true },
145 { "Hold", 0, 4, true, true },
146 { "Loiter", 0, 5, true, true },
147 { "Follow", 0, 6, true, true },
148 { "Simple", 0, 7, true, true },
149 { "Dock", 0, 8, true, true },
150 { "Circle", 0, 9, true, true },
151 { "Auto", 0, 10, true, true },
152 { "RTL", 0, 11, true, true },
153 { "Smart RTL", 0, 12, true, true },
154 { "Guided", 0, 15, true, true },
155 { "Initializing", 0, 16, false, true },
156};
157
158QList<MockLink::FlightMode_t> MockLink::_apmSubAvailableFlightModes = {
159 // Mode Name Standard Mode Custom Mode CanBeSet adv
160 { "Manual", 0, 19, true, true },
161 { "Stabilize", 0, 0, true, true },
162 { "Acro", 0, 1, true, true },
163 { "Depth Hold", 0, 2, true, true },
164 { "Auto", 0, 3, true, true },
165 { "Guided", 0, 4, true, true },
166 { "Circle", 0, 7, true, true },
167 { "Surface", 0, 9, true, true },
168 { "Position Hold", 0, 16, true, true },
169 { "Motor Detection", 0, 20, false, true },
170 { "Surftrak", 0, 21, true, true },
171};
172
174 : LinkInterface(config, parent)
175 , _mockConfig(qobject_cast<const MockConfiguration*>(_config.get()))
176 , _firmwareType(_mockConfig->firmwareType())
177 , _vehicleType(_mockConfig->vehicleType())
178 , _sendStatusText(_mockConfig->sendStatusText())
179 , _apmStartFreshParams(_mockConfig->apmStartFreshParams())
180 , _enableCamera(_mockConfig->enableCamera())
181 , _enableGimbal(_mockConfig->enableGimbal())
182 , _enableProximity(_mockConfig->enableProximity())
183 , _failureMode(_mockConfig->failureMode())
184 , _stayMavlinkV1(_mockConfig->stayMavlinkV1())
185 , _ftpCapability(_mockConfig->ftpCapability())
186 , _sendRadioStatusEnabled(_mockConfig->sendRadioStatus())
187 , _vehicleSystemId(
188 _mockConfig->systemId()
189 ? _mockConfig->systemId()
190 : (_mockConfig->incrementVehicleId() ? _nextVehicleSystemId++ : static_cast<int>(_nextVehicleSystemId)))
191 , _vehicleLatitude(_defaultVehicleLatitude + ((static_cast<int>(_vehicleSystemId & 0xFF) - 128) * 0.0001))
192 , _vehicleLongitude(_defaultVehicleLongitude + ((static_cast<int>(_vehicleSystemId & 0xFF) - 128) * 0.0001))
193 , _boardVendorId(_mockConfig->boardVendorId())
194 , _boardProductId(_mockConfig->boardProductId())
195 , _missionItemHandler(new MockLinkMissionItemHandler(this))
196 , _mockLinkCamera(
197 _enableCamera
198 ? new MockLinkCamera(this, _mockConfig->cameraCaptureVideo(), _mockConfig->cameraCaptureImage(),
199 _mockConfig->cameraHasModes(), _mockConfig->cameraHasVideoStream(),
200 _mockConfig->cameraCanCaptureImageInVideoMode(),
201 _mockConfig->cameraCanCaptureVideoInImageMode(), _mockConfig->cameraHasBasicZoom(),
202 _mockConfig->cameraHasTrackingPoint(), _mockConfig->cameraHasTrackingRectangle())
203 : nullptr)
204 , _mockLinkGimbal(_enableGimbal
205 ? new MockLinkGimbal(this, _mockConfig->gimbalHasRollAxis(),
206 _mockConfig->gimbalHasPitchAxis(), _mockConfig->gimbalHasYawAxis(),
207 _mockConfig->gimbalHasYawFollow(), _mockConfig->gimbalHasYawLock(),
208 _mockConfig->gimbalHasRetract(), _mockConfig->gimbalHasNeutral(),
209 static_cast<uint8_t>(_mockConfig->gimbalDeviceId()))
210 : nullptr)
211 , _mockLinkPX4Calibration(new MockLinkPX4Calibration(this))
212 , _mockLinkFTP(new MockLinkFTP(_vehicleSystemId, _vehicleComponentId, this))
213 , _requestedVideoStreamType(_mockConfig->videoStreamTypeEnum())
214{
215 qCDebug(MockLinkLog) << this;
216
217 if (_mockConfig->startArmed()) {
218 setArmed(true);
219 }
220
221 if (_mockConfig->preloadMission()) {
222 _missionItemHandler->loadSimpleMultirotorMission();
223 }
224
225 // Initialize ADS-B vehicles with different starting conditions
226 _adsbVehicles.reserve(_numberOfVehicles);
227 for (int i = 0; i < _numberOfVehicles; ++i) {
228 ADSBVehicle vehicle{};
229 vehicle.angle = i * 72.0; // Different starting directions (angles 0, 72, 144, 216, 288)
230
231 // Set initial coordinates slightly offset from the default coordinates
232 const double latOffset = 0.001 * i;
233 const double lonOffset = 0.001 * (i % 2 == 0 ? i : -i);
234 vehicle.coordinate = QGeoCoordinate(_defaultVehicleLatitude + latOffset, _defaultVehicleLongitude + lonOffset);
235
236 // Set a unique starting altitude for each vehicle near the home altitude
237 vehicle.altitude = _defaultVehicleHomeAltitude + (i * 5);
238
239 _adsbVehicles.append(vehicle);
240 }
241
242 (void) QObject::connect(this, &MockLink::writeBytesQueuedSignal, this, &MockLink::_writeBytesQueued, Qt::QueuedConnection);
243
244 _loadParams();
245 _runningTime.start();
246
247 _workerThread = new QThread(this);
248 _workerThread->setObjectName(QStringLiteral("Mock_%1").arg(_mockConfig->name()));
249 _worker = new MockLinkWorker(this);
250 _worker->moveToThread(_workerThread);
251 (void) connect(_workerThread, &QThread::started, _worker, &MockLinkWorker::startWork);
252 (void) connect(_workerThread, &QThread::finished, _worker, &QObject::deleteLater);
253 _workerThread->start();
254}
255
257{
259
260 delete _mockLinkCamera;
261 delete _mockLinkGimbal;
262 delete _mockLinkPX4Calibration;
263
264 if (!_logDownloadFilename.isEmpty()) {
265 QFile::remove(_logDownloadFilename);
266 }
267
268 if (_workerThread) {
269 _workerThread->quit();
270 _workerThread->wait();
271 }
272
273 qCDebug(MockLinkLog) << this;
274}
275
276bool MockLink::_connect()
277{
278 if (!_connected) {
279 _connected = true;
280 _disconnectedEmitted = false;
281 // ArduPilot starts out sending MAVLink v1 and only switches to v2 once it sees a v2
282 // message from the GCS. Emulate that: outgoing traffic starts as v1.
283 // High latency links are exempt: QGC doesn't transmit on them, so the upgrade could never happen.
284 // Note: high latency takes precedence over OptionStayMavlinkV1 (the two are not meant to be combined).
285 _mavlinkV2Upgraded = linkConfiguration()->isHighLatency() || _vehicleSystemId > UINT8_MAX;
286 mavlink_status_t *const outgoingStatus = mavlink_get_channel_status(_outgoingMavlinkChannel);
287 if (_mavlinkV2Upgraded) {
288 outgoingStatus->flags &= ~MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
289 } else {
290 outgoingStatus->flags |= MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
291 }
292 mavlink_status_t *const incomingStatus = mavlink_get_channel_status(_incomingMavlinkChannel);
293 incomingStatus->flags &= ~MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
294
295 _startVideoStreamServer();
296
297 // The worker's first tick may have run before the link connected, so send a heartbeat now and let the vehicle
298 // appear without waiting a tick. QGC drops v1 telemetry, so the 1 Hz batch waits for the v2 upgrade unless
299 // traffic already starts as v2.
300 if (_workerThread && _workerThread->isRunning()) {
301 const bool sendTelemetry = _mavlinkV2Upgraded;
302 (void) QMetaObject::invokeMethod(
303 _worker,
304 [this, sendTelemetry] {
305 run10HzTasks();
306 if (sendTelemetry) {
307 run1HzTasks();
308 }
309 },
310 Qt::QueuedConnection);
311 }
312
313 emit connected();
314 }
315
316 return true;
317}
318
320{
321 _missionItemHandler->shutdown();
322
323 // Stop worker thread first to prevent any more messages from being sent.
324 // This must happen before setting _connected = false to avoid race conditions
325 // where the worker checks _connected (true), then we set it false, then the
326 // worker continues sending messages to a disconnecting/destroyed vehicle.
327 if (_workerThread && _workerThread->isRunning()) {
328 _workerThread->quit();
329 _workerThread->wait();
330 }
331
332 // signing/streams pointers alias MockLink memory — clear before emit in case the disconnected signal frees us.
333 if (_outgoingMavlinkChannelIsSet()) {
334 mavlink_status_t* const outgoingStatus = mavlink_get_channel_status(_outgoingMavlinkChannel);
335 outgoingStatus->signing = nullptr;
336 outgoingStatus->signing_streams = nullptr;
337 mavlink_reset_channel_status(_outgoingMavlinkChannel);
338 }
339
340 // Must run before the disconnected emit below: that signal can release the last
341 // shared_ptr to this MockLink, so touching members afterwards is use-after-free.
342 _stopVideoStreamServer();
343
344 if (_connected) {
345 _connected = false;
346 if (!_disconnectedEmitted.exchange(true)) {
347 emit disconnected();
348 }
349 }
350}
351
352void MockLink::_startVideoStreamServer()
353{
354 // Only serve a stream when a camera advertising a video stream is present and a type was requested.
355 if (_videoStreamServer || !_mockLinkCamera || !_mockConfig->cameraHasVideoStream()
356 || _requestedVideoStreamType == MockConfiguration::VideoStreamNone) {
357 return;
358 }
359
361 quint16 port = 5600;
362 switch (_requestedVideoStreamType) {
365 port = 5600;
366 break;
369 port = 5601;
370 break;
373 port = 8554;
374 break;
377 port = 5600;
378 break;
381 port = 5600;
382 break;
384 return;
385 }
386
387 auto *server = new MockVideoStreamServer();
388 if (!server->start(serverType, QStringLiteral("127.0.0.1"), port)) {
389 qCWarning(MockLinkLog) << "Failed to start mock video stream server for type" << _requestedVideoStreamType;
390 delete server;
391 return;
392 }
393
394 _videoStreamServer = server;
395 {
396 QMutexLocker locker(&_videoStreamMutex);
397 _servedVideoStreamType = _requestedVideoStreamType;
398 _videoStreamUri = server->servedUri();
399 }
400 qCDebug(MockLinkLog) << "Mock video stream server serving" << server->servedUri();
401}
402
403void MockLink::_stopVideoStreamServer()
404{
405 // Clear the served-stream snapshot first so observers (servedVideoStream) stop
406 // advertising the URI before the server actually goes away.
407 {
408 QMutexLocker locker(&_videoStreamMutex);
409 _servedVideoStreamType = MockConfiguration::VideoStreamNone;
410 _videoStreamUri.clear();
411 }
412 if (_videoStreamServer) {
413 delete _videoStreamServer;
414 _videoStreamServer = nullptr;
415 }
416}
417
418bool MockLink::cameraStreamTransmitted(uint8_t compId, uint8_t streamId) const
419{
420 return _mockLinkCamera && _mockLinkCamera->streamTransmitted(compId, streamId);
421}
422
424{
425 QMutexLocker locker(&_videoStreamMutex);
426 type = _servedVideoStreamType;
427 uri = _videoStreamUri;
428}
429
431{
432 if (!_mavlinkStarted || !_connected || !mavlinkChannelIsSet()) {
433 return;
434 }
435
436 if (linkConfiguration()->isHighLatency() && _highLatencyTransmissionEnabled) {
437 _sendHighLatency2();
438 return;
439 }
440
441 _sendVibration();
442 _sendBatteryStatus();
443 _sendNamedValueFloats();
444 _sendSysStatus();
445 if (_enableADSB) {
446 _sendADSBVehicles();
447 }
448 if (_vehicleType != MAV_TYPE_SUBMARINE) {
449 _sendRemoteIDArmStatus();
450 }
451 _sendAvailableModesMonitor();
452
453 if (_enableGimbal) {
454 _mockLinkGimbal->run1HzTasks();
455 }
456
457 if (_enableProximity) {
458 _sendDistanceSensors();
459 }
460
461 _sendEscInfo();
462 _sendEscStatus();
463 if (_sendRadioStatusEnabled) {
464 _sendRadioStatus();
465 }
466
467 if (!QGC::runningUnitTests()) {
468 // Sending RC Channels during unit test breaks RC tests which does it's own RC simulation
469 _sendRCChannels();
470 }
471
472 if (_sendHomePositionDelayCount > 0 && !QGC::runningUnitTests()) {
473 // We delay home position to simulate a real vehicle, but not during unit tests to keep them fast
474 _sendHomePositionDelayCount--;
475 } else {
476 _sendHomePosition();
477 }
478}
479
481{
482 if (linkConfiguration()->isHighLatency()) {
483 return;
484 }
485
486 if (_mavlinkStarted && _connected && mavlinkChannelIsSet()) {
487 _sendHeartBeat();
488 if (_companionParams) {
489 _sendCompanionHeartBeat();
490 }
491 const bool gpsDelayExpired = (_sendGPSPositionDelayCount == 0);
492 if (_sendGPSPositionDelayCount > 0) {
493 // We delay gps position for better testing
494 _sendGPSPositionDelayCount--;
495 }
496 if (gpsDelayExpired || QGC::runningUnitTests()) {
497 if (_vehicleType != MAV_TYPE_SUBMARINE) {
498 _sendGpsRawInt();
499 _sendGlobalPositionInt();
500 }
501 _sendExtendedSysState();
502 }
503
504 _sendAttitudeQuaternion();
505 _sendAttitudeTarget();
506 _sendLocalPositionNed();
507 _sendPositionTargetLocalNed();
508
509 _mockLinkPX4Calibration->run10HzTasks();
510
511 if (_enableCamera) {
512 // Same rate as the autopilot heartbeat, so camera discovery starts right after initial connect
513 _mockLinkCamera->sendCameraHeartbeats();
514 _mockLinkCamera->run10HzTasks();
515 }
516 }
517}
518
520{
521 if (_mavlinkStarted && _connected && mavlinkChannelIsSet()) {
522 // Standard modes are served even on high-latency links since the request is still accepted there.
523 _availableModesWorker();
524 }
525
526 if (linkConfiguration()->isHighLatency()) {
527 return;
528 }
529
530 if (_mavlinkStarted && _connected && mavlinkChannelIsSet()) {
531 const int paramSends = QGC::runningUnitTests() ? kTestParamRequestListBatch : 1;
532 for (int i = 0; i < paramSends; ++i) {
533 _paramRequestListWorker();
534 }
535 _logDownloadWorker();
536 _apmCompassCalWorker();
537 _apmAccelCalWorker();
538 }
539}
540
542{
543 _sendStatusTextMessages();
544}
545
547{
548 sendStatusTextMessage(MAV_SEVERITY_INFO, QStringLiteral("Status text boot info"));
549 sendStatusTextMessage(MAV_SEVERITY_NOTICE, QStringLiteral("Status text boot notice"));
550}
551
553{
554 // should only be called by the LinkManager during setup
555 if (_incomingMavlinkChannelIsSet() || _outgoingMavlinkChannelIsSet() || mavlinkChannelIsSet()) {
556 qCWarning(MockLinkLog) << "Mock MAVLink channels are already allocated";
557 return false;
558 }
559
561 qCWarning(MockLinkLog) << "LinkInterface::_allocateMavlinkChannel failed";
562 return false;
563 }
564
565 _incomingMavlinkChannel = LinkManager::instance()->allocateMavlinkChannel();
566 if (!_incomingMavlinkChannelIsSet()) {
567 qCWarning(MockLinkLog) << "_allocateMavlinkChannel aux failed";
569 return false;
570 }
571
572 _outgoingMavlinkChannel = LinkManager::instance()->allocateMavlinkChannel();
573 if (!_outgoingMavlinkChannelIsSet()) {
574 qCWarning(MockLinkLog) << "_allocateMavlinkChannel vehicle failed";
575 LinkManager::instance()->freeMavlinkChannel(_incomingMavlinkChannel);
576 _incomingMavlinkChannel = LinkManager::invalidMavlinkChannel();
578 return false;
579 }
580
581 qCDebug(MockLinkLog) << "_allocateMavlinkChannel aux:" << _incomingMavlinkChannel << "vehicle:" << _outgoingMavlinkChannel;
582 return true;
583}
584
586{
587 qCDebug(MockLinkLog) << "_freeMavlinkChannel aux:" << _incomingMavlinkChannel << "vehicle:" << _outgoingMavlinkChannel;
588 if (!_incomingMavlinkChannelIsSet()) {
589 if (_outgoingMavlinkChannelIsSet() || mavlinkChannelIsSet()) {
590 qCWarning(MockLinkLog) << "Releasing a partially allocated mock MAVLink channel set";
591 }
592 }
593
594 if (_outgoingMavlinkChannelIsSet()) {
595 // Detach our _mockSigning before the channel is freed; the bytes back this struct in MockLink memory.
596 mavlink_reset_channel_status(_outgoingMavlinkChannel);
597 LinkManager::instance()->freeMavlinkChannel(_outgoingMavlinkChannel);
598 _outgoingMavlinkChannel = LinkManager::invalidMavlinkChannel();
599 }
600 if (_incomingMavlinkChannelIsSet()) {
601 mavlink_reset_channel_status(_incomingMavlinkChannel);
602 LinkManager::instance()->freeMavlinkChannel(_incomingMavlinkChannel);
603 _incomingMavlinkChannel = LinkManager::invalidMavlinkChannel();
604 }
605 if (mavlinkChannelIsSet()) {
607 }
608}
609
610bool MockLink::_incomingMavlinkChannelIsSet() const
611{
612 return (LinkManager::invalidMavlinkChannel() != _incomingMavlinkChannel);
613}
614
615bool MockLink::_outgoingMavlinkChannelIsSet() const
616{
617 return (LinkManager::invalidMavlinkChannel() != _outgoingMavlinkChannel);
618}
619
620void MockLink::_loadParams()
621{
622 QFile paramFile;
623 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
624 if (_vehicleType == MAV_TYPE_FIXED_WING) {
625 paramFile.setFileName(":/FirmwarePlugin/APM/Plane.OfflineEditing.params");
626 } else if (_vehicleType == MAV_TYPE_SUBMARINE ) {
627 paramFile.setFileName(":/FirmwarePlugin/APM/Sub.OfflineEditing.params");
628 } else if (_vehicleType == MAV_TYPE_GROUND_ROVER ) {
629 paramFile.setFileName(":/FirmwarePlugin/APM/Rover.OfflineEditing.params");
630 } else {
631 paramFile.setFileName(":/FirmwarePlugin/APM/Copter.OfflineEditing.params");
632 }
633 } else if (_firmwareType == MAV_AUTOPILOT_GENERIC) {
634 paramFile.setFileName(":/MockLink/GenericMockLink.params");
635 } else {
636 paramFile.setFileName(":/MockLink/PX4MockLink.params");
637 }
638
639 if (!paramFile.open(QFile::ReadOnly)) {
640 qCWarning(MockLinkLog) << "Cannot open mock parameters:" << paramFile.fileName() << paramFile.errorString();
641 return;
642 }
643
644 QTextStream paramStream(&paramFile);
645 while (!paramStream.atEnd()) {
646 const QString line = paramStream.readLine();
647
648 if (line.startsWith("#")) {
649 continue;
650 }
651
652 const QStringList paramData = line.split("\t");
653 if (paramData.size() != 5) {
654 qCWarning(MockLinkLog) << "Invalid mock parameter row in" << paramFile.fileName();
655 _mapParamName2Value.clear();
656 _mapParamName2MavParamType.clear();
657 return;
658 }
659
660 const int compId = paramData.at(1).toInt();
661 const QString paramName = paramData.at(2);
662 const QString valStr = paramData.at(3);
663 const uint paramType = paramData.at(4).toUInt();
664
665 QVariant paramValue;
666 switch (paramType) {
667 case MAV_PARAM_TYPE_REAL32:
668 paramValue = QVariant(valStr.toFloat());
669 break;
670 case MAV_PARAM_TYPE_UINT32:
671 paramValue = QVariant(valStr.toUInt());
672 break;
673 case MAV_PARAM_TYPE_INT32:
674 paramValue = QVariant(valStr.toInt());
675 break;
676 case MAV_PARAM_TYPE_UINT16:
677 paramValue = QVariant((quint16)valStr.toUInt());
678 break;
679 case MAV_PARAM_TYPE_INT16:
680 paramValue = QVariant((qint16)valStr.toInt());
681 break;
682 case MAV_PARAM_TYPE_UINT8:
683 paramValue = QVariant((quint8)valStr.toUInt());
684 break;
685 case MAV_PARAM_TYPE_INT8:
686 paramValue = QVariant((qint8)valStr.toUInt());
687 break;
688 default:
689 qCCritical(MockLinkVerboseLog) << "Unknown type" << paramType;
690 paramValue = QVariant(valStr.toInt());
691 break;
692 }
693
694 qCDebug(MockLinkVerboseLog) << "Loading param" << paramName << paramValue;
695
696 _mapParamName2Value[compId][paramName] = paramValue;
697 _mapParamName2MavParamType[compId][paramName] = static_cast<MAV_PARAM_TYPE>(paramType);
698 }
699
700 if (_hasNonDefaultParamComponent()) {
701 auto &values = _mapParamName2Value[_nonDefaultParamComponentId];
702 auto &types = _mapParamName2MavParamType[_nonDefaultParamComponentId];
703 values[QStringLiteral("CAN_TERMINATE")] = QVariant(static_cast<qint32>(0));
704 types[QStringLiteral("CAN_TERMINATE")] = MAV_PARAM_TYPE_INT32;
705 values[QLatin1StringView(_nonDefaultFailParam)] = QVariant(static_cast<qint32>(8));
706 types[QLatin1StringView(_nonDefaultFailParam)] = MAV_PARAM_TYPE_INT32;
707 values[QStringLiteral("BATT_AMP_OFFSET")] = QVariant(0.0f);
708 types[QStringLiteral("BATT_AMP_OFFSET")] = MAV_PARAM_TYPE_REAL32;
709 values[QStringLiteral("OPTIONS")] = QVariant(static_cast<qint32>(0));
710 types[QStringLiteral("OPTIONS")] = MAV_PARAM_TYPE_INT32;
711 // Sort after the four above so their indices stay fixed for the shared-index failure mode
712 for (const char *name: {"TEMP1_ADDR", "TEMP1_TYPE", "TEMP2_ADDR", "TEMP2_TYPE", "TEMP3_ADDR", "TEMP3_TYPE", "UAVCAN_NODE_ID", "UAVCAN_RATE", "VOLT_MULT", "VOLT_PIN"}) {
713 values[QLatin1StringView(name)] = QVariant(static_cast<qint32>(0));
714 types[QLatin1StringView(name)] = MAV_PARAM_TYPE_INT32;
715 }
716 }
717
718 if (_companionParams) {
719 for (const char* name : {"CMP_ENABLE", "CMP_PORT", "CMP_RATE"}) {
720 _mapParamName2Value[_companionComponentId][QLatin1StringView(name)] = QVariant(static_cast<qint32>(1));
721 _mapParamName2MavParamType[_companionComponentId][QLatin1StringView(name)] = MAV_PARAM_TYPE_INT32;
722 }
723 }
724
725 if (_firmwareType == MAV_AUTOPILOT_PX4) {
726 for (const auto& [name, value] : kPX4UnusedParams) {
727 _px4UnusedParams[QLatin1StringView(name)] = value;
728 }
729 }
730
731 if ((_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) && _apmStartFreshParams) {
732 _applyAPMFreshFlashState();
733 }
734}
735
746void MockLink::_resetParamsToDefaults()
747{
748 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
749 // ArduPilot firmware default for calibration-indicator parameters is 0 (uncalibrated).
750 // Resetting these causes QGC's APMSensorsComponent::setupComplete() to return false,
751 // which is the correct post-reset state on a real vehicle.
752 for (auto compIt = _mapParamName2Value.begin(); compIt != _mapParamName2Value.end(); ++compIt) {
753 for (auto paramIt = compIt.value().begin(); paramIt != compIt.value().end(); ++paramIt) {
754 if (kAPMCalOffsetParams.contains(paramIt.key())) {
755 paramIt.value() = QVariant(0.0f);
756 }
757 }
758 }
759 return;
760 }
761
762 if (_firmwareType != MAV_AUTOPILOT_PX4) {
763 qCWarning(MockLinkLog) << "Param reset to defaults not supported for firmware type" << _firmwareType;
764 return;
765 }
766
767 QFile metaDataFile(QStringLiteral(":/MockLink/Parameter.MetaData.json"));
768 if (!metaDataFile.open(QFile::ReadOnly)) {
769 qCWarning(MockLinkLog) << "Unable to open parameter metadata for reset" << metaDataFile.fileName();
770 return;
771 }
772
773 QJsonParseError parseError{};
774 const QJsonDocument doc = QJsonDocument::fromJson(metaDataFile.readAll(), &parseError);
775 if (parseError.error != QJsonParseError::NoError) {
776 qCWarning(MockLinkLog) << "Unable to parse parameter metadata for reset:" << parseError.errorString();
777 return;
778 }
779
780 QHash<QString, QVariant> defaults;
781 const QJsonArray parameters = doc.object().value(QStringLiteral("parameters")).toArray();
782 for (const QJsonValue &parameter : parameters) {
783 const QJsonObject paramObject = parameter.toObject();
784 if (paramObject.contains(QStringLiteral("default"))) {
785 defaults[paramObject.value(QStringLiteral("name")).toString()] = paramObject.value(QStringLiteral("default")).toVariant();
786 }
787 }
788
789 for (auto compIt = _mapParamName2Value.begin(); compIt != _mapParamName2Value.end(); ++compIt) {
790 const int compId = compIt.key();
791 for (auto paramIt = compIt.value().begin(); paramIt != compIt.value().end(); ++paramIt) {
792 const QString &paramName = paramIt.key();
793 if (!_resetSysAutostartOnParamReset && (paramName == QLatin1String("SYS_AUTOSTART"))) {
794 continue;
795 }
796 const auto defaultIt = defaults.constFind(paramName);
797 if (defaultIt == defaults.constEnd()) {
798 continue;
799 }
800 switch (_mapParamName2MavParamType[compId][paramName]) {
801 case MAV_PARAM_TYPE_REAL32:
802 paramIt.value() = QVariant(defaultIt->toFloat());
803 break;
804 case MAV_PARAM_TYPE_UINT32:
805 paramIt.value() = QVariant(defaultIt->toUInt());
806 break;
807 case MAV_PARAM_TYPE_INT32:
808 paramIt.value() = QVariant(defaultIt->toInt());
809 break;
810 case MAV_PARAM_TYPE_UINT16:
811 paramIt.value() = QVariant(static_cast<quint16>(defaultIt->toUInt()));
812 break;
813 case MAV_PARAM_TYPE_INT16:
814 paramIt.value() = QVariant(static_cast<qint16>(defaultIt->toInt()));
815 break;
816 case MAV_PARAM_TYPE_UINT8:
817 paramIt.value() = QVariant(static_cast<quint8>(defaultIt->toUInt()));
818 break;
819 case MAV_PARAM_TYPE_INT8:
820 paramIt.value() = QVariant(static_cast<qint8>(defaultIt->toInt()));
821 break;
822 default:
823 qCWarning(MockLinkLog) << "Param reset skipped unhandled type" << _mapParamName2MavParamType[compId][paramName] << paramName;
824 break;
825 }
826 }
827 }
828}
829
833void MockLink::_applyAPMFreshFlashState()
834{
835 // Compass and accel offsets to 0 (uncalibrated)
836 _resetParamsToDefaults();
837
838 auto &paramMap = _mapParamName2Value[MAV_COMP_ID_AUTOPILOT1];
839 const auto &paramTypeMap = _mapParamName2MavParamType[MAV_COMP_ID_AUTOPILOT1];
840
841 // Set an integer param preserving the storage type used by _loadParams()
842 auto setIntParam = [&paramMap, &paramTypeMap](const QString &paramName, int value) {
843 if (!paramMap.contains(paramName)) {
844 return;
845 }
846 switch (paramTypeMap.value(paramName)) {
847 case MAV_PARAM_TYPE_UINT32: paramMap[paramName] = QVariant(static_cast<quint32>(value)); break;
848 case MAV_PARAM_TYPE_INT32: paramMap[paramName] = QVariant(value); break;
849 case MAV_PARAM_TYPE_UINT16: paramMap[paramName] = QVariant(static_cast<quint16>(value)); break;
850 case MAV_PARAM_TYPE_INT16: paramMap[paramName] = QVariant(static_cast<qint16>(value)); break;
851 case MAV_PARAM_TYPE_UINT8: paramMap[paramName] = QVariant(static_cast<quint8>(value)); break;
852 case MAV_PARAM_TYPE_INT8: paramMap[paramName] = QVariant(static_cast<qint8>(value)); break;
853 default: paramMap[paramName] = QVariant(value); break;
854 }
855 };
856
857 // No airframe selected. Not all vehicle types have FRAME_CLASS (Plane/Sub don't).
858 setIntParam(QStringLiteral("FRAME_CLASS"), 0);
859
860 // Radio uncalibrated: RC min/max/trim at firmware defaults for the mapped attitude channels
861 const QStringList rcMapParams = {
862 QStringLiteral("RCMAP_ROLL"),
863 QStringLiteral("RCMAP_PITCH"),
864 QStringLiteral("RCMAP_YAW"),
865 QStringLiteral("RCMAP_THROTTLE"),
866 };
867 for (const QString &mapParam : rcMapParams) {
868 if (!paramMap.contains(mapParam)) {
869 continue;
870 }
871 const int channel = paramMap[mapParam].toInt();
872 setIntParam(QStringLiteral("RC%1_MIN").arg(channel), 1100);
873 setIntParam(QStringLiteral("RC%1_MAX").arg(channel), 1900);
874 setIntParam(QStringLiteral("RC%1_TRIM").arg(channel), 1500);
875 }
876}
877
878void MockLink::_sendHeartBeat()
879{
880 // Like real firmware: ACTIVE while airborne, STANDBY on the ground (same condition as
881 // EXTENDED_SYS_STATE landed state, and what ArduPilot's flying detection in QGC keys off)
882 const uint8_t mavState = (_vehicleAltitudeAMSL > _defaultVehicleHomeAltitude) ? MAV_STATE_ACTIVE : MAV_STATE_STANDBY;
883
884 mavlink_message_t msg{};
885 (void) mavlink_msg_heartbeat_pack_chan(
886 _vehicleSystemId,
887 _vehicleComponentId,
888 _outgoingMavlinkChannel,
889 &msg,
890 _vehicleType, // MAV_TYPE
891 _firmwareType, // MAV_AUTOPILOT
892 _mavBaseMode, // MAV_MODE
893 _mavCustomMode, // custom mode
894 mavState // MAV_STATE
895 );
897}
898
899void MockLink::_sendCompanionHeartBeat()
900{
901 mavlink_message_t msg{};
902 (void) mavlink_msg_heartbeat_pack_chan(_vehicleSystemId, _companionComponentId, _outgoingMavlinkChannel, &msg,
903 MAV_TYPE_ONBOARD_CONTROLLER, MAV_AUTOPILOT_INVALID, 0, 0, MAV_STATE_ACTIVE);
905}
906
907void MockLink::_sendHighLatency2()
908{
909 qCDebug(MockLinkLog) << "Sending" << _mavCustomMode;
910
911 union px4_custom_mode px4_cm{};
912 px4_cm.data = _mavCustomMode;
913
914 mavlink_message_t msg{};
915 (void) mavlink_msg_high_latency2_pack_chan(
916 _vehicleSystemId,
917 _vehicleComponentId,
918 _outgoingMavlinkChannel,
919 &msg,
920 0, // timestamp
921 _vehicleType, // MAV_TYPE
922 _firmwareType, // MAV_AUTOPILOT
923 px4_cm.custom_mode_hl, // custom_mode
924 static_cast<int32_t>(_vehicleLatitude * 1E7),
925 static_cast<int32_t>(_vehicleLongitude * 1E7),
926 static_cast<int16_t>(_vehicleAltitudeAMSL),
927 static_cast<int16_t>(_vehicleAltitudeAMSL), // target_altitude,
928 0, // heading
929 0, // target_heading
930 0, // target_distance
931 0, // throttle
932 0, // airspeed
933 0, // airspeed_sp
934 0, // groundspeed
935 0, // windspeed,
936 0, // wind_heading
937 UINT8_MAX, // eph not known
938 UINT8_MAX, // epv not known
939 0, // temperature_air
940 0, // climb_rate
941 -1, // battery, do not use?
942 0, // wp_num
943 0, // failure_flags
944 0, 0, 0 // custom0, custom1, custom2
945 );
947}
948
949void MockLink::_sendSysStatus()
950{
951 const uint8_t prearmCheck = _prearmCheck;
952 const bool prearmCheckEnabled = (prearmCheck & _prearmCheckEnabled) != 0;
953 const bool prearmCheckPassed = (prearmCheck & _prearmCheckPassed) != 0;
954 const uint32_t prearmCheckBit = prearmCheckEnabled ? static_cast<uint32_t>(MAV_SYS_STATUS_PREARM_CHECK) : 0;
955 const uint32_t sensorsHealth =
956 (prearmCheckEnabled && prearmCheckPassed) ? static_cast<uint32_t>(MAV_SYS_STATUS_PREARM_CHECK) : 0;
957
958 mavlink_message_t msg{};
959 (void) mavlink_msg_sys_status_pack_chan(
960 _vehicleSystemId, _vehicleComponentId, _outgoingMavlinkChannel, &msg,
961 MAV_SYS_STATUS_SENSOR_GPS | prearmCheckBit, // onboard_control_sensors_present
962 prearmCheckBit, // onboard_control_sensors_enabled
963 sensorsHealth, // onboard_control_sensors_health
964 250, // load
965 4200 * 4, // voltage_battery
966 8000, // current_battery
967 _battery1PctRemaining, // battery_remaining
968 0, 0, 0, 0, 0, 0, 0, 0, 0);
970}
971
972void MockLink::_sendBatteryStatus()
973{
974 if (_battery1PctRemaining > 1) {
975 _battery1PctRemaining = static_cast<int8_t>(100 - (_runningTime.elapsed() / 1000));
976 _battery1TimeRemaining = static_cast<double>(_batteryMaxTimeRemaining) * (static_cast<double>(_battery1PctRemaining) / 100.0);
977 if (_battery1PctRemaining > 50) {
978 _battery1ChargeState = MAV_BATTERY_CHARGE_STATE_OK;
979 } else if (_battery1PctRemaining > 30) {
980 _battery1ChargeState = MAV_BATTERY_CHARGE_STATE_LOW;
981 } else if (_battery1PctRemaining > 20) {
982 _battery1ChargeState = MAV_BATTERY_CHARGE_STATE_CRITICAL;
983 } else {
984 _battery1ChargeState = MAV_BATTERY_CHARGE_STATE_EMERGENCY;
985 }
986 }
987
988 if (_battery2PctRemaining > 1) {
989 _battery2PctRemaining = static_cast<int8_t>(100 - ((_runningTime.elapsed() / 1000) / 2));
990 _battery2TimeRemaining = static_cast<double>(_batteryMaxTimeRemaining) * (static_cast<double>(_battery2PctRemaining) / 100.0);
991 if (_battery2PctRemaining > 50) {
992 _battery2ChargeState = MAV_BATTERY_CHARGE_STATE_OK;
993 } else if (_battery2PctRemaining > 30) {
994 _battery2ChargeState = MAV_BATTERY_CHARGE_STATE_LOW;
995 } else if (_battery2PctRemaining > 20) {
996 _battery2ChargeState = MAV_BATTERY_CHARGE_STATE_CRITICAL;
997 } else {
998 _battery2ChargeState = MAV_BATTERY_CHARGE_STATE_EMERGENCY;
999 }
1000 }
1001
1002 mavlink_message_t msg{};
1003 uint16_t rgVoltages[10]{};
1004 uint16_t rgVoltagesNone[10]{};
1005 uint16_t rgVoltagesExtNone[4]{};
1006
1007 for (size_t i = 0; i < std::size(rgVoltages); i++) {
1008 rgVoltages[i] = UINT16_MAX;
1009 rgVoltagesNone[i] = UINT16_MAX;
1010 }
1011 rgVoltages[0] = rgVoltages[1] = rgVoltages[2] = 4200;
1012
1013 (void) mavlink_msg_battery_status_pack_chan(
1014 _vehicleSystemId,
1015 _vehicleComponentId,
1016 _outgoingMavlinkChannel,
1017 &msg,
1018 1, // battery id
1019 MAV_BATTERY_FUNCTION_ALL,
1020 MAV_BATTERY_TYPE_LIPO,
1021 2100, // temp cdegC
1022 rgVoltages,
1023 600, // battery cA
1024 100, // current consumed mAh
1025 -1, // energy consumed not supported
1026 _battery1PctRemaining,
1027 _battery1TimeRemaining,
1028 _battery1ChargeState,
1029 rgVoltagesExtNone,
1030 0, // MAV_BATTERY_MODE
1031 0 // MAV_BATTERY_FAULT
1032 );
1034
1035 (void) mavlink_msg_battery_status_pack_chan(
1036 _vehicleSystemId,
1037 _vehicleComponentId,
1038 _outgoingMavlinkChannel,
1039 &msg,
1040 2, // battery id
1041 MAV_BATTERY_FUNCTION_ALL,
1042 MAV_BATTERY_TYPE_LIPO,
1043 INT16_MAX, // temp cdegC
1044 rgVoltagesNone,
1045 600, // battery cA
1046 100, // current consumed mAh
1047 -1, // energy consumed not supported
1048 _battery2PctRemaining,
1049 _battery2TimeRemaining,
1050 _battery2ChargeState,
1051 rgVoltagesExtNone,
1052 0, // MAV_BATTERY_MODE
1053 0 // MAV_BATTERY_FAULT
1054 );
1056}
1057
1058void MockLink::_sendNamedValueFloats()
1059{
1060 const uint32_t timeBootMs = static_cast<uint32_t>(_runningTime.elapsed());
1061
1062 // Send two named float values with varying data to exercise Inspector instance separation
1063 const float sinVal = static_cast<float>(std::sin(static_cast<double>(timeBootMs) / 1000.0));
1064 const float cosVal = static_cast<float>(std::cos(static_cast<double>(timeBootMs) / 1000.0));
1065
1066 // NAMED_VALUE_FLOAT.name is a fixed 10-byte field; pack_chan memcpys 10 bytes unconditionally.
1067 static constexpr char kSinName[10] = "sin_wave";
1068 static constexpr char kCosName[10] = "cos_wave";
1069
1070 mavlink_message_t msg{};
1071 (void) mavlink_msg_named_value_float_pack_chan(
1072 _vehicleSystemId,
1073 _vehicleComponentId,
1074 _outgoingMavlinkChannel,
1075 &msg,
1076 timeBootMs,
1077 kSinName,
1078 sinVal
1079 );
1081
1082 (void) mavlink_msg_named_value_float_pack_chan(
1083 _vehicleSystemId,
1084 _vehicleComponentId,
1085 _outgoingMavlinkChannel,
1086 &msg,
1087 timeBootMs,
1088 kCosName,
1089 cosVal
1090 );
1092}
1093
1094void MockLink::_sendVibration()
1095{
1096 mavlink_message_t msg{};
1097 (void) mavlink_msg_vibration_pack_chan(
1098 _vehicleSystemId,
1099 _vehicleComponentId,
1100 _outgoingMavlinkChannel,
1101 &msg,
1102 0, // time_usec
1103 50.5, // vibration_x,
1104 10.5, // vibration_y,
1105 60.0, // vibration_z,
1106 1, // clipping_0
1107 2, // clipping_0
1108 3 // clipping_0
1109 );
1111}
1112
1113void MockLink::_sendDistanceSensors()
1114{
1115 // Simulated proximity sensor ring: one DISTANCE_SENSOR message per yaw orientation.
1116 // Two orientations are deliberately never sent so the UI shows sectors with no data.
1117 static constexpr MAV_SENSOR_ORIENTATION rgOrientations[] = {
1118 MAV_SENSOR_ROTATION_NONE,
1119 MAV_SENSOR_ROTATION_YAW_45,
1120 MAV_SENSOR_ROTATION_YAW_90,
1121 MAV_SENSOR_ROTATION_YAW_180,
1122 MAV_SENSOR_ROTATION_YAW_270,
1123 MAV_SENSOR_ROTATION_YAW_315,
1124 };
1125
1126 static constexpr uint16_t minDistanceCm = 20;
1127 static constexpr uint16_t maxDistanceCm = 4000;
1128
1129 const uint32_t timeBootMs = static_cast<uint32_t>(_runningTime.elapsed());
1130 const float quaternion[4]{};
1131
1132 for (size_t i = 0; i < std::size(rgOrientations); i++) {
1133 // Slow sweep between 5m and 35m, phase shifted per array entry so the arcs move independently
1134 const double sweep = std::sin((timeBootMs / 5000.0) + (i * M_PI / 4));
1135 const uint16_t currentDistanceCm = static_cast<uint16_t>(2000 + (1500 * sweep));
1136
1137 mavlink_message_t msg{};
1138 (void) mavlink_msg_distance_sensor_pack_chan(
1139 _vehicleSystemId,
1140 _vehicleComponentId,
1141 _outgoingMavlinkChannel,
1142 &msg,
1143 timeBootMs,
1144 minDistanceCm,
1145 maxDistanceCm,
1146 currentDistanceCm,
1147 MAV_DISTANCE_SENSOR_LASER,
1148 static_cast<uint8_t>(i), // id
1149 rgOrientations[i],
1150 255, // covariance - unknown
1151 0.0f, // horizontal_fov - unknown
1152 0.0f, // vertical_fov - unknown
1153 quaternion, // valid only for MAV_SENSOR_ROTATION_CUSTOM
1154 0 // signal_quality - unknown
1155 );
1157 }
1158}
1159
1161{
1162 if (!_commLost) {
1163 uint8_t buffer[MAVLINK_MAX_PACKET_LEN]{};
1164 const int cBuffer = mavlink_msg_to_send_buffer(buffer, &msg);
1165 const QByteArray bytes(reinterpret_cast<char*>(buffer), cBuffer);
1166 emit bytesReceived(this, bytes);
1167 if (_duplicateResponses) {
1168 emit bytesReceived(this, bytes);
1169 }
1170 }
1171}
1172
1174{
1175 if (!_worker || !_workerThread || !_workerThread->isRunning() || (QThread::currentThread() == _workerThread)) {
1176 return;
1177 }
1178 // The worker never waits on the calling thread, so it reaches this no-op once its current task returns
1179 (void) QMetaObject::invokeMethod(_worker, [] {}, Qt::BlockingQueuedConnection);
1180}
1181
1182void MockLink::_writeBytes(const QByteArray &bytes)
1183{
1184 // This prevents the responses to mavlink messages from being sent until the _writeBytes returns.
1185 emit writeBytesQueuedSignal(bytes);
1186}
1187
1188void MockLink::_writeBytesQueued(const QByteArray &bytes)
1189{
1190 if (!_connected || !mavlinkChannelIsSet()) {
1191 qCDebug(MockLinkLog) << "Dropping queued bytes on disconnected/uninitialized mock link";
1192 return;
1193 }
1194
1195 if (_inNSH) {
1196 _handleIncomingNSHBytes(bytes.constData(), bytes.length());
1197 return;
1198 }
1199
1200 if (bytes.startsWith(QByteArrayLiteral("\r\r\r"))) {
1201 _inNSH = true;
1202 _handleIncomingNSHBytes(&bytes.constData()[3], bytes.length() - 3);
1203 }
1204
1205 _handleIncomingMavlinkBytes(reinterpret_cast<const uint8_t*>(bytes.constData()), bytes.length());
1206}
1207
1208void MockLink::_handleIncomingNSHBytes(const char *bytes, int cBytes)
1209{
1210 Q_UNUSED(cBytes);
1211
1212 // Drop back out of NSH
1213 if ((cBytes == 4) && (bytes[0] == '\r') && (bytes[1] == '\r') && (bytes[2] == '\r')) {
1214 _inNSH = false;
1215 return;
1216 }
1217
1218 if (cBytes > 0) {
1219 qCDebug(MockLinkLog) << "NSH:" << bytes;
1220#if 0
1221 // MockLink not quite ready to handle this correctly yet
1222 if (strncmp(bytes, "sh /etc/init.d/rc.usb\n", cBytes) == 0) {
1223 // This is the mavlink start command
1224 _mavlinkStarted = true;
1225 }
1226#endif
1227 }
1228}
1229
1230void MockLink::_handleIncomingMavlinkBytes(const uint8_t *bytes, int cBytes)
1231{
1232 mavlink_message_t msg{};
1233 mavlink_status_t comm{};
1234
1235 QMutexLocker lock(&_incomingMavlinkMutex);
1236 for (qint64 i = 0; i < cBytes; i++) {
1237 const int parsed = mavlink_parse_char(_incomingMavlinkChannel, bytes[i], &msg, &comm);
1238 if (!parsed) {
1239 continue;
1240 }
1241 if (!_mavlinkV2Upgraded && !_stayMavlinkV1 && (msg.magic == MAVLINK_STX)) {
1242 // First v2 message from GCS: switch outgoing traffic to v2, same as ArduPilot does.
1243 _mavlinkV2Upgraded = true;
1244 mavlink_status_t *const outgoingStatus = mavlink_get_channel_status(_outgoingMavlinkChannel);
1245 outgoingStatus->flags &= ~MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
1246 qCDebug(MockLinkLog) << "Received MAVLink v2 message from GCS, upgrading outgoing traffic to v2";
1247 // Earlier v1 telemetry was dropped by QGC: send the 1 Hz batch now rather than up to a second later
1248 _runOnWorkerWhenConnected([this] { run1HzTasks(); });
1249 }
1250 lock.unlock();
1251 _handleIncomingMavlinkMsg(msg);
1252 lock.relock();
1253 }
1254}
1255
1256void MockLink::_updateIncomingMessageCounts(const mavlink_message_t &msg)
1257{
1258 _receivedMavlinkMessageCountMap[msg.msgid]++;
1259 _lastReceivedMavlinkMessageMap[msg.msgid] = msg;
1260
1261 // Update command-specific counts if this is a COMMAND_LONG message
1262 if (msg.msgid == MAVLINK_MSG_ID_COMMAND_LONG) {
1263 mavlink_command_long_t request{};
1264 mavlink_msg_command_long_decode(&msg, &request);
1265
1266 _receivedMavCommandCountMap[static_cast<MAV_CMD>(request.command)]++;
1267 _receivedMavCommandByCompCountMap[static_cast<MAV_CMD>(request.command)][request.target_component]++;
1268
1269 if (request.command == MAV_CMD_REQUEST_MESSAGE) {
1270 _receivedRequestMessageCountMap[static_cast<uint32_t>(request.param1)]++;
1271 _receivedRequestMessageByCompAndMsgCountMap[request.target_component][static_cast<int>(request.param1)]++;
1272 }
1273 } else if (msg.msgid == MAVLINK_MSG_ID_COMMAND_INT) {
1274 mavlink_command_int_t request{};
1275 mavlink_msg_command_int_decode(&msg, &request);
1276
1277 _receivedMavCommandCountMap[static_cast<MAV_CMD>(request.command)]++;
1278 _receivedMavCommandByCompCountMap[static_cast<MAV_CMD>(request.command)][request.target_component]++;
1279 }
1280}
1281
1282void MockLink::_handleIncomingMavlinkMsg(const mavlink_message_t &msg)
1283{
1284 _updateIncomingMessageCounts(msg);
1285
1286 if (_missionItemHandler->handleMavlinkMessage(msg)) {
1287 return;
1288 }
1289
1290 if (_enableCamera && _mockLinkCamera->handleMavlinkMessage(msg)) {
1291 return;
1292 }
1293
1294 if (_enableGimbal && _mockLinkGimbal->handleMavlinkMessage(msg)) {
1295 return;
1296 }
1297
1298 switch (msg.msgid) {
1299 case MAVLINK_MSG_ID_HEARTBEAT:
1300 _handleHeartBeat(msg);
1301 break;
1302 case MAVLINK_MSG_ID_PARAM_REQUEST_LIST:
1303 _handleParamRequestList(msg);
1304 break;
1305 case MAVLINK_MSG_ID_SET_MODE:
1306 _handleSetMode(msg);
1307 break;
1308 case MAVLINK_MSG_ID_PARAM_SET:
1309 _handleParamSet(msg);
1310 break;
1311 case MAVLINK_MSG_ID_PARAM_REQUEST_READ:
1312 _handleParamRequestRead(msg);
1313 break;
1314 case MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL:
1315 _handleFTP(msg);
1316 break;
1317 case MAVLINK_MSG_ID_COMMAND_LONG:
1318 _handleCommandLong(msg);
1319 break;
1320 case MAVLINK_MSG_ID_COMMAND_INT:
1321 _handleCommandInt(msg);
1322 break;
1323 case MAVLINK_MSG_ID_MANUAL_CONTROL:
1324 _handleManualControl(msg);
1325 break;
1326 case MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE:
1327 _handleRCChannelsOverride(msg);
1328 break;
1329 case MAVLINK_MSG_ID_LOG_REQUEST_LIST:
1330 _handleLogRequestList(msg);
1331 break;
1332 case MAVLINK_MSG_ID_LOG_REQUEST_DATA:
1333 _handleLogRequestData(msg);
1334 break;
1335 case MAVLINK_MSG_ID_LOG_ERASE:
1336 _handleLogErase(msg);
1337 break;
1338 case MAVLINK_MSG_ID_PARAM_MAP_RC:
1339 _handleParamMapRC(msg);
1340 break;
1341 case MAVLINK_MSG_ID_SETUP_SIGNING:
1342 _handleSetupSigning(msg);
1343 break;
1344 case MAVLINK_MSG_ID_COMMAND_ACK:
1345 // GCS sends COMMAND_ACK(command=0) via nextClicked() to acknowledge each pose
1346 // during APM full accel calibration (the "Next" button press).
1347 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
1349 mavlink_msg_command_ack_decode(&msg, &ack);
1350 if (ack.command == 0) {
1351 QMutexLocker locker(&_apmAccelCalMutex);
1352 if (_apmAccelCalPosIndex >= 0 && _apmAccelCalPosIndex < 6) {
1353 _apmAccelCalGotAck = true;
1354 }
1355 }
1356 }
1357 break;
1358 default:
1359 break;
1360 }
1361}
1362
1363void MockLink::_handleHeartBeat(const mavlink_message_t &msg)
1364{
1365 Q_UNUSED(msg);
1366 qCDebug(MockLinkVerboseLog) << "Heartbeat";
1367}
1368
1369void MockLink::_handleParamMapRC(const mavlink_message_t &msg)
1370{
1371 mavlink_param_map_rc_t paramMapRC{};
1372 mavlink_msg_param_map_rc_decode(&msg, &paramMapRC);
1373
1374 const QString paramName(QString::fromLocal8Bit(paramMapRC.param_id, static_cast<int>(strnlen(paramMapRC.param_id, MAVLINK_MSG_PARAM_MAP_RC_FIELD_PARAM_ID_LEN))));
1375
1376 if (paramMapRC.param_index == -1) {
1377 qCDebug(MockLinkLog) << QStringLiteral("MockLink - PARAM_MAP_RC: param(%1) tuningID(%2) centerValue(%3) scale(%4) min(%5) max(%6)").arg(paramName).arg(paramMapRC.parameter_rc_channel_index).arg(paramMapRC.param_value0).arg(paramMapRC.scale).arg(paramMapRC.param_value_min).arg(paramMapRC.param_value_max);
1378 } else if (paramMapRC.param_index == -2) {
1379 qCDebug(MockLinkLog) << "MockLink - PARAM_MAP_RC: Clear tuningID" << paramMapRC.parameter_rc_channel_index;
1380 } else {
1381 qCWarning(MockLinkLog) << "MockLink - PARAM_MAP_RC: Unsupported param_index" << paramMapRC.param_index;
1382 }
1383}
1384
1385void MockLink::_handleSetupSigning(const mavlink_message_t &msg)
1386{
1387 mavlink_setup_signing_t setupSigning{};
1388 mavlink_msg_setup_signing_decode(&msg, &setupSigning);
1389
1390 if (mavlink_msg_get_target_sysid(&msg, mavlink_get_msg_entry(msg.msgid)) != _vehicleSystemId) {
1391 return;
1392 }
1393
1394 // All-zero key = disable signing
1395 bool allZeroKey = true;
1396 for (const uint8_t byte : setupSigning.secret_key) {
1397 if (byte != 0) {
1398 allZeroKey = false;
1399 break;
1400 }
1401 }
1402
1403 _signingEnabled = !allZeroKey;
1404
1405 // Write C-state directly; routing through SigningController would clobber its _keyHint mid-confirmation.
1406 mavlink_status_t* const status = mavlink_get_channel_status(_outgoingMavlinkChannel);
1407 if (_signingEnabled) {
1408 memcpy(_mockSigning.secret_key, setupSigning.secret_key, sizeof(_mockSigning.secret_key));
1409 _mockSigning.link_id = _outgoingMavlinkChannel;
1410 _mockSigning.flags = MAVLINK_SIGNING_FLAG_SIGN_OUTGOING;
1411 _mockSigning.timestamp = MAVLinkSigning::currentSigningTimestampTicks();
1412 _mockSigning.accept_unsigned_callback = MAVLinkSigning::insecureConnectionAcceptUnsignedCallback;
1413 status->signing = &_mockSigning;
1414 status->signing_streams = &_mockSigningStreams;
1415 } else {
1416 QGC::secureZero(_mockSigning.secret_key, sizeof(_mockSigning.secret_key));
1417 _mockSigning.accept_unsigned_callback = nullptr;
1418 status->signing = nullptr;
1419 status->signing_streams = nullptr;
1420 }
1421
1422 qCDebug(MockLinkLog) << "Signing" << (_signingEnabled ? "enabled" : "disabled");
1423}
1424
1425void MockLink::_handleSetMode(const mavlink_message_t &msg)
1426{
1427 mavlink_set_mode_t request{};
1428 mavlink_msg_set_mode_decode(&msg, &request);
1429
1430 const quint32 targetSystem = mavlink_msg_get_target_sysid(&msg, mavlink_get_msg_entry(msg.msgid));
1431 if (targetSystem != _vehicleSystemId) {
1432 qCDebug(MockLinkLog) << "Ignoring SET_MODE for system" << targetSystem;
1433 return;
1434 }
1435
1436 _mavBaseMode = request.base_mode;
1437 _mavCustomMode = request.custom_mode;
1438}
1439
1440void MockLink::_handleManualControl(const mavlink_message_t &msg)
1441{
1442 mavlink_manual_control_t manualControl{};
1443 mavlink_msg_manual_control_decode(&msg, &manualControl);
1444
1445 // INT16_MAX means "axis invalid/not provided" per MAVLink spec
1446 const auto axisStr = [](int16_t v) -> QString {
1447 return (v == INT16_MAX) ? QStringLiteral("invalid") : QString::number(v);
1448 };
1449 // Extension fields are only valid when the corresponding enabled_extensions bit is set
1450 const auto extStr = [](int16_t v, bool enabled) -> QString {
1451 return enabled ? QString::number(v) : QStringLiteral("disabled");
1452 };
1453
1454 const uint8_t ext = manualControl.enabled_extensions;
1455
1456 qCDebug(MockLinkVerboseLog).noquote()
1457 << "MANUAL_CONTROL"
1458 << "target:" << manualControl.target
1459 << "x:" << axisStr(manualControl.x)
1460 << "y:" << axisStr(manualControl.y)
1461 << "z:" << axisStr(manualControl.z)
1462 << "r:" << axisStr(manualControl.r)
1463 << "buttons:" << QStringLiteral("0x%1").arg(manualControl.buttons, 4, 16, QLatin1Char('0'))
1464 << "buttons2:" << QStringLiteral("0x%1").arg(manualControl.buttons2, 4, 16, QLatin1Char('0'))
1465 << "enabled_extensions:" << QStringLiteral("0x%1").arg(ext, 2, 16, QLatin1Char('0'))
1466 << "s(pitch):" << extStr(manualControl.s, ext & (1 << 0))
1467 << "t(roll):" << extStr(manualControl.t, ext & (1 << 1))
1468 << "aux1:" << extStr(manualControl.aux1, ext & (1 << 2))
1469 << "aux2:" << extStr(manualControl.aux2, ext & (1 << 3))
1470 << "aux3:" << extStr(manualControl.aux3, ext & (1 << 4))
1471 << "aux4:" << extStr(manualControl.aux4, ext & (1 << 5))
1472 << "aux5:" << extStr(manualControl.aux5, ext & (1 << 6))
1473 << "aux6:" << extStr(manualControl.aux6, ext & (1 << 7));
1474}
1475
1476void MockLink::_handleRCChannelsOverride(const mavlink_message_t &msg)
1477{
1478 mavlink_rc_channels_override_t override{};
1479 mavlink_msg_rc_channels_override_decode(&msg, &override);
1480
1481 // Per the MAVLink spec:
1482 // Channels 1-8: UINT16_MAX = ignore (no state change), 0 = release back to RC radio
1483 // Channels 9-18: UINT16_MAX or 0 = ignore, UINT16_MAX-1 = release back to RC radio
1484 const uint16_t rawValues[18] = {
1485 override.chan1_raw, override.chan2_raw, override.chan3_raw, override.chan4_raw,
1486 override.chan5_raw, override.chan6_raw, override.chan7_raw, override.chan8_raw,
1487 override.chan9_raw, override.chan10_raw, override.chan11_raw, override.chan12_raw,
1488 override.chan13_raw, override.chan14_raw, override.chan15_raw, override.chan16_raw,
1489 override.chan17_raw, override.chan18_raw,
1490 };
1491
1492 bool anyChange = false;
1493 for (int i = 0; i < kRcChannelOverrideChannelCount; ++i) {
1494 const uint16_t raw = rawValues[i];
1495 const bool isExtended = (i >= 8);
1496
1497 RCChannelOverride::State newState;
1498 if (isExtended) {
1499 if (raw == 0 || raw == UINT16_MAX) {
1500 continue; // ignore — no change to this channel's state
1501 } else if (raw == static_cast<uint16_t>(UINT16_MAX - 1)) {
1502 newState = RCChannelOverride::State::Released;
1503 } else {
1504 newState = RCChannelOverride::State::Overridden;
1505 }
1506 } else {
1507 if (raw == UINT16_MAX) {
1508 continue; // ignore — no change to this channel's state
1509 } else if (raw == 0) {
1510 newState = RCChannelOverride::State::Released;
1511 } else {
1512 newState = RCChannelOverride::State::Overridden;
1513 }
1514 }
1515
1516 RCChannelOverride &ch = _rcChannelOverrides[i];
1517 if (ch.state == newState) {
1518 continue;
1519 }
1520
1521 anyChange = true;
1522
1523 const auto stateLabel = [](RCChannelOverride::State s) -> const char * {
1524 switch (s) {
1525 case RCChannelOverride::State::Ignore: return "ignore";
1526 case RCChannelOverride::State::Released: return "released";
1527 case RCChannelOverride::State::Overridden: return "overridden";
1528 }
1529 return "unknown";
1530 };
1531 qCDebug(MockLinkLog).noquote() << QStringLiteral("RC_CHANNELS_OVERRIDE ch%1: %2 -> %3").arg(i + 1).arg(stateLabel(ch.state)).arg(stateLabel(newState));
1532
1533 ch.state = newState;
1534 ch.value = (newState == RCChannelOverride::State::Overridden) ? raw : 0;
1535 }
1536
1537 if (anyChange) {
1538 QStringList active;
1539 for (int i = 0; i < kRcChannelOverrideChannelCount; ++i) {
1540 if (_rcChannelOverrides[i].state == RCChannelOverride::State::Overridden) {
1541 active << QStringLiteral("ch%1").arg(i + 1);
1542 }
1543 }
1544 if (active.isEmpty()) {
1545 qCDebug(MockLinkLog) << "RC_CHANNELS_OVERRIDE: no channels currently overridden";
1546 } else {
1547 qCDebug(MockLinkLog).noquote() << "RC_CHANNELS_OVERRIDE active overrides:" << active.join(QStringLiteral(", "));
1548 }
1549 }
1550
1551 for (int i = 0; i < kRcChannelOverrideChannelCount; ++i) {
1552 if (_rcChannelOverrides[i].state == RCChannelOverride::State::Overridden) {
1553 qCDebug(MockLinkVerboseLog).noquote() << QStringLiteral("RC_CHANNELS_OVERRIDE ch%1 value: %2").arg(i + 1).arg(_rcChannelOverrides[i].value);
1554 }
1555 }
1556}
1557
1558void MockLink::_setParamFloatUnionIntoMap(int componentId, const QString &paramName, float paramFloat)
1559{
1560 if (!_mapParamName2Value.contains(componentId) || !_mapParamName2Value[componentId].contains(paramName) ||
1561 !_mapParamName2MavParamType.contains(componentId) ||
1562 !_mapParamName2MavParamType[componentId].contains(paramName)) {
1563 qCWarning(MockLinkLog) << "Cannot update unknown mock parameter" << componentId << paramName;
1564 return;
1565 }
1566
1567 const MAV_PARAM_TYPE paramType = _mapParamName2MavParamType[componentId][paramName];
1568 QVariant paramVariant;
1569 mavlink_param_union_t valueUnion{};
1570 valueUnion.param_float = paramFloat;
1571 switch (paramType) {
1572 case MAV_PARAM_TYPE_REAL32:
1573 paramVariant = QVariant::fromValue(valueUnion.param_float);
1574 break;
1575 case MAV_PARAM_TYPE_UINT32:
1576 paramVariant = QVariant::fromValue(valueUnion.param_uint32);
1577 break;
1578 case MAV_PARAM_TYPE_INT32:
1579 paramVariant = QVariant::fromValue(valueUnion.param_int32);
1580 break;
1581 case MAV_PARAM_TYPE_UINT16:
1582 paramVariant = QVariant::fromValue(valueUnion.param_uint16);
1583 break;
1584 case MAV_PARAM_TYPE_INT16:
1585 paramVariant = QVariant::fromValue(valueUnion.param_int16);
1586 break;
1587 case MAV_PARAM_TYPE_UINT8:
1588 paramVariant = QVariant::fromValue(valueUnion.param_uint8);
1589 break;
1590 case MAV_PARAM_TYPE_INT8:
1591 paramVariant = QVariant::fromValue(valueUnion.param_int8);
1592 break;
1593 default:
1594 qCCritical(MockLinkLog) << "Invalid parameter type" << paramType;
1595 paramVariant = QVariant::fromValue(valueUnion.param_int32);
1596 break;
1597 }
1598
1599 qCDebug(MockLinkLog) << "_setParamFloatUnionIntoMap" << paramName << paramVariant;
1600 _mapParamName2Value[componentId][paramName] = paramVariant;
1601}
1602
1603void MockLink::setMockParamValue(int componentId, const QString &paramName, float value)
1604{
1605 mavlink_param_union_t valueUnion{};
1606 valueUnion.param_float = value;
1607 _setParamFloatUnionIntoMap(componentId, paramName, valueUnion.param_float);
1608}
1609
1610float MockLink::_floatUnionForParam(int componentId, const QString &paramName)
1611{
1612 if (!_mapParamName2Value.contains(componentId) || !_mapParamName2Value[componentId].contains(paramName) ||
1613 !_mapParamName2MavParamType.contains(componentId) ||
1614 !_mapParamName2MavParamType[componentId].contains(paramName)) {
1615 qCWarning(MockLinkLog) << "Cannot read unknown mock parameter" << componentId << paramName;
1616 return qQNaN();
1617 }
1618
1619 const MAV_PARAM_TYPE paramType = _mapParamName2MavParamType[componentId][paramName];
1620 const QVariant paramVar = _mapParamName2Value[componentId][paramName];
1621
1622 mavlink_param_union_t valueUnion{};
1623 switch (paramType) {
1624 case MAV_PARAM_TYPE_REAL32:
1625 valueUnion.param_float = paramVar.toFloat();
1626 break;
1627 case MAV_PARAM_TYPE_UINT32:
1628 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
1629 valueUnion.param_float = paramVar.toUInt();
1630 } else {
1631 valueUnion.param_uint32 = paramVar.toUInt();
1632 }
1633 break;
1634 case MAV_PARAM_TYPE_INT32:
1635 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
1636 valueUnion.param_float = paramVar.toInt();
1637 } else {
1638 valueUnion.param_int32 = paramVar.toInt();
1639 }
1640 break;
1641 case MAV_PARAM_TYPE_UINT16:
1642 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
1643 valueUnion.param_float = paramVar.toUInt();
1644 } else {
1645 valueUnion.param_uint16 = paramVar.toUInt();
1646 }
1647 break;
1648 case MAV_PARAM_TYPE_INT16:
1649 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
1650 valueUnion.param_float = paramVar.toInt();
1651 } else {
1652 valueUnion.param_int16 = paramVar.toInt();
1653 }
1654 break;
1655 case MAV_PARAM_TYPE_UINT8:
1656 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
1657 valueUnion.param_float = paramVar.toUInt();
1658 } else {
1659 valueUnion.param_uint8 = paramVar.toUInt();
1660 }
1661 break;
1662 case MAV_PARAM_TYPE_INT8:
1663 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
1664 valueUnion.param_float = (unsigned char)paramVar.toChar().toLatin1();
1665 } else {
1666 valueUnion.param_int8 = (unsigned char)paramVar.toChar().toLatin1();
1667 }
1668 break;
1669 default:
1670 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
1671 valueUnion.param_float = paramVar.toInt();
1672 } else {
1673 valueUnion.param_int32 = paramVar.toInt();
1674 }
1675 qCCritical(MockLinkLog) << "Invalid parameter type" << paramType;
1676 }
1677
1678 return valueUnion.param_float;
1679}
1680
1681uint32_t MockLink::_computeParamHash(int componentId) const
1682{
1683 // Volatile parameters are excluded from the hash, matching PX4 firmware and
1684 // ParameterManager::_tryCacheHashLoad. The list comes from the same metadata
1685 // json served to QGC so the two sides always agree.
1686 static const QSet<QString> volatileParams = []() {
1687 QSet<QString> volatiles;
1688 QFile metaDataFile(QStringLiteral(":/MockLink/Parameter.MetaData.json"));
1689 if (metaDataFile.open(QFile::ReadOnly)) {
1690 QJsonParseError parseError{};
1691 const QJsonDocument doc = QJsonDocument::fromJson(metaDataFile.readAll(), &parseError);
1692 if (parseError.error != QJsonParseError::NoError) {
1693 qCWarning(MockLinkLog) << "Unable to parse parameter metadata for volatile param list:" << parseError.errorString();
1694 }
1695 const QJsonArray parameters = doc.object().value(QStringLiteral("parameters")).toArray();
1696 for (const QJsonValue &parameter : parameters) {
1697 const QJsonObject paramObject = parameter.toObject();
1698 if (paramObject.value(QStringLiteral("volatile")).toBool()) {
1699 volatiles.insert(paramObject.value(QStringLiteral("name")).toString());
1700 }
1701 }
1702 } else {
1703 qCWarning(MockLinkLog) << "Unable to open parameter metadata for volatile param list" << metaDataFile.fileName();
1704 }
1705 return volatiles;
1706 }();
1707
1708 uint32_t crc = 0;
1709 const QMap<QString, QVariant> params = _mapParamName2Value.value(componentId);
1710 const QMap<QString, MAV_PARAM_TYPE> paramTypes = _mapParamName2MavParamType.value(componentId);
1711 for (auto it = params.constBegin(); it != params.constEnd(); ++it) {
1712 const QString &name = it.key();
1713 if (volatileParams.contains(name)) {
1714 continue;
1715 }
1716 const QVariant &value = it.value();
1717 const MAV_PARAM_TYPE mavType = paramTypes.value(name);
1719
1720 crc = QGC::crc32(reinterpret_cast<const uint8_t *>(qPrintable(name)), name.length(), crc);
1721 crc = QGC::crc32(static_cast<const uint8_t *>(value.constData()), FactMetaData::typeToSize(factType), crc);
1722 }
1723 return crc;
1724}
1725
1726bool MockLink::_hasNonDefaultParamComponent() const
1727{
1728 switch (_failureMode) {
1733 return true;
1734 default:
1735 return false;
1736 }
1737}
1738
1739bool MockLink::_shouldSkipParamSend(int componentId, const QString &paramName, int paramIndex) const
1740{
1741 switch (_failureMode) {
1744 return paramName == _failParam;
1746 return (componentId == _nonDefaultParamComponentId) && (paramName == _nonDefaultFailParam);
1748 return paramIndex == _sharedFailParamIndex;
1751 return (componentId == _nonDefaultParamComponentId) && (paramIndex >= _nonDefaultStreamedParamCount);
1752 default:
1753 return false;
1754 }
1755}
1756
1757bool MockLink::_shouldSkipParamRead(int componentId, const QString &paramName, int paramIndex)
1758{
1759 switch (_failureMode) {
1761 return paramName == _failParam;
1763 return (componentId == _nonDefaultParamComponentId) && (paramName == _nonDefaultFailParam);
1765 return (componentId == MAV_COMP_ID_AUTOPILOT1) && (paramIndex == _sharedFailParamIndex);
1767 return componentId == _nonDefaultParamComponentId;
1769 if (componentId != _nonDefaultParamComponentId) {
1770 return false;
1771 }
1772 if (_nonDefaultReadAttempted.contains(qMakePair(componentId, paramIndex))) {
1773 return false;
1774 }
1775 _nonDefaultReadAttempted.insert(qMakePair(componentId, paramIndex));
1776 return true;
1777 default:
1778 return false;
1779 }
1780}
1781
1782void MockLink::_handleParamRequestList(const mavlink_message_t &msg)
1783{
1785 return;
1786 }
1787
1788 mavlink_param_request_list_t request{};
1789 mavlink_msg_param_request_list_decode(&msg, &request);
1790
1791 const quint32 targetSystem = mavlink_msg_get_target_sysid(&msg, mavlink_get_msg_entry(msg.msgid));
1792 if (targetSystem != _vehicleSystemId) {
1793 qCDebug(MockLinkLog) << "Ignoring PARAM_REQUEST_LIST for system" << targetSystem;
1794 return;
1795 }
1796 _paramRequestListTargetLog.append(request.target_component);
1797
1798 // Cache component IDs and first component's param names to avoid repeated keys() calls in worker
1799 // Thread safety: Lock mutex before modifying shared state accessed by worker thread
1800 QMutexLocker locker(&_paramRequestListMutex);
1801 if (request.target_component == MAV_COMP_ID_ALL) {
1802 _paramRequestListComponentIds = _mapParamName2Value.keys();
1803 } else {
1804 _paramRequestListComponentIds.clear();
1805 if (_mapParamName2Value.contains(request.target_component)) {
1806 _paramRequestListComponentIds.append(request.target_component);
1807 }
1808 }
1809 // Stream the autopilot last, like PX4 does with bridged DroneCAN nodes. Otherwise QGC finishes the
1810 // initial load as soon as the autopilot completes and never sees the other components.
1811 if (_paramRequestListComponentIds.removeOne(MAV_COMP_ID_AUTOPILOT1)) {
1812 _paramRequestListComponentIds.append(MAV_COMP_ID_AUTOPILOT1);
1813 }
1814 if (!_paramRequestListComponentIds.isEmpty()) {
1815 _paramRequestListParamNames = _mapParamName2Value[_paramRequestListComponentIds.first()].keys();
1816 }
1817
1818 // Start the worker routine
1819 _currentParamRequestListComponentIndex = 0;
1820 _currentParamRequestListParamIndex = 0;
1821 _paramRequestListHashCheckSent = false;
1822}
1823
1824void MockLink::_paramRequestListWorker()
1825{
1826 if (_currentParamRequestListComponentIndex == -1) {
1827 // Initial request complete
1828 return;
1829 }
1830
1831 // Thread safety: Lock mutex before accessing shared state modified by main thread
1832 QMutexLocker locker(&_paramRequestListMutex);
1833
1834 // Use cached lists instead of calling keys() on every iteration (500Hz)
1835 if (_currentParamRequestListComponentIndex >= _paramRequestListComponentIds.count()) {
1836 _currentParamRequestListComponentIndex = -1;
1837 return;
1838 }
1839
1840 const int componentId = _paramRequestListComponentIds.at(_currentParamRequestListComponentIndex);
1841 const int cParameters = _paramRequestListParamNames.count();
1842
1843 if (_currentParamRequestListParamIndex >= cParameters) {
1844 // All regular params sent — for PX4, append _HASH_CHECK as the last entry in the stream.
1845 // Uses param_count=0, param_index=-1 (same as standalone response) so ParameterManager
1846 // handles it via the _HASH_CHECK early-return path without affecting param count tracking.
1847 if (_firmwareType == MAV_AUTOPILOT_PX4 && !_paramRequestListHashCheckSent) {
1848 _paramRequestListHashCheckSent = true;
1849
1850 mavlink_param_union_t valueUnion{};
1851 valueUnion.type = MAV_PARAM_TYPE_UINT32;
1852 valueUnion.param_uint32 = _computeParamHash(componentId);
1853
1854 char paramId[MAVLINK_MSG_ID_PARAM_VALUE_LEN]{};
1855 (void) strncpy(paramId, "_HASH_CHECK", MAVLINK_MSG_ID_PARAM_VALUE_LEN);
1856
1857 qCDebug(MockLinkLog) << "Sending _HASH_CHECK in PARAM_REQUEST_LIST stream" << componentId << "hash:" << valueUnion.param_uint32;
1858
1859 mavlink_message_t responseMsg{};
1860 (void) mavlink_msg_param_value_pack_chan(
1861 _vehicleSystemId,
1862 componentId,
1863 _outgoingMavlinkChannel,
1864 &responseMsg,
1865 paramId,
1866 valueUnion.param_float,
1867 MAV_PARAM_TYPE_UINT32,
1868 0, // param_count: 0 to avoid affecting ParameterManager's count tracking
1869 -1 // param_index: -1 signals this is a virtual/out-of-band parameter
1870 );
1871 respondWithMavlinkMessage(responseMsg);
1872 return;
1873 }
1874
1875 // Move to next component
1876 if (++_currentParamRequestListComponentIndex >= _paramRequestListComponentIds.count()) {
1877 _currentParamRequestListComponentIndex = -1;
1878 _paramRequestListComponentIds.clear();
1879 _paramRequestListParamNames.clear();
1880 } else {
1881 // Cache param names for the new component
1882 _paramRequestListParamNames = _mapParamName2Value[_paramRequestListComponentIds.at(_currentParamRequestListComponentIndex)].keys();
1883 _currentParamRequestListParamIndex = 0;
1884 _paramRequestListHashCheckSent = false;
1885 }
1886 return;
1887 }
1888
1889 const QString &paramName = _paramRequestListParamNames.at(_currentParamRequestListParamIndex);
1890
1891 if (_shouldSkipParamSend(componentId, paramName, _currentParamRequestListParamIndex)) {
1892 qCDebug(MockLinkLog) << "Skipping param send:" << paramName;
1893 } else {
1894 char paramId[MAVLINK_MSG_ID_PARAM_VALUE_LEN]{};
1895 mavlink_message_t responseMsg{};
1896
1897 if (!_mapParamName2Value[componentId].contains(paramName) ||
1898 !_mapParamName2MavParamType[componentId].contains(paramName) ||
1899 paramName.length() > MAVLINK_MSG_ID_PARAM_VALUE_LEN) {
1900 qCWarning(MockLinkLog) << "Cannot stream invalid mock parameter" << componentId << paramName;
1901 _currentParamRequestListComponentIndex = -1;
1902 _paramRequestListComponentIds.clear();
1903 _paramRequestListParamNames.clear();
1904 return;
1905 }
1906
1907 const MAV_PARAM_TYPE paramType = _mapParamName2MavParamType[componentId][paramName];
1908
1909 (void) strncpy(paramId, paramName.toLocal8Bit().constData(), MAVLINK_MSG_ID_PARAM_VALUE_LEN);
1910
1911 qCDebug(MockLinkLog) << "Sending msg_param_value" << componentId << paramId << paramType << _mapParamName2Value[componentId][paramId];
1912
1913 (void) mavlink_msg_param_value_pack_chan(
1914 _vehicleSystemId,
1915 componentId, // component id
1916 _outgoingMavlinkChannel,
1917 &responseMsg, // Outgoing message
1918 paramId, // Parameter name
1919 _floatUnionForParam(componentId, paramName), // Parameter value
1920 paramType, // MAV_PARAM_TYPE
1921 cParameters, // Total number of parameters
1922 _currentParamRequestListParamIndex // Index of this parameter
1923 );
1924 respondWithMavlinkMessage(responseMsg);
1925 }
1926
1927 // Move to next param index
1928 ++_currentParamRequestListParamIndex;
1929}
1930
1931void MockLink::_handleParamSet(const mavlink_message_t &msg)
1932{
1933 mavlink_param_set_t request{};
1934 mavlink_msg_param_set_decode(&msg, &request);
1935
1936 const quint32 targetSystem = mavlink_msg_get_target_sysid(&msg, mavlink_get_msg_entry(msg.msgid));
1937 if (targetSystem != _vehicleSystemId) {
1938 qCDebug(MockLinkLog) << "Ignoring PARAM_SET for system" << targetSystem;
1939 return;
1940 }
1941 const int componentId = request.target_component;
1942
1943 // Param may not be null terminated if exactly fits
1944 char paramId[MAVLINK_MSG_PARAM_SET_FIELD_PARAM_ID_LEN + 1]{};
1945 paramId[MAVLINK_MSG_PARAM_SET_FIELD_PARAM_ID_LEN] = 0;
1946 (void) strncpy(paramId, request.param_id, MAVLINK_MSG_PARAM_SET_FIELD_PARAM_ID_LEN);
1947
1948 qCDebug(MockLinkLog) << "_handleParamSet" << componentId << paramId << request.param_type;
1949
1950 // PX4 special case: _HASH_CHECK is a virtual parameter used by ParameterManager
1951 // to signal cache-hit and stop parameter streaming. It is intentionally not part
1952 // of the normal parameter maps.
1953 if ((_firmwareType == MAV_AUTOPILOT_PX4) && (strncmp(paramId, "_HASH_CHECK", MAVLINK_MSG_PARAM_SET_FIELD_PARAM_ID_LEN) == 0)) {
1954 QMutexLocker locker(&_paramRequestListMutex);
1955 _currentParamRequestListComponentIndex = -1;
1956 _paramRequestListComponentIds.clear();
1957 _paramRequestListParamNames.clear();
1958 qCDebug(MockLinkLog) << "Received _HASH_CHECK PARAM_SET, stopping parameter stream";
1959 return;
1960 }
1961
1962 // Real firmware rejects a PARAM_SET it doesn't recognize rather than crashing.
1963 // QGC can legitimately send these: loading a QGC-format param file sends params
1964 // not currently known to the vehicle (e.g. params unlocked by another param).
1965 if (!_mapParamName2Value.contains(componentId) || !_mapParamName2MavParamType.contains(componentId)) {
1966 qCDebug(MockLinkLog) << "_handleParamSet unknown component, rejecting with PARAM_ERROR - componentId:" << componentId << "param:" << paramId;
1967 _sendParamError(componentId, paramId, -1, MAV_PARAM_ERROR_COMPONENT_NOT_FOUND);
1968 return;
1969 }
1970 const QString paramName = QString::fromLatin1(paramId);
1971 const bool px4UnusedParam = !_mapParamName2Value[componentId].contains(paramId) &&
1972 (componentId == MAV_COMP_ID_AUTOPILOT1) && _px4UnusedParams.contains(paramName);
1973 if (!px4UnusedParam && !_mapParamName2Value[componentId].contains(paramId)) {
1974 qCDebug(MockLinkLog) << "_handleParamSet unknown param, rejecting with PARAM_ERROR - componentId:" << componentId << "param:" << paramId;
1975 _sendParamError(componentId, paramId, -1, MAV_PARAM_ERROR_DOES_NOT_EXIST);
1976 return;
1977 }
1978 const MAV_PARAM_TYPE paramType =
1979 px4UnusedParam ? MAV_PARAM_TYPE_INT32 : _mapParamName2MavParamType[componentId][paramId];
1980 if (request.param_type != paramType) {
1981 qCDebug(MockLinkLog) << "_handleParamSet type mismatch, rejecting with PARAM_ERROR - param:" << paramId
1982 << "requested type:" << request.param_type << "actual type:" << paramType;
1983 _sendParamError(componentId, paramId, -1, MAV_PARAM_ERROR_TYPE_MISMATCH);
1984 return;
1985 }
1986
1987 // Apply failure behaviors before committing change.
1988 if (_paramSetFailureMode == FailParamSetFirstAttemptNoAck && _paramSetFailureFirstAttemptPending) {
1989 qCDebug(MockLinkLog) << "Param set failure: first attempt no ack" << paramId;
1990 _paramSetFailureFirstAttemptPending = false;
1991 return;
1992 }
1993
1994 if (_paramSetFailureMode == FailParamSetNoAck) {
1995 qCDebug(MockLinkLog) << "Param set failure: no ack" << paramId;
1996 return;
1997 }
1998
1999 if (_paramSetFailureMode == FailParamSetParamError) {
2000 qCDebug(MockLinkLog) << "Param set failure: PARAM_ERROR" << paramId;
2001 _sendParamError(componentId, paramId,
2002 _mapParamName2Value[componentId].keys().indexOf(paramId),
2003 MAV_PARAM_ERROR_VALUE_OUT_OF_RANGE);
2004 return;
2005 }
2006
2007 if (px4UnusedParam) {
2008 mavlink_param_union_t valueUnion{};
2009 valueUnion.param_float = request.param_value;
2010 _px4UnusedParams[paramName] = valueUnion.param_int32;
2011 _sendPX4UnusedParamValue(paramName);
2012 return;
2013 }
2014
2015 // Normal success path
2016 _setParamFloatUnionIntoMap(componentId, paramId, request.param_value);
2017
2018 mavlink_message_t responseMsg;
2019 mavlink_msg_param_value_pack_chan(
2020 _vehicleSystemId,
2021 componentId, // component id
2022 _outgoingMavlinkChannel,
2023 &responseMsg, // Outgoing message
2024 paramId, // Parameter name
2025 request.param_value, // Send same value back
2026 request.param_type, // Send same type back
2027 _mapParamName2Value[componentId].count(), // Total number of parameters
2028 _mapParamName2Value[componentId].keys().indexOf(paramId) // Index of this parameter
2029 );
2030 respondWithMavlinkMessage(responseMsg);
2031}
2032
2033void MockLink::_handleParamRequestRead(const mavlink_message_t &msg)
2034{
2035 mavlink_message_t responseMsg{};
2036 mavlink_param_request_read_t request{};
2037 mavlink_msg_param_request_read_decode(&msg, &request);
2038
2039 const QString paramName(QString::fromLocal8Bit(request.param_id, static_cast<int>(strnlen(request.param_id, MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN))));
2040 const int componentId = request.target_component;
2041
2042 // special case for magic _HASH_CHECK value (PX4 only)
2043 if ((_firmwareType == MAV_AUTOPILOT_PX4) && (paramName == "_HASH_CHECK")) {
2044 _hashCheckRequestCount++;
2045 if (_hashCheckNoResponse) {
2046 return;
2047 }
2048
2049 const int hashComponentId = _mapParamName2Value.contains(MAV_COMP_ID_AUTOPILOT1)
2050 ? MAV_COMP_ID_AUTOPILOT1
2051 : _mapParamName2Value.keys().first();
2052
2053 mavlink_param_union_t valueUnion{};
2054 valueUnion.type = MAV_PARAM_TYPE_UINT32;
2055 valueUnion.param_uint32 = _computeParamHash(hashComponentId);
2056 (void) mavlink_msg_param_value_pack_chan(
2057 _vehicleSystemId,
2058 hashComponentId,
2059 _outgoingMavlinkChannel,
2060 &responseMsg,
2061 request.param_id,
2062 valueUnion.param_float,
2063 MAV_PARAM_TYPE_UINT32,
2064 0,
2065 -1
2066 );
2067 respondWithMavlinkMessage(responseMsg);
2068 return;
2069 }
2070
2071 if (!_mapParamName2Value.contains(componentId)) {
2072 qCDebug(MockLinkLog) << "_handleParamRequestRead unknown component, rejecting with PARAM_ERROR - componentId:" << componentId << "param:" << paramName;
2073 const QByteArray paramIdBytes = paramName.toLocal8Bit();
2074 _sendParamError(componentId, paramIdBytes.constData(), request.param_index, MAV_PARAM_ERROR_COMPONENT_NOT_FOUND);
2075 return;
2076 }
2077
2078 char paramId[MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN + 1]{};
2079 paramId[0] = 0;
2080
2081 const quint32 targetSystem = mavlink_msg_get_target_sysid(&msg, mavlink_get_msg_entry(msg.msgid));
2082 if (targetSystem != _vehicleSystemId) {
2083 qCDebug(MockLinkLog) << "Ignoring PARAM_REQUEST_READ for system" << targetSystem;
2084 return;
2085 }
2086
2087 if (request.param_index == -1) {
2088 // Request is by param name. Param may not be null terminated if exactly fits
2089 (void) strncpy(paramId, request.param_id, MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN);
2090 } else {
2091 // Request is by index
2092 if (request.param_index < 0 || request.param_index >= _mapParamName2Value[componentId].size()) {
2093 qCWarning(MockLinkLog) << "Invalid mock parameter index" << componentId << request.param_index;
2094 _sendParamError(componentId, "", request.param_index, MAV_PARAM_ERROR_DOES_NOT_EXIST);
2095 return;
2096 }
2097
2098 const QString key = _mapParamName2Value[componentId].keys().at(request.param_index);
2099 if (key.length() > MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN) {
2100 qCWarning(MockLinkLog) << "Mock parameter name exceeds the wire limit" << componentId << key;
2101 return;
2102 }
2103 strcpy(paramId, key.toLocal8Bit().constData());
2104 _paramRequestReadIndexLog.append(qMakePair(componentId, static_cast<int>(request.param_index)));
2105 }
2106
2107 // By-name requests only, where paramName is the requested name
2108 const bool px4UnusedParam =
2109 (request.param_index == -1) && (componentId == MAV_COMP_ID_AUTOPILOT1) && _px4UnusedParams.contains(paramName);
2110 if (!px4UnusedParam && (!_mapParamName2Value[componentId].contains(paramId) ||
2111 !_mapParamName2MavParamType[componentId].contains(paramId))) {
2112 // Real firmware rejects a read of a parameter it doesn't know about (e.g. QGC
2113 // refreshing a param after a failed PARAM_SET for a param not on the vehicle)
2114 qCDebug(MockLinkLog) << "_handleParamRequestRead unknown param, rejecting with PARAM_ERROR - componentId:" << componentId << "param:" << paramId;
2115 _sendParamError(componentId, paramId, request.param_index, MAV_PARAM_ERROR_DOES_NOT_EXIST);
2116 return;
2117 }
2118
2119 const int paramIndex = (request.param_index == -1) ? static_cast<int>(_mapParamName2Value[componentId].keys().indexOf(paramId)) : request.param_index;
2120 if (_shouldSkipParamRead(componentId, paramId, paramIndex)) {
2121 qCDebug(MockLinkLog) << "Ignoring request read for" << paramId;
2122 return;
2123 }
2124
2125 if (_paramRequestReadFailureMode == FailParamRequestReadFirstAttemptNoResponse && _paramRequestReadFailureFirstAttemptPending) {
2126 qCDebug(MockLinkLog) << "Param request read failure: first attempt no response" << paramId;
2127 _paramRequestReadFailureFirstAttemptPending = false;
2128 return;
2129 }
2130
2131 if (_paramRequestReadFailureMode == FailParamRequestReadNoResponse) {
2132 qCDebug(MockLinkLog) << "Param request read failure: no response" << paramId;
2133 return;
2134 }
2135
2136 if (_paramRequestReadFailureMode == FailParamRequestReadParamError) {
2137 qCDebug(MockLinkLog) << "Param request read failure: PARAM_ERROR" << paramId;
2138 _sendParamError(componentId, paramId, request.param_index, MAV_PARAM_ERROR_DOES_NOT_EXIST);
2139 return;
2140 }
2141
2142 if (px4UnusedParam) {
2143 _sendPX4UnusedParamValue(paramName);
2144 return;
2145 }
2146
2147 (void) mavlink_msg_param_value_pack_chan(
2148 _vehicleSystemId,
2149 componentId, // component id
2150 _outgoingMavlinkChannel,
2151 &responseMsg, // Outgoing message
2152 paramId, // Parameter name
2153 _floatUnionForParam(componentId, paramId), // Parameter value
2154 _mapParamName2MavParamType[componentId][paramId], // Parameter type
2155 _mapParamName2Value[componentId].count(), // Total number of parameters
2156 _mapParamName2Value[componentId].keys().indexOf(paramId) // Index of this parameter
2157 );
2158 respondWithMavlinkMessage(responseMsg);
2159}
2160
2161void MockLink::_sendPX4UnusedParamValue(const QString& paramName)
2162{
2163 mavlink_param_union_t valueUnion{};
2164 valueUnion.param_int32 = _px4UnusedParams.value(paramName);
2165
2166 char paramId[MAVLINK_MSG_PARAM_VALUE_FIELD_PARAM_ID_LEN + 1]{};
2167 (void) strncpy(paramId, paramName.toLatin1().constData(), MAVLINK_MSG_PARAM_VALUE_FIELD_PARAM_ID_LEN);
2168
2169 // Like PX4, an unused parameter has no index in the parameter list
2170 mavlink_message_t responseMsg{};
2171 (void) mavlink_msg_param_value_pack_chan(_vehicleSystemId, MAV_COMP_ID_AUTOPILOT1, _outgoingMavlinkChannel,
2172 &responseMsg, paramId, valueUnion.param_float, MAV_PARAM_TYPE_INT32,
2173 _mapParamName2Value[MAV_COMP_ID_AUTOPILOT1].count(), -1);
2174 respondWithMavlinkMessage(responseMsg);
2175}
2176
2177QVariant MockLink::paramValue(int componentId, const QString& paramName) const
2178{
2179 if ((componentId == MAV_COMP_ID_AUTOPILOT1) && _px4UnusedParams.contains(paramName)) {
2180 return QVariant::fromValue(_px4UnusedParams.value(paramName));
2181 }
2182 return _mapParamName2Value.value(componentId).value(paramName);
2183}
2184
2185void MockLink::_sendParamError(int componentId, const char *paramId, int16_t paramIndex, uint8_t errorCode)
2186{
2187 mavlink_message_t responseMsg{};
2188 char paramIdBuf[MAVLINK_MSG_PARAM_ERROR_FIELD_PARAM_ID_LEN + 1] = {};
2189 (void) strncpy(paramIdBuf, paramId, MAVLINK_MSG_PARAM_ERROR_FIELD_PARAM_ID_LEN);
2190
2191 (void) mavlink_msg_param_error_pack_chan(
2192 _vehicleSystemId,
2193 static_cast<uint8_t>(componentId),
2194 _outgoingMavlinkChannel,
2195 &responseMsg,
2196 MAVLinkProtocol::instance()->getSystemId(),
2198 paramIdBuf,
2199 paramIndex,
2200 errorCode
2201 );
2202 respondWithMavlinkMessage(responseMsg);
2203}
2204
2205void MockLink::_handleFTP(const mavlink_message_t &msg)
2206{
2207 _mockLinkFTP->mavlinkMessageReceived(msg);
2208}
2209
2210void MockLink::_handleInProgressCommandLong(const mavlink_command_long_t &request)
2211{
2212 uint8_t commandResult = MAV_RESULT_UNSUPPORTED;
2213
2214 switch (request.command) {
2216 // Test command which sends in progress messages and then acceptance ack
2217 commandResult = MAV_RESULT_ACCEPTED;
2218 break;
2220 // Test command which sends in progress messages and then failure ack
2221 commandResult = MAV_RESULT_FAILED;
2222 break;
2224 // Test command which sends in progress messages and then never sends final result ack
2225 break;
2226 }
2227
2228 mavlink_message_t commandAck{};
2229 (void) mavlink_msg_command_ack_pack_chan(
2230 _vehicleSystemId,
2231 _vehicleComponentId,
2232 _outgoingMavlinkChannel,
2233 &commandAck,
2234 request.command,
2235 MAV_RESULT_IN_PROGRESS,
2236 1, // progress
2237 0, // result_param2
2238 0, // target_system
2239 0 // target_component
2240 );
2241 respondWithMavlinkMessage(commandAck);
2242
2244 (void) mavlink_msg_command_ack_pack_chan(
2245 _vehicleSystemId,
2246 _vehicleComponentId,
2247 _outgoingMavlinkChannel,
2248 &commandAck,
2249 request.command,
2250 commandResult,
2251 0, // progress
2252 0, // result_param2
2253 0, // target_system
2254 0 // target_component
2255 );
2256 respondWithMavlinkMessage(commandAck);
2257 }
2258}
2259
2260void MockLink::_handleCommandLongSetMessageInterval(const mavlink_command_long_t &request, bool &accepted)
2261{
2262 // Accept only the message IDs that MAVLinkStreamConfig requests for PID tuning.
2263 // Anything else gets MAV_RESULT_UNSUPPORTED so unit tests will catch unexpected usage.
2264 static const QSet<int> kPidTuningMessageIds = {
2265 MAVLINK_MSG_ID_ATTITUDE_QUATERNION,
2266 MAVLINK_MSG_ID_ATTITUDE_TARGET,
2267 MAVLINK_MSG_ID_LOCAL_POSITION_NED,
2268 MAVLINK_MSG_ID_POSITION_TARGET_LOCAL_NED,
2269 MAVLINK_MSG_ID_NAV_CONTROLLER_OUTPUT,
2270 MAVLINK_MSG_ID_VFR_HUD,
2271 };
2272 accepted = kPidTuningMessageIds.contains(static_cast<int>(request.param1));
2273}
2274
2275void MockLink::_handleCommandLong(const mavlink_message_t &msg)
2276{
2277 static bool firstCmdUser3 = true;
2278 static bool firstCmdUser4 = true;
2279
2280 mavlink_command_long_t request{};
2281 mavlink_msg_command_long_decode(&msg, &request);
2282
2283 // Ignore commands for other components: QGC would match an ack from the autopilot to a pending autopilot command
2284 if ((request.target_component != _vehicleComponentId) && (request.target_component != MAV_COMP_ID_ALL)) {
2285 return;
2286 }
2287
2288 uint8_t commandResult = MAV_RESULT_UNSUPPORTED;
2289
2290 switch (request.command) {
2291 case MAV_CMD_COMPONENT_ARM_DISARM:
2292 if (request.param1 == 0.0f) {
2293 _mavBaseMode &= ~MAV_MODE_FLAG_SAFETY_ARMED;
2294 } else {
2295 _mavBaseMode |= MAV_MODE_FLAG_SAFETY_ARMED;
2296 }
2297 commandResult = MAV_RESULT_ACCEPTED;
2298 break;
2299 case MAV_CMD_DO_SET_MODE:
2300 // Preserve the armed flag like real firmware does
2301 _mavBaseMode = (_mavBaseMode & MAV_MODE_FLAG_SAFETY_ARMED) | static_cast<uint8_t>(request.param1);
2302 _mavCustomMode = static_cast<uint32_t>(request.param2);
2303 commandResult = MAV_RESULT_ACCEPTED;
2304 break;
2305 case MAV_CMD_MISSION_START:
2306 commandResult = MAV_RESULT_ACCEPTED;
2307 break;
2308 case MAV_CMD_PREFLIGHT_CALIBRATION: {
2309 // PX4's commander rejects every calibration command while one runs, a cancel included, while the running
2310 // calibration takes the cancel. Real PX4 acks both ways; the rejection is the case the GCS must tolerate.
2311 const bool px4Busy = (_firmwareType == MAV_AUTOPILOT_PX4) && _mockLinkPX4Calibration->calibrationActive();
2312 const bool cancelRequest = (request.param1 == 0) && (request.param2 == 0) && (request.param3 == 0) &&
2313 (request.param4 == 0) && (request.param5 == 0) && (request.param6 == 0) &&
2314 (request.param7 == 0);
2315 commandResult = px4Busy ? MAV_RESULT_TEMPORARILY_REJECTED : MAV_RESULT_ACCEPTED;
2316 // A rejected start does nothing, so it cannot replace the calibration which is running
2317 if (!px4Busy || cancelRequest) {
2318 _handlePreFlightCalibration(request);
2319 }
2320 break;
2321 }
2322 case MAV_CMD_DO_MOTOR_TEST:
2323 commandResult = MAV_RESULT_ACCEPTED;
2324 break;
2325 case MAV_CMD_FIXED_MAG_CAL_YAW:
2326 // PX4 large vehicle compass calibration: the tests send the result as a status text
2327 commandResult = _largeVehicleCalibrationRejected ? MAV_RESULT_TEMPORARILY_REJECTED : MAV_RESULT_ACCEPTED;
2328 break;
2329 case MAV_CMD_DO_START_MAG_CAL:
2330 // APM onboard compass calibration: start sending MAG_CAL_PROGRESS then MAG_CAL_REPORT.
2331 // Note: does NOT stop stale failed report streaming - like real ArduPilot, only
2332 // MAV_CMD_DO_CANCEL_MAG_CAL stops the failed report stream.
2333 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
2334 if (_apmMagCalStartFailureMode) {
2335 commandResult = MAV_RESULT_FAILED;
2336 } else {
2337 QMutexLocker locker(&_apmCompassCalMutex);
2338 _apmCompassCalProgress = 0;
2339 _apmCompassCalTickCount = 0;
2340 commandResult = MAV_RESULT_ACCEPTED;
2341 }
2342 }
2343 break;
2344 case MAV_CMD_DO_CANCEL_MAG_CAL:
2345 // Stop APM compass calibration worker
2346 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
2347 QMutexLocker locker(&_apmCompassCalMutex);
2348 _apmStaleFailedMagCalReportStreaming = false;
2349 _apmCompassCalProgress = -1;
2350 commandResult = MAV_RESULT_ACCEPTED;
2351 }
2352 break;
2353 case MAV_CMD_CONTROL_HIGH_LATENCY:
2354 if (linkConfiguration()->isHighLatency()) {
2355 _highLatencyTransmissionEnabled = static_cast<int>(request.param1) != 0;
2356 emit highLatencyTransmissionEnabledChanged(_highLatencyTransmissionEnabled);
2357 commandResult = MAV_RESULT_ACCEPTED;
2358 } else {
2359 commandResult = MAV_RESULT_FAILED;
2360 }
2361 break;
2362 case MAV_CMD_PREFLIGHT_STORAGE:
2363 if (static_cast<int>(request.param1) == 2) {
2364 // Reset all parameters to firmware defaults (unit test support)
2365 _resetParamsToDefaults();
2366 }
2367 commandResult = MAV_RESULT_ACCEPTED;
2368 break;
2369 case MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN:
2370 // Unit test support: accept the reboot command so tests can exercise
2371 // flows which restart the vehicle (e.g. airframe Apply and Restart).
2372 // The actual reboot is not simulated.
2373 commandResult = MAV_RESULT_ACCEPTED;
2374 break;
2375 case MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES:
2376 commandResult = MAV_RESULT_ACCEPTED;
2377 _respondWithAutopilotVersion();
2378 break;
2379 case MAV_CMD_REQUEST_MESSAGE:
2380 {
2381 bool accepted = false;
2382 bool noAck = false;
2383 _handleRequestMessage(request, accepted, noAck);
2384 if (noAck) {
2385 // FailRequestMessageCommandNoResponse: don't send any ack, let vehicle timeout
2386 return;
2387 }
2388 if (accepted) {
2389 commandResult = MAV_RESULT_ACCEPTED;
2390 }
2391 break;
2392 }
2393 case MAV_CMD_NAV_TAKEOFF:
2394 switch (_takeoffFailureMode.load()) {
2395 case FailTakeoffNone:
2396 _handleTakeoff(request);
2397 commandResult = MAV_RESULT_ACCEPTED;
2398 break;
2400 commandResult = MAV_RESULT_TEMPORARILY_REJECTED;
2401 break;
2403 return;
2404 }
2405 break;
2407 // Test command which always returns MAV_RESULT_ACCEPTED
2408 commandResult = MAV_RESULT_ACCEPTED;
2409 break;
2411 // Test command which always returns MAV_RESULT_FAILED
2412 commandResult = MAV_RESULT_FAILED;
2413 break;
2415 // Test command which does not respond to first request and returns MAV_RESULT_ACCEPTED on second attempt
2416 if (firstCmdUser3) {
2417 firstCmdUser3 = false;
2418 return;
2419 } else {
2420 firstCmdUser3 = true;
2421 commandResult = MAV_RESULT_ACCEPTED;
2422 }
2423 break;
2425 // Test command which does not respond to first request and returns MAV_RESULT_FAILED on second attempt
2426 if (firstCmdUser4) {
2427 firstCmdUser4 = false;
2428 return;
2429 } else {
2430 firstCmdUser4 = true;
2431 commandResult = MAV_RESULT_FAILED;
2432 }
2433 break;
2436 // Test command which never responds
2437 return;
2441 _handleInProgressCommandLong(request);
2442 return;
2443 case MAV_CMD_SET_MESSAGE_INTERVAL:
2444 {
2445 bool accepted = false;
2446
2447 _handleCommandLongSetMessageInterval(request, accepted);
2448 if (accepted) {
2449 commandResult = MAV_RESULT_ACCEPTED;
2450 }
2451 break;
2452 }
2453 }
2454
2455 mavlink_message_t commandAck{};
2456 (void) mavlink_msg_command_ack_pack_chan(
2457 _vehicleSystemId,
2458 _vehicleComponentId,
2459 _outgoingMavlinkChannel,
2460 &commandAck,
2461 request.command,
2462 commandResult,
2463 0, // progress
2464 0, // result_param2
2465 0, // target_system
2466 0 // target_component
2467 );
2468 respondWithMavlinkMessage(commandAck);
2469}
2470
2471void MockLink::_handleCommandInt(const mavlink_message_t &msg)
2472{
2473 mavlink_command_int_t request{};
2474 mavlink_msg_command_int_decode(&msg, &request);
2475
2476 // Ignore commands for other components: QGC would match an ack from the autopilot to a pending autopilot command
2477 if ((request.target_component != _vehicleComponentId) && (request.target_component != MAV_COMP_ID_ALL)) {
2478 return;
2479 }
2480
2481 // Unrecognized commands are reported as unsupported (mirroring the COMMAND_LONG default).
2482 // This lets unit tests exercise "try command, fall back to legacy message" code paths
2483 // such as Vehicle::setEstimatorOrigin.
2484 uint8_t commandResult = MAV_RESULT_UNSUPPORTED;
2485
2486 switch (request.command) {
2487 case MAV_CMD_DO_SET_ROI_LOCATION:
2488 // Unit test support: accept ROI commands so tests can verify Vehicle::guidedModeROI
2489 commandResult = MAV_RESULT_ACCEPTED;
2490 break;
2491 case MAV_CMD_DO_SET_HOME:
2492 // Unit test support: accept so tests can verify how Vehicle sends set home
2493 commandResult = MAV_RESULT_ACCEPTED;
2494 break;
2495 case MAV_CMD_DO_SET_MODE:
2496 // Preserve the armed flag like real firmware does
2497 _mavBaseMode = (_mavBaseMode & MAV_MODE_FLAG_SAFETY_ARMED) | static_cast<uint8_t>(request.param1);
2498 _mavCustomMode = static_cast<uint32_t>(request.param2);
2499 commandResult = MAV_RESULT_ACCEPTED;
2500 break;
2501 case MAV_CMD_DO_REPOSITION: // Unit test support: lets tests verify how firmware plugins send reposition
2502 case MAV_CMD_MISSION_START:
2503 commandResult = MAV_RESULT_ACCEPTED;
2504 break;
2505 default:
2506 break;
2507 }
2508
2509 mavlink_message_t commandAck{};
2510 (void) mavlink_msg_command_ack_pack_chan(
2511 _vehicleSystemId,
2512 _vehicleComponentId,
2513 _outgoingMavlinkChannel,
2514 &commandAck,
2515 request.command,
2516 commandResult,
2517 0, // progress
2518 0, // result_param2
2519 0, // target_system
2520 0 // target_component
2521 );
2522 respondWithMavlinkMessage(commandAck);
2523}
2524
2525void MockLink::sendUnexpectedCommandAck(MAV_CMD command, MAV_RESULT ackResult)
2526{
2527 mavlink_message_t commandAck{};
2528 (void) mavlink_msg_command_ack_pack_chan(
2529 _vehicleSystemId,
2530 _vehicleComponentId,
2531 _outgoingMavlinkChannel,
2532 &commandAck,
2533 command,
2534 ackResult,
2535 0, // progress
2536 0, // result_param2
2537 0, // target_system
2538 0 // target_component
2539 );
2540 respondWithMavlinkMessage(commandAck);
2541}
2542
2543void MockLink::_respondWithAutopilotVersion()
2544{
2545 union FlightVersion {
2546 uint32_t raw;
2547
2548 struct {
2549 uint8_t type; // bits 0–7
2550 uint8_t patch; // bits 8–15
2551 uint8_t minor; // bits 16–23
2552 uint8_t major; // bits 24–31
2553 } parts;
2554
2555 FlightVersion(uint32_t version = 0) : raw(version) {}
2556 };
2557 FlightVersion flightVersion;
2558
2559 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
2560 flightVersion.parts.major = 4;
2561 flightVersion.parts.minor = 7;
2562 flightVersion.parts.patch = 0;
2563 flightVersion.parts.type = FIRMWARE_VERSION_TYPE_OFFICIAL;
2564 } else if (_firmwareType == MAV_AUTOPILOT_PX4) {
2565 flightVersion.parts.major = 1;
2566 flightVersion.parts.minor = 17;
2567 flightVersion.parts.patch = 0;
2568 flightVersion.parts.type = FIRMWARE_VERSION_TYPE_OFFICIAL;
2569 }
2570
2571 const uint8_t customVersion[8]{};
2572 const uint64_t capabilities = MAV_PROTOCOL_CAPABILITY_MAVLINK2 | MAV_PROTOCOL_CAPABILITY_MISSION_FENCE | MAV_PROTOCOL_CAPABILITY_MISSION_RALLY | MAV_PROTOCOL_CAPABILITY_MISSION_INT
2573 | MAV_PROTOCOL_CAPABILITY_COMMAND_INT // matches modern PX4/ArduPilot so tests exercise the preferred COMMAND_INT path
2574 | ((_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) ? MAV_PROTOCOL_CAPABILITY_TERRAIN : 0)
2575 | (_ftpCapability ? MAV_PROTOCOL_CAPABILITY_FTP : 0);
2576
2577 mavlink_message_t msg{};
2578 (void) mavlink_msg_autopilot_version_pack_chan(
2579 _vehicleSystemId,
2580 _vehicleComponentId,
2581 _outgoingMavlinkChannel,
2582 &msg,
2583 capabilities,
2584 flightVersion.raw, // flight_sw_version,
2585 0, // middleware_sw_version,
2586 0, // os_sw_version,
2587 0, // board_version,
2588 reinterpret_cast<const uint8_t*>(&customVersion), // flight_custom_version,
2589 reinterpret_cast<const uint8_t*>(&customVersion), // middleware_custom_version,
2590 reinterpret_cast<const uint8_t*>(&customVersion), // os_custom_version,
2591 _boardVendorId,
2592 _boardProductId,
2593 0, // uid
2594 0 // uid2
2595 );
2597}
2598
2599void MockLink::_sendHomePosition()
2600{
2601 const float bogus[4]{};
2602
2603 mavlink_message_t msg{};
2604 (void) mavlink_msg_home_position_pack_chan(
2605 _vehicleSystemId,
2606 _vehicleComponentId,
2607 _outgoingMavlinkChannel,
2608 &msg,
2609 static_cast<int32_t>(_vehicleLatitude * 1E7),
2610 static_cast<int32_t>(_vehicleLongitude * 1E7),
2611 static_cast<int32_t>(_defaultVehicleHomeAltitude * 1000),
2612 0.0f, 0.0f, 0.0f,
2613 &bogus[0],
2614 0.0f, 0.0f, 0.0f,
2615 0
2616 );
2618}
2619
2620void MockLink::_sendGpsRawInt()
2621{
2622 static uint64_t timeTick = 0;
2623
2624 mavlink_message_t msg{};
2625 (void) mavlink_msg_gps_raw_int_pack_chan(
2626 _vehicleSystemId,
2627 _vehicleComponentId,
2628 _outgoingMavlinkChannel,
2629 &msg,
2630 timeTick++, // time since boot
2631 GPS_FIX_TYPE_3D_FIX,
2632 static_cast<int32_t>(_vehicleLatitude * 1E7),
2633 static_cast<int32_t>(_vehicleLongitude * 1E7),
2634 static_cast<int32_t>(_vehicleAltitudeAMSL * 1000),
2635 3 * 100, // hdop
2636 3 * 100, // vdop
2637 UINT16_MAX, // velocity not known
2638 UINT16_MAX, // course over ground not known
2639 8, // satellites visible
2640 //-- Extension
2641 0, // Altitude (above WGS84, EGM96 ellipsoid), in meters * 1000 (positive for up).
2642 0, // Position uncertainty in meters * 1000 (positive for up).
2643 0, // Altitude uncertainty in meters * 1000 (positive for up).
2644 0, // Speed uncertainty in meters * 1000 (positive for up).
2645 0, // Heading / track uncertainty in degrees * 1e5.
2646 65535 // Yaw not provided
2647 );
2649}
2650
2651void MockLink::_sendGlobalPositionInt()
2652{
2653 static uint64_t timeTick = 0;
2654
2655 mavlink_message_t msg{};
2656 (void) mavlink_msg_global_position_int_pack_chan(
2657 _vehicleSystemId,
2658 _vehicleComponentId,
2659 _outgoingMavlinkChannel,
2660 &msg,
2661 timeTick++, // time since boot
2662 static_cast<int32_t>(_vehicleLatitude * 1E7),
2663 static_cast<int32_t>(_vehicleLongitude * 1E7),
2664 static_cast<int32_t>(_vehicleAltitudeAMSL * 1000),
2665 static_cast<int32_t>((_vehicleAltitudeAMSL - _defaultVehicleHomeAltitude) * 1000),
2666 0, 0, 0, // no speed sent
2667 UINT16_MAX // no heading sent
2668 );
2670}
2671
2672void MockLink::_sendAttitudeQuaternion()
2673{
2674 const uint32_t timeBootMs = static_cast<uint32_t>(_runningTime.elapsed());
2675 const float t = timeBootMs / 1000.0f;
2676
2677 AttitudeOverride override;
2678 {
2679 QMutexLocker locker(&_attitudeOverrideMutex);
2680 override = _attitudeOverride;
2681 }
2682 const bool overridden = override.enabled;
2683
2684 // Synthesize sinusoidal Euler angles (rad) unless a test pinned the attitude
2685 const float roll = overridden ? override.rollRad : 0.20f * std::sin(2.0f * static_cast<float>(M_PI) * 0.50f * t);
2686 const float pitch = overridden ? override.pitchRad : 0.10f * std::sin(2.0f * static_cast<float>(M_PI) * 0.40f * t);
2687 const float yaw = overridden ? override.yawRad : 0.30f * std::sin(2.0f * static_cast<float>(M_PI) * 0.10f * t);
2688
2689 // ZYX Euler → quaternion
2690 const float cr = std::cos(roll / 2.0f), sr = std::sin(roll / 2.0f);
2691 const float cp = std::cos(pitch / 2.0f), sp = std::sin(pitch / 2.0f);
2692 const float cy = std::cos(yaw / 2.0f), sy = std::sin(yaw / 2.0f);
2693 const float q1 = cr * cp * cy + sr * sp * sy; // w
2694 const float q2 = sr * cp * cy - cr * sp * sy; // x
2695 const float q3 = cr * sp * cy + sr * cp * sy; // y
2696 const float q4 = cr * cp * sy - sr * sp * cy; // z
2697
2698 // Body rates = time-derivatives of the Euler angles
2699 const float rollspeed = overridden ? 0.0f : 0.20f * (2.0f * static_cast<float>(M_PI) * 0.50f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.50f * t);
2700 const float pitchspeed = overridden ? 0.0f : 0.10f * (2.0f * static_cast<float>(M_PI) * 0.40f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.40f * t);
2701 const float yawspeed = overridden ? 0.0f : 0.30f * (2.0f * static_cast<float>(M_PI) * 0.10f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.10f * t);
2702
2703 const float reprOffsetQ[4] = {1.0f, 0.0f, 0.0f, 0.0f}; // identity
2704
2705 mavlink_message_t msg{};
2706 (void) mavlink_msg_attitude_quaternion_pack_chan(
2707 _vehicleSystemId,
2708 _vehicleComponentId,
2709 _outgoingMavlinkChannel,
2710 &msg,
2711 timeBootMs,
2712 q1, q2, q3, q4,
2713 rollspeed, pitchspeed, yawspeed,
2714 reprOffsetQ
2715 );
2717}
2718
2719void MockLink::_sendAttitudeTarget()
2720{
2721 // Setpoint: same shape as actual, phase-shifted by +0.3 rad
2722 const uint32_t timeBootMs = static_cast<uint32_t>(_runningTime.elapsed());
2723 const float t = timeBootMs / 1000.0f;
2724 static constexpr float kPhase = 0.3f; // rad
2725
2726 const float roll = 0.20f * std::sin(2.0f * static_cast<float>(M_PI) * 0.50f * t + kPhase);
2727 const float pitch = 0.10f * std::sin(2.0f * static_cast<float>(M_PI) * 0.40f * t + kPhase);
2728 const float yaw = 0.30f * std::sin(2.0f * static_cast<float>(M_PI) * 0.10f * t + kPhase);
2729
2730 const float cr = std::cos(roll / 2.0f), sr = std::sin(roll / 2.0f);
2731 const float cp = std::cos(pitch / 2.0f), sp = std::sin(pitch / 2.0f);
2732 const float cy = std::cos(yaw / 2.0f), sy = std::sin(yaw / 2.0f);
2733 const float qSp[4] = {
2734 cr * cp * cy + sr * sp * sy,
2735 sr * cp * cy - cr * sp * sy,
2736 cr * sp * cy + sr * cp * sy,
2737 cr * cp * sy - sr * sp * cy,
2738 };
2739
2740 const float bodyRollRate = 0.20f * (2.0f * static_cast<float>(M_PI) * 0.50f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.50f * t + kPhase);
2741 const float bodyPitchRate = 0.10f * (2.0f * static_cast<float>(M_PI) * 0.40f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.40f * t + kPhase);
2742 const float bodyYawRate = 0.30f * (2.0f * static_cast<float>(M_PI) * 0.10f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.10f * t + kPhase);
2743
2744 mavlink_message_t msg{};
2745 (void) mavlink_msg_attitude_target_pack_chan(
2746 _vehicleSystemId,
2747 _vehicleComponentId,
2748 _outgoingMavlinkChannel,
2749 &msg,
2750 timeBootMs,
2751 0, // type_mask: all fields valid
2752 qSp,
2753 bodyRollRate, bodyPitchRate, bodyYawRate,
2754 0.5f // thrust
2755 );
2757}
2758
2759void MockLink::_sendLocalPositionNed()
2760{
2761 const uint32_t timeBootMs = static_cast<uint32_t>(_runningTime.elapsed());
2762 const float t = timeBootMs / 1000.0f;
2763
2764 const float x = 5.0f * std::sin(2.0f * static_cast<float>(M_PI) * 0.08f * t);
2765 const float y = 5.0f * std::sin(2.0f * static_cast<float>(M_PI) * 0.10f * t);
2766 const float z = -10.0f + 1.0f * std::sin(2.0f * static_cast<float>(M_PI) * 0.15f * t); // negative = up in NED
2767 const float vx = 5.0f * (2.0f * static_cast<float>(M_PI) * 0.08f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.08f * t);
2768 const float vy = 5.0f * (2.0f * static_cast<float>(M_PI) * 0.10f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.10f * t);
2769 const float vz = 1.0f * (2.0f * static_cast<float>(M_PI) * 0.15f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.15f * t);
2770
2771 mavlink_message_t msg{};
2772 (void) mavlink_msg_local_position_ned_pack_chan(
2773 _vehicleSystemId,
2774 _vehicleComponentId,
2775 _outgoingMavlinkChannel,
2776 &msg,
2777 timeBootMs,
2778 x, y, z,
2779 vx, vy, vz
2780 );
2782}
2783
2784void MockLink::_sendPositionTargetLocalNed()
2785{
2786 // Setpoint: same shape as _sendLocalPositionNed, with a 0.5 s time offset (not a phase in rad)
2787 const uint32_t timeBootMs = static_cast<uint32_t>(_runningTime.elapsed());
2788 const float t = timeBootMs / 1000.0f + 0.5f; // +0.5 s time lead
2789
2790 const float x = 5.0f * std::sin(2.0f * static_cast<float>(M_PI) * 0.08f * t);
2791 const float y = 5.0f * std::sin(2.0f * static_cast<float>(M_PI) * 0.10f * t);
2792 const float z = -10.0f + 1.0f * std::sin(2.0f * static_cast<float>(M_PI) * 0.15f * t);
2793 const float vx = 5.0f * (2.0f * static_cast<float>(M_PI) * 0.08f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.08f * t);
2794 const float vy = 5.0f * (2.0f * static_cast<float>(M_PI) * 0.10f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.10f * t);
2795 const float vz = 1.0f * (2.0f * static_cast<float>(M_PI) * 0.15f) * std::cos(2.0f * static_cast<float>(M_PI) * 0.15f * t);
2796
2797 mavlink_message_t msg{};
2798 (void) mavlink_msg_position_target_local_ned_pack_chan(
2799 _vehicleSystemId,
2800 _vehicleComponentId,
2801 _outgoingMavlinkChannel,
2802 &msg,
2803 timeBootMs,
2804 MAV_FRAME_LOCAL_NED,
2805 0, // type_mask: all fields valid
2806 x, y, z,
2807 vx, vy, vz,
2808 0.0f, 0.0f, 0.0f, // acceleration not used
2809 0.0f, 0.0f // yaw, yaw_rate not used
2810 );
2812}
2813
2814void MockLink::_sendExtendedSysState()
2815{
2816 mavlink_message_t msg{};
2817 (void) mavlink_msg_extended_sys_state_pack_chan(
2818 _vehicleSystemId,
2819 _vehicleComponentId,
2820 _outgoingMavlinkChannel,
2821 &msg,
2822 MAV_VTOL_STATE_UNDEFINED,
2823 (_vehicleAltitudeAMSL > _defaultVehicleHomeAltitude) ? MAV_LANDED_STATE_IN_AIR : MAV_LANDED_STATE_ON_GROUND
2824 );
2826}
2827
2828void MockLink::_sendChunkedStatusText(uint16_t chunkId, bool missingChunks)
2829{
2830 constexpr int cChunks = 4;
2831
2832 int num = 0;
2833 for (int i = 0; i < cChunks; i++) {
2834 if (missingChunks && (i & 1)) {
2835 continue;
2836 }
2837
2838 int cBuf = MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN;
2839 char msgBuf[MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN]{};
2840
2841 if (i == cChunks - 1) {
2842 // Last chunk is partial
2843 cBuf /= 2;
2844 }
2845
2846 for (int j = 0; j < cBuf - 1; j++) {
2847 msgBuf[j] = '0' + num++;
2848 if (num > 9) {
2849 num = 0;
2850 }
2851 }
2852 msgBuf[cBuf-1] = 'A' + i;
2853
2854 mavlink_message_t msg{};
2855 (void) mavlink_msg_statustext_pack_chan(
2856 _vehicleSystemId,
2857 _vehicleComponentId,
2858 _outgoingMavlinkChannel,
2859 &msg,
2860 MAV_SEVERITY_INFO,
2861 msgBuf,
2862 chunkId,
2863 i // chunk sequence number
2864 );
2866 }
2867}
2868
2869void MockLink::_sendStatusTextMessages()
2870{
2871 struct StatusMessage {
2872 MAV_SEVERITY severity;
2873 const char *msg;
2874 };
2875
2876 static constexpr struct StatusMessage rgMessages[] = {
2877 { MAV_SEVERITY_INFO, "#Testing audio output" },
2878 { MAV_SEVERITY_EMERGENCY, "Status text emergency" },
2879 { MAV_SEVERITY_ALERT, "Status text alert" },
2880 { MAV_SEVERITY_CRITICAL, "Status text critical" },
2881 { MAV_SEVERITY_ERROR, "Status text error" },
2882 { MAV_SEVERITY_WARNING, "Status text warning" },
2883 { MAV_SEVERITY_NOTICE, "Status text notice" },
2884 { MAV_SEVERITY_INFO, "Status text info" },
2885 { MAV_SEVERITY_DEBUG, "Status text debug" },
2886 };
2887
2888 mavlink_message_t msg{};
2889 for (size_t i = 0; i < std::size(rgMessages); i++) {
2890 const struct StatusMessage *status = &rgMessages[i];
2891 char statusText[MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN] = {};
2892 (void) std::strncpy(statusText, status->msg, sizeof(statusText) - 1);
2893
2894 (void) mavlink_msg_statustext_pack_chan(
2895 _vehicleSystemId,
2896 _vehicleComponentId,
2897 _outgoingMavlinkChannel,
2898 &msg,
2899 status->severity,
2900 statusText,
2901 0, // Not a chunked sequence
2902 0 // Not a chunked sequence
2903 );
2905 }
2906
2907 _sendChunkedStatusText(1, false /* missingChunks */);
2908 _sendChunkedStatusText(2, true /* missingChunks */);
2909 _sendChunkedStatusText(3, false /* missingChunks */); // This should cause the previous incomplete chunk to spit out
2910 _sendChunkedStatusText(4, true /* missingChunks */); // This should cause the timeout to fire
2911}
2912
2913MockLink *MockLink::_startMockLink(MockConfiguration *mockConfig)
2914{
2915 mockConfig->setDynamic(true);
2917
2918 if (LinkManager::instance()->createConnectedLink(config)) {
2919 return qobject_cast<MockLink*>(config->link());
2920 }
2921
2922 return nullptr;
2923}
2924
2925MockLink *MockLink::_startMockLinkWorker(const QString &configName, MAV_AUTOPILOT firmwareType, MAV_TYPE vehicleType, MockConfiguration::Options options, MockConfiguration::FailureMode_t failureMode, MockConfiguration::VideoStreamType videoStreamType)
2926{
2927 MockConfiguration *const mockConfig = new MockConfiguration(configName);
2928
2929 mockConfig->setFirmwareType(firmwareType);
2930 mockConfig->setVehicleType(vehicleType);
2931 mockConfig->setSendStatusText(options.testFlag(MockConfiguration::OptionSendStatusText));
2932 mockConfig->setEnableCamera(options.testFlag(MockConfiguration::OptionEnableCamera));
2933 mockConfig->setEnableGimbal(options.testFlag(MockConfiguration::OptionEnableGimbal));
2934 mockConfig->setEnableProximity(options.testFlag(MockConfiguration::OptionEnableProximity));
2935 mockConfig->setPreloadMission(options.testFlag(MockConfiguration::OptionPreloadMission));
2936 mockConfig->setStayMavlinkV1(options.testFlag(MockConfiguration::OptionStayMavlinkV1));
2938 mockConfig->setFtpCapability(options.testFlag(MockConfiguration::OptionFtpCapability));
2939 mockConfig->setSendRadioStatus(!options.testFlag(MockConfiguration::OptionNoRadioStatus));
2940 mockConfig->setCompanionParams(options.testFlag(MockConfiguration::OptionCompanionParams));
2941 mockConfig->setVideoStreamType(videoStreamType);
2942 mockConfig->setFailureMode(failureMode);
2943
2944 return _startMockLink(mockConfig);
2945}
2946
2947MockLink *MockLink::startPX4MockLink(MockConfiguration::Options options, MockConfiguration::FailureMode_t failureMode, MockConfiguration::VideoStreamType videoStreamType)
2948{
2949 return _startMockLinkWorker(QStringLiteral("PX4 MultiRotor MockLink"), MAV_AUTOPILOT_PX4, MAV_TYPE_QUADROTOR, options, failureMode, videoStreamType);
2950}
2951
2953{
2954 return _startMockLinkWorker(QStringLiteral("PX4 MultiRotor MockLink"), MAV_AUTOPILOT_PX4, MAV_TYPE_QUADROTOR, options | MockConfiguration::OptionPreloadMission, failureMode);
2955}
2956
2958{
2959 return _startMockLinkWorker(QStringLiteral("Generic MockLink"), MAV_AUTOPILOT_GENERIC, MAV_TYPE_QUADROTOR, options, failureMode, videoStreamType);
2960}
2961
2963{
2964 return _startMockLinkWorker(QStringLiteral("No Initial Connect MockLink"), MAV_AUTOPILOT_PX4, MAV_TYPE_GENERIC, options, failureMode);
2965}
2966
2968{
2969 return _startMockLinkWorker(QStringLiteral("ArduCopter MockLink"),MAV_AUTOPILOT_ARDUPILOTMEGA, MAV_TYPE_QUADROTOR, options, failureMode, videoStreamType);
2970}
2971
2973{
2974 return _startMockLinkWorker(QStringLiteral("ArduPlane MockLink"), MAV_AUTOPILOT_ARDUPILOTMEGA, MAV_TYPE_FIXED_WING, options, failureMode, videoStreamType);
2975}
2976
2978{
2979 return _startMockLinkWorker(QStringLiteral("ArduSub MockLink"), MAV_AUTOPILOT_ARDUPILOTMEGA, MAV_TYPE_SUBMARINE, options, failureMode, videoStreamType);
2980}
2981
2983{
2984 return _startMockLinkWorker(QStringLiteral("ArduRover MockLink"), MAV_AUTOPILOT_ARDUPILOTMEGA, MAV_TYPE_GROUND_ROVER, options, failureMode, videoStreamType);
2985}
2986
2987void MockLink::_sendRCChannels()
2988{
2989 mavlink_message_t msg{};
2990 (void) mavlink_msg_rc_channels_pack_chan(
2991 _vehicleSystemId,
2992 _vehicleComponentId,
2993 _outgoingMavlinkChannel,
2994 &msg,
2995 0, // time_boot_ms
2996 16, // chancount
2997 1500, 1500, 1500, 1500, 1500, 1500, 1500, 1500, // channel 1-8
2998 1500, 1500, 1500, 1500, 1500, 1500, 1500, 1500, // channel 9-16
2999 UINT16_MAX, UINT16_MAX, // channel 17/18 unused
3000 0 // rssi
3001 );
3003}
3004
3005void MockLink::_handlePreFlightCalibration(const mavlink_command_long_t& request)
3006{
3007 if ((request.param1 == 0) && (request.param2 == 0) && (request.param3 == 0) &&
3008 (request.param4 == 0) && (request.param5 == 0) && (request.param6 == 0) &&
3009 (request.param7 == 0)) {
3010 // All zeros is a calibration cancel request.
3011 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
3012 // Send ACCELCAL_VEHICLE_POS_FAILED so controller calls _stopCalibration(Failed)
3013 QMutexLocker locker(&_apmAccelCalMutex);
3014 if (_apmAccelCalPosIndex >= 0) {
3015 mavlink_message_t msg{};
3017 cmd.target_system = 255;
3018 cmd.target_component = MAV_COMP_ID_MISSIONPLANNER;
3019 cmd.command = MAV_CMD_ACCELCAL_VEHICLE_POS;
3020 cmd.param1 = static_cast<float>(ACCELCAL_VEHICLE_POS_FAILED);
3021 (void) mavlink_msg_command_long_encode_chan(
3022 _vehicleSystemId, _vehicleComponentId, _outgoingMavlinkChannel, &msg, &cmd);
3024 _apmAccelCalPosIndex = -1;
3025 }
3026 } else {
3027 // PX4: See PX4 calibrate_cancel_check().
3028 (void) _mockLinkPX4Calibration->cancel();
3029 }
3030 return;
3031 }
3032
3033 if (request.param2 == 1) {
3034 // Magnetometer calibration runs the full pose-driven simulation
3035 _mockLinkPX4Calibration->startMagCalibration();
3036 return;
3037 }
3038
3039 if ((request.param3 == 1) && (_firmwareType != MAV_AUTOPILOT_ARDUPILOTMEGA)) {
3040 _mockLinkPX4Calibration->startBaroCalibration(_baroCalibrationFails);
3041 return;
3042 }
3043
3044 if ((request.param5 == 2) && (_firmwareType != MAV_AUTOPILOT_ARDUPILOTMEGA)) {
3045 _mockLinkPX4Calibration->startLevelCalibration(_levelCalibrationFails);
3046 return;
3047 }
3048
3049 if (request.param1 == 1) {
3050 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
3051 sendStatusTextMessage(MAV_SEVERITY_INFO, QStringLiteral("[cal] calibration started: 2 gyro"));
3052 } else {
3053 _mockLinkPX4Calibration->startGyroCalibration(_gyroCalibrationFails);
3054 }
3055 return;
3056 }
3057
3058 if (request.param5 == 1) {
3059 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
3060 // APM full accelerometer calibration: drive the ACCELCAL_VEHICLE_POS handshake
3061 QMutexLocker locker(&_apmAccelCalMutex);
3062 _apmAccelCalPosIndex = 0;
3063 _apmAccelCalGotAck = false;
3064 _apmAccelCalTickCount = 0;
3065 } else {
3066 // Accelerometer calibration runs the full pose-driven simulation
3067 _mockLinkPX4Calibration->startAccelCalibration();
3068 }
3069 }
3070}
3071
3072void MockLink::sendStatusTextMessage(uint8_t severity, const QString &text)
3073{
3074 char statusText[MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN] = {};
3075 (void) std::strncpy(statusText, text.toUtf8().constData(), sizeof(statusText) - 1);
3076
3077 mavlink_message_t msg{};
3078 (void) mavlink_msg_statustext_pack_chan(
3079 _vehicleSystemId,
3080 _vehicleComponentId,
3081 _outgoingMavlinkChannel,
3082 &msg,
3083 severity,
3084 statusText,
3085 0,
3086 0 // Not chunked
3087 );
3089}
3090
3091void MockLink::_handleTakeoff(const mavlink_command_long_t &request)
3092{
3093 _vehicleAltitudeAMSL = request.param7 + _defaultVehicleHomeAltitude;
3094 _mavBaseMode |= MAV_MODE_FLAG_SAFETY_ARMED;
3095}
3096
3097void MockLink::_handleLogRequestList(const mavlink_message_t &msg)
3098{
3099 mavlink_log_request_list_t request{};
3100 mavlink_msg_log_request_list_decode(&msg, &request);
3101
3102 if ((request.start != 0) && (request.end != 0xffff)) {
3103 qCWarning(MockLinkLog) << "_handleLogRequestList cannot handle partial requests";
3104 return;
3105 }
3106
3107 // When simulated FTP log files are set, LOG_ENTRY responses describe the same logs so
3108 // both transports report a consistent log list (matching PX4 behavior).
3109 const QList<MockLinkFTP::LogFile> logFiles = _mockLinkFTP->logFiles();
3110 if (!_logsErased && !logFiles.isEmpty()) {
3111 const uint16_t numLogs = static_cast<uint16_t>(logFiles.count());
3112 for (uint16_t id = 0; id < numLogs; id++) {
3113 mavlink_message_t responseMsg{};
3114 (void) mavlink_msg_log_entry_pack_chan(
3115 _vehicleSystemId,
3116 _vehicleComponentId,
3117 _outgoingMavlinkChannel,
3118 &responseMsg,
3119 id, // log id
3120 numLogs, // num_logs
3121 numLogs - 1, // last_log_num
3122 logFiles[id].mtime, // time_utc
3123 static_cast<uint32_t>(logFiles[id].size) // size
3124 );
3125 respondWithMavlinkMessage(responseMsg);
3126 }
3127 return;
3128 }
3129
3130 const uint16_t numLogs = _logsErased ? 0 : 1;
3131 const uint16_t logId = _logsErased ? 0 : _logDownloadLogId;
3132 const uint32_t logSize = _logsErased ? 0 : _logDownloadFileSize;
3133 mavlink_message_t responseMsg{};
3134 mavlink_msg_log_entry_pack_chan(
3135 _vehicleSystemId,
3136 _vehicleComponentId,
3137 _outgoingMavlinkChannel,
3138 &responseMsg,
3139 logId, // log id
3140 numLogs, // num_logs
3141 numLogs, // last_log_num
3142 0, // time_utc
3143 logSize // size
3144 );
3145 respondWithMavlinkMessage(responseMsg);
3146}
3147
3148void MockLink::_handleLogErase(const mavlink_message_t &msg)
3149{
3150 mavlink_log_erase_t request{};
3151 mavlink_msg_log_erase_decode(&msg, &request);
3152
3153 if ((mavlink_msg_get_target_sysid(&msg, mavlink_get_msg_entry(msg.msgid)) != _vehicleSystemId) ||
3154 (request.target_component != _vehicleComponentId)) {
3155 return;
3156 }
3157
3158 _logsErased = true;
3159 _mockLinkFTP->setLogFiles({});
3160}
3161
3162QString MockLink::_createRandomFile(uint32_t byteCount)
3163{
3164 QTemporaryFile tempFile;
3165 tempFile.setAutoRemove(false);
3166 if (!tempFile.open()) {
3167 qCWarning(MockLinkLog) << "MockLink::createRandomFile open failed" << tempFile.errorString();
3168 return QString();
3169 }
3170
3171 for (uint32_t bytesWritten = 0; bytesWritten < byteCount; bytesWritten++) {
3172 const unsigned char byte = (QRandomGenerator::global()->generate() * 0xFF) / RAND_MAX;
3173 (void) tempFile.write(reinterpret_cast<const char*>(&byte), 1);
3174 }
3175
3176 tempFile.close();
3177 return tempFile.fileName();
3178}
3179
3180QString MockLink::_createLogContentsFile(const QString &logName)
3181{
3182 QTemporaryFile tempFile;
3183 tempFile.setAutoRemove(false);
3184 if (!tempFile.open()) {
3185 qCWarning(MockLinkLog) << "_createLogContentsFile open failed" << tempFile.errorString();
3186 return QString();
3187 }
3188 (void) tempFile.write(_mockLinkFTP->logFileContents(logName));
3189 tempFile.close();
3190 return tempFile.fileName();
3191}
3192
3193void MockLink::_handleLogRequestData(const mavlink_message_t &msg)
3194{
3195 mavlink_log_request_data_t request{};
3196 mavlink_msg_log_request_data_decode(&msg, &request);
3197
3198 // Serialize with _logDownloadWorker which reads this state every 2ms on the worker thread
3199 QMutexLocker locker(&_logDownloadMutex);
3200
3201 const QList<MockLinkFTP::LogFile> logFiles = _logsErased ? QList<MockLinkFTP::LogFile>() : _mockLinkFTP->logFiles();
3202 if (!logFiles.isEmpty()) {
3203 // Serve the simulated FTP log files so LOG_ENTRY/LOG_REQUEST_DATA stay consistent with the FTP transport
3204 if (request.id >= logFiles.count()) {
3205 qCWarning(MockLinkLog) << "_handleLogRequestData id out of range:" << request.id;
3206 return;
3207 }
3208 if (_logDownloadFilename.isEmpty() || (_logDownloadId != request.id)) {
3209 _logDownloadFilename = _createLogContentsFile(logFiles[request.id].name);
3210 _logDownloadId = request.id;
3211 _logDownloadSize = static_cast<uint32_t>(logFiles[request.id].size);
3212 }
3213 } else {
3214#ifdef QGC_UNITTEST_BUILD
3215 if (_logDownloadFilename.isEmpty()) {
3216 _logDownloadFilename = _createRandomFile(_logDownloadFileSize);
3217 }
3218#endif
3219 if (request.id != _logDownloadLogId) {
3220 qCWarning(MockLinkLog) << "_handleLogRequestData id must be" << _logDownloadLogId;
3221 return;
3222 }
3223 _logDownloadId = _logDownloadLogId;
3224 _logDownloadSize = _logDownloadFileSize;
3225 }
3226
3227 if (request.ofs > (_logDownloadSize - 1)) {
3228 qCWarning(MockLinkLog) << "_handleLogRequestData offset past end of file request.ofs:size" << request.ofs << _logDownloadSize;
3229 return;
3230 }
3231
3232 // This will trigger _logDownloadWorker to send data
3233 _logDownloadCurrentOffset = request.ofs;
3234 if (request.ofs + request.count > _logDownloadSize) {
3235 request.count = _logDownloadSize - request.ofs;
3236 }
3237 _logDownloadBytesRemaining = request.count;
3238}
3239
3240void MockLink::_logDownloadWorker()
3241{
3242 // Runs every 2ms (500Hz on worker thread). Must protect shared state modified by main thread.
3243 // Without lock: main could write new offset/count while we're reading, causing corrupted downloads.
3244 QMutexLocker locker(&_logDownloadMutex);
3245 if (_logDownloadBytesRemaining == 0) {
3246 return;
3247 }
3248
3249 QFile file(_logDownloadFilename);
3250 if (!file.open(QIODevice::ReadOnly)) {
3251 qCWarning(MockLinkLog) << "_logDownloadWorker open failed" << file.errorString();
3252 _logDownloadBytesRemaining = 0; // Abort transfer on I/O failure
3253 return;
3254 }
3255
3256 uint8_t buffer[MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN]{};
3257
3258 const qint64 bytesToRead = qMin(_logDownloadBytesRemaining, (uint32_t)MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN);
3259 if (!file.seek(_logDownloadCurrentOffset)) {
3260 qCWarning(MockLinkLog) << "_logDownloadWorker seek failed - offset:" << _logDownloadCurrentOffset << file.errorString();
3261 _logDownloadBytesRemaining = 0; // Abort transfer on I/O failure
3262 return;
3263 }
3264 if (file.read(reinterpret_cast<char*>(buffer), bytesToRead) != bytesToRead) {
3265 qCWarning(MockLinkLog) << "_logDownloadWorker read failed - bytesToRead:" << bytesToRead << file.errorString();
3266 _logDownloadBytesRemaining = 0; // Abort transfer on I/O failure
3267 return;
3268 }
3269
3270 qCDebug(MockLinkLog) << "_logDownloadWorker" << _logDownloadCurrentOffset << _logDownloadBytesRemaining;
3271
3272 mavlink_message_t responseMsg{};
3273 (void) mavlink_msg_log_data_pack_chan(
3274 _vehicleSystemId,
3275 _vehicleComponentId,
3276 _outgoingMavlinkChannel,
3277 &responseMsg,
3278 _logDownloadId,
3279 _logDownloadCurrentOffset,
3280 bytesToRead,
3281 &buffer[0]
3282 );
3283 respondWithMavlinkMessage(responseMsg);
3284
3285 _logDownloadCurrentOffset += bytesToRead;
3286 _logDownloadBytesRemaining -= bytesToRead;
3287
3288 file.close();
3289}
3290
3291void MockLink::_sendADSBVehicles()
3292{
3293 for (int i = 0; i < _adsbVehicles.size(); ++i) {
3294 // Slightly change the direction to simulate different paths
3295 _adsbVehicles[i].angle += (i + 1); // Vary the change to make each path unique
3296
3297 // Move each vehicle by a smaller distance to simulate slower speed
3298 _adsbVehicles[i].coordinate = _adsbVehicles[i].coordinate.atDistanceAndAzimuth(5, _adsbVehicles[i].angle); // 50 meters per update for slower speed
3299
3300 // Simulate slight variations in altitude
3301 _adsbVehicles[i].altitude += (i % 2 == 0 ? 0.5 : -0.5); // Increase or decrease altitude
3302
3303 QByteArray callsign = QString("N12345%1").arg(i, 2, 10, QChar('0')).toLatin1();
3304 callsign.resize(MAVLINK_MSG_ADSB_VEHICLE_FIELD_CALLSIGN_LEN);
3305
3306 // Prepare and send MAVLink message for each vehicle
3307 mavlink_message_t responseMsg{};
3308 (void) mavlink_msg_adsb_vehicle_pack_chan(
3309 _vehicleSystemId,
3310 _vehicleComponentId,
3311 _outgoingMavlinkChannel,
3312 &responseMsg,
3313 12345 + i, // Unique ICAO address for each vehicle
3314 _adsbVehicles[i].coordinate.latitude() * 1e7,
3315 _adsbVehicles[i].coordinate.longitude() * 1e7,
3316 ADSB_ALTITUDE_TYPE_GEOMETRIC,
3317 _adsbVehicles[i].altitude * 1000, // Altitude in millimeters
3318 // Use the current angle as heading
3319 static_cast<uint16_t>(_adsbVehicles[i].angle * 100), // Heading in centidegrees
3320 0, 0, // Horizontal/Vertical velocity
3321 callsign.constData(), // Unique callsign
3322 ADSB_EMITTER_TYPE_ROTOCRAFT,
3323 1, // Seconds since last communication
3324 ADSB_FLAGS_VALID_COORDS | ADSB_FLAGS_VALID_ALTITUDE | ADSB_FLAGS_VALID_HEADING | ADSB_FLAGS_VALID_CALLSIGN | ADSB_FLAGS_SIMULATED,
3325 0 // Squawk code
3326 );
3327 respondWithMavlinkMessage(responseMsg);
3328 }
3329}
3330
3331void MockLink::_moveADSBVehicle(int vehicleIndex)
3332{
3333 _adsbAngles[vehicleIndex] += 10; // Increment angle for smoother movement
3334 QGeoCoordinate &coord = _adsbVehicleCoordinates[vehicleIndex];
3335
3336 // Update the position based on the new angle
3337 coord = QGeoCoordinate(coord.latitude(), coord.longitude()).atDistanceAndAzimuth(500, _adsbAngles[vehicleIndex]);
3338 coord.setAltitude(100); // Keeping altitude constant for simplicity
3339}
3340
3341void MockLink::_handleRequestMessageAutopilotVersion(const mavlink_command_long_t &/*request*/, bool &accepted)
3342{
3343 accepted = true;
3344
3345 switch (_failureMode) {
3347 break;
3349 accepted = false;
3350 return;
3352 accepted = true;
3353 return;
3354 default:
3355 break;
3356 }
3357
3358 _respondWithAutopilotVersion();
3359}
3360
3361void MockLink::_handleRequestMessageDebug(const mavlink_command_long_t &/*request*/, bool &accepted, bool &noAck)
3362{
3363 accepted = true;
3364 noAck = false;
3365
3366 switch (_requestMessageFailureMode) {
3368 break;
3370 return;
3372 accepted = false;
3373 return;
3375 accepted = false;
3376 noAck = true;
3377 return;
3378 }
3379
3380 mavlink_message_t responseMsg{};
3381 (void) mavlink_msg_debug_pack_chan(
3382 _vehicleSystemId,
3383 _vehicleComponentId,
3384 _outgoingMavlinkChannel,
3385 &responseMsg,
3386 0, 0, 0
3387 );
3388 respondWithMavlinkMessage(responseMsg);
3389}
3390
3391void MockLink::_handleRequestMessageAvailableModes(const mavlink_command_long_t &request, bool &accepted)
3392{
3393 accepted = true;
3394
3395 if (request.param2 == 0) {
3396 // Request for available modes to be streamed out
3397 QMutexLocker locker(&_availableModesWorkerMutex);
3398 if (_availableModesWorkerNextModeIndex != 0) {
3399 qCWarning(MockLinkLog) << "MAVLINK_MSG_ID_AVAILABLE_MODES: _availableModesWorker already running - _availableModesWorkerNextModeIndex:" << _availableModesWorkerNextModeIndex;
3400 accepted = false;
3401 return;
3402 }
3403 qCDebug(MockLinkLog) << "MAVLINK_MSG_ID_AVAILABLE_MODES: starting available modes sequence worker";
3404 _availableModesWorkerNextModeIndex = 1; // Start with the first mode in sequence (1-based index)
3405 } else {
3406 // Request for specific mode
3407 if (request.param2 < 1 || request.param2 > _flightModeList().count()) {
3408 qCWarning(MockLinkLog) << "MAVLINK_MSG_ID_AVAILABLE_MODES: requested mode index out of range" << request.param2 << _flightModeList().count();
3409 accepted = false;
3410 return;
3411 }
3412 qCDebug(MockLinkLog) << "MAVLINK_MSG_ID_AVAILABLE_MODES: received specific mode request for index" << request.param2;
3413 // Match other single-message requests: do not ACK now and leave the payload waiting for a worker timer.
3414 _sendAvailableMode(static_cast<uint8_t>(request.param2));
3415 }
3416}
3417
3418void MockLink::_handleRequestMessage(const mavlink_command_long_t &request, bool &accepted, bool &noAck)
3419{
3420 accepted = false;
3421 noAck = false;
3422
3423 const uint32_t requestedMessageId = static_cast<uint32_t>(request.param1);
3424
3425 // Per-message-ID no-response injection: silently drop the request (no ACK, no message)
3426 {
3427 QMutexLocker locker(&_requestMessageNoResponseMutex);
3428 if (_requestMessageNoResponseIds.contains(requestedMessageId)) {
3429 noAck = true;
3430 return;
3431 }
3432 }
3433
3434 switch (static_cast<int>(request.param1)) {
3435 case MAVLINK_MSG_ID_AUTOPILOT_VERSION:
3436 _handleRequestMessageAutopilotVersion(request, accepted);
3437 break;
3438 case MAVLINK_MSG_ID_COMPONENT_METADATA:
3439 if (_firmwareType == MAV_AUTOPILOT_PX4) {
3440 _sendGeneralMetaData();
3441 accepted = true;
3442 }
3443 break;
3444 case MAVLINK_MSG_ID_DEBUG:
3445 _handleRequestMessageDebug(request, accepted, noAck);
3446 break;
3447 case MAVLINK_MSG_ID_AVAILABLE_MODES:
3448 _handleRequestMessageAvailableModes(request, accepted);
3449 break;
3450 }
3451}
3452
3453void MockLink::_sendGeneralMetaData()
3454{
3455 static constexpr const char metaDataURI[MAVLINK_MSG_COMPONENT_METADATA_FIELD_URI_LEN] = "mftp://[;comp=1]general.json";
3456
3457 mavlink_message_t responseMsg{};
3458 (void) mavlink_msg_component_metadata_pack_chan(
3459 _vehicleSystemId,
3460 _vehicleComponentId,
3461 _outgoingMavlinkChannel,
3462 &responseMsg,
3463 0, // time_boot_ms
3464 25436021, // general_metadata_file_crc (crc32 of General.MetaData.json)
3465 metaDataURI
3466 );
3467 respondWithMavlinkMessage(responseMsg);
3468}
3469
3470void MockLink::setRemoteIDArmStatus(uint8_t status, const QString& error)
3471{
3472 {
3473 QMutexLocker locker(&_remoteIDArmStatusMutex);
3474 _remoteIDArmStatus = status;
3475 _remoteIDArmStatusError = error;
3476 }
3477
3478 _runOnWorkerWhenConnected([this] {
3479 if (_vehicleType != MAV_TYPE_SUBMARINE) {
3480 _sendRemoteIDArmStatus();
3481 }
3482 });
3483}
3484
3485void MockLink::setPrearmCheck(bool enabled, bool passed)
3486{
3487 _prearmCheck = (enabled ? _prearmCheckEnabled : 0) | (passed ? _prearmCheckPassed : 0);
3488 _runOnWorkerWhenConnected([this] { _sendSysStatus(); });
3489}
3490
3491void MockLink::_runOnWorkerWhenConnected(const std::function<void()>& send)
3492{
3493 // disconnect() stops the worker thread, whose finished signal deletes _worker
3494 if (!_connected || !_workerThread || !_workerThread->isRunning()) {
3495 return;
3496 }
3497
3498 // Runs on the worker thread like the 1Hz tasks that normally send these messages
3499 (void) QMetaObject::invokeMethod(
3500 _worker,
3501 [this, send] {
3502 if (_connected && mavlinkChannelIsSet() && !linkConfiguration()->isHighLatency()) {
3503 send();
3504 }
3505 },
3506 Qt::QueuedConnection);
3507}
3508
3509void MockLink::_sendRemoteIDArmStatus()
3510{
3511 uint8_t armStatus;
3512 QByteArray errorUtf8;
3513 {
3514 QMutexLocker locker(&_remoteIDArmStatusMutex);
3515 armStatus = _remoteIDArmStatus;
3516 errorUtf8 = _remoteIDArmStatusError.toUtf8();
3517 }
3518
3519 char armStatusError[MAVLINK_MSG_OPEN_DRONE_ID_ARM_STATUS_FIELD_ERROR_LEN] = {};
3520 std::strncpy(armStatusError, errorUtf8.constData(), sizeof(armStatusError) - 1);
3521
3522 mavlink_message_t msg{};
3523 (void) mavlink_msg_open_drone_id_arm_status_pack_chan(
3524 _vehicleSystemId,
3525 MAV_COMP_ID_ODID_TXRX_1,
3526 static_cast<uint8_t>(_outgoingMavlinkChannel),
3527 &msg,
3528 armStatus,
3529 armStatusError
3530 );
3532}
3533
3534void MockLink::_sendEscInfo()
3535{
3536 // Send ESC_INFO for 4 motors starting at index 0.
3537 // count=4 and info bitmask=0x0F (all 4 online) makes the ESC indicator visible.
3538 static const uint16_t failureFlags[4] = {0, 0, 0, 0};
3539 static const uint32_t errorCount[4] = {0, 0, 0, 0};
3540 static const int16_t temperature[4] = {3000, 3000, 3000, 3000}; // centidegrees
3541
3542 mavlink_message_t msg{};
3543 (void) mavlink_msg_esc_info_pack_chan(
3544 _vehicleSystemId,
3545 _vehicleComponentId,
3546 _outgoingMavlinkChannel,
3547 &msg,
3548 0, // index: first group starts at 0
3549 static_cast<uint64_t>(_runningTime.elapsed()) * 1000, // time_usec
3550 0, // counter
3551 4, // count: 4 motors
3552 ESC_CONNECTION_TYPE_DSHOT, // connection_type
3553 0x0F, // info: bitmask — motors 0-3 online
3554 failureFlags,
3555 errorCount,
3556 temperature
3557 );
3559}
3560
3561void MockLink::_sendEscStatus()
3562{
3563 static const int32_t rpm[4] = {5000, 5000, 5000, 5000};
3564 static const float voltage[4] = {16.0f, 16.0f, 16.0f, 16.0f};
3565 static const float current[4] = {5.0f, 5.0f, 5.0f, 5.0f};
3566
3567 mavlink_message_t msg{};
3568 (void) mavlink_msg_esc_status_pack_chan(
3569 _vehicleSystemId,
3570 _vehicleComponentId,
3571 _outgoingMavlinkChannel,
3572 &msg,
3573 0, // index: first group
3574 static_cast<uint64_t>(_runningTime.elapsed()) * 1000, // time_usec
3575 rpm,
3576 voltage,
3577 current
3578 );
3580}
3581
3582void MockLink::_sendRadioStatus()
3583{
3584 // Send a RADIO_STATUS message to make the TelemetryRSSI indicator visible.
3585 // Any non-zero rssi value triggers showIndicator (TelemetryRSSIIndicator checks lrssi.rawValue != 0).
3586 mavlink_message_t msg{};
3587 (void) mavlink_msg_radio_status_pack_chan(
3588 _vehicleSystemId,
3589 _vehicleComponentId,
3590 _outgoingMavlinkChannel,
3591 &msg,
3592 100, // rssi: local signal strength
3593 100, // remrssi: remote signal strength
3594 50, // txbuf: transmit buffer fill (%)
3595 10, // noise: local background noise
3596 10, // remnoise: remote background noise
3597 0, // rxerrors
3598 0 // fixed
3599 );
3601}
3602
3604{
3605 _commLost = true;
3607}
3608
3610{
3611 return _mockLinkFTP;
3612}
3613
3614void MockLink::setVehicleAttitudeOverrideDeg(float rollDeg, float pitchDeg, float yawDeg)
3615{
3616 QMutexLocker locker(&_attitudeOverrideMutex);
3617 _attitudeOverride.enabled = true;
3618 _attitudeOverride.rollRad = qDegreesToRadians(rollDeg);
3619 _attitudeOverride.pitchRad = qDegreesToRadians(pitchDeg);
3620 _attitudeOverride.yawRad = qDegreesToRadians(yawDeg);
3621}
3622
3624{
3625 QMutexLocker locker(&_attitudeOverrideMutex);
3626 _attitudeOverride.enabled = false;
3627}
3628
3629void MockLink::_sendAvailableMode(uint8_t modeIndexOneBased)
3630{
3631 if (modeIndexOneBased < 1 || modeIndexOneBased > _availableModesCount()) {
3632 qCWarning(MockLinkLog) << "modeIndexOneBased out of range" << modeIndexOneBased << _availableModesCount();
3633 return;
3634 }
3635
3636 qCDebug(MockLinkLog) << "_sendAvailableMode modeIndexOneBased:" << modeIndexOneBased;
3637
3638 const FlightMode_t &availableMode = _flightModeList()[modeIndexOneBased - 1];
3639
3640 if (_availableModesSequenceBumpAtIndex.load() == modeIndexOneBased) {
3641 ++_availableModesMonitorSeqNumber;
3642
3643 if (_availableModesSequenceBumpRepeatedly.load() && _availableModesMonitorSeqNumber.load() == 0) {
3644 ++_availableModesMonitorSeqNumber;
3645 }
3646
3647 if (!_availableModesSequenceBumpRepeatedly.load()) {
3648 _availableModesSequenceBumpAtIndex = 0;
3649 }
3650 }
3651
3652 char modeName[MAVLINK_MSG_AVAILABLE_MODES_FIELD_MODE_NAME_LEN] = {};
3653 std::strncpy(modeName, availableMode.name, sizeof(modeName) - 1);
3654
3655 mavlink_message_t msg{};
3656
3657 (void) mavlink_msg_available_modes_pack_chan(
3658 _vehicleSystemId, _vehicleComponentId, _outgoingMavlinkChannel, &msg, _availableModesCount(), modeIndexOneBased,
3659 availableMode.standard_mode, availableMode.custom_mode,
3660 availableMode.canBeSet ? 0 : MAV_MODE_PROPERTY_NOT_USER_SELECTABLE, modeName, _availableModesMonitorSeqNumber);
3662}
3663
3664void MockLink::_availableModesWorker()
3665{
3666 // Protect the streaming cursor from a concurrent request to start another sequence.
3667 QMutexLocker locker(&_availableModesWorkerMutex);
3668 if (_availableModesWorkerNextModeIndex == 0) {
3669 // Not active
3670 return;
3671 }
3672
3673 _sendAvailableMode(_availableModesWorkerNextModeIndex);
3674 if (++_availableModesWorkerNextModeIndex > _availableModesCount()) {
3675 // All modes sent, stop worker
3676 _availableModesWorkerNextModeIndex = 0;
3677 qCDebug(MockLinkLog) << "_availableModesWorker: all modes sent, stopping worker";
3678 }
3679}
3680
3681void MockLink::_sendAvailableModesMonitor()
3682{
3683 mavlink_message_t msg{};
3684
3685 (void) mavlink_msg_available_modes_monitor_pack_chan(
3686 _vehicleSystemId,
3687 _vehicleComponentId,
3688 _outgoingMavlinkChannel,
3689 &msg,
3690 _availableModesMonitorSeqNumber);
3692}
3693
3694int MockLink::_availableModesCount() const
3695{
3696 if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
3697 return _flightModeList().count();
3698 }
3699 return _flightModeList().count() - (_availableModesMonitorSeqNumber == 0 ? 1 : 0); // Exclude the delayed mode
3700}
3701
3702const QList<MockLink::FlightMode_t> &MockLink::_flightModeList() const
3703{
3704 if (_firmwareType != MAV_AUTOPILOT_ARDUPILOTMEGA) {
3705 return _availableFlightModes;
3706 }
3707
3708 switch (_vehicleType) {
3709 case MAV_TYPE_FIXED_WING:
3710 return _apmPlaneAvailableFlightModes;
3711 case MAV_TYPE_GROUND_ROVER:
3712 return _apmRoverAvailableFlightModes;
3713 case MAV_TYPE_SUBMARINE:
3714 return _apmSubAvailableFlightModes;
3715 default:
3716 return _apmCopterAvailableFlightModes;
3717 }
3718}
3719
3720// ---------------------------------------------------------------------------
3721// ArduPilot compass calibration simulation
3722//
3723// Driven by _apmCompassCalProgress: -1 = inactive, 0..100 = current pct.
3724// Main thread sets it to 0 to start and -1 to stop.
3725// Worker sends MAG_CAL_PROGRESS at ~10Hz (every 50 calls of 500Hz worker),
3726// then sends MAG_CAL_REPORT when pct reaches 100.
3727// ---------------------------------------------------------------------------
3729{
3730 QMutexLocker locker(&_apmCompassCalMutex);
3731 _apmStaleFailedMagCalReportStreaming = true;
3732 _apmCompassCalTickCount = 0;
3733}
3734
3736{
3737 QMutexLocker locker(&_apmCompassCalMutex);
3738 return _apmStaleFailedMagCalReportStreaming;
3739}
3740
3741void MockLink::_apmCompassCalWorker()
3742{
3743 if (_firmwareType != MAV_AUTOPILOT_ARDUPILOTMEGA) {
3744 return;
3745 }
3746
3747 QMutexLocker locker(&_apmCompassCalMutex);
3748 if ((_apmCompassCalProgress < 0) && !_apmStaleFailedMagCalReportStreaming) {
3749 return;
3750 }
3751
3752 // Tick ~10 Hz: advance every 50 calls of the 500 Hz worker
3753 if (++_apmCompassCalTickCount < 50) {
3754 return;
3755 }
3756 _apmCompassCalTickCount = 0;
3757
3758 if (_apmStaleFailedMagCalReportStreaming) {
3759 // Simulate ArduPilot streaming the report from a previously failed cal until cancelled
3760 mavlink_message_t msg{};
3761 mavlink_mag_cal_report_t report{};
3762 report.compass_id = 0;
3763 report.cal_mask = 0x01;
3764 report.cal_status = MAG_CAL_FAILED;
3765 report.fitness = 999.0f;
3766 (void) mavlink_msg_mag_cal_report_encode_chan(
3767 _vehicleSystemId, _vehicleComponentId, _outgoingMavlinkChannel, &msg, &report);
3769 return;
3770 }
3771
3772 const int pct = _apmCompassCalProgress;
3773
3774 // Send MAG_CAL_PROGRESS for all 3 active compasses
3775 mavlink_message_t msg{};
3776 for (uint8_t id = 0; id < 3; ++id) {
3777 mavlink_mag_cal_progress_t progress{};
3778 progress.compass_id = id;
3779 progress.cal_mask = 0x07; // all 3 compasses
3780 progress.cal_status = MAG_CAL_RUNNING_STEP_ONE;
3781 progress.completion_pct = static_cast<uint8_t>(qMin(pct, 100));
3782 (void) mavlink_msg_mag_cal_progress_encode_chan(
3783 _vehicleSystemId, _vehicleComponentId, _outgoingMavlinkChannel, &msg, &progress);
3785 }
3786
3787 if (pct >= 100) {
3788 // Send MAG_CAL_REPORT for all 3 compasses
3789 for (uint8_t id = 0; id < 3; ++id) {
3790 mavlink_mag_cal_report_t report{};
3791 report.compass_id = id;
3792 report.cal_mask = 0x07;
3793 report.cal_status = MAG_CAL_SUCCESS;
3794 report.fitness = 0.5f;
3795 (void) mavlink_msg_mag_cal_report_encode_chan(
3796 _vehicleSystemId, _vehicleComponentId, _outgoingMavlinkChannel, &msg, &report);
3798 }
3799
3800 // Write non-zero offsets so QGC sees all compasses as calibrated after refresh.
3801 // _mapParamName2Value is owned by MockLink's main thread; dispatch the write there
3802 // to avoid a data race with concurrent param reads on the main thread.
3803 (void) QMetaObject::invokeMethod(this, [this] {
3804 constexpr int compId = MAV_COMP_ID_AUTOPILOT1;
3805 _mapParamName2Value[compId][QStringLiteral("COMPASS_OFS_X")] = QVariant(10.0f);
3806 _mapParamName2Value[compId][QStringLiteral("COMPASS_OFS_Y")] = QVariant(10.0f);
3807 _mapParamName2Value[compId][QStringLiteral("COMPASS_OFS_Z")] = QVariant(10.0f);
3808 _mapParamName2Value[compId][QStringLiteral("COMPASS_OFS2_X")] = QVariant(10.0f);
3809 _mapParamName2Value[compId][QStringLiteral("COMPASS_OFS2_Y")] = QVariant(10.0f);
3810 _mapParamName2Value[compId][QStringLiteral("COMPASS_OFS2_Z")] = QVariant(10.0f);
3811 _mapParamName2Value[compId][QStringLiteral("COMPASS_OFS3_X")] = QVariant(10.0f);
3812 _mapParamName2Value[compId][QStringLiteral("COMPASS_OFS3_Y")] = QVariant(10.0f);
3813 _mapParamName2Value[compId][QStringLiteral("COMPASS_OFS3_Z")] = QVariant(10.0f);
3814 }, Qt::QueuedConnection);
3815
3816 _apmCompassCalProgress = -1; // deactivate
3817 } else {
3818 _apmCompassCalProgress = qMin(pct + 5, 100);
3819 }
3820}
3821
3822// ---------------------------------------------------------------------------
3823// ArduPilot full accelerometer calibration simulation
3824//
3825// The firmware sends COMMAND_LONG(MAV_CMD_ACCELCAL_VEHICLE_POS, pos) to QGC
3826// and waits for a COMMAND_ACK (the "Next" button press) before advancing.
3827// State: _apmAccelCalPosIndex -1=inactive, 0..5=current pose, 6=done.
3828// ---------------------------------------------------------------------------
3829void MockLink::_apmAccelCalWorker()
3830{
3831 if (_firmwareType != MAV_AUTOPILOT_ARDUPILOTMEGA) {
3832 return;
3833 }
3834
3835 QMutexLocker locker(&_apmAccelCalMutex);
3836 if (_apmAccelCalPosIndex < 0) {
3837 return;
3838 }
3839
3840 if (_apmAccelCalPosIndex == 6) {
3841 // All poses done: send SUCCESS
3842 mavlink_message_t msg{};
3844 cmd.target_system = 255; // GCS
3845 cmd.target_component = MAV_COMP_ID_MISSIONPLANNER;
3846 cmd.command = MAV_CMD_ACCELCAL_VEHICLE_POS;
3847 cmd.param1 = static_cast<float>(ACCELCAL_VEHICLE_POS_SUCCESS);
3848 (void) mavlink_msg_command_long_encode_chan(
3849 _vehicleSystemId, _vehicleComponentId, _outgoingMavlinkChannel, &msg, &cmd);
3851
3852 // Write non-zero accel offsets.
3853 // _mapParamName2Value is owned by MockLink's main thread; dispatch the write there
3854 // to avoid a data race with concurrent param reads on the main thread.
3855 (void) QMetaObject::invokeMethod(this, [this] {
3856 constexpr int compId = MAV_COMP_ID_AUTOPILOT1;
3857 _mapParamName2Value[compId][QStringLiteral("INS_ACCOFFS_X")] = QVariant(0.1f);
3858 _mapParamName2Value[compId][QStringLiteral("INS_ACCOFFS_Y")] = QVariant(0.1f);
3859 _mapParamName2Value[compId][QStringLiteral("INS_ACCOFFS_Z")] = QVariant(0.1f);
3860 }, Qt::QueuedConnection);
3861
3862 _apmAccelCalPosIndex = -1;
3863 return;
3864 }
3865
3866 // Send the current position request once; wait for Next ack before advancing
3867 if (!_apmAccelCalGotAck) {
3868 // Throttle re-sends to ~10 Hz
3869 if (++_apmAccelCalTickCount < 50) {
3870 return;
3871 }
3872 _apmAccelCalTickCount = 0;
3873
3874 mavlink_message_t msg{};
3876 cmd.target_system = 255;
3877 cmd.target_component = MAV_COMP_ID_MISSIONPLANNER;
3878 cmd.command = MAV_CMD_ACCELCAL_VEHICLE_POS;
3879 cmd.param1 = static_cast<float>(kAPMAccelCalPosSequence[_apmAccelCalPosIndex]);
3880 (void) mavlink_msg_command_long_encode_chan(
3881 _vehicleSystemId, _vehicleComponentId, _outgoingMavlinkChannel, &msg, &cmd);
3883 } else {
3884 // Ack received — advance to next pose
3885 _apmAccelCalGotAck = false;
3886 _apmAccelCalPosIndex++;
3887 }
3888}
std::shared_ptr< LinkConfiguration > SharedLinkConfigurationPtr
mavlink_status_t * mavlink_get_channel_status(uint8_t chan)
Definition QGCMAVLink.cc:53
struct __mavlink_setup_signing_t mavlink_setup_signing_t
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
struct __mavlink_command_ack_t mavlink_command_ack_t
struct param_union mavlink_param_union_t
struct __mavlink_command_long_t mavlink_command_long_t
static size_t typeToSize(ValueType_t type)
void setDynamic(bool dynamic=true)
Set if this is this a dynamic configuration. (decided at runtime).
void bytesReceived(LinkInterface *link, const QByteArray &data)
void disconnected()
virtual void _freeMavlinkChannel()
LinkInterface(SharedLinkConfigurationPtr &config, QObject *parent=nullptr)
Links are only created by LinkManager so constructor is not public.
void _connectionRemoved()
bool mavlinkChannelIsSet() const
virtual bool _allocateMavlinkChannel()
void connected()
SharedLinkConfigurationPtr linkConfiguration()
SharedLinkConfigurationPtr _config
SharedLinkConfigurationPtr addConfiguration(LinkConfiguration *config)
uint8_t allocateMavlinkChannel()
static LinkManager * instance()
void freeMavlinkChannel(uint8_t channel)
static constexpr uint8_t invalidMavlinkChannel()
static int getComponentId()
static MAVLinkProtocol * instance()
@ VideoStreamRtpUdpH265
RTP/UDP H.265 -> udp265://.
@ VideoStreamNone
No stream served.
@ VideoStreamRtpUdpH264
RTP/UDP H.264 -> udp://.
@ VideoStreamRtspH264
RTSP H.264 -> rtsp://.
@ VideoStreamMpegTsTcp
MPEG-TS over TCP -> tcp://.
@ VideoStreamMpegTsUdp
MPEG-TS over UDP -> mpegts://.
void setVehicleType(MAV_TYPE vehicleType)
@ FailMissingParamOnAllRequestsNonDefaultComponent
Adds a second (non-autopilot) param component which never sends one of its params.
@ FailInitialConnectRequestMessageAutopilotVersionLost
REQUEST_MESSAGE:AUTOPILOT_VERSION success, AUTOPILOT_VERSION never sent.
@ FailMissingParamOnInitialRequest
Not all params are sent on initial request, should still succeed since QGC will re-query missing para...
@ FailMissingParamOnAllRequests
Not all params are sent on initial request, QGC retries will fail as well.
@ FailNonDefaultComponentLossy
Second component streams only its first two params and drops the first read of every param.
@ FailMissingParamSharedIndexAcrossComponents
Autopilot never sends its param at index 1; second component skips its index 1 on initial request onl...
@ FailInitialConnectRequestMessageAutopilotVersionFailure
REQUEST_MESSAGE:AUTOPILOT_VERSION returns failure.
@ FailNonDefaultComponentDead
Second component streams only its first two params and never answers a read.
@ FailParamNoResponseToRequestList
Do not respond to PARAM_REQUEST_LIST.
void setFailureMode(FailureMode_t failureMode)
void setEnableProximity(bool enableProximity)
void setApmStartFreshParams(bool apmStartFreshParams)
void setEnableCamera(bool enableCamera)
void setEnableGimbal(bool enableGimbal)
void setSendStatusText(bool sendStatusText)
void setCompanionParams(bool companionParams)
bool cameraHasVideoStream() const
void setFtpCapability(bool ftpCapability)
void setFirmwareType(MAV_AUTOPILOT firmwareType)
void setSendRadioStatus(bool sendRadioStatus)
void setVideoStreamType(int value)
void setPreloadMission(bool preloadMission)
void setStayMavlinkV1(bool stayV1)
Simulates MAVLink Camera Protocol v2 components for MockLink.
Simulates MAVLink Gimbal Manager Protocol for MockLink.
Simulates the PX4 commander magnetometer and accelerometer calibration protocols for MockLink.
Worker class that runs periodic tasks for MockLink simulation.
@ MpegTsTcp
MPEG-TS over TCP -> tcp://.
@ RtpUdpH265
RTP/H.265 over UDP -> udp265://.
@ RtpUdpH264
RTP/H.264 over UDP -> udp://.
@ MpegTsUdp
MPEG-TS over UDP -> mpegts://.
static FactMetaData::ValueType_t mavTypeToFactType(MAV_PARAM_TYPE mavType)
QByteArray line(std::string_view command)
command as one CR/LF-terminated line.
constexpr const char * toString(HwVideoBufferPath path) noexcept
Definition GstHwTypes.h:37
uint64_t currentSigningTimestampTicks()
Current signing timestamp in 10µs ticks since 2015-01-01.
bool insecureConnectionAcceptUnsignedCallback(const mavlink_status_t *status, uint32_t message_id)
std::optional< T > number(std::string_view field, int base=DECIMAL_BASE)
std::optional< double > coordinate(std::string_view field, std::string_view hemisphere, bool latitude)
QString modeName(const QString &paramName, const QStringList &enumStrings, const QVariantList &enumValues, const QStringList &externalNames, int value)
Label of the mode a parameter value selects, as modeChoices shows it. Empty for a value with no choic...
quint32 crc32(const quint8 *src, unsigned len, unsigned state)
Definition QGCMath.cc:66
bool runningUnitTests()
void secureZero(void *data, size_t size)
GPSCommandSequence port(QByteArrayView port, unsigned baud)
Clears the SBF output of port, keeps a serial port at the link's baud, and selects SBF and the WGS84 ...
Definition SBFPlan.cc:34
@ PX4_CUSTOM_MAIN_MODE_AUTO
@ PX4_CUSTOM_SUB_MODE_AUTO_RESERVED_DO_NOT_USE