QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GimbalController.cc
Go to the documentation of this file.
1#include "GimbalController.h"
2
3#include <cmath>
4#include <cstring>
5
6#include "AppMessages.h"
7#include "Gimbal.h"
9#include "MAVLinkLib.h"
10#include "MAVLinkProtocol.h"
11#include "ParameterManager.h"
12#include "QGCCameraManager.h"
13#include "QGCLoggingCategory.h"
14#include "QmlObjectListModel.h"
15#include "SettingsManager.h"
16#include "Vehicle.h"
17#include "VehicleLinkManager.h"
18
19QGC_LOGGING_CATEGORY(GimbalControllerLog, "Gimbal.GimbalController")
20
22 : QObject(vehicle)
23 , _vehicle(vehicle)
24 , _gimbals(new QmlObjectListModel(this))
25{
26 qCDebug(GimbalControllerLog) << this;
27
28 (void) connect(_vehicle, &Vehicle::initialConnectComplete, this, &GimbalController::_initialConnectCompleted, Qt::UniqueConnection);
29 (void) connect(_vehicle, &Vehicle::mavlinkMessageReceived, this, &GimbalController::_mavlinkMessageReceived);
30
32 (void) connect(&_rateSenderTimer, &QTimer::timeout, this, &GimbalController::_rateSenderTimeout);
33}
34
36{
37 qCDebug(GimbalControllerLog) << this;
38}
39
40void GimbalController::_initialConnectCompleted()
41{
42 _initialConnectComplete = true;
43}
44
46{
47 if (!gimbal) {
48 qCCritical(GimbalControllerLog) << "Set active gimbal: attempted to set a nullptr, returning";
49 return;
50 }
51
52 if (gimbal != _activeGimbal) {
53 qCDebug(GimbalControllerLog) << "Set active gimbal:" << gimbal;
54 _activeGimbal = gimbal;
56 }
57}
58
59void GimbalController::_mavlinkMessageReceived(const mavlink_message_t &message)
60{
61 if (!_initialConnectComplete) {
62 return;
63 }
64
65 switch (message.msgid) {
66 case MAVLINK_MSG_ID_HEARTBEAT:
67 _handleHeartbeat(message);
68 break;
69 case MAVLINK_MSG_ID_GIMBAL_MANAGER_INFORMATION:
70 _handleGimbalManagerInformation(message);
71 break;
72 case MAVLINK_MSG_ID_GIMBAL_MANAGER_STATUS:
73 _handleGimbalManagerStatus(message);
74 break;
75 case MAVLINK_MSG_ID_GIMBAL_DEVICE_ATTITUDE_STATUS:
76 _handleGimbalDeviceAttitudeStatus(message);
77 break;
78 case MAVLINK_MSG_ID_GIMBAL_DEVICE_INFORMATION:
79 _handleGimbalDeviceInformation(message);
80 break;
81 default:
82 break;
83 }
84}
85
86void GimbalController::_handleHeartbeat(const mavlink_message_t &message)
87{
88 if (!_potentialGimbalManagers.contains(message.compid)) {
89 qCDebug(GimbalControllerLog) << "new potential gimbal manager component:" << message.compid;
90 }
91
92 PotentialGimbalManager &gimbalManager = _potentialGimbalManagers[message.compid];
93
94 // Note that we are working over potential gimbal managers here, instead of potential gimbals.
95 // This is because we address the gimbal manager by compid, but a gimbal device might have an
96 // id different than the message compid it comes from. For more information see https://mavlink.io/en/services/gimbal_v2.html
97 if (!gimbalManager.receivedGimbalManagerInformation && (gimbalManager.requestGimbalManagerInformationRetries > 0)) {
98 if (_requestGimbalInformation(message.compid)) {
99 --gimbalManager.requestGimbalManagerInformationRetries;
100 }
101 }
102}
103
104void GimbalController::_handleGimbalManagerInformation(const mavlink_message_t &message)
105{
106 mavlink_gimbal_manager_information_t information{};
107 mavlink_msg_gimbal_manager_information_decode(&message, &information);
108
109 if (information.gimbal_device_id == 0) {
110 qCWarning(GimbalControllerLog) << "_handleGimbalManagerInformation for invalid gimbal device:"
111 << information.gimbal_device_id << ", from component id:" << message.compid;
112 return;
113 }
114
115 qCDebug(GimbalControllerLog) << "_handleGimbalManagerInformation for gimbal device:" << information.gimbal_device_id << ", component id:" << message.compid;
116
117 const GimbalPairId pairId{message.compid, information.gimbal_device_id};
118
119 auto gimbalIt = _potentialGimbals.find(pairId);
120 if (gimbalIt == _potentialGimbals.constEnd()) {
121 gimbalIt = _potentialGimbals.insert(pairId, new Gimbal(this));
122 }
123
124 Gimbal *const gimbal = gimbalIt.value();
125 gimbal->setManagerCompid(message.compid);
126 gimbal->setDeviceId(information.gimbal_device_id);
127 gimbal->setCapabilityFlags(information.cap_flags);
128
129 if (!gimbal->_receivedGimbalManagerInformation) {
130 qCDebug(GimbalControllerLog) << "gimbal manager with compId:" << message.compid
131 << " is responsible for gimbal device:" << information.gimbal_device_id;
132 }
133
134 gimbal->_receivedGimbalManagerInformation = true;
135 // It is important to flag our potential gimbal manager as well, so we stop requesting gimbal_manger_information message
136 PotentialGimbalManager &gimbalManager = _potentialGimbalManagers[message.compid];
137 gimbalManager.receivedGimbalManagerInformation = true;
138
139 _checkComplete(*gimbal, pairId);
140}
141
142void GimbalController::_handleGimbalManagerStatus(const mavlink_message_t &message)
143{
144 mavlink_gimbal_manager_status_t status{};
145 mavlink_msg_gimbal_manager_status_decode(&message, &status);
146
147 // qCDebug(GimbalControllerLog) << "_handleGimbalManagerStatus for gimbal device:" << status.gimbal_device_id << ", component id:" << message.compid;
148
149 if (status.gimbal_device_id == 0) {
150 qCDebug(GimbalControllerLog) << "gimbal manager with compId:" << message.compid
151 << "reported status of gimbal device id:" << status.gimbal_device_id << "which is not a valid gimbal device id";
152 return;
153 }
154
155 const GimbalPairId pairId{message.compid, status.gimbal_device_id};
156
157 auto gimbalIt = _potentialGimbals.find(pairId);
158 if (gimbalIt == _potentialGimbals.constEnd()) {
159 gimbalIt = _potentialGimbals.insert(pairId, new Gimbal(this));
160 }
161
162 Gimbal *const gimbal = gimbalIt.value();
163 if (gimbal->deviceId()->rawValue().toUInt() == 0) {
164 gimbal->setDeviceId(status.gimbal_device_id);
165 } else if (gimbal->deviceId()->rawValue().toUInt() != status.gimbal_device_id) {
166 qCWarning(GimbalControllerLog) << "conflicting GIMBAL_MANAGER_STATUS.gimbal_device_id:" << status.gimbal_device_id;
167 }
168
169 if (gimbal->managerCompid()->rawValue().toUInt() == 0) {
170 gimbal->setManagerCompid(message.compid);
171 } else if (gimbal->managerCompid()->rawValue().toUInt() != message.compid) {
172 qCWarning(GimbalControllerLog) << "conflicting GIMBAL_MANAGER_STATUS compid:" << message.compid;
173 }
174
175 // Only log this message once
176 if (!gimbal->_receivedGimbalManagerStatus) {
177 qCDebug(GimbalControllerLog) << "_handleGimbalManagerStatus: gimbal manager with compId" << message.compid
178 << "is responsible for gimbal device" << status.gimbal_device_id;
179 }
180
181 gimbal->_receivedGimbalManagerStatus = true;
182
183 const bool haveControl =
184 (status.primary_control_sysid == MAVLinkProtocol::instance()->getSystemId()) &&
185 (status.primary_control_compid == MAVLinkProtocol::getComponentId());
186
187 const bool othersHaveControl = !haveControl &&
188 (status.primary_control_sysid != 0 && status.primary_control_compid != 0);
189
190 if (gimbal->gimbalHaveControl() != haveControl) {
191 gimbal->setGimbalHaveControl(haveControl);
192 }
193
194 if (gimbal->gimbalOthersHaveControl() != othersHaveControl) {
195 gimbal->setGimbalOthersHaveControl(othersHaveControl);
196 }
197
198 _checkComplete(*gimbal, pairId);
199}
200
201void GimbalController::_handleGimbalDeviceAttitudeStatus(const mavlink_message_t &message)
202{
203 mavlink_gimbal_device_attitude_status_t attitude_status{};
204 mavlink_msg_gimbal_device_attitude_status_decode(&message, &attitude_status);
205
206 GimbalPairId pairId{};
207
208 if (attitude_status.gimbal_device_id == 0) {
209 // If gimbal_device_id is 0, we must take the compid of the message
210 pairId.deviceId = message.compid;
211
212 // We do a reverse lookup here
213 const auto foundGimbal = std::find_if(_potentialGimbals.begin(), _potentialGimbals.end(),
214 [pairId](Gimbal *gimbal) { return (gimbal->deviceId()->rawValue().toUInt() == pairId.deviceId); });
215
216 if (foundGimbal == _potentialGimbals.constEnd()) {
217 qCDebug(GimbalControllerLog) << "_handleGimbalDeviceAttitudeStatus for unknown device id:"
218 << pairId.deviceId << "from component id:" << message.compid;
219 return;
220 }
221
222 pairId.managerCompid = foundGimbal.key().managerCompid;
223 } else if (attitude_status.gimbal_device_id <= 6) {
224 // If the gimbal_device_id field is set to 1-6, we must use this device id instead
225 pairId.deviceId = attitude_status.gimbal_device_id;
226 pairId.managerCompid = message.compid;
227 } else {
228 // Otherwise, this is invalid and we don't know how to deal with it.
229 qCDebug(GimbalControllerLog) << "_handleGimbalDeviceAttitudeStatus for invalid device id: "
230 << attitude_status.gimbal_device_id << " from component id: " << message.compid;
231 return;
232 }
233
234 auto gimbalIt = _potentialGimbals.find(pairId);
235 if (gimbalIt == _potentialGimbals.end()) {
236 gimbalIt = _potentialGimbals.insert(pairId, new Gimbal(this));
237 }
238
239 Gimbal *const gimbal = gimbalIt.value();
240
241 gimbal->setRetracted((attitude_status.flags & GIMBAL_DEVICE_FLAGS_RETRACT) > 0);
242 gimbal->setYawLock((attitude_status.flags & GIMBAL_DEVICE_FLAGS_YAW_LOCK) > 0);
243 gimbal->_neutral = (attitude_status.flags & GIMBAL_DEVICE_FLAGS_NEUTRAL) > 0;
244
245 float roll, pitch, yaw;
246 mavlink_quaternion_to_euler(attitude_status.q, &roll, &pitch, &yaw);
247
248 gimbal->setAbsoluteRoll(qRadiansToDegrees(roll));
249 gimbal->setAbsolutePitch(qRadiansToDegrees(pitch));
250
251 // The two yaw frame flags are mutually exclusive. Both set is malformed: ignore both and fall back to the
252 // legacy YAW_LOCK frame semantics with the vehicle's heading.
253 constexpr uint16_t kYawFrameFlags = GIMBAL_DEVICE_FLAGS_YAW_IN_VEHICLE_FRAME | GIMBAL_DEVICE_FLAGS_YAW_IN_EARTH_FRAME;
254 uint16_t flags = attitude_status.flags;
255 const bool yawFrameFlagsInvalid = (flags & kYawFrameFlags) == kYawFrameFlags;
256 if (yawFrameFlagsInvalid) {
257 flags &= ~kYawFrameFlags;
258 }
259 if (yawFrameFlagsInvalid != gimbal->_yawFrameFlagsInvalid) {
260 gimbal->_yawFrameFlagsInvalid = yawFrameFlagsInvalid;
261 if (yawFrameFlagsInvalid) {
262 qCWarning(GimbalControllerLog) << "GIMBAL_DEVICE_ATTITUDE_STATUS has both yaw frame flags set, ignoring them for device:"
263 << gimbal->deviceId()->rawValue().toUInt();
264 }
265 }
266
267 // Spec: delta_yaw (gimbal's own estimate of vehicle heading) is only meaningful when a yaw frame flag is
268 // set; NaN means unknown. Without it fall back to the vehicle's heading.
269 const bool frameFlagged = (flags & kYawFrameFlags) != 0;
270 const bool deltaYawValid = frameFlagged && !std::isnan(attitude_status.delta_yaw);
271 const float deltaYawDeg = deltaYawValid ? std::remainder(qRadiansToDegrees(attitude_status.delta_yaw), 360.0f) : qQNaN();
272 if (deltaYawValid != gimbal->_deltaYawValid) {
273 gimbal->_deltaYawValid = deltaYawValid;
274 qCDebug(GimbalControllerLog) << "delta_yaw heading source" << (deltaYawValid ? "available" : "unavailable")
275 << "for device:" << gimbal->deviceId()->rawValue().toUInt();
276 }
277 gimbal->setDeltaYaw(deltaYawDeg);
278
279 const float headingDeg = deltaYawValid ? deltaYawDeg : _vehicle->heading()->rawValue().toFloat();
280
281 const bool yaw_in_vehicle_frame = _yawInVehicleFrame(flags);
282 if (yaw_in_vehicle_frame) {
283 const float bodyYaw = qRadiansToDegrees(yaw);
284 const float absoluteYaw = std::remainder(bodyYaw + headingDeg, 360.0f);
285
286 gimbal->setBodyYaw(bodyYaw);
287 gimbal->setAbsoluteYaw(absoluteYaw);
288
289 } else {
290 const float absoluteYaw = qRadiansToDegrees(yaw);
291 const float bodyYaw = std::remainder(absoluteYaw - headingDeg, 360.0f);
292
293 gimbal->setBodyYaw(bodyYaw);
294 gimbal->setAbsoluteYaw(absoluteYaw);
295 }
296
297 gimbal->_receivedGimbalDeviceAttitudeStatus = true;
298
299 _checkComplete(*gimbal, pairId);
300}
301
302void GimbalController::_handleGimbalDeviceInformation(const mavlink_message_t& message)
303{
304 mavlink_gimbal_device_information_t information{};
305 mavlink_msg_gimbal_device_information_decode(&message, &information);
306
307 // Build a human-readable name: prefer the user-set custom name, otherwise
308 // combine vendor and model. The char arrays are not guaranteed null-terminated.
309 const auto toString = [](std::span<const char> field) { return QGCMAVLink::boundedStringField(field).trimmed(); };
310 QString name = toString(information.custom_name);
311 if (name.isEmpty()) {
312 const QString vendor = toString(information.vendor_name);
313 const QString model = toString(information.model_name);
314 name = QStringLiteral("%1 %2").arg(vendor, model).trimmed();
315 }
316
317 if (name.isEmpty()) {
318 return;
319 }
320
321 // Match to the gimbal. If gimbal_device_id is 1-6 the manager and device
322 // share this component id, so the pair is {compid, gimbal_device_id}.
323 // Otherwise the device is its own component and its compid is the device id.
324 Gimbal* gimbal = nullptr;
325 if (information.gimbal_device_id != 0) {
326 const auto it = _potentialGimbals.find(GimbalPairId{message.compid, information.gimbal_device_id});
327 if (it != _potentialGimbals.constEnd()) {
328 gimbal = it.value();
329 }
330 } else {
331 for (Gimbal* const candidate : _potentialGimbals) {
332 if (candidate->deviceId()->rawValue().toUInt() == message.compid) {
333 gimbal = candidate;
334 break;
335 }
336 }
337 }
338
339 if (gimbal) {
340 gimbal->setDeviceName(name);
341 gimbal->_receivedGimbalDeviceInformation = true;
342 qCDebug(GimbalControllerLog) << "gimbal device name:" << name << "for compid:" << message.compid;
343 }
344}
345
346bool GimbalController::_requestGimbalInformation(uint8_t compid)
347{
348 qCDebug(GimbalControllerLog) << "_requestGimbalInformation(" << compid << ")";
349
350 if (!_vehicle) {
351 return false;
352 }
353 if (_pendingInformationRequestCompId != -1) {
354 qCDebug(GimbalControllerLog) << "_requestGimbalInformation: request already in flight for compid" << _pendingInformationRequestCompId;
355 return false;
356 }
357
358 // Must go through requestMessage rather than sending MAV_CMD_REQUEST_MESSAGE directly so
359 // that it serializes with other request-message users targeting the same component
360 // (a raw send collides with theirs in the command queue's duplicate-command check).
361 _pendingInformationRequestCompId = compid;
362 _vehicle->requestMessage(_requestMessageResultHandler,
363 this,
364 compid,
365 MAVLINK_MSG_ID_GIMBAL_MANAGER_INFORMATION);
366 return true;
367}
368
369void GimbalController::_requestMessageResultHandler(void* resultHandlerData, MAV_RESULT result, VehicleTypes::RequestMessageResultHandlerFailureCode_t failureCode, const mavlink_message_t& message)
370{
371 Q_UNUSED(message);
372
373 auto* controller = static_cast<GimbalController*>(resultHandlerData);
374 controller->_pendingInformationRequestCompId = -1;
375
376 // Success is handled by the normal GIMBAL_MANAGER_INFORMATION message dispatch and
377 // failures are retried from _checkComplete, so just log here.
378 if (result != MAV_RESULT_ACCEPTED) {
379 qCDebug(GimbalControllerLog) << "GIMBAL_MANAGER_INFORMATION request failed - result:" << result << "failureCode:" << failureCode;
380 }
381}
382
383void GimbalController::_requestDeviceInformationResultHandler(
384 void* resultHandlerData, MAV_RESULT result, VehicleTypes::RequestMessageResultHandlerFailureCode_t failureCode,
385 const mavlink_message_t& message)
386{
387 Q_UNUSED(resultHandlerData);
388 Q_UNUSED(message);
389
390 // Success is handled by the normal GIMBAL_DEVICE_INFORMATION message dispatch. The name is
391 // optional, so on failure we keep showing the IDs.
392 if (result != MAV_RESULT_ACCEPTED) {
393 qCDebug(GimbalControllerLog) << "GIMBAL_DEVICE_INFORMATION request failed - result:" << result
394 << "failureCode:" << failureCode;
395 }
396}
397
398void GimbalController::_checkComplete(Gimbal &gimbal, GimbalPairId pairId)
399{
400 if (gimbal._isComplete) {
401 // Already complete, nothing to do.
402 return;
403 }
404
405 if (!gimbal._receivedGimbalManagerInformation && gimbal._requestInformationRetries > 0) {
406 if (_requestGimbalInformation(pairId.managerCompid)) {
407 --gimbal._requestInformationRetries;
408 }
409 }
410 // Limit the rate of set message interval requests, per gimbal
411 const qint64 now = QDateTime::currentMSecsSinceEpoch();
412 const int statusRequestSpacingMs = QGC::runningUnitTests() ? kTestStatusRequestSpacingMs : kStatusRequestSpacingMs;
413 if (!gimbal._receivedGimbalManagerStatus && (gimbal._requestStatusRetries > 0) &&
414 (now - gimbal._lastStatusRequestMs > statusRequestSpacingMs)) {
415 gimbal._lastStatusRequestMs = now;
416 _vehicle->sendMavCommand(pairId.managerCompid,
417 MAV_CMD_SET_MESSAGE_INTERVAL,
418 false /* no error */,
419 MAVLINK_MSG_ID_GIMBAL_MANAGER_STATUS,
420 (gimbal._requestStatusRetries > 2) ? 0 : 5000000); // request default rate, if we don't succeed, last attempt is fixed 0.2 Hz instead
421 --gimbal._requestStatusRetries;
422 qCDebug(GimbalControllerLog) << "attempt to set GIMBAL_MANAGER_STATUS message at"
423 << (gimbal._requestStatusRetries > 2 ? "default rate" : "0.2 Hz") << "interval for device:"
424 << gimbal.deviceId()->rawValue().toUInt() << "manager compID:" << pairId.managerCompid
425 << ", retries remaining:" << gimbal._requestStatusRetries;
426 }
427
428 if (!gimbal._receivedGimbalDeviceAttitudeStatus && (gimbal._requestAttitudeRetries > 0) &&
429 gimbal._receivedGimbalManagerInformation && (pairId.deviceId != 0)) {
430 // We request the attitude directly from the gimbal device component.
431 // We can only do that once we have received the gimbal manager information
432 // telling us which gimbal device it is responsible for.
433 uint8_t gimbalDeviceCompid = pairId.deviceId;
434 // If the device ID is 1-6, we need to request the message from the manager itself.
435 if (gimbalDeviceCompid <= 6) {
436 gimbalDeviceCompid = pairId.managerCompid;
437 }
438 _vehicle->sendMavCommand(gimbalDeviceCompid,
439 MAV_CMD_SET_MESSAGE_INTERVAL,
440 false /* no error */,
441 MAVLINK_MSG_ID_GIMBAL_DEVICE_ATTITUDE_STATUS,
442 0 /* request default rate */);
443
444 --gimbal._requestAttitudeRetries;
445 }
446
447 if (!gimbal._receivedGimbalManagerInformation || !gimbal._receivedGimbalManagerStatus || !gimbal._receivedGimbalDeviceAttitudeStatus) {
448 // Not complete yet.
449 return;
450 }
451
452 gimbal._isComplete = true;
453
454 // Now that discovery is done, make a best-effort request for the gimbal
455 // device information, which carries the vendor/model/custom name.
456 // If it's never answered (e.g. the SITL gimbal sends empty names),
457 // we simply fall back to showing the IDs.
458 if (pairId.deviceId != 0) {
459 uint8_t gimbalDeviceCompid = pairId.deviceId;
460 // If the device ID is 1-6, the device shares the manager's component id.
461 if (gimbalDeviceCompid <= 6) {
462 gimbalDeviceCompid = pairId.managerCompid;
463 }
464 // Use requestMessage so it serializes with other request-message users targeting this component.
465 _vehicle->requestMessage(_requestDeviceInformationResultHandler, nullptr, gimbalDeviceCompid,
466 MAVLINK_MSG_ID_GIMBAL_DEVICE_INFORMATION);
467 }
468
469 // If there is no current active gimbal, set this one as active
470 if (!_activeGimbal) {
471 setActiveGimbal(&gimbal);
472 }
473
474 _gimbals->append(&gimbal);
475 // This is needed for new Gimbals telemetry to be available for the user to show in flyview telemetry panel
476 _vehicle->_addFactGroup(&gimbal, QStringLiteral("%1%2%3").arg(_gimbalFactGroupNamePrefix).arg(pairId.managerCompid).arg(pairId.deviceId));
477}
478
479bool GimbalController::_tryGetGimbalControl()
480{
481 if (!_activeGimbal) {
482 qCCritical(GimbalControllerLog) << "_tryGetGimbalControl: active gimbal is nullptr, returning";
483 return false;
484 }
485
486 if (!_gcsSystemIdSupportsGimbalControl()) {
487 if (!_gcsSystemIdUnsupportedMessageShown) {
488 _gcsSystemIdUnsupportedMessageShown = true;
489 _showGcsSystemIdUnsupportedMessage();
490 }
491 return false;
492 }
493
494 if (_activeGimbal->gimbalOthersHaveControl()) {
495 qCDebug(GimbalControllerLog) << "Others in control, showing popup for user to confirm control..";
497 return false;
498 } else if (!_activeGimbal->gimbalHaveControl()) {
499 qCDebug(GimbalControllerLog) << "Nobody in control, acquiring control ourselves..";
501 }
502
503 return true;
504}
505
506bool GimbalController::_gcsSystemIdSupportsGimbalControl()
507{
508 // GIMBAL_MANAGER_STATUS reports the controlling system in an 8-bit field, so a wider GCS id can never own
509 // the gimbal.
510 return MAVLinkProtocol::instance()->getSystemId() <= UINT8_MAX;
511}
512
513void GimbalController::_showGcsSystemIdUnsupportedMessage()
514{
515 QGC::showAppMessage(tr("Gimbal control unavailable. The gimbal can only identify a ground station with a system "
516 "ID from 1 to 255, but this one uses ID %1. Change MAVLink System ID in Application "
517 "Settings > Telemetry to 255 or lower to control the gimbal.")
518 .arg(MAVLinkProtocol::instance()->getSystemId()));
519}
520
521bool GimbalController::_yawInVehicleFrame(uint32_t flags)
522{
523 if ((flags & GIMBAL_DEVICE_FLAGS_YAW_IN_VEHICLE_FRAME) > 0) {
524 return true;
525 } else if ((flags & GIMBAL_DEVICE_FLAGS_YAW_IN_EARTH_FRAME) > 0) {
526 return false;
527 } else {
528 // For backwards compatibility: if both new flags are 0, yaw lock defines the frame.
529 return ((flags & GIMBAL_DEVICE_FLAGS_YAW_LOCK) == 0);
530 }
531}
532
534{
535 if (!_activeGimbal) {
536 qCCritical(GimbalControllerLog) << "gimbalPitchStart: active gimbal is nullptr, returning";
537 return;
538 }
539
540 const float speed = SettingsManager::instance()->gimbalControllerSettings()->joystickButtonsSpeed()->rawValue().toInt();
541 activeGimbal()->setPitchRate(direction * speed);
542
543 sendRate();
544}
545
547{
548 if (!_activeGimbal) {
549 qCCritical(GimbalControllerLog) << "gimbalYawStart: active gimbal is nullptr, returning";
550 return;
551 }
552
553 const float speed = SettingsManager::instance()->gimbalControllerSettings()->joystickButtonsSpeed()->rawValue().toInt();
554 activeGimbal()->setYawRate(direction * speed);
555 sendRate();
556}
557
559{
560 if (!_activeGimbal) {
561 qCCritical(GimbalControllerLog) << "gimbalPitchStop: active gimbal is nullptr, returning";
562 return;
563 }
564
565 activeGimbal()->setPitchRate(0.0f);
566 sendRate();
567}
568
570{
571 if (!_activeGimbal) {
572 qCCritical(GimbalControllerLog) << "gimbalYawStop: active gimbal is nullptr, returning";
573 return;
574 }
575
576 activeGimbal()->setYawRate(0.0f);
577 sendRate();
578}
579
581{
582 if (!_activeGimbal) {
583 qCCritical(GimbalControllerLog) << "gimbalYawStep: active gimbal is nullptr, returning";
584 return;
585 }
586
588 const bool preserveYawLock = settings->preserveYawLockOnPositionCommands()->rawValue().toBool();
589 if (preserveYawLock && _activeGimbal->yawLock()) {
590 // Preserve yaw lock: send command in earth frame with yaw lock flag
591 sendPitchAbsoluteYaw(0.0, _vehicle->heading()->rawValue().toFloat(), true);
592 } else {
593 // Default behavior: send command in body frame (yaw follow)
594 sendPitchBodyYaw(0.0, 0.0, true);
595 }
596}
597
599{
600 if (!_activeGimbal) {
601 qCDebug(GimbalControllerLog) << "tilt90Gimbal: active gimbal is nullptr, returning";
602 return;
603 }
604
606 const bool preserveYawLock = settings->preserveYawLockOnPositionCommands()->rawValue().toBool();
607 if (preserveYawLock && _activeGimbal->yawLock()) {
608 // Preserve yaw lock: send command in earth frame with yaw lock flag
609 sendPitchAbsoluteYaw(-90.0, _activeGimbal->absoluteYaw()->rawValue().toFloat(), true);
610 } else {
611 // Default behavior: send command in body frame (yaw follow)
612 sendPitchBodyYaw(-90.0, 0.0, true);
613 }
614}
615
616void GimbalController::gimbalOnScreenControl(float panPct, float tiltPct, bool clickAndPoint, bool clickAndDrag, bool /*rateControl*/, bool /*retract*/, bool /*neutral*/, bool /*yawlock*/)
617{
618 // Pan and tilt comes as +-(0-1)
619
620 if (!_activeGimbal) {
621 qCCritical(GimbalControllerLog) << "gimbalOnScreenControl: active gimbal is nullptr, returning";
622 return;
623 }
624
625 if (clickAndPoint) { // based on FOV
626 const float hFov = SettingsManager::instance()->gimbalControllerSettings()->cameraHFov()->rawValue().toFloat();
627 const float vFov = SettingsManager::instance()->gimbalControllerSettings()->cameraVFov()->rawValue().toFloat();
628
629 const float panIncDesired = panPct * hFov * 0.5f;
630 const float tiltIncDesired = tiltPct * vFov * 0.5f;
631
632 const float panDesired = panIncDesired + _activeGimbal->bodyYaw()->rawValue().toFloat();
633 const float tiltDesired = tiltIncDesired + _activeGimbal->absolutePitch()->rawValue().toFloat();
634
635 if (_activeGimbal->yawLock()) {
636 sendPitchAbsoluteYaw(tiltDesired, panIncDesired + _activeGimbal->absoluteYaw()->rawValue().toFloat(), false);
637 } else {
638 sendPitchBodyYaw(tiltDesired, panDesired, false);
639 }
640 } else if (clickAndDrag) { // based on maximum speed
641 // Should send rate commands, but it seems for some reason it is not working on AP side.
642 // Pitch works ok but yaw doesn't stop, it keeps like inertia, like if it was buffering the messages.
643 // So we do a workaround with angle targets
644 const float maxSpeed = SettingsManager::instance()->gimbalControllerSettings()->cameraSlideSpeed()->rawValue().toFloat();
645
646 const float panIncDesired = panPct * maxSpeed * 0.1f;
647 const float tiltIncDesired = tiltPct * maxSpeed * 0.1f;
648
649 const float panDesired = panIncDesired + _activeGimbal->bodyYaw()->rawValue().toFloat();
650 const float tiltDesired = tiltIncDesired + _activeGimbal->absolutePitch()->rawValue().toFloat();
651
652 if (_activeGimbal->yawLock()) {
653 sendPitchAbsoluteYaw(tiltDesired, panIncDesired + _activeGimbal->absoluteYaw()->rawValue().toFloat(), false);
654 } else {
655 sendPitchBodyYaw(tiltDesired, panDesired, false);
656 }
657 }
658}
659
660void GimbalController::sendPitchBodyYaw(float pitch, float yaw, bool showError)
661{
662 if (!_tryGetGimbalControl()) {
663 return;
664 }
665
666 _rateSenderTimer.stop();
667 _activeGimbal->setAbsolutePitch(0.0f);
668 _activeGimbal->setYawRate(0.0f);
669
670 // qCDebug(GimbalControllerLog) << "sendPitch: " << pitch << " BodyYaw: " << yaw;
671
672 const unsigned flags = GIMBAL_MANAGER_FLAGS_ROLL_LOCK
673 | GIMBAL_MANAGER_FLAGS_PITCH_LOCK
674 | GIMBAL_MANAGER_FLAGS_YAW_IN_VEHICLE_FRAME;
675
676 _vehicle->sendMavCommand(
677 _activeGimbal->managerCompid()->rawValue().toUInt(),
678 MAV_CMD_DO_GIMBAL_MANAGER_PITCHYAW,
679 showError,
680 pitch,
681 yaw,
682 NAN,
683 NAN,
684 flags,
685 0,
686 _activeGimbal->deviceId()->rawValue().toUInt());
687}
688
689void GimbalController::sendPitchAbsoluteYaw(float pitch, float yaw, bool showError)
690{
691 if (!_tryGetGimbalControl()) {
692 return;
693 }
694
695 _rateSenderTimer.stop();
696 _activeGimbal->setAbsolutePitch(0.0f);
697 _activeGimbal->setYawRate(0.0f);
698
699 if (yaw > 180.0f) {
700 yaw -= 360.0f;
701 }
702
703 if (yaw < -180.0f) {
704 yaw += 360.0f;
705 }
706
707 // qCDebug() << "sendPitch: " << pitch << " absoluteYaw: " << yaw;
708
709 const unsigned flags = GIMBAL_MANAGER_FLAGS_ROLL_LOCK
710 | GIMBAL_MANAGER_FLAGS_PITCH_LOCK
711 | GIMBAL_MANAGER_FLAGS_YAW_LOCK
712 | GIMBAL_MANAGER_FLAGS_YAW_IN_EARTH_FRAME;
713
714 _vehicle->sendMavCommand(
715 _activeGimbal->managerCompid()->rawValue().toUInt(),
716 MAV_CMD_DO_GIMBAL_MANAGER_PITCHYAW,
717 showError,
718 pitch,
719 yaw,
720 NAN,
721 NAN,
722 flags,
723 0,
724 _activeGimbal->deviceId()->rawValue().toUInt());
725}
726
728{
729 if (!_tryGetGimbalControl()) {
730 return;
731 }
732
733 uint32_t flags = 0;
734 if (set) {
735 flags |= GIMBAL_DEVICE_FLAGS_RETRACT;
736 } else {
737 flags &= ~GIMBAL_DEVICE_FLAGS_RETRACT;
738 }
739
740 sendPitchYawFlags(flags);
741}
742
744{
745 if (!_tryGetGimbalControl()) {
746 return;
747 }
748
749 // We send raw mavlink instead of using MAV_CMD_DO_GIMBAL_MANAGER_PITCHYAW because
750 // when both pitch and yaw stop simultaneously, Vehicle's duplicate command detection
751 // drops the second sendMavCommand call, leaving one axis spinning indefinitely.
752 _sendGimbalAttitudeRates(_activeGimbal->pitchRate(), _activeGimbal->yawRate());
753
754 // Stop timeout if both unset.
755 if ((_activeGimbal->pitchRate() == 0.f) && (_activeGimbal->yawRate() == 0.f)) {
756 _rateSenderTimer.stop();
757 } else {
758 _rateSenderTimer.start();
759 }
760}
761
762void GimbalController::sendGimbalRate(float pitch_rate_deg_s, float yaw_rate_deg_s)
763{
764 if (!_tryGetGimbalControl()) {
765 return;
766 }
767
768 _sendGimbalAttitudeRates(pitch_rate_deg_s, yaw_rate_deg_s);
769
770 if (pitch_rate_deg_s == 0.f && yaw_rate_deg_s == 0.f) {
771 _rateSenderTimer.stop();
772 } else {
773 _rateSenderTimer.start();
774 }
775}
776
777void GimbalController::_sendGimbalAttitudeRates(float pitch_rate_deg_s,
778 float yaw_rate_deg_s)
779{
780
781 auto sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
782 if (!sharedLink) {
783 qCDebug(GimbalControllerLog) << "_sendGimbalAttitudeRates: primary link gone!";
784 return;
785 }
786
787 uint32_t flags =
788 GIMBAL_MANAGER_FLAGS_ROLL_LOCK |
789 GIMBAL_MANAGER_FLAGS_PITCH_LOCK |
790 GIMBAL_MANAGER_FLAGS_YAW_IN_VEHICLE_FRAME; // use vehicle/body frame
791
792 // Preserve current yaw-lock state instead of changing it:
793 if (_activeGimbal->yawLock()) {
794 flags |= GIMBAL_MANAGER_FLAGS_YAW_LOCK;
795 }
796
797 const float qnan[4] = {NAN, NAN, NAN, NAN};
799
800 mavlink_msg_gimbal_manager_set_attitude_pack_chan(
801 MAVLinkProtocol::instance()->getSystemId(),
803 sharedLink->mavlinkChannel(),
804 &msg,
805 _vehicle->id(),
806 static_cast<uint8_t>(_activeGimbal->managerCompid()->rawValue().toUInt()),
807 flags,
808 static_cast<uint8_t>(_activeGimbal->deviceId()->rawValue().toUInt()),
809 qnan,
810 NAN,
811 qDegreesToRadians(pitch_rate_deg_s),
812 qDegreesToRadians(yaw_rate_deg_s)
813 );
814
815 _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg);
816}
817
818void GimbalController::_rateSenderTimeout()
819{
820 // Send rate again to avoid timeout on autopilot side.
821 sendRate();
822}
823
825{
826 if (!_tryGetGimbalControl()) {
827 return;
828 }
829
830 // Roll and pitch are usually "locked", so with horizon and not with aircraft.
831 uint32_t flags = GIMBAL_DEVICE_FLAGS_ROLL_LOCK | GIMBAL_DEVICE_FLAGS_PITCH_LOCK;
832 if (set) {
833 flags |= GIMBAL_DEVICE_FLAGS_YAW_LOCK;
834 }
835
836 sendPitchYawFlags(flags);
837}
838
840{
841 const bool yaw_in_vehicle_frame = _yawInVehicleFrame(flags);
842
843 _vehicle->sendMavCommand(
844 _activeGimbal->managerCompid()->rawValue().toUInt(),
845 MAV_CMD_DO_GIMBAL_MANAGER_PITCHYAW,
846 true,
847 _activeGimbal->absolutePitch()->rawValue().toFloat(),
848 yaw_in_vehicle_frame ? _activeGimbal->bodyYaw()->rawValue().toFloat() : _activeGimbal->absoluteYaw()->rawValue().toFloat(),
849 NAN,
850 NAN,
851 flags,
852 0,
853 _activeGimbal->deviceId()->rawValue().toUInt());
854}
855
857{
858 if (!_activeGimbal) {
859 qCCritical(GimbalControllerLog) << "acquireGimbalControl: active gimbal is nullptr, returning";
860 return;
861 }
862
863 if (!_gcsSystemIdSupportsGimbalControl()) {
864 _showGcsSystemIdUnsupportedMessage();
865 return;
866 }
867
868 _vehicle->sendMavCommand(
869 _activeGimbal->managerCompid()->rawValue().toUInt(),
870 MAV_CMD_DO_GIMBAL_MANAGER_CONFIGURE,
871 true,
872 MAVLinkProtocol::instance()->getSystemId(), // Set us in primary control.
873 MAVLinkProtocol::getComponentId(), // Set us in primary control
874 -1.f, // Leave secondary unchanged
875 -1.f, // Leave secondary unchanged
876 NAN, // Reserved
877 NAN, // Reserved
878 _activeGimbal->deviceId()->rawValue().toUInt());
879}
880
882{
883 if (!_activeGimbal) {
884 qCCritical(GimbalControllerLog) << "releaseGimbalControl: active gimbal is nullptr, returning";
885 return;
886 }
887
888 _vehicle->sendMavCommand(
889 _activeGimbal->managerCompid()->rawValue().toUInt(),
890 MAV_CMD_DO_GIMBAL_MANAGER_CONFIGURE,
891 true,
892 -3.f, // Release primary control if we have control
893 -3.f, // Release primary control if we have control
894 -1.f, // Leave secondary control unchanged
895 -1.f, // Leave secondary control unchanged
896 NAN, // Reserved
897 NAN, // Reserved
898 _activeGimbal->deviceId()->rawValue().toUInt());
899}
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
QVariant rawValue() const
Definition Fact.h:87
static constexpr int kTestRateResendIntervalMs
void sendPitchYawFlags(uint32_t flags)
Q_INVOKABLE void sendGimbalRate(float pitch_rate_deg_s, float yaw_rate_deg_s)
Q_INVOKABLE void setGimbalYawLock(bool set)
Q_INVOKABLE void centerGimbal()
Gimbal * activeGimbal() const
void activeGimbalChanged()
Q_INVOKABLE void sendRate()
static constexpr int kRateResendIntervalMs
Rate command resend period while an axis is moving.
Q_INVOKABLE void sendPitchAbsoluteYaw(float pitch, float yaw, bool showError=true)
static constexpr int kTestStatusRequestSpacingMs
Shortened status request spacing in unit tests.
GimbalController(Vehicle *vehicle)
Q_INVOKABLE void gimbalOnScreenControl(float panpct, float tiltpct, bool clickAndPoint, bool clickAndDrag, bool rateControl, bool retract=false, bool neutral=false, bool yawlock=false)
Q_INVOKABLE void acquireGimbalControl()
void setActiveGimbal(Gimbal *gimbal)
void gimbalYawStart(int direction)
static constexpr int kStatusRequestSpacingMs
Minimum time between GIMBAL_MANAGER_STATUS interval requests, per gimbal.
Q_INVOKABLE void setGimbalRetract(bool set)
void showAcquireGimbalControlPopup()
void gimbalPitchStart(int direction)
Q_INVOKABLE void releaseGimbalControl()
Q_INVOKABLE void sendPitchBodyYaw(float pitch, float yaw, bool showError=true)
Q_INVOKABLE void tilt90Gimbal()
Definition Gimbal.h:9
void setAbsolutePitch(float absPitch)
Definition Gimbal.h:54
void setYawLock(bool yawLock)
Definition Gimbal.h:71
void setPitchRate(float pitchRate)
Definition Gimbal.h:69
void setManagerCompid(uint id)
Definition Gimbal.h:59
Fact * managerCompid()
Definition Gimbal.h:42
Fact * deviceId()
Definition Gimbal.h:41
void setAbsoluteYaw(float absYaw)
Definition Gimbal.h:56
void setYawRate(float yawRate)
Definition Gimbal.h:70
bool gimbalOthersHaveControl() const
Definition Gimbal.h:51
void setGimbalHaveControl(bool set)
Definition Gimbal.h:73
void setBodyYaw(float yaw)
Definition Gimbal.h:55
void setDeviceId(uint id)
Definition Gimbal.h:58
void setRetracted(bool retracted)
Definition Gimbal.h:72
void setDeviceName(const QString &name)
Definition Gimbal.h:61
bool gimbalHaveControl() const
Definition Gimbal.h:50
void setAbsoluteRoll(float absRoll)
Definition Gimbal.h:53
void setGimbalOthersHaveControl(bool set)
Definition Gimbal.h:74
void setDeltaYaw(float delta)
Definition Gimbal.h:57
void setCapabilityFlags(uint32_t flags)
Definition Gimbal.cc:76
static int getComponentId()
quint32 getSystemId() const
static MAVLinkProtocol * instance()
static SettingsManager * instance()
GimbalControllerSettings * gimbalControllerSettings() const
WeakLinkInterfacePtr primaryLink() const
void initialConnectComplete()
VehicleLinkManager * vehicleLinkManager()
Definition Vehicle.h:602
void mavlinkMessageReceived(const mavlink_message_t &message)
constexpr const char * toString(HwVideoBufferPath path) noexcept
Definition GstHwTypes.h:37
bool runningUnitTests()
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.
Definition AppMessages.cc:9
RequestMessageResultHandlerFailureCode_t