QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
PX4FirmwarePlugin.cc
Go to the documentation of this file.
1#include "PX4FirmwarePlugin.h"
2
3#include <algorithm>
4
5#include <QtCore/QString>
6
7#include "AppMessages.h"
8#include "MAVLinkLib.h"
11#include "PX4VehicleReadiness.h"
12#include "ParameterManager.h"
13#include "ParameterMetaData.h"
14#include "PlanViewSettings.h"
15#include "QGCLoggingCategory.h"
16#include "SettingsManager.h"
17#include "Vehicle.h"
18#include "px4_custom_mode.h"
19
20QGC_LOGGING_CATEGORY(PX4FirmwarePluginLog, "FirmwarePlugin.PX4FirmwarePlugin")
21
28
30{
31 const QString manualFlightModeName = tr("Manual");
32 const QString acroFlightModeName = tr("Acro");
33 const QString stabilizedFlightModeName = tr("Stabilized");
34 const QString rattitudeFlightModeName = tr("Rattitude");
35 const QString altCtlFlightModeName = tr("Altitude");
36 const QString posCtlFlightModeName = tr("Position");
37 const QString offboardFlightModeName = tr("Offboard");
38 const QString readyFlightModeName = tr("Ready");
39 const QString takeoffFlightModeName = tr("Takeoff");
40 const QString holdFlightModeName = tr("Hold");
41 const QString missionFlightModeName = tr("Mission");
42 const QString rtlFlightModeName = tr("Return");
43 const QString landingFlightModeName = tr("Land");
44 const QString preclandFlightModeName = tr("Precision Land");
45 const QString followMeFlightModeName = tr("Follow Me");
46 const QString simpleFlightModeName = tr("Simple");
47 const QString orbitFlightModeName = tr("Orbit");
48 const QString slowFlightModeName = tr("Position Slow");
49 const QString altitudeCruiseFlightModeName = tr("Altitude Cruise");
50 const QString terminationFlightModeName = tr("Termination");
51 const QString vtolTakeoffFlightModeName = tr("VTOL Takeoff");
52 const QString guidedCourseFlightModeName = tr("Guided Course");
53
55 { PX4CustomMode::MANUAL, manualFlightModeName },
56 { PX4CustomMode::STABILIZED, stabilizedFlightModeName },
57 { PX4CustomMode::ACRO, acroFlightModeName },
58 { PX4CustomMode::RATTITUDE, rattitudeFlightModeName },
59 { PX4CustomMode::ALTCTL, altCtlFlightModeName },
60 { PX4CustomMode::OFFBOARD, offboardFlightModeName },
61 { PX4CustomMode::SIMPLE, simpleFlightModeName },
62 { PX4CustomMode::POSCTL_POSCTL, posCtlFlightModeName },
63 { PX4CustomMode::POSCTL_ORBIT, orbitFlightModeName },
64 { PX4CustomMode::POSCTL_SLOW, slowFlightModeName },
65 { PX4CustomMode::ALTITUDE_CRUISE, altitudeCruiseFlightModeName },
66 { PX4CustomMode::TERMINATION, terminationFlightModeName },
67 { PX4CustomMode::AUTO_LOITER, holdFlightModeName },
68 { PX4CustomMode::AUTO_MISSION, missionFlightModeName },
69 { PX4CustomMode::AUTO_RTL, rtlFlightModeName },
70 { PX4CustomMode::AUTO_FOLLOW_TARGET, followMeFlightModeName },
71 { PX4CustomMode::AUTO_LAND, landingFlightModeName },
72 { PX4CustomMode::AUTO_PRECLAND, preclandFlightModeName },
73 { PX4CustomMode::AUTO_READY, readyFlightModeName },
74 { PX4CustomMode::AUTO_TAKEOFF, takeoffFlightModeName },
75 { PX4CustomMode::AUTO_VTOL_TAKEOFF, vtolTakeoffFlightModeName },
76 { PX4CustomMode::AUTO_GUIDED_COURSE, guidedCourseFlightModeName },
77 });
78
79 static FlightModeList availableFlightModes = {
80 // Mode Name Custom Mode CanBeSet adv
81 { manualFlightModeName, PX4CustomMode::MANUAL, true, true },
82 { stabilizedFlightModeName, PX4CustomMode::STABILIZED, true, true },
83 { acroFlightModeName, PX4CustomMode::ACRO, true, true },
84 { rattitudeFlightModeName, PX4CustomMode::RATTITUDE, true, false},
85 { altCtlFlightModeName, PX4CustomMode::ALTCTL, true, false},
86 { offboardFlightModeName, PX4CustomMode::OFFBOARD, true, true },
87 { simpleFlightModeName, PX4CustomMode::SIMPLE, false, false},
88 { posCtlFlightModeName, PX4CustomMode::POSCTL_POSCTL, true, false},
89 { slowFlightModeName, PX4CustomMode::POSCTL_SLOW, true, true },
90 { altitudeCruiseFlightModeName, PX4CustomMode::ALTITUDE_CRUISE, true, true },
91 { orbitFlightModeName, PX4CustomMode::POSCTL_ORBIT, false, true },
92 { holdFlightModeName, PX4CustomMode::AUTO_LOITER, true, true },
93 { missionFlightModeName, PX4CustomMode::AUTO_MISSION, true, true },
94 { rtlFlightModeName, PX4CustomMode::AUTO_RTL, true, true },
95 { followMeFlightModeName, PX4CustomMode::AUTO_FOLLOW_TARGET, false, true },
96 { landingFlightModeName, PX4CustomMode::AUTO_LAND, false, true },
97 { preclandFlightModeName, PX4CustomMode::AUTO_PRECLAND, true, true },
98 { readyFlightModeName, PX4CustomMode::AUTO_READY, false, false},
99 { takeoffFlightModeName, PX4CustomMode::AUTO_TAKEOFF, false, false},
100 { vtolTakeoffFlightModeName, PX4CustomMode::AUTO_VTOL_TAKEOFF, false, true },
101 { terminationFlightModeName, PX4CustomMode::TERMINATION, false, true },
102 { guidedCourseFlightModeName, PX4CustomMode::AUTO_GUIDED_COURSE, false, true },
103 };
104
105 updateAvailableFlightModes(availableFlightModes);
106}
107
111
113{
114 return new PX4AutoPilotPlugin(vehicle, vehicle);
115}
116
117QStringList PX4FirmwarePlugin::flightModes(Vehicle* vehicle) const
118{
119 QStringList flightModesList;
120
121 for (auto &mode : _flightModeList) {
122 if (mode.canBeSet){
123 bool fw = (vehicle->fixedWing() && mode.fixedWing);
124 bool mc = (vehicle->multiRotor() && mode.multiRotor);
125
126 // show all modes for generic, vtol, etc
127 bool other = !vehicle->fixedWing() && !vehicle->multiRotor();
128 if (fw || mc || other) {
129 flightModesList += mode.mode_name;
130 }
131 }
132 }
133
134 return flightModesList;
135}
136
137QString PX4FirmwarePlugin::flightMode(uint8_t base_mode, uint32_t custom_mode) const
138{
139 QString flightMode = "Unknown";
140
141 if (base_mode & MAV_MODE_FLAG_CUSTOM_MODE_ENABLED) {
142 return _modeEnumToString.value(custom_mode, tr("Unknown %1:%2").arg(base_mode).arg(custom_mode));
143 }
144
145 return flightMode;
146}
147
148bool PX4FirmwarePlugin::setFlightMode(const QString& flightMode, uint8_t* base_mode, uint32_t* custom_mode) const
149{
150 *base_mode = 0;
151 *custom_mode = 0;
152
153 bool found = false;
154
155 for (auto &mode: _flightModeList){
156 if(flightMode.compare(mode.mode_name, Qt::CaseInsensitive) == 0){
157 *base_mode = MAV_MODE_FLAG_CUSTOM_MODE_ENABLED;
158 *custom_mode = mode.custom_mode;
159 found = true;
160 break;
161 }
162 }
163
164 if (!found) {
165 qCWarning(PX4FirmwarePluginLog) << "Unknown flight Mode" << flightMode;
166 }
167
168 return found;
169}
170
171bool PX4FirmwarePlugin::isCapable(const Vehicle *vehicle, FirmwareCapabilities capabilities) const
172{
174 //-- This is arbitrary until I find how to really tell if ROI is avaiable
175 if (vehicle->multiRotor()) {
177 }
178 if (vehicle->multiRotor() || vehicle->vtol()) {
180 }
181 if (vehicle->vtol()) {
183 }
184 if (vehicle->fixedWing()) {
186 }
187 return (capabilities & available) == capabilities;
188}
189
194
196{
197 // PX4 stack does not want home position sent in the first position.
198 // Subsequent sequence numbers must be adjusted.
199 return false;
200}
201
203{
204 QList<MAV_CMD> supportedCommands = {
205 MAV_CMD_NAV_WAYPOINT,
206 MAV_CMD_NAV_LOITER_UNLIM, MAV_CMD_NAV_LOITER_TIME,
207 MAV_CMD_NAV_RETURN_TO_LAUNCH,
208 MAV_CMD_DO_JUMP,
209 MAV_CMD_DO_DIGICAM_CONTROL,
210 MAV_CMD_DO_SET_CAM_TRIGG_DIST,
211 MAV_CMD_DO_SET_SERVO,
212 MAV_CMD_DO_SET_ACTUATOR,
213 MAV_CMD_DO_CHANGE_SPEED,
214 MAV_CMD_DO_SET_HOME,
215 MAV_CMD_DO_LAND_START,
216 MAV_CMD_DO_SET_ROI_LOCATION, MAV_CMD_DO_SET_ROI_WPNEXT_OFFSET, MAV_CMD_DO_SET_ROI_NONE,
217 MAV_CMD_DO_MOUNT_CONFIGURE,
218 MAV_CMD_DO_MOUNT_CONTROL,
219 MAV_CMD_SET_CAMERA_MODE,
220 MAV_CMD_IMAGE_START_CAPTURE, MAV_CMD_IMAGE_STOP_CAPTURE, MAV_CMD_VIDEO_START_CAPTURE, MAV_CMD_VIDEO_STOP_CAPTURE,
221 MAV_CMD_NAV_DELAY,
222 MAV_CMD_CONDITION_YAW,
223 MAV_CMD_NAV_LOITER_TO_ALT,
224 MAV_CMD_DO_GRIPPER
225 };
226
227 QList<MAV_CMD> vtolCommands = {
228 MAV_CMD_DO_VTOL_TRANSITION, MAV_CMD_NAV_VTOL_TAKEOFF, MAV_CMD_NAV_VTOL_LAND,
229 };
230
231 QList<MAV_CMD> flightCommands = {
232 MAV_CMD_NAV_LAND, MAV_CMD_NAV_TAKEOFF,
233 };
234
235 if (vehicleClass == QGCMAVLink::VehicleClassGeneric) {
236 supportedCommands += vtolCommands;
237 supportedCommands += flightCommands;
238 }
239 if (vehicleClass == QGCMAVLink::VehicleClassVTOL) {
240 supportedCommands += vtolCommands;
241 supportedCommands += flightCommands;
242 } else if (vehicleClass == QGCMAVLink::VehicleClassFixedWing || vehicleClass == QGCMAVLink::VehicleClassMultiRotor) {
243 supportedCommands += flightCommands;
244 }
245
246 if (SettingsManager::instance()->planViewSettings()->useConditionGate()->rawValue().toBool()) {
247 supportedCommands.append(MAV_CMD_CONDITION_GATE);
248 }
249
250 return supportedCommands;
251}
252
254{
255 switch (vehicleClass) {
257 return QStringLiteral(":/json/PX4-MavCmdInfoCommon.json");
259 return QStringLiteral(":/json/PX4-MavCmdInfoFixedWing.json");
261 return QStringLiteral(":/json/PX4-MavCmdInfoMultiRotor.json");
263 return QStringLiteral(":/json/PX4-MavCmdInfoVTOL.json");
265 return QStringLiteral(":/json/PX4-MavCmdInfoSub.json");
267 return QStringLiteral(":/json/PX4-MavCmdInfoRover.json");
268 default:
269 qCWarning(PX4FirmwarePluginLog) << "PX4FirmwarePlugin::missionCommandOverrides called with bad VehicleClass_t:" << vehicleClass;
270 return QString();
271 }
272}
273
278
279namespace {
280
284void sendRepositionKeepLatLon(Vehicle* vehicle, float yaw, float amslAltitude,
285 const Vehicle::MavCmdAckHandlerInfo_t* ackHandlerInfo = nullptr)
286{
287 const int compId = vehicle->defaultComponentId();
288 const float groundSpeed = -1.0f; // no change
289 const float flags = MAV_DO_REPOSITION_FLAGS_CHANGE_MODE;
290 // PX4 before 1.12 advertises COMMAND_INT but reads the INT32_MAX "no change" latitude/longitude as
291 // 214.7483647 degrees
292 const bool commandInt =
293 (vehicle->capabilityBits() & MAV_PROTOCOL_CAPABILITY_COMMAND_INT) && (vehicle->versionCompare(1, 12, 0) >= 0);
294
295 if (commandInt) {
296 if (ackHandlerInfo) {
297 vehicle->sendMavCommandIntWithHandler(ackHandlerInfo, compId, MAV_CMD_DO_REPOSITION, MAV_FRAME_GLOBAL,
298 groundSpeed, flags, 0.0f, yaw, NAN, NAN, amslAltitude);
299 } else {
300 vehicle->sendMavCommandInt(compId, MAV_CMD_DO_REPOSITION, MAV_FRAME_GLOBAL, true /* showError */,
301 groundSpeed, flags, 0.0f, yaw, NAN, NAN, amslAltitude);
302 }
303 } else if (ackHandlerInfo) {
304 vehicle->sendMavCommandWithHandler(ackHandlerInfo, compId, MAV_CMD_DO_REPOSITION, groundSpeed, flags, 0.0f, yaw,
305 NAN, NAN, amslAltitude);
306 } else {
307 vehicle->sendMavCommand(compId, MAV_CMD_DO_REPOSITION, true /* showError */, groundSpeed, flags, 0.0f, yaw, NAN,
308 NAN, amslAltitude);
309 }
310}
311
312} // namespace
313
315{
316 sendRepositionKeepLatLon(vehicle, NAN, NAN);
317}
318
319void PX4FirmwarePlugin::guidedModeRTL(Vehicle* vehicle, bool smartRTL) const
320{
321 Q_UNUSED(smartRTL);
323}
324
329
330namespace {
331
332void px4TakeoffResultHandler(void* resultHandlerData, int /*compId*/, const mavlink_command_ack_t& ack,
334{
335 auto* vehicle = static_cast<Vehicle*>(resultHandlerData);
336
337 switch (failureCode) {
339 if (ack.result == MAV_RESULT_ACCEPTED) {
340 // Now that we are in takeoff mode we can arm the vehicle which will cause it to takeoff.
341 // We specifically don't retry arming if it fails. This way we don't fight with the user if
342 // They are trying to disarm.
343 if (!vehicle->armed()) {
344 vehicle->setArmedShowError(true);
345 }
346 } else {
348 }
349 break;
351 QGC::showAppMessage(PX4FirmwarePlugin::tr("Vehicle did not respond to takeoff command."));
352 break;
354 QGC::showAppMessage(PX4FirmwarePlugin::tr(
355 "Takeoff not sent: a previous takeoff command is still waiting for a vehicle response."));
356 break;
357 }
358}
359
360} // namespace
361
362void PX4FirmwarePlugin::guidedModeTakeoff(Vehicle* vehicle, double takeoffAltRel) const
363{
364 double vehicleAltitudeAMSL = vehicle->altitudeAMSL()->rawValue().toDouble();
365 if (qIsNaN(vehicleAltitudeAMSL)) {
366 QGC::showAppMessage(tr("Unable to takeoff, vehicle position not known."));
367 return;
368 }
369
370 double takeoffAltAMSL = takeoffAltRel + vehicleAltitudeAMSL;
371
372 Vehicle::MavCmdAckHandlerInfo_t handlerInfo = {};
373 handlerInfo.resultHandler = px4TakeoffResultHandler;
374 handlerInfo.resultHandlerData = vehicle;
375
376 vehicle->sendMavCommandWithHandler(&handlerInfo, vehicle->defaultComponentId(), MAV_CMD_NAV_TAKEOFF,
377 NAN, // No pitch requested
378 NAN, // param 2 unused
379 0, // param 3 takeoff flags
380 NAN, NAN, NAN, // No yaw, lat, lon
381 static_cast<float>(takeoffAltAMSL)); // AMSL altitude
382}
383
385{
386 QString speedParam("MPC_XY_VEL_MAX");
387
389 const Fact* speedFact =
391 if (speedFact) {
392 return speedFact->rawValue().toDouble();
393 }
394 }
395
397}
398
400{
401 QString airspeedMax("FW_AIRSPD_MAX");
402
404 const Fact* airspeedFact =
406 if (airspeedFact) {
407 return airspeedFact->rawValue().toDouble();
408 }
409 }
410
412}
413
415{
416 QString airspeedMin("FW_AIRSPD_MIN");
417
419 const Fact* airspeedFact =
421 if (airspeedFact) {
422 return airspeedFact->rawValue().toDouble();
423 }
424 }
425
427}
428
433
439
440bool PX4FirmwarePlugin::guidedModeGotoLocation(Vehicle* vehicle, const QGeoCoordinate& gotoCoord, double forwardFlightLoiterRadius) const
441{
442 // PX4 doesn't support setting the forward flight loiter radius of
443 // MAV_CMD_DO_REPOSITION
444 Q_UNUSED(forwardFlightLoiterRadius)
445
446 if (qIsNaN(vehicle->altitudeAMSL()->rawValue().toDouble())) {
447 QGC::showAppMessage(tr("Unable to go to location, vehicle position not known."));
448 return false;
449 }
450
451 if (vehicle->capabilityBits() & MAV_PROTOCOL_CAPABILITY_COMMAND_INT) {
452 vehicle->sendMavCommandInt(vehicle->defaultComponentId(),
453 MAV_CMD_DO_REPOSITION,
454 MAV_FRAME_GLOBAL,
455 true, // show error is fails
456 -1.0f,
457 MAV_DO_REPOSITION_FLAGS_CHANGE_MODE,
458 0.0f,
459 NAN,
460 gotoCoord.latitude(),
461 gotoCoord.longitude(),
462 vehicle->altitudeAMSL()->rawValue().toFloat());
463 } else {
464 vehicle->sendMavCommand(vehicle->defaultComponentId(),
465 MAV_CMD_DO_REPOSITION,
466 true, // show error is fails
467 -1.0f,
468 MAV_DO_REPOSITION_FLAGS_CHANGE_MODE,
469 0.0f,
470 NAN,
471 static_cast<float>(gotoCoord.latitude()),
472 static_cast<float>(gotoCoord.longitude()),
473 vehicle->altitudeAMSL()->rawValue().toFloat());
474 }
475
476 return true;
477}
478
484
485static void _pauseVehicleThenChangeAltResultHandler(void* resultHandlerData, int /*compId*/, const mavlink_command_ack_t& ack, Vehicle::MavCmdResultFailureCode_t failureCode)
486{
487 if (ack.result != MAV_RESULT_ACCEPTED) {
488 switch (failureCode) {
490 qCDebug(PX4FirmwarePluginLog) << QStringLiteral("MAV_CMD_DO_REPOSITION error(%1)").arg(ack.result);
491 break;
493 qCDebug(PX4FirmwarePluginLog) << "MAV_CMD_DO_REPOSITION no response from vehicle";
494 break;
496 qCDebug(PX4FirmwarePluginLog) << "Internal Error: MAV_CMD_DO_REPOSITION could not be sent due to duplicate command";
497 break;
498 }
499 }
500
501 PauseVehicleThenChangeAltData_t* pData = static_cast<PauseVehicleThenChangeAltData_t*>(resultHandlerData);
502 pData->plugin->_changeAltAfterPause(resultHandlerData, ack.result == MAV_RESULT_ACCEPTED /* pauseSucceeded */);
503}
504
505void PX4FirmwarePlugin::_changeAltAfterPause(void* resultHandlerData, bool pauseSucceeded)
506{
507 PauseVehicleThenChangeAltData_t* pData = static_cast<PauseVehicleThenChangeAltData_t*>(resultHandlerData);
508
509 if (pauseSucceeded) {
510 sendRepositionKeepLatLon(pData->vehicle, NAN, static_cast<float>(pData->newAMSLAlt));
511 } else {
512 QGC::showAppMessage(tr("Unable to pause vehicle."));
513 }
514
515 delete pData;
516}
517
518void PX4FirmwarePlugin::guidedModeChangeAltitude(Vehicle* vehicle, double altitudeChange, bool pauseVehicle)
519{
520 if (!vehicle->homePosition().isValid()) {
521 QGC::showAppMessage(tr("Unable to change altitude, home position unknown."));
522 return;
523 }
524 if (qIsNaN(vehicle->homePosition().altitude())) {
525 QGC::showAppMessage(tr("Unable to change altitude, home position altitude unknown."));
526 return;
527 }
528
529 double currentAltRel = vehicle->altitudeRelative()->rawValue().toDouble();
530 double newAltRel = currentAltRel + altitudeChange;
531
533 resultData->plugin = this;
534 resultData->vehicle = vehicle;
535 resultData->newAMSLAlt = vehicle->homePosition().altitude() + newAltRel;
536
537 if (pauseVehicle) {
538 Vehicle::MavCmdAckHandlerInfo_t handlerInfo = {};
540 handlerInfo.resultHandlerData = resultData;
541
542 sendRepositionKeepLatLon(vehicle, NAN, NAN, &handlerInfo);
543 } else {
544 _changeAltAfterPause(resultData, true /* pauseSucceeded */);
545 }
546}
547
549{
550
551 vehicle->sendMavCommand(
552 vehicle->defaultComponentId(),
553 MAV_CMD_DO_CHANGE_SPEED,
554 true, // show error is fails
555 1, // 0: airspeed, 1: groundspeed
556 static_cast<float>(groundspeed), // groundspeed setpoint
557 -1, // throttle
558 0, // 0: absolute speed, 1: relative to current
559 NAN, NAN,NAN); // param 5-7 unused
560}
561
563{
564
565 vehicle->sendMavCommand(
566 vehicle->defaultComponentId(),
567 MAV_CMD_DO_CHANGE_SPEED,
568 true, // show error is fails
569 0, // 0: airspeed, 1: groundspeed
570 static_cast<float>(airspeed_equiv), // groundspeed setpoint
571 -1, // throttle
572 0, // 0: absolute speed, 1: relative to current
573 NAN, NAN,NAN); // param 5-7 unused
574}
575
576void PX4FirmwarePlugin::guidedModeChangeHeading(Vehicle* vehicle, const QGeoCoordinate &headingCoord) const
577{
579 QGC::showAppMessage(tr("Vehicle does not support guided rotate"));
580 return;
581 }
582
583 const float radians = qDegreesToRadians(vehicle->coordinate().azimuthTo(headingCoord));
584
585 sendRepositionKeepLatLon(vehicle, radians, NAN);
586}
587
588bool PX4FirmwarePlugin::guidedModeROI(Vehicle* vehicle, const QGeoCoordinate& roiCenterCoord, double relativeAltitudeMeters) const
589{
590 // PX4 ignores the frame on MAV_CMD_DO_SET_ROI_LOCATION and treats the altitude as AMSL
591 // (PX4-Autopilot#28257), so convert above-home to AMSL before sending.
592 const QGeoCoordinate homePosition = vehicle->homePosition();
593 if (!homePosition.isValid() || qIsNaN(homePosition.altitude())) {
594 QGC::showAppMessage(tr("Unable to set ROI, home position altitude unknown."));
595 return false;
596 }
597
598 _sendROICommand(vehicle, roiCenterCoord, MAV_FRAME_GLOBAL, static_cast<float>(homePosition.altitude() + relativeAltitudeMeters));
599 return true;
600}
601
603{
605 if (!_armVehicleAndValidate(vehicle)) {
606 QGC::showAppMessage(tr("Unable to start takeoff: Vehicle rejected arming."));
607 return;
608 }
609 } else {
610 QGC::showAppMessage(tr("Unable to start takeoff: Vehicle not changing to %1 flight mode.").arg(takeOffFlightMode()));
611 }
612}
613
615{
617 if (!_armVehicleAndValidate(vehicle)) {
618 QGC::showAppMessage(tr("Unable to start mission: Vehicle rejected arming."));
619 return;
620 }
621 } else {
622 QGC::showAppMessage(tr("Unable to start mission: Vehicle not changing to %1 flight mode.").arg(missionFlightMode()));
623 }
624}
625
626void PX4FirmwarePlugin::setGuidedMode(Vehicle* vehicle, bool guidedMode) const
627{
628 if (guidedMode) {
630 } else {
631 pauseVehicle(vehicle);
632 }
633}
634
639
644
649
654
659
664
669
674
679
684
685bool PX4FirmwarePlugin::isGuidedMode(const Vehicle* vehicle) const
686{
687 // Not supported by generic vehicle
688 return (vehicle->flightMode() == pauseFlightMode() || vehicle->flightMode() == takeOffFlightMode() || vehicle->flightMode() == landFlightMode());
689}
690
692{
693 //-- Don't process messages to/from UDP Bridge. It doesn't suffer from these issues
694 if (message->compid == MAV_COMP_ID_UDP_BRIDGE) {
695 return true;
696 }
697
698 switch (message->msgid) {
699 case MAVLINK_MSG_ID_AUTOPILOT_VERSION:
700 _handleAutopilotVersion(vehicle, message);
701 break;
702 }
703
704 return true;
705}
706
707void PX4FirmwarePlugin::_handleAutopilotVersion(Vehicle* vehicle, mavlink_message_t* message)
708{
709 Q_UNUSED(vehicle);
710
711 auto* instanceData = qobject_cast<PX4FirmwarePluginInstanceData*>(vehicle->firmwarePluginInstanceData());
712 if (!instanceData->versionNotified) {
713 bool notifyUser = false;
714 int supportedMajorVersion = 1;
715 int supportedMinorVersion = 4;
716 int supportedPatchVersion = 1;
717
718 mavlink_autopilot_version_t version;
719 mavlink_msg_autopilot_version_decode(message, &version);
720
721 if (version.flight_sw_version != 0) {
722 int majorVersion, minorVersion, patchVersion;
723
724 majorVersion = (version.flight_sw_version >> (8*3)) & 0xFF;
725 minorVersion = (version.flight_sw_version >> (8*2)) & 0xFF;
726 patchVersion = (version.flight_sw_version >> (8*1)) & 0xFF;
727
728 if (majorVersion < supportedMajorVersion) {
729 notifyUser = true;
730 } else if (majorVersion == supportedMajorVersion) {
731 if (minorVersion < supportedMinorVersion) {
732 notifyUser = true;
733 } else if (minorVersion == supportedMinorVersion) {
734 notifyUser = patchVersion < supportedPatchVersion;
735 }
736 }
737 } else {
738 notifyUser = true;
739 }
740
741 if (notifyUser) {
742 instanceData->versionNotified = true;
743 QGC::showAppMessage(tr("QGroundControl supports PX4 Pro firmware Version %1.%2.%3 and above. You are using a version prior to that which will lead to unpredictable results. Please upgrade your firmware.").arg(supportedMajorVersion).arg(supportedMinorVersion).arg(supportedPatchVersion));
744 }
745 }
746}
747
748uint32_t PX4FirmwarePlugin::highLatencyCustomModeTo32Bits(uint16_t hlCustomMode) const
749{
750 union px4_custom_mode px4_cm;
751 px4_cm.data = 0;
752 px4_cm.custom_mode_hl = hlCustomMode;
753
754 return px4_cm.data;
755}
756
757QString PX4FirmwarePlugin::_getLatestVersionFileUrl(Vehicle* vehicle) const
758{
759 Q_UNUSED(vehicle);
760 return QStringLiteral("https://api.github.com/repos/PX4/Firmware/releases");
761}
762
764{
765 return QStringLiteral("v([0-9,\\.]*) Stable");
766}
767
769{
770 return ((vehicle->vehicleType() == MAV_TYPE_GROUND_ROVER) || (vehicle->vehicleType() == MAV_TYPE_SUBMARINE));
771}
772
774{
775 static const char* HOOBS_HI = "LND_FLIGHT_T_HI";
776 static const char* HOOBS_LO = "LND_FLIGHT_T_LO";
777 uint64_t hobbsTimeSeconds = 0;
778
783 hobbsTimeSeconds = ((uint64_t)factHi->rawValue().toUInt() << 32 | (uint64_t)factLo->rawValue().toUInt()) / 1000000;
784 qCDebug(PX4FirmwarePluginLog) << "Hobbs Meter raw PX4:" << "(" << factHi->rawValue().toUInt() << factLo->rawValue().toUInt() << ")";
785 }
786
787 int hours = hobbsTimeSeconds / 3600;
788 int minutes = (hobbsTimeSeconds % 3600) / 60;
789 int seconds = hobbsTimeSeconds % 60;
790 QString timeStr = QString::asprintf("%04d:%02d:%02d", hours, minutes, seconds);
791 qCDebug(PX4FirmwarePluginLog) << "Hobbs Meter string:" << timeStr;
792 return timeStr;
793}
794
795bool PX4FirmwarePlugin::hasGripper(const Vehicle* vehicle) const
796{
797 ParameterManager* paramMgr = vehicle->parameterManager();
798
799 // PX4 versions prior to v1.17 use the PD_GRIPPER_EN boolean
800 const QString gripperEnableParam = QStringLiteral("PD_GRIPPER_EN");
801 if (paramMgr->parameterExists(ParameterManager::defaultComponentId, gripperEnableParam)) {
802 const Fact* gripperFact = paramMgr->getParameter(ParameterManager::defaultComponentId, gripperEnableParam);
803 return gripperFact && gripperFact->rawValue().toInt() != 0;
804 }
805
806 // PX4 v1.17+ removed PD_GRIPPER_EN; PD_GRIPPER_TYPE >= 0 means enabled (-1 = Undefined)
807 const QString gripperTypeParam = QStringLiteral("PD_GRIPPER_TYPE");
808 if (paramMgr->parameterExists(ParameterManager::defaultComponentId, gripperTypeParam)) {
809 const Fact* gripperFact = paramMgr->getParameter(ParameterManager::defaultComponentId, gripperTypeParam);
810 return gripperFact && gripperFact->rawValue().toInt() >= 0;
811 }
812
813 return false;
814}
815
817{
818 for(auto &mode: modeList){
819 PX4CustomMode::Mode cMode = static_cast<PX4CustomMode::Mode>(mode.custom_mode);
820
821 // Update Multi Rotor
822 switch (cMode) {
841 mode.multiRotor = true;
842 break;
847 mode.multiRotor = false;
848 break;
849 }
850
851 // Update Fixed Wing
852 switch (cMode){
858 mode.fixedWing = false;
859 break;
877 mode.fixedWing = true;
878 break;
879 }
880 }
881 _updateFlightModeList(modeList);
882}
883
884QString PX4FirmwarePlugin::externalFlightModeName(const FlightModeList& modeList, int externalIndex)
885{
887 "kExternalFlightModeCount must match the PX4 external sub modes");
888 if ((externalIndex < 1) || (externalIndex > kExternalFlightModeCount)) {
889 return QString();
890 }
891
892 px4_custom_mode customMode{};
894 customMode.sub_mode = static_cast<uint8_t>(PX4_CUSTOM_SUB_MODE_EXTERNAL1 + externalIndex - 1);
895 const auto mode = std::find_if(modeList.cbegin(), modeList.cend(), [&customMode](const FirmwareFlightMode& entry) {
896 return entry.custom_mode == customMode.data;
897 });
898 if (mode == modeList.cend()) {
899 return QString();
900 }
901 const QString& name = mode->mode_name;
902
903 // PX4 reports external slots with no registered mode under this name (AVAILABLE_MODES.hpp). QGC may have added
904 // " (N)" to keep the names unique.
905 if (name.startsWith(QStringLiteral("(Mode not available)"))) {
906 return QString();
907 }
908 return name;
909}
910
912{
913 QStringList names;
914 for (int externalIndex = 1; externalIndex <= kExternalFlightModeCount; externalIndex++) {
915 names.append(externalFlightModeName(modeList, externalIndex));
916 }
917
918 return names;
919}
920
921QVariant PX4FirmwarePlugin::expandedToolbarIndicatorSource(const Vehicle* /*vehicle*/, const QString& indicatorName) const
922{
923 if (indicatorName == "Battery") {
924 return QVariant::fromValue(QUrl::fromUserInput("qrc:/qml/QGroundControl/FirmwarePlugin/PX4/PX4BatteryIndicator.qml"));
925 } else if (indicatorName == "FlightMode") {
926 return QVariant::fromValue(QUrl::fromUserInput("qrc:/qml/QGroundControl/FirmwarePlugin/PX4/PX4FlightModeIndicator.qml"));
927 }
928
929 return QVariant();
930}
QList< FirmwareFlightMode > FlightModeList
static void _pauseVehicleThenChangeAltResultHandler(void *resultHandlerData, int, const mavlink_command_ack_t &ack, Vehicle::MavCmdResultFailureCode_t failureCode)
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
struct __mavlink_command_ack_t mavlink_command_ack_t
The AutoPilotPlugin class is an abstract base class which represents the methods and objects which ar...
A Fact is used to hold a single value within the system.
Definition Fact.h:15
QVariant rawValue() const
Definition Fact.h:87
void _setModeEnumToModeStringMapping(FlightModeCustomModeMap enumToString)
FlightModeList _flightModeList
virtual double minimumEquivalentAirspeed(Vehicle *) const
FirmwareCapabilities
Set of optional capabilites which firmware may support.
@ ChangeHeadingCapability
Vehicle supports changing heading at current location.
@ GuidedTakeoffCapability
Vehicle supports guided takeoff.
@ TakeoffVehicleCapability
Vehicle supports taking off.
@ GuidedModeCapability
Vehicle supports guided mode commands.
@ OrbitModeCapability
Vehicle supports orbit mode.
@ SetFlightModeCapability
FirmwarePlugin::setFlightMode method is supported.
@ VTOLMulticopterTakeoffCapability
VTOL supports MAV_CMD_NAV_TAKEOFF while remaining in multicopter mode.
@ ROIModeCapability
Vehicle supports ROI (both in Fly guided mode and from Plan creation).
@ PauseVehicleCapability
Vehicle supports pausing at current location.
void _sendROICommand(Vehicle *vehicle, const QGeoCoordinate &coord, MAV_FRAME frame, float altitude) const
Build + send MAV_CMD_DO_SET_ROI_LOCATION (COMMAND_INT when the vehicle supports it).
virtual double maximumEquivalentAirspeed(Vehicle *) const
bool _setFlightModeAndValidate(Vehicle *vehicle, const QString &flightMode) const
void _updateFlightModeList(FlightModeList &flightModeList)
virtual QString _versionRegex() const
Returns regex QString to extract version information from text.
bool _armVehicleAndValidate(Vehicle *vehicle) const
FlightModeCustomModeMap _modeEnumToString
virtual double maximumHorizontalSpeedMultirotorMetersSecond(Vehicle *) const
bool versionNotified
true: user notified over version issue
PX4FirmwarePluginInstanceData(QObject *parent=nullptr)
void initializeVehicle(Vehicle *vehicle) override
Called when Vehicle is first created to perform any firmware specific setup.
bool isCapable(const Vehicle *vehicle, FirmwareCapabilities capabilities) const override
bool adjustIncomingMavlinkMessage(Vehicle *vehicle, mavlink_message_t *message) override
VehicleReadiness * createVehicleReadiness(Vehicle *vehicle) const override
void setGuidedMode(Vehicle *vehicle, bool guidedMode) const override
Set guided flight mode.
QString gotoFlightMode(void) const override
Returns the flight mode which the vehicle will be in if it is performing a goto location.
QList< MAV_CMD > supportedMissionCommands(QGCMAVLink::VehicleClass_t vehicleClass) const override
List of supported mission commands. Empty list for all commands supported.
bool guidedModeGotoLocation(Vehicle *vehicle, const QGeoCoordinate &gotoCoord, double forwardFlightLoiterRadius) const override
QString flightMode(uint8_t base_mode, uint32_t custom_mode) const override
QString takeOffFlightMode(void) const override
Returns the flight mode for TakeOff.
QString pauseFlightMode(void) const override
Returns The flight mode which indicates the vehicle is paused.
bool sendHomePositionToVehicle(void) const override
bool setFlightMode(const QString &flightMode, uint8_t *base_mode, uint32_t *custom_mode) const override
void startMission(Vehicle *vehicle) const override
Command the vehicle to start the mission.
void updateAvailableFlightModes(FlightModeList &modeList) override
Update Available flight modes received from vehicle.
ParameterMetaData * _createParameterMetaData() final
static QString externalFlightModeName(const FlightModeList &modeList, int externalIndex)
Name a vehicle's AVAILABLE_MODES list gives an External Mode (1-based), empty if no mode is registere...
QString takeControlFlightMode(void) const override
Returns the flight mode to use when the operator wants to take back control from autonomouse flight.
bool fixedWingAirSpeedLimitsAvailable(Vehicle *vehicle) const override
QString missionFlightMode(void) const override
Returns the flight mode for running missions.
void pauseVehicle(Vehicle *vehicle) const override
QString landFlightMode(void) const override
Returns the flight mode for Land.
QString rtlFlightMode(void) const override
Returns the flight mode for RTL.
static constexpr int kExternalFlightModeCount
Number of PX4 External Mode slots. PX4FirmwarePlugin.cc checks it against px4_custom_mode....
void guidedModeRTL(Vehicle *vehicle, bool smartRTL) const override
Command vehicle to return to launch.
void guidedModeChangeHeading(Vehicle *vehicle, const QGeoCoordinate &headingCoord) const override
Command vehicle to rotate towards specified location.
bool guidedModeROI(Vehicle *vehicle, const QGeoCoordinate &roiCenterCoord, double relativeAltitudeMeters) const override
uint32_t highLatencyCustomModeTo32Bits(uint16_t hlCustomMode) const override
Convert from HIGH_LATENCY2.custom_mode value to correct 32 bit value.
void startTakeoff(Vehicle *vehicle) const override
Command the vehicle to start a takeoff.
double maximumHorizontalSpeedMultirotorMetersSecond(Vehicle *vehicle) const override
QStringList flightModes(Vehicle *vehicle) const override
QString getHobbsMeter(Vehicle *vehicle) const override
gets hobbs meter from autopilot. This should be reimplmeented for each firmware
bool isGuidedMode(const Vehicle *vehicle) const override
Returns whether the vehicle is in guided mode or not.
void guidedModeTakeoff(Vehicle *vehicle, double takeoffAltRel) const override
Command vehicle to takeoff from current location to the specified height.
QVariant expandedToolbarIndicatorSource(const Vehicle *vehicle, const QString &indicatorName) const override
double minimumEquivalentAirspeed(Vehicle *vehicle) const override
QString followFlightMode(void) const override
Returns the flight mode which the vehicle will be for follow me.
void guidedModeChangeEquivalentAirspeedMetersSecond(Vehicle *vehicle, double airspeed_equiv) const override
bool supportsNegativeThrust(Vehicle *vehicle) const override
bool mulirotorSpeedLimitsAvailable(Vehicle *vehicle) const override
QString missionCommandOverrides(QGCMAVLink::VehicleClass_t vehicleClass) const override
double maximumEquivalentAirspeed(Vehicle *vehicle) const override
void guidedModeChangeAltitude(Vehicle *vehicle, double altitudeRel, bool pauseVehicle) override
QString stabilizedFlightMode(void) const override
Returns the flight mode for Stabilized.
void _changeAltAfterPause(void *resultHandlerData, bool pauseSucceeded)
AutoPilotPlugin * autopilotPlugin(Vehicle *vehicle) const override
bool hasGripper(const Vehicle *vehicle) const override
static QStringList externalFlightModeNames(const FlightModeList &modeList)
externalFlightModeName of each of External Mode 1-8, in order
void guidedModeChangeGroundSpeedMetersSecond(Vehicle *vehicle, double groundspeed) const override
void guidedModeLand(Vehicle *vehicle) const override
Command vehicle to land at current location.
PX4 guided action readiness.
bool parameterExists(int componentId, const QString &paramName) const
Fact * getParameter(int componentId, const QString &paramName)
static constexpr int defaultComponentId
static SettingsManager * instance()
Whether the vehicle would accept the Arm, Takeoff and Start Mission guided actions.
void sendMavCommand(int compId, MAV_CMD command, bool showError, float param1=0.0f, float param2=0.0f, float param3=0.0f, float param4=0.0f, float param5=0.0f, float param6=0.0f, float param7=0.0f)
Definition Vehicle.cc:2196
QString flightMode() const
Definition Vehicle.cc:1515
bool vtol() const
Definition Vehicle.cc:1808
QGeoCoordinate homePosition()
Definition Vehicle.cc:1481
bool multiRotor() const
Definition Vehicle.cc:1803
void setFirmwarePluginInstanceData(FirmwarePluginInstanceData *firmwarePluginInstanceData)
Definition Vehicle.cc:2614
uint64_t capabilityBits() const
Definition Vehicle.h:732
static void showCommandAckError(const mavlink_command_ack_t &ack)
Definition Vehicle.cc:2255
MAV_TYPE vehicleType() const
Definition Vehicle.h:449
void sendMavCommandInt(int compId, MAV_CMD command, MAV_FRAME frame, bool showError, float param1, float param2, float param3, float param4, double param5, double param6, float param7)
Definition Vehicle.cc:2225
int defaultComponentId() const
Definition Vehicle.h:705
ParameterManager * parameterManager()
Definition Vehicle.h:600
bool fixedWing() const
Definition Vehicle.cc:1783
QGeoCoordinate coordinate()
Definition Vehicle.h:430
void sendMavCommandIntWithHandler(const MavCmdAckHandlerInfo_t *ackHandlerInfo, int compId, MAV_CMD command, MAV_FRAME frame, float param1=0.0f, float param2=0.0f, float param3=0.0f, float param4=0.0f, double param5=0.0f, double param6=0.0f, float param7=0.0f)
Definition Vehicle.cc:2230
bool armed() const
Definition Vehicle.h:470
class FirmwarePluginInstanceData * firmwarePluginInstanceData()
Definition Vehicle.h:720
Q_INVOKABLE int versionCompare(const QString &compare) const
Used to check if running current version is equal or higher than the one being compared.
Definition Vehicle.cc:2833
void sendMavCommandWithHandler(const MavCmdAckHandlerInfo_t *ackHandlerInfo, int compId, MAV_CMD command, float param1=0.0f, float param2=0.0f, float param3=0.0f, float param4=0.0f, float param5=0.0f, float param6=0.0f, float param7=0.0f)
Sends the command and calls the callback with the result.
Definition Vehicle.cc:2220
void setArmedShowError(bool armed)
Definition Vehicle.h:472
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.
Definition AppMessages.cc:9
@ PX4_CUSTOM_MAIN_MODE_AUTO
@ PX4_CUSTOM_SUB_MODE_EXTERNAL1
@ PX4_CUSTOM_SUB_MODE_EXTERNAL8
static constexpr VehicleClass_t VehicleClassGeneric
MavCmdResultHandler resultHandler
nullptr for no handler
struct VehicleTypes::MavCmdAckHandlerInfo_s MavCmdAckHandlerInfo_t
Callback info bundle for sendMavCommandWithHandler.
@ MavCmdResultFailureDuplicateCommand
Unable to send command since duplicate is already being waited on for response.
@ MavCmdResultCommandResultOnly
commandResult specifies full success/fail info
@ MavCmdResultFailureNoResponseToCommand
No response from vehicle to command.
uint16_t custom_mode_hl