5#include <QtCore/QRegularExpression>
6#include <QtCore/QSettings>
7#include <QtCore/QStandardPaths>
8#include <QtCore/QThread>
38 qCDebug(FirmwarePluginLog) <<
this;
43 qCDebug(FirmwarePluginLog) <<
this;
53 Q_UNUSED(custom_mode);
56 const uint8_t baseModeBit;
60 static constexpr Bit2Name rgBit2Name[] = {
61 { MAV_MODE_FLAG_MANUAL_INPUT_ENABLED,
"Manual" },
62 { MAV_MODE_FLAG_STABILIZE_ENABLED,
"Stabilize" },
63 { MAV_MODE_FLAG_GUIDED_ENABLED,
"Guided" },
64 { MAV_MODE_FLAG_AUTO_ENABLED,
"Auto" },
65 { MAV_MODE_FLAG_TEST_ENABLED,
"Test" },
71 }
else if (base_mode & MAV_MODE_FLAG_CUSTOM_MODE_ENABLED) {
74 for (
size_t i = 0; i < std::size(rgBit2Name); i++) {
75 if (base_mode & rgBit2Name[i].baseModeBit) {
91 Q_UNUSED(custom_mode);
93 qCWarning(FirmwarePluginLog) <<
"FirmwarePlugin::setFlightMode called on base class, not supported";
100 switch (vehicleClass) {
102 return QStringLiteral(
":/json/MavCmdInfoCommon.json");
104 return QStringLiteral(
":/json/MavCmdInfoFixedWing.json");
106 return QStringLiteral(
":/json/MavCmdInfoMultiRotor.json");
108 return QStringLiteral(
":/json/MavCmdInfoVTOL.json");
110 return QStringLiteral(
":/json/MavCmdInfoSub.json");
112 return QStringLiteral(
":/json/MavCmdInfoRover.json");
114 qCWarning(FirmwarePluginLog) <<
"FirmwarePlugin::missionCommandOverrides called with bad VehicleClass_t:" << vehicleClass;
122 Q_UNUSED(guidedMode);
148 Q_UNUSED(takeoffAltRel);
156 Q_UNUSED(forwardFlightLoiterRadius);
186 _sendROICommand(vehicle, roiCenterCoord, MAV_FRAME_GLOBAL_RELATIVE_ALT,
static_cast<float>(relativeAltitudeMeters));
192 qCDebug(FirmwarePluginLog) <<
"_sendROICommand: lat" << coord.latitude() <<
"lon" << coord.longitude()
193 <<
"frame" << frame <<
"altitude" << altitude;
195 if (vehicle->
capabilityBits() & MAV_PROTOCOL_CAPABILITY_COMMAND_INT) {
198 MAV_CMD_DO_SET_ROI_LOCATION,
201 static_cast<float>(qQNaN()),
202 static_cast<float>(qQNaN()),
203 static_cast<float>(qQNaN()),
204 static_cast<float>(qQNaN()),
211 MAV_CMD_DO_SET_ROI_LOCATION,
213 static_cast<float>(qQNaN()),
214 static_cast<float>(qQNaN()),
215 static_cast<float>(qQNaN()),
216 static_cast<float>(qQNaN()),
217 static_cast<float>(coord.latitude()),
218 static_cast<float>(coord.longitude()),
246 QVariant::fromValue(QUrl::fromUserInput(
"qrc:/qml/QGroundControl/Toolbar/TelemetryRSSIIndicator.qml")),
247 QVariant::fromValue(QUrl::fromUserInput(
"qrc:/qml/QGroundControl/Toolbar/RCRSSIIndicator.qml")),
248 QVariant::fromValue(QUrl::fromUserInput(
"qrc:/qml/QGroundControl/Toolbar/BatteryIndicator.qml")),
249 QVariant::fromValue(QUrl::fromUserInput(
"qrc:/qml/QGroundControl/Toolbar/RemoteIDIndicator.qml")),
250 QVariant::fromValue(QUrl::fromUserInput(
"qrc:/qml/QGroundControl/Toolbar/GimbalIndicator.qml")),
251 QVariant::fromValue(QUrl::fromUserInput(
"qrc:/qml/QGroundControl/Toolbar/EscIndicator.qml")),
252 QVariant::fromValue(QUrl::fromUserInput(
"qrc:/qml/QGroundControl/Toolbar/JoystickIndicator.qml")),
253 QVariant::fromValue(QUrl::fromUserInput(
"qrc:/qml/QGroundControl/Toolbar/MultiVehicleSelector.qml")),
256 QVariant::fromValue(QUrl::fromUserInput(
"qrc:/qml/QGroundControl/Toolbar/GCSControlIndicator.qml")),
266 if (vehicle->
armed()) {
270 bool vehicleArmed =
false;
276 for (
int i = 0; i < 15; i++) {
277 if (vehicle->
armed()) {
281 QThread::msleep(100);
282 QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
294 bool flightModeChanged =
false;
297 for (
int retries = 0; retries < 3; retries++) {
301 for (
int i = 0; i < 13; i++) {
303 flightModeChanged =
true;
306 QThread::msleep(100);
307 QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
310 if (flightModeChanged) {
315 return flightModeChanged;
330 rollSupported =
false;
331 pitchSupported =
false;
332 yawSupported =
false;
350 qCDebug(FirmwarePluginLog) <<
"Skipping version check";
355 qCDebug(FirmwarePluginLog) <<
"Downloading" << versionFile;
357 (void) connect(downloader, &
QGCFileDownload::finished,
this, [vehicle,
this, versionFile](
bool success,
const QString &localFile,
const QString &errorMsg) {
360 }
else if (!errorMsg.isEmpty()) {
361 qCDebug(FirmwarePluginLog) <<
"Failed to download the latest fw version file. Error:" << errorMsg;
363 sender()->deleteLater();
366 if (!downloader->
start(versionFile)) {
367 downloader->deleteLater();
374 qCDebug(FirmwarePluginLog) <<
"Download complete" << remoteFile << localFile;
376 QFile versionFile(localFile);
377 if (!versionFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
378 qCWarning(FirmwarePluginLog) <<
"Error opening downloaded version file.";
382 QTextStream stream(&versionFile);
383 const QString versionFileContents = stream.readAll();
385 const QRegularExpressionMatch match = QRegularExpression(
_versionRegex()).match(versionFileContents);
387 qCDebug(FirmwarePluginLog) <<
"Looking for version number...";
389 if (match.hasMatch()) {
390 version = match.captured(1);
392 qCWarning(FirmwarePluginLog) <<
"Unable to parse version info from file" << remoteFile;
396 qCDebug(FirmwarePluginLog) <<
"Latest stable version = " << version;
401 if ((currType == FIRMWARE_VERSION_TYPE_OFFICIAL) && (vehicle->
versionCompare(version) < 0)) {
402 const QString currentVersionNumber = QStringLiteral(
"%1.%2.%3").arg(vehicle->
firmwareMajorVersion())
408 settings.beginGroup(QStringLiteral(
"LastNotifiedStableFirmware"));
413 settings.setValue(settingsKey, version);
415 QGC::showAppMessage(tr(
"Vehicle is not running latest stable firmware! Running %1, latest stable is %2.").arg(currentVersionNumber, version));
439 if ((currMajor == major) && (currMinor == minor) && (currPatch == patch)) {
443 if ((currMajor > major)
444 || ((currMajor == major) && (currMinor > minor))
445 || ((currMajor == major) && (currMinor == minor) && (currPatch > patch)))
455 const QStringList versionNumbers = compare.split(
".");
456 if (versionNumbers.size() != 3) {
457 qCWarning(FirmwarePluginLog) <<
"Error parsing version number: wrong format";
461 const int major = versionNumbers[0].toInt();
462 const int minor = versionNumbers[1].toInt();
463 const int patch = versionNumbers[2].toInt();
470 const float altitude =
static_cast<float>(motionReport.
altMetersAMSL);
471 if (!vehicle || !qIsFinite(altitude)) {
472 qCDebug(FirmwarePluginLog) <<
"Follow target requires a vehicle and finite altitude";
480 mavlink_follow_target_t follow_target{};
482 follow_target.timestamp =
qgcApp()->msecsSinceBoot();
483 follow_target.est_capabilities = estimationCapabilities;
484 follow_target.position_cov[0] =
static_cast<float>(motionReport.
pos_std_dev[0]);
485 follow_target.position_cov[2] =
static_cast<float>(motionReport.
pos_std_dev[2]);
486 follow_target.alt = altitude;
487 follow_target.lat = motionReport.
lat_int;
488 follow_target.lon = motionReport.
lon_int;
489 follow_target.vel[0] =
static_cast<float>(motionReport.
vxMetersPerSec);
490 follow_target.vel[1] =
static_cast<float>(motionReport.
vyMetersPerSec);
495 sharedLink->mavlinkChannel(), &message, &follow_target);
521 qCDebug(FirmwarePluginLog) <<
"Flight Mode:" <<
flightMode.mode_name <<
" Custom Mode:" <<
flightMode.custom_mode;
528 if (existingFlightMode.custom_mode == newFlightMode.
custom_mode) {
529 qCDebug(FirmwarePluginLog) <<
"Flight Mode:" << newFlightMode.
mode_name <<
" Custom Mode:" << newFlightMode.
custom_mode
530 <<
" already exists, not adding again.";
543 const QString path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
544 + QStringLiteral(
"/ParameterMetaData");
556 qCDebug(FirmwarePluginLog) <<
"No parameter metadata parser for firmware plugin" <<
this <<
"(expected for generic firmware)";
558 qCWarning(FirmwarePluginLog) <<
"No parameter metadata parser for firmware plugin" <<
this;
564 if (!metaDataFile.isEmpty()) {
573 if (autopilot == MAV_AUTOPILOT_GENERIC) {
580 qCDebug(FirmwarePluginLog) <<
"Using internal parameter metadata:" << internalFile;
585 if (internalVersion.isNull()) {
591 if (internalVersion.isNull()) {
592 qCDebug(FirmwarePluginLog) <<
"Using internal parameter metadata:" << internalFile;
596 const int wantedMajorVersion = internalVersion.majorVersion();
600 const QStringList entries = cacheDir.entryList(QStringList(wildcard), QDir::Files);
603 QVersionNumber bestVersion;
604 for (
const QString &entry : entries) {
606 if (ver.isNull() || ver.majorVersion() != wantedMajorVersion) {
609 if (bestVersion.isNull() || ver > bestVersion) {
611 bestFile = cacheDir.filePath(entry);
615 if (bestFile.isEmpty()) {
616 qCDebug(FirmwarePluginLog) <<
"No cached parameter metadata found, using internal:" << internalFile;
620 if (internalVersion.majorVersion() == wantedMajorVersion && bestVersion <= internalVersion) {
621 qCDebug(FirmwarePluginLog) <<
"Internal metadata" << internalVersion.toString() <<
">= cache" << bestVersion.toString()
622 <<
"— using internal:" << internalFile;
625 qCDebug(FirmwarePluginLog) <<
"Using cached parameter metadata" << bestVersion.toString() <<
":" << bestFile;
632 if (autopilot == MAV_AUTOPILOT_GENERIC) {
638 if (data.isEmpty()) {
639 qCWarning(FirmwarePluginLog) <<
"Cannot cache parameter metadata: failed to read" << metaDataFile << readError;
645 bool validJson =
false;
648 qCDebug(FirmwarePluginLog) <<
"Skipping cache of non-JSON parameter metadata:" << metaDataFile;
651 if (newVersion.isNull()) {
655 newVersion = QVersionNumber(1, 0);
658 const int majorVersion = newVersion.majorVersion();
661 const QString wildcard = QStringLiteral(
"%1_%2.%3.*.json").arg(
kCachedMetaDataFilePrefix).arg(autopilot).arg(majorVersion);
662 const QStringList existing = cacheDir.entryList(QStringList(wildcard), QDir::Files);
664 for (
const QString &file : existing) {
669 if (!existingVersion.isNull() && newVersion < existingVersion) {
674 const QString cachePath = cacheDir.filePath(
675 QStringLiteral(
"%1_%2.%3.%4.json").arg(
kCachedMetaDataFilePrefix).arg(autopilot).arg(majorVersion).arg(newVersion.minorVersion()));
677 qCWarning(FirmwarePluginLog) <<
"Failed to cache parameter metadata to" << cachePath;
681 for (
const QString &file : existing) {
682 const QString fullPath = cacheDir.filePath(file);
683 if (fullPath != cachePath && !QFile::remove(fullPath)) {
684 qCWarning(FirmwarePluginLog) <<
"Failed to remove old cache file:" << file;
static constexpr const char * kCachedMetaDataFilePrefix
static const QString guided_mode_not_supported_by_vehicle
static QDir _parameterMetaDataCacheDir(bool ensureExists=false)
QList< FirmwareFlightMode > FlightModeList
std::shared_ptr< LinkInterface > SharedLinkInterfacePtr
struct __mavlink_message mavlink_message_t
Unified file download utility with decompression, verification, and QML support.
#define QGC_LOGGING_CATEGORY(name, categoryStr)
struct __mavlink_camera_information_t mavlink_camera_information_t
The AutoPilotPlugin class is an abstract base class which represents the methods and objects which ar...
virtual CommandSupportedResult anyVersionSupportsCommand(MAV_CMD) const
CommandSupportedResult getCommandSupported(MAV_CMD cmd) const
virtual void guidedModeChangeEquivalentAirspeedMetersSecond(Vehicle *vehicle, double airspeed_equiv) const
virtual void guidedModeChangeAltitude(Vehicle *vehicle, double altitudeChange, bool pauseVehicle)
virtual void startMission(Vehicle *vehicle) const
Command the vehicle to start the mission.
virtual void checkIfIsLatestStable(Vehicle *vehicle) const
Used to check if running firmware is latest stable version.
FlightModeList _flightModeList
virtual const QVariantList & toolIndicators(const Vehicle *vehicle)
virtual void guidedModeChangeGroundSpeedMetersSecond(Vehicle *vehicle, double groundspeed) const
virtual VehicleReadiness * createVehicleReadiness(Vehicle *vehicle) const
virtual bool setFlightMode(const QString &flightMode, uint8_t *base_mode, uint32_t *custom_mode) const
virtual ~FirmwarePlugin()
virtual void _versionFileDownloadFinished(const QString &remoteFile, const QString &localFile, Vehicle *vehicle) const
Callback to process file with latest release information.
virtual void guidedModeTakeoff(Vehicle *vehicle, double takeoffAltRel) const
Command vehicle to takeoff from current location to the specified height.
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).
void cacheParameterMetaDataFile(const QString &metaDataFile)
virtual QString missionCommandOverrides(QGCMAVLinkTypes::VehicleClass_t vehicleClass) const
bool _setFlightModeAndValidate(Vehicle *vehicle, const QString &flightMode) const
virtual QString _internalParameterMetaDataFile(const Vehicle *) const
virtual QString _getLatestVersionFileUrl(Vehicle *) const
returns url with latest firmware release information.
void _updateFlightModeList(FlightModeList &flightModeList)
virtual void guidedModeChangeHeading(Vehicle *vehicle, const QGeoCoordinate &headingCoord) const
Command vehicle to rotate towards specified location.
virtual bool guidedModeGotoLocation(Vehicle *vehicle, const QGeoCoordinate &gotoCoord, double forwardFlightLoiterRadius=0.0) const
static QString stableFirmwareSettingsKey(const Vehicle *vehicle)
Settings key identifying the stable firmware stream (firmware + vehicle class) for this vehicle.
virtual QString flightMode(uint8_t base_mode, uint32_t custom_mode) const
virtual void startTakeoff(Vehicle *vehicle) const
Command the vehicle to start a takeoff.
void _addNewFlightMode(FirmwareFlightMode &flightMode)
virtual void pauseVehicle(Vehicle *vehicle) const
virtual MAV_AUTOPILOT _autopilotType() const
int versionCompare(const Vehicle *vehicle, const QString &compare) const
virtual Autotune * createAutotune(Vehicle *vehicle) const
Creates Autotune object.
static bool isStableFirmwareVersionUnseen(const QString &latestVersion, const QString &seenVersion)
ParameterMetaData * loadParameterMetaData(const Vehicle *vehicle)
virtual AutoPilotPlugin * autopilotPlugin(Vehicle *vehicle) const
virtual void guidedModeRTL(Vehicle *vehicle, bool smartRTL) const
Command vehicle to return to launch.
virtual ParameterMetaData * _createParameterMetaData()
virtual QString _versionRegex() const
Returns regex QString to extract version information from text.
bool _armVehicleAndValidate(Vehicle *vehicle) const
QVariantList _toolIndicatorList
QString _cachedParameterMetaDataFile(const Vehicle *vehicle) const
virtual void setGuidedMode(Vehicle *vehicle, bool guidedMode) const
Set guided flight mode.
FlightModeCustomModeMap _modeEnumToString
virtual bool guidedModeROI(Vehicle *vehicle, const QGeoCoordinate &roiCenterCoord, double relativeAltitudeMeters) const
virtual void batteryConsumptionData(Vehicle *vehicle, int &mAhBattery, double &hoverAmps, double &cruiseAmps) const
virtual QGCCameraManager * createCameraManager(Vehicle *vehicle) const
Creates vehicle camera manager.
virtual void sendGCSMotionReport(Vehicle *vehicle, const FollowMe::GCSMotionReport &motionReport, uint8_t estimationCapabilities) const
Sends the appropriate mavlink message for follow me support.
QMap< int, remapParamNameMinorVersionRemapMap_t > remapParamNameMajorVersionMap_t
virtual const remapParamNameMajorVersionMap_t & paramNameRemapMajorVersionMap() const
virtual void guidedModeLand(Vehicle *vehicle) const
Command vehicle to land at current location.
FirmwarePlugin(QObject *parent=nullptr)
virtual MavlinkCameraControlInterface * createCameraControl(const mavlink_camera_information_t *info, Vehicle *vehicle, int compID, QObject *parent=nullptr) const
Camera control.
virtual bool hasGimbal(Vehicle *vehicle, bool &rollSupported, bool &pitchSupported, bool &yawSupported) const
This is the generic implementation of the AutoPilotPlugin class for mavs we do not have a specific Au...
static int getComponentId()
static MAVLinkProtocol * instance()
Abstract base class for all camera controls: real and simulated.
File download with progress, decompression, and hash verification.
void finished(bool success, const QString &localPath, const QString &errorMessage)
bool start(const QString &remoteUrl)
static VehicleClass_t vehicleClass(MAV_TYPE mavType)
static const char * vehicleClassToCanonicalString(VehicleClass_t vehicleClass)
static constexpr const VehicleClass_t VehicleClassSub
static constexpr const VehicleClass_t VehicleClassFixedWing
static constexpr const VehicleClass_t VehicleClassMultiRotor
static constexpr const VehicleClass_t VehicleClassRoverBoat
static FirmwareClass_t firmwareClass(MAV_AUTOPILOT autopilot)
static const char * firmwareClassToCanonicalString(FirmwareClass_t firmwareClass)
static constexpr const VehicleClass_t VehicleClassVTOL
static bool shouldNotify(const QString &latestVersion, const QString &lastNotifiedVersion)
MAVLink Camera API controller - connected to a real mavlink v2 camera.
WeakLinkInterfacePtr primaryLink() const
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)
QString flightMode() const
void setNewStableFirmwareVersion(const QString &version)
uint64_t capabilityBits() const
MAV_TYPE vehicleType() const
VehicleLinkManager * vehicleLinkManager()
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)
int firmwareMinorVersion() const
MAV_AUTOPILOT firmwareType() const
bool sendMessageOnLinkThreadSafe(LinkInterface *link, mavlink_message_t message)
void setFlightMode(const QString &flightMode)
int firmwareVersionType() const
int defaultComponentId() const
int firmwarePatchVersion() const
Q_INVOKABLE int versionCompare(const QString &compare) const
Used to check if running current version is equal or higher than the one being compared.
int firmwareMajorVersion() const
void setArmed(bool armed, bool showError)
QByteArray readFile(const QString &filePath, QString *errorString, qint64 maxBytes)
Read file contents, transparently decompressing .gz/.xz/.zst/.bz2/.lz4 files.
bool atomicWrite(const QString &filePath, const QByteArray &data)
bool ensureDirectoryExists(const QString &path)
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.
static constexpr VehicleClass_t VehicleClassGeneric