QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
LinkInterface.cc
Go to the documentation of this file.
1#include "LinkInterface.h"
2#include "MAVLinkLib.h"
3#include "LinkManager.h"
4#include "AppMessages.h"
5#include "QGCApplication.h"
7#include "SigningController.h"
8
9#include <QtCore/QThread>
10#include <QtQml/QQmlEngine>
11
12QGC_LOGGING_CATEGORY(LinkInterfaceLog, "Comms.LinkInterface")
13
14namespace {
15 constexpr int WORKER_SHUTDOWN_TIMEOUT_MS = 3000;
16}
17
19 : QObject(parent)
20 , _config(config)
21{
22 QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);
23}
24
26{
27 if (_vehicleReferenceCount != 0) {
28 qCWarning(LinkInterfaceLog) << "still have vehicle references:" << _vehicleReferenceCount;
29 }
30
31 _config.reset();
32}
33
34void LinkInterface::_shutdownWorkerThread(QThread *thread, const QLoggingCategory &category, bool allowTerminate)
35{
36 if (!thread) {
37 return;
38 }
39
40 // Self-shutdown: wait() would fail and terminate() would kill the calling thread mid-destructor
41 if (thread->isCurrentThread()) {
42 qCCritical(category) << "Shutdown called from worker thread itself, orphaning";
43 thread->quit();
44 _orphanWorkerThread(thread);
45 return;
46 }
47
48 thread->quit();
49 if (thread->wait(WORKER_SHUTDOWN_TIMEOUT_MS)) {
50 return;
51 }
52
53 if (allowTerminate) {
54 qCWarning(category) << "Worker thread did not stop within timeout, terminating";
55 thread->terminate();
56 if (thread->wait(WORKER_SHUTDOWN_TIMEOUT_MS)) {
57 return;
58 }
59 }
60
61 // Orphan the running thread — leaking it beats the ~QThread abort in deleteChildren()
62 qCCritical(category) << "Worker thread could not be stopped, leaking it to avoid abort";
63 _orphanWorkerThread(thread);
64}
65
66void LinkInterface::_orphanWorkerThread(QThread *thread)
67{
68 thread->setParent(nullptr);
69
70 // Workers hold raw pointers into the configuration: keep it alive until the thread
71 // finishes so a stalled worker that resumes can't dereference a destroyed config.
72 (void) QObject::connect(thread, &QThread::finished, thread, [config = _config]() { Q_UNUSED(config); });
73
74 // Self-heal if the thread eventually exits: deleting the thread destroys the
75 // connection above, releasing the config. At app exit there is no main loop to
76 // deliver this, so both leak — the intended last-resort behavior.
77 (void) QObject::connect(thread, &QThread::finished, thread, &QObject::deleteLater);
78}
79
81{
82 if (!mavlinkChannelIsSet()) {
83 qCWarning(LinkInterfaceLog) << "mavlinkChannelIsSet() == false";
84 }
85
86 return _mavlinkChannel;
87}
88
90{
91 return (LinkManager::invalidMavlinkChannel() != _mavlinkChannel);
92}
93
95{
96 if (mavlinkChannelIsSet()) {
97 qCWarning(LinkInterfaceLog) << "already have" << _mavlinkChannel;
98 return true;
99 }
100
101 _mavlinkChannel = LinkManager::instance()->allocateMavlinkChannel();
102
103 if (!mavlinkChannelIsSet()) {
104 qCWarning(LinkInterfaceLog) << "failed";
105 return false;
106 }
107
108 qCDebug(LinkInterfaceLog) << "_allocateMavlinkChannel" << _mavlinkChannel;
109
110 mavlink_set_proto_version(_mavlinkChannel, MAVLINK_VERSION); // We only support v2 protcol
111
112 _signingController = std::make_unique<SigningController>(static_cast<mavlink_channel_t>(_mavlinkChannel));
113 _signingController->clearSigning();
114
115 qCDebug(LinkInterfaceLog) << "SigningController created for channel" << _mavlinkChannel
116 << (isSecureConnection() ? "(secure)" : "(will auto-detect)");
117
118 return true;
119}
120
122{
123 qCDebug(LinkInterfaceLog) << _mavlinkChannel;
124
125 if (!mavlinkChannelIsSet()) {
126 return;
127 }
128
129 // Destroy the controller before freeing the channel so it can flush the final timestamp.
130 _signingController.reset();
131
132 // mavlink_reset_channel_status only resets parse_state — null signing/streams explicitly to avoid dangling derefs.
133 mavlink_status_t* const status = mavlink_get_channel_status(_mavlinkChannel);
134 status->signing = nullptr;
135 status->signing_streams = nullptr;
136 mavlink_reset_channel_status(_mavlinkChannel);
137
138 LinkManager::instance()->freeMavlinkChannel(_mavlinkChannel);
139 _mavlinkChannel = LinkManager::invalidMavlinkChannel();
140}
141
142void LinkInterface::writeBytesThreadSafe(const char *bytes, int length)
143{
144 const QByteArray data(bytes, length);
145 (void) QMetaObject::invokeMethod(this, "_writeBytes", Qt::AutoConnection, data);
146}
147
149{
150 // Re-sign with a current timestamp; the cached-resend path (Vehicle::sendMessageMultiple) otherwise ships frozen
151 // signed bytes whose timestamp drifts behind wall clock and gets OLD_TIMESTAMP-rejected. No-op when signing is
152 // disabled or the message isn't outgoing-signed. The secret key stays in the signing layer.
153 if (_signingController) {
154 (void) _signingController->signOutgoing(message);
155 }
156
157 uint8_t buffer[MAVLINK_MAX_PACKET_LEN];
158 const int len = mavlink_msg_to_send_buffer(buffer, &message);
159 writeBytesThreadSafe(reinterpret_cast<const char *>(buffer), len);
160}
161
163{
164 if (_vehicleReferenceCount != 0) {
165 _vehicleReferenceCount--;
167 } else {
168 qCWarning(LinkInterfaceLog) << "called with no vehicle references";
169 }
170}
171
173{
174 if (_vehicleReferenceCount == 0) {
175 // Since there are no vehicles on the link we can disconnect it right now
176 disconnect();
177 } else {
178 // If there are still vehicles on this link we allow communication lost to trigger and don't automatically disconect until all the vehicles go away
179 }
180}
181
183{
184 if (!_radioStatusSeen) {
185 _radioStatusSeen = true;
186 qCDebug(LinkInterfaceLog) << "RADIO_STATUS seen, treating link as radio link:" << _config->name();
187 }
188}
189
191{
192 if (_mavlinkV1TrafficReported || _mavlinkV2TrafficSeen) {
193 return;
194 }
195
196 // Defer the warning: ArduPilot starts out sending v1 and upgrades to v2 once it sees v2
197 // traffic from QGC. Only warn if the link never produces v2 within the grace period.
198 if (!_mavlinkV1FirstSeenTimer.isValid()) {
199 _mavlinkV1FirstSeenTimer.start();
200 }
201 if (_mavlinkV1FirstSeenTimer.elapsed() < _mavlinkV1TrafficGraceMsecs) {
202 return;
203 }
204
205 _mavlinkV1TrafficReported = true;
206
208 const QString linkName = linkConfig ? linkConfig->name() : QStringLiteral("unknown");
209 qCWarning(LinkInterfaceLog) << "MAVLink v1 traffic detected on link" << linkName;
210 const QString message = tr("MAVLink v1 traffic detected on link '%1'. "
211 "%2 only supports MAVLink v2. "
212 "Please ensure your vehicle is configured to use MAVLink v2.")
213 .arg(linkName).arg(qgcApp()->applicationName());
214 QGC::showAppMessage(message);
215}
std::shared_ptr< LinkConfiguration > SharedLinkConfigurationPtr
mavlink_channel_t
mavlink_status_t * mavlink_get_channel_status(uint8_t chan)
Definition QGCMAVLink.cc:53
#define qgcApp()
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
virtual ~LinkInterface()
uint8_t mavlinkChannel() const
void _shutdownWorkerThread(QThread *thread, const QLoggingCategory &category, bool allowTerminate=true)
virtual void _freeMavlinkChannel()
LinkInterface(SharedLinkConfigurationPtr &config, QObject *parent=nullptr)
Links are only created by LinkManager so constructor is not public.
virtual Q_INVOKABLE void disconnect()=0
void sendMessageThreadSafe(mavlink_message_t &message)
void reportMavlinkV1Traffic()
void _connectionRemoved()
bool mavlinkChannelIsSet() const
virtual bool _allocateMavlinkChannel()
void removeVehicleReference()
virtual bool isSecureConnection() const
void writeBytesThreadSafe(const char *bytes, int length)
SharedLinkConfigurationPtr linkConfiguration()
SharedLinkConfigurationPtr _config
void reportRadioStatusReceived()
uint8_t allocateMavlinkChannel()
static LinkManager * instance()
void freeMavlinkChannel(uint8_t channel)
static constexpr uint8_t invalidMavlinkChannel()
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.
Definition AppMessages.cc:9