QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
LinkManager.cc
Go to the documentation of this file.
1#include "LinkManager.h"
2#include "LogReplayLink.h"
3#include "QGCNetworkHelper.h"
4#include "MAVLinkProtocol.h"
6#include "AppMessages.h"
9#include "SettingsManager.h"
10#include "MavlinkSettings.h"
11#include "AutoConnectSettings.h"
12#include "TCPLink.h"
13#include "UDPLink.h"
14#include "BluetoothLink.h"
15
16#ifndef QGC_NO_SERIAL_LINK
17#include "SerialAutoConnect.h"
18#include "SerialLink.h"
19#include "SerialPortManager.h"
20#ifdef Q_OS_ANDROID
21#include "AndroidSerialAccess.h"
22#include "AppSettings.h"
23#endif
24#endif
25
26#ifdef QT_DEBUG
27#include "MockLink.h"
28#endif
29
30#include <algorithm>
31#include <chrono>
32#include <utility>
33
34#include <QtCore/QApplicationStatic>
35#include <QtCore/QTimer>
36
37QGC_LOGGING_CATEGORY(LinkManagerLog, "Comms.LinkManager")
38QGC_LOGGING_CATEGORY(LinkManagerVerboseLog, "Comms.LinkManager:verbose")
39
40Q_APPLICATION_STATIC(LinkManager, _linkManagerInstance);
41
42LinkManager::LinkManager(QObject *parent)
43 : QObject(parent)
44 , _portListTimer(new QTimer(this))
45 , _qmlConfigurations(new QmlObjectListModel(this))
46{
47 qCDebug(LinkManagerLog) << this;
48
49 (void) qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
50 (void) qRegisterMetaType<LinkInterface*>("LinkInterface*");
51#ifndef QGC_NO_SERIAL_LINK
52 (void) qRegisterMetaType<QGCSerialPortInfo>("QGCSerialPortInfo");
54 &LinkManager::_updateSerialPorts);
55 // On Android the user's answer to a request for USB permission starts a scan of the ports.
57 &LinkManager::_connectLinkAwaitingUsbPermission);
58#endif
59}
60
62{
63 qCDebug(LinkManagerLog) << this;
64}
65
67{
68 return _linkManagerInstance();
69}
70
72{
73 _autoConnectSettings = SettingsManager::instance()->autoConnectSettings();
74
75#ifndef QGC_NO_SERIAL_LINK
76#ifdef Q_OS_ANDROID
77 Fact* const usePosixSerial = SettingsManager::instance()->appSettings()->androidUsePosixSerial();
78 AndroidSerialAccess::setUsePosixSerial(usePosixSerial->rawValue().toBool());
79 // The setting applies at once. Turning it off takes the device nodes off the port list, which closes a link
80 // or a GPS receiver that has one open, as when its device is unplugged.
81 (void) connect(usePosixSerial, &Fact::rawValueChanged, this, [](const QVariant& value) {
84 });
85#endif
86 if (!_serialAutoConnect) {
87 _serialAutoConnect = std::make_unique<SerialAutoConnect>(
89 [this](SharedLinkConfigurationPtr& config) { createConnectedLink(config); });
90 }
91#endif
92
93 if (!QGC::runningUnitTests()) {
94 (void) connect(_portListTimer, &QTimer::timeout, this, &LinkManager::_updateAutoConnectLinks);
95 _portListTimer->start(_autoconnectUpdateTimerMSecs); // timeout must be long enough to get past bootloader on second pass
96 }
97}
98
99QList<SharedLinkInterfacePtr> LinkManager::links()
100{
101 QMutexLocker locker(&_linksMutex);
102 return _rgLinks;
103}
104
105QmlObjectListModel *LinkManager::_qmlLinkConfigurations()
106{
107 return _qmlConfigurations;
108}
109
111{
112 for (SharedLinkConfigurationPtr &sharedConfig : _rgLinkConfigs) {
113 if (sharedConfig.get() == config) {
114 sharedConfig->setAutoConnectStarted(true);
115 sharedConfig->resetReconnectBackoff();
116#ifndef QGC_NO_SERIAL_LINK
117 if (_serialPortInUseMsg(*sharedConfig)) {
118 continue;
119 }
120 if (_awaitUsbPermission(sharedConfig)) {
121 continue;
122 }
123#endif
124 createConnectedLink(sharedConfig);
125 }
126 }
127}
128
130{
131 if (!link) {
132 return;
133 }
134
135 const SharedLinkConfigurationPtr config = link->linkConfiguration();
136 if (config) {
137 config->setSuppressAutoReconnect(true);
138 }
139
140 link->disconnect();
141}
142
143#ifndef QGC_NO_SERIAL_LINK
144bool LinkManager::_serialPortInUseMsg(const LinkConfiguration& config)
145{
146 const auto* serialConfig = qobject_cast<const SerialConfiguration*>(&config);
147 const QString port = serialConfig ? serialConfig->portName().trimmed() : QString();
148 if (port.isEmpty() || SerialPortManager::instance()->canReservePort(port)) {
149 return false;
150 }
151
152 // A link that has the port can be named for the user to disconnect. What else reserves a port, as the GPS
153 // does, is named if it said what it is.
154 const QList<SharedLinkInterfacePtr> currentLinks = links();
155 for (const SharedLinkInterfacePtr& link : currentLinks) {
156 const SharedLinkConfigurationPtr linkConfig = link->linkConfiguration();
157 const auto* linkSerialConfig = qobject_cast<const SerialConfiguration*>(linkConfig.get());
158 if (!linkSerialConfig) {
159 continue;
160 }
161 if (SerialPortManager::instance()->isSamePort(linkSerialConfig->portName(), port)) {
162 // Said in so many words: a link that was connected automatically is named after what QGC takes the
163 // device for, which the user may not know it by.
165 tr("Cannot connect '%1': its serial port is already open as the link '%2'. Disconnect that link first.")
166 .arg(config.name(), linkConfig->name()));
167 return true;
168 }
169 }
170
171 const QString owner = SerialPortManager::instance()->reservationOwner(port);
172 if (owner.isEmpty()) {
173 QGC::showAppMessage(tr("Cannot connect '%1': the serial port is in use.").arg(config.name()));
174 } else {
175 //: %2 is what has the port open, such as "the GPS receiver"
176 QGC::showAppMessage(tr("Cannot connect '%1': the serial port is in use by %2.").arg(config.name(), owner));
177 }
178 return true;
179}
180
181bool LinkManager::_awaitUsbPermission(const SharedLinkConfigurationPtr& config)
182{
183 // The user asked for this connection, so they are asked again for a USB device that they have denied QGC:
184 // opening the port asks only once for each time the device is attached. The port cannot be opened until
185 // they answer, so the link is connected once they have allowed it.
186 const auto* serialConfig = qobject_cast<const SerialConfiguration*>(config.get());
187 if (!serialConfig || !SerialPortManager::instance()->requestAccess(serialConfig->portName())) {
188 // A link that waits for its permission goes on waiting: this connection has nothing to ask for.
189 return false;
190 }
191
192 qCDebug(LinkManagerLog) << "Connecting" << config->name() << "once the user allows its USB device";
193 // As when a link is connected at once: the user wants this link, whatever they stopped before.
194 config->setSuppressAutoReconnect(false);
195 _configAwaitingUsbPermission = config;
196 // A permission that the user grants later than this, by other means, connects nothing by itself.
197 _usbPermissionDeadline.setRemainingTime(std::chrono::minutes(1));
198 return true;
199}
200
201void LinkManager::_connectLinkAwaitingUsbPermission()
202{
203 SharedLinkConfigurationPtr config = _configAwaitingUsbPermission.lock();
204 if (!config) {
205 return;
206 }
207 if (_usbPermissionDeadline.hasExpired()) {
208 _configAwaitingUsbPermission.reset();
209 return;
210 }
211
212 const auto* serialConfig = qobject_cast<const SerialConfiguration*>(config.get());
213 if (serialConfig && SerialPortManager::instance()->accessDenied(serialConfig->portName())) {
214 // The user has answered, so nothing is left to wait for. They are told only of a link that they still want.
215 qCDebug(LinkManagerLog) << "USB device refused, not connecting" << config->name();
216 _configAwaitingUsbPermission.reset();
217 if (!config->link() && !config->suppressAutoReconnect()) {
218 QGC::showAppMessage(tr("Cannot connect '%1': USB permission was denied.").arg(config->name()));
219 }
220 return;
221 }
222 if (_connectionsSuspended || !serialConfig || !SerialPortManager::instance()->hasAccess(serialConfig->portName())) {
223 return;
224 }
225
226 // Not if the link was connected or stopped by other means since the user asked for it.
227 if (!config->link() && !config->suppressAutoReconnect()) {
228 qCDebug(LinkManagerLog) << "USB device allowed, connecting" << config->name();
229 if (!createConnectedLink(config)) {
230 // An automatic connection may be trying the port at this moment. The next scan tries again.
231 return;
232 }
233 }
234 _configAwaitingUsbPermission.reset();
235}
236#endif
237
239{
240 if (!config) {
241 return;
242 }
243
244 config->setSuppressAutoReconnect(true);
245
246 if (LinkInterface *const link = config->link()) {
247 link->disconnect();
248 }
249}
250
252{
253 config->setSuppressAutoReconnect(false);
254
255 SharedLinkInterfacePtr link = nullptr;
256
257 switch(config->type()) {
258#ifndef QGC_NO_SERIAL_LINK
260 const auto* serialConfig = qobject_cast<const SerialConfiguration*>(config.get());
261 if (!serialConfig) {
262 return false;
263 }
264 auto reservation = SerialPortManager::instance()->reservePort(serialConfig->portName());
265 if (!reservation) {
266 qCDebug(LinkManagerLog) << "Serial port is already reserved:" << serialConfig->portName();
267 return false;
268 }
269 link = std::make_shared<SerialLink>(config, std::move(reservation));
270 break;
271 }
272#endif
274 link = std::make_shared<UDPLink>(config);
275 break;
277 link = std::make_shared<TCPLink>(config);
278 break;
280 link = std::make_shared<BluetoothLink>(config);
281 break;
283 link = std::make_shared<LogReplayLink>(config);
284 break;
285#ifdef QT_DEBUG
286 case LinkConfiguration::TypeMock:
287 link = std::make_shared<MockLink>(config);
288 break;
289#endif
291 default:
292 break;
293 }
294
295 if (!link) {
296 return false;
297 }
298
299 if (!link->_allocateMavlinkChannel()) {
300 qCWarning(LinkManagerLog) << "Link failed to setup mavlink channels";
301 return false;
302 }
303
304 // Set up signal connections before adding to list, so link is fully initialized
305 (void) connect(link.get(), &LinkInterface::communicationError, this, &LinkManager::_communicationError);
308 (void) connect(link.get(), &LinkInterface::connected, this, &LinkManager::_linkConnected);
309 (void) connect(link.get(), &LinkInterface::disconnected, this, &LinkManager::_linkDisconnected);
310
312
313 // Try to connect before adding to active links list
314 if (!link->_connect()) {
315 (void) disconnect(link.get(), &LinkInterface::communicationError, this, &LinkManager::_communicationError);
318 (void) disconnect(link.get(), &LinkInterface::disconnected, this, &LinkManager::_linkDisconnected);
319 link->_freeMavlinkChannel();
320 config->setLink(nullptr);
321 return false;
322 }
323
324 {
325 QMutexLocker locker(&_linksMutex);
326 _rgLinks.append(link);
327 }
328 config->setLink(link);
329
330 return true;
331}
332
333void LinkManager::_linkConnected()
334{
335 const LinkInterface *const link = qobject_cast<LinkInterface*>(sender());
336 const SharedLinkConfigurationPtr config = link ? link->linkConfiguration() : nullptr;
337 if (config) {
338 config->noteConnected();
339#ifndef QGC_NO_SERIAL_LINK
340 // The port is open, so on Android the user has let QGC open its device by now, if only after the link
341 // was saved.
342 if (_usePersistentPortName(config.get())) {
344 }
345#endif
346 }
347}
348
349void LinkManager::_communicationError(const QString &title, const QString &error)
350{
351 const LinkInterface *const link = qobject_cast<LinkInterface*>(sender());
352 const SharedLinkConfigurationPtr config = link ? link->linkConfiguration() : nullptr;
353
354 // Auto-connect links retry on a timer; a popup per failed attempt is just noise. Log only.
355 if (config && config->isAutoConnect() && !config->suppressAutoReconnect()) {
356 qCDebug(LinkManagerLog) << "Auto-connect link error (will retry):" << title << error;
357 return;
358 }
359
360 // Dynamic links recreated on a timer: only the first attempt of a failure streak pops up
361 if (config && (config->reconnectAttempts() > 1)) {
362 qCDebug(LinkManagerLog) << "Link error on retry:" << title << error;
363 return;
364 }
365
366 QGC::showAppMessage(error, title);
367}
368
370{
371 QMutexLocker locker(&_linksMutex);
372
373 for (const SharedLinkInterfacePtr &link : _rgLinks) {
374 const SharedLinkConfigurationPtr linkConfig = link->linkConfiguration();
375 if (linkConfig && (linkConfig->type() == LinkConfiguration::TypeUdp) && (linkConfig->name() == _mavlinkForwardingLinkName)) {
376 return link;
377 }
378 }
379
380 return nullptr;
381}
382
384{
385 QMutexLocker locker(&_linksMutex);
386
387 for (const SharedLinkInterfacePtr &link : _rgLinks) {
388 const SharedLinkConfigurationPtr linkConfig = link->linkConfiguration();
389 if (linkConfig && (linkConfig->type() == LinkConfiguration::TypeUdp) && (linkConfig->name() == _mavlinkForwardingSupportLinkName)) {
390 return link;
391 }
392 }
393
394 return nullptr;
395}
396
398{
399 QList<SharedLinkInterfacePtr> links;
400 {
401 QMutexLocker locker(&_linksMutex);
402 links = _rgLinks;
403 }
404
405 for (const SharedLinkInterfacePtr &sharedLink: links) {
406 sharedLink->disconnect();
407 }
408}
409
410void LinkManager::_linkDisconnected()
411{
412 LinkInterface* const link = qobject_cast<LinkInterface*>(sender());
413
414 if (!link) {
415 return;
416 }
417
418 SharedLinkInterfacePtr linkToCleanup;
420 {
421 QMutexLocker locker(&_linksMutex);
422
423 for (auto it = _rgLinks.begin(); it != _rgLinks.end(); ++it) {
424 if (it->get() == link) {
425 config = it->get()->linkConfiguration();
426 const QString linkName = config ? config->name() : QStringLiteral("<null config>");
427 qCDebug(LinkManagerLog) << linkName << "use_count:" << it->use_count();
428 linkToCleanup = *it;
429 (void) _rgLinks.erase(it);
430 break;
431 }
432 }
433 }
434
435 if (!linkToCleanup) {
436 qCDebug(LinkManagerLog) << "link already removed";
437 return;
438 }
439
440 if (config) {
441 config->noteDisconnected();
442 config->setLink(nullptr);
443
444 if (config->isDynamic() && (config->name() == _mavlinkForwardingSupportLinkName) &&
445 _mavlinkSupportForwardingEnabled) {
446 _mavlinkSupportForwardingEnabled = false;
448 }
449 }
450
451 (void) disconnect(link, &LinkInterface::communicationError, this, &LinkManager::_communicationError);
454 (void) disconnect(link, &LinkInterface::connected, this, &LinkManager::_linkConnected);
455 (void) disconnect(link, &LinkInterface::disconnected, this, &LinkManager::_linkDisconnected);
456
457 link->_freeMavlinkChannel();
458}
459
461{
462 QMutexLocker locker(&_linksMutex);
463
464 for (const SharedLinkInterfacePtr &sharedLink: _rgLinks) {
465 if (sharedLink.get() == link) {
466 return sharedLink;
467 }
468 }
469
470 // Link not found - this is normal during disconnect when queued signals are still processing.
471 // Callers should check for nullptr return value.
472 qCDebug(LinkManagerLog) << "link not in list (likely disconnected)";
473 return SharedLinkInterfacePtr(nullptr);
474}
475
476bool LinkManager::_connectionsSuspendedMsg() const
477{
478 if (_connectionsSuspended) {
479 QGC::showAppMessage(tr("Connect not allowed: %1").arg(_connectionsSuspendedReason));
480 return true;
481 }
482
483 return false;
484}
485
487{
488 QSettings settings;
489 settings.remove(LinkConfiguration::settingsRoot());
490
491 int trueCount = 0;
492 for (int i = 0; i < _rgLinkConfigs.count(); i++) {
493 SharedLinkConfigurationPtr linkConfig = _rgLinkConfigs[i];
494 if (!linkConfig) {
495 qCWarning(LinkManagerLog) << "Internal error for link configuration in LinkManager";
496 continue;
497 }
498
499 if (linkConfig->isDynamic()) {
500 continue;
501 }
502
503 const QString root = LinkConfiguration::settingsRoot() + QStringLiteral("/Link%1").arg(trueCount++);
504 settings.setValue(root + "/name", linkConfig->name());
505 settings.setValue(root + "/type", linkConfig->type());
506 settings.setValue(root + "/auto", linkConfig->isAutoConnect());
507 settings.setValue(root + "/high_latency", linkConfig->isHighLatency());
508 linkConfig->saveSettings(settings, root);
509 }
510
511 const QString root = QString(LinkConfiguration::settingsRoot());
512 settings.setValue(root + "/count", trueCount);
513}
514
516{
517 QSettings settings;
518 // Is the group even there?
519 if (settings.contains(LinkConfiguration::settingsRoot() + "/count")) {
520 // Find out how many configurations we have
521 const int count = settings.value(LinkConfiguration::settingsRoot() + "/count").toInt();
522 for (int i = 0; i < count; i++) {
523 const QString root = LinkConfiguration::settingsRoot() + QStringLiteral("/Link%1").arg(i);
524 if (!settings.contains(root + "/type")) {
525 qCWarning(LinkManagerLog) << "Link Configuration" << root << "has no type.";
526 continue;
527 }
528
529 LinkConfiguration::LinkType type = static_cast<LinkConfiguration::LinkType>(settings.value(root + "/type").toInt());
530 if (type >= LinkConfiguration::TypeLast) {
531 qCWarning(LinkManagerLog) << "Link Configuration" << root << "an invalid type:" << type;
532 continue;
533 }
534
535 if (!settings.contains(root + "/name")) {
536 qCWarning(LinkManagerLog) << "Link Configuration" << root << "has no name.";
537 continue;
538 }
539
540 const QString name = settings.value(root + "/name").toString();
541 if (name.isEmpty()) {
542 qCWarning(LinkManagerLog) << "Link Configuration" << root << "has an empty name.";
543 continue;
544 }
545
546 LinkConfiguration* link = nullptr;
547 switch(type) {
548#ifndef QGC_NO_SERIAL_LINK
550 link = new SerialConfiguration(name);
551 break;
552#endif
554 link = new UDPConfiguration(name);
555 break;
557 link = new TCPConfiguration(name);
558 break;
560 link = new BluetoothConfiguration(name);
561 break;
563 link = new LogReplayConfiguration(name);
564 break;
565#ifdef QT_DEBUG
566 case LinkConfiguration::TypeMock:
567 link = new MockConfiguration(name);
568 break;
569#endif
571 default:
572 break;
573 }
574
575 if (link) {
576 const bool autoConnect = settings.value(root + "/auto").toBool();
577 link->setAutoConnect(autoConnect);
578 const bool highLatency = settings.value(root + "/high_latency").toBool();
579 link->setHighLatency(highLatency);
580 link->loadSettings(settings, root);
581 addConfiguration(link);
582 }
583 }
584 }
585
586 // Enable automatic Serial PX4/3DR Radio hunting
587 _configurationsLoaded = true;
588}
589
590void LinkManager::_addUDPAutoConnectLink()
591{
592 if (!_autoConnectSettings->autoConnectUDP()->rawValue().toBool()) {
593 return;
594 }
595
596 _retryDynamicUdpLink(_defaultUDPLinkName, [this](UDPConfiguration& udpConfig) {
597 udpConfig.setAutoConnect(true);
598 // Listening is this link's main job; an unresolvable target must not stop it
599 udpConfig.setRequireResolvedHosts(false);
600 udpConfig.setLocalPort(_autoConnectSettings->udpListenPort()->rawValue().toUInt());
601 const QString targetHostIP = _autoConnectSettings->udpTargetHostIP()->rawValue().toString();
602 if (!targetHostIP.isEmpty()) {
603 udpConfig.addHost(targetHostIP, _autoConnectSettings->udpTargetHostPort()->rawValue().toUInt());
604 }
605 });
606}
607
608void LinkManager::_addMAVLinkForwardingLink()
609{
610 if (!SettingsManager::instance()->mavlinkSettings()->forwardMavlink()->rawValue().toBool()) {
611 return;
612 }
613
614 _retryDynamicUdpLink(_mavlinkForwardingLinkName, [](UDPConfiguration& udpConfig) {
615 udpConfig.setForwarding(true);
616 udpConfig.addHost(
617 SettingsManager::instance()->mavlinkSettings()->forwardMavlinkHostName()->rawValue().toString());
618 });
619}
620
621void LinkManager::_retryDynamicUdpLink(const QString& name, const std::function<void(UDPConfiguration&)>& configure)
622{
623 SharedLinkConfigurationPtr config = _findDynamicUdpConfiguration(name);
624 if (config && (config->link() || !config->reconnectReady())) {
625 return;
626 }
627
628 UDPConfiguration udpConfig(name);
629 udpConfig.setDynamic(true);
630 configure(udpConfig);
631
632 // Reuse the config on retry so its backoff applies and configs don't pile up
633 if (config) {
634 config->copyFrom(&udpConfig);
635 qCDebug(LinkManagerLog) << "Retrying dynamic UDP link:" << name;
636 } else {
637 config = addConfiguration(new UDPConfiguration(&udpConfig));
638 qCDebug(LinkManagerLog) << "New dynamic UDP link added:" << name << udpConfig.hostList();
639 }
640
641 config->noteReconnectAttempt();
642 createConnectedLink(config);
643}
644
645SharedLinkConfigurationPtr LinkManager::_findDynamicUdpConfiguration(const QString& name) const
646{
647 // User-created links may use the same name; those must never be reused
648 for (const SharedLinkConfigurationPtr& config : _rgLinkConfigs) {
649 if (config && config->isDynamic() && (config->type() == LinkConfiguration::TypeUdp) &&
650 (config->name() == name)) {
651 return config;
652 }
653 }
654
655 return nullptr;
656}
657
658void LinkManager::_reconnectAutoConnectLinks()
659{
660 for (SharedLinkConfigurationPtr &config : _rgLinkConfigs) {
661 if (!config || config->isDynamic() || !config->isAutoConnect()) {
662 continue;
663 }
664
665 // Only re-establish links started this session (boot or manual connect); a freshly
666 // added auto-connect config waits for next app start rather than connecting now.
667 if (config->link() || config->suppressAutoReconnect() || !config->autoConnectStarted()) {
668 continue;
669 }
670
671 // Exponential backoff between attempts so a dead host isn't hammered every tick.
672 if (!config->reconnectReady()) {
673 continue;
674 }
675
676 qCDebug(LinkManagerLog) << "Reconnecting auto-connect link" << config->name();
677 config->noteReconnectAttempt();
678 createConnectedLink(config);
679 }
680}
681
682void LinkManager::_updateAutoConnectLinks()
683{
684#ifndef QGC_NO_SERIAL_LINK
685 // Existing links still need fresh unplug checks while new connections are suspended.
687#endif
688 if (_connectionsSuspended) {
689 return;
690 }
691
692 _addUDPAutoConnectLink();
693 _addMAVLinkForwardingLink();
694 _reconnectAutoConnectLinks();
695
696#ifndef QGC_NO_SERIAL_LINK
697 if (_serialAutoConnect) {
698 _serialAutoConnect->update(ports, {_autoConnectSettings->autoConnectPixhawk()->rawValue().toBool(),
699 _autoConnectSettings->autoConnectSiKRadio()->rawValue().toBool(),
700 _autoConnectSettings->autoConnectLibrePilot()->rawValue().toBool()});
701 }
702#endif
703}
704
706{
707 setConnectionsSuspended(tr("Shutdown"));
709
710 // Wait for all the vehicles to go away to ensure an orderly shutdown and deletion of all objects
711 while (MultiVehicleManager::instance()->vehicles()->count()) {
712 QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
713 }
714}
715
717{
718 //-- Must follow same order as enum LinkType in LinkConfiguration.h
719 static QStringList list;
720 if (!list.isEmpty()) {
721 return list;
722 }
723
724#ifndef QGC_NO_SERIAL_LINK
725 list += tr("Serial");
726#endif
727 list += tr("UDP");
728 list += tr("TCP");
729 list += tr("Bluetooth");
730#ifdef QT_DEBUG
731 list += tr("Mock Link");
732#endif
733 list += tr("Log Replay");
734
735 if (list.size() != static_cast<int>(LinkConfiguration::TypeLast)) {
736 qCWarning(LinkManagerLog) << "Internal error";
737 }
738
739 return list;
740}
741
743{
744 if (!config || !editedConfig) {
745 qCWarning(LinkManagerLog) << "Internal error";
746 return;
747 }
748
749 config->copyFrom(editedConfig);
750#ifndef QGC_NO_SERIAL_LINK
751 // The persistent name of the port may have changed while the editor was open.
752 (void) _usePersistentPortName(config);
753#endif
755 emit config->nameChanged(config->name());
756 // Discard temporary duplicate
757 delete editedConfig;
758}
759
761{
762 if (!config) {
763 qCWarning(LinkManagerLog) << "Internal error";
764 return;
765 }
766
767 addConfiguration(config);
768#ifndef QGC_NO_SERIAL_LINK
769 // The persistent name of the port may have changed since the port was chosen in the editor.
770 (void) _usePersistentPortName(config);
771#endif
773}
774
776{
777#ifndef QGC_NO_SERIAL_LINK
779 _updateSerialPorts();
780 }
781#endif
782
783 return LinkConfiguration::createSettings(type, name);
784}
785
787{
788 if (!config) {
789 qCWarning(LinkManagerLog) << "Internal error";
790 return nullptr;
791 }
792
793 LinkConfiguration* const editedConfig = LinkConfiguration::duplicateSettings(config);
794#ifndef QGC_NO_SERIAL_LINK
795 if (auto* const serialConfig = qobject_cast<SerialConfiguration*>(editedConfig)) {
796 _updateSerialPorts();
797 // The editor lists ports by their persistent names, so a link saved by the system location of its port
798 // takes that name here.
799 serialConfig->setPortName(SerialPortManager::instance()->persistentName(serialConfig->portName()));
800 }
801#endif
802
803 return editedConfig;
804}
805
807{
808 if (!config) {
809 qCWarning(LinkManagerLog) << "Internal error";
810 return;
811 }
812
813 LinkInterface* const link = config->link();
814 if (link) {
815 link->disconnect();
816 }
817
818 _removeConfiguration(config);
820}
821
823{
824 SharedLinkConfigurationPtr config = _findDynamicUdpConfiguration(_mavlinkForwardingSupportLinkName);
825 if (config && config->link()) {
826 return;
827 }
828
829 UDPConfiguration udpConfig(_mavlinkForwardingSupportLinkName);
830 udpConfig.setDynamic(true);
831 udpConfig.setForwarding(true);
832 udpConfig.addHost(
833 SettingsManager::instance()->mavlinkSettings()->forwardMavlinkAPMSupportHostName()->rawValue().toString());
834
835 if (config) {
836 config->copyFrom(&udpConfig);
837 } else {
838 config = addConfiguration(new UDPConfiguration(&udpConfig));
839 }
840
841 if (!createConnectedLink(config)) {
842 return;
843 }
844
845 // Cleared again in _linkDisconnected if the connect fails
846 _mavlinkSupportForwardingEnabled = true;
848}
849
850void LinkManager::_removeConfiguration(const LinkConfiguration *config)
851{
852 (void) _qmlConfigurations->removeOne(config);
853
854 for (auto it = _rgLinkConfigs.begin(); it != _rgLinkConfigs.end(); ++it) {
855 if (it->get() == config) {
856 (void) _rgLinkConfigs.erase(it);
857 return;
858 }
859 }
860
861 qCWarning(LinkManagerLog) << "called with unknown config";
862}
863
868
870{
871 QMutexLocker locker(&_linksMutex);
872
873 for (const SharedLinkInterfacePtr &sharedLink : _rgLinks) {
874 if (sharedLink.get() == link) {
875 return true;
876 }
877 }
878
879 return false;
880}
881
883{
884 (void) _qmlConfigurations->append(config);
885 (void) _rgLinkConfigs.append(SharedLinkConfigurationPtr(config));
886
887 return _rgLinkConfigs.last();
888}
889
890bool LinkManager::containsConfiguration(const QString& name) const
891{
892 return std::ranges::any_of(_rgLinkConfigs, [&name](const SharedLinkConfigurationPtr& config) {
893 return config && (config->name() == name);
894 });
895}
896
898{
899 for (SharedLinkConfigurationPtr &sharedConfig : _rgLinkConfigs) {
900 if (sharedConfig->isAutoConnect()) {
901 sharedConfig->setAutoConnectStarted(true);
902 createConnectedLink(sharedConfig);
903 }
904 }
905}
906
908{
909 for (uint8_t mavlinkChannel = 0; mavlinkChannel < MAVLINK_COMM_NUM_BUFFERS; mavlinkChannel++) {
910 if (_mavlinkChannelsUsedBitMask & (1 << mavlinkChannel)) {
911 continue;
912 }
913
914 mavlink_reset_channel_status(mavlinkChannel);
915 mavlink_status_t* const mavlinkStatus = mavlink_get_channel_status(mavlinkChannel);
916 mavlinkStatus->flags |= MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
917 _mavlinkChannelsUsedBitMask |= (1 << mavlinkChannel);
918 qCDebug(LinkManagerLog) << "allocateMavlinkChannel" << mavlinkChannel;
919 return mavlinkChannel;
920 }
921
922 qCWarning(LinkManagerLog) << "allocateMavlinkChannel: all channels reserved!";
923 return invalidMavlinkChannel();
924}
925
927{
928 qCDebug(LinkManagerLog) << "freeMavlinkChannel" << channel;
929
930 if (invalidMavlinkChannel() == channel) {
931 return;
932 }
933
934 _mavlinkChannelsUsedBitMask &= ~(1 << channel);
935}
936
938{
939 LogReplayConfiguration* const linkConfig = new LogReplayConfiguration(tr("Log Replay"));
940 linkConfig->setLogFilename(logFile);
941 linkConfig->setName(linkConfig->logFilenameShort());
942
943 SharedLinkConfigurationPtr sharedConfig = addConfiguration(linkConfig);
944 if (createConnectedLink(sharedConfig)) {
945 return qobject_cast<LogReplayLink*>(sharedConfig->link());
946 }
947
948 return nullptr;
949}
950
951bool LinkManager::isLinkUSBDirect([[maybe_unused]] const LinkInterface *link)
952{
953#ifndef QGC_NO_SERIAL_LINK
954 const SerialLink* const serialLink = qobject_cast<const SerialLink*>(link);
955 if (!serialLink) {
956 return false;
957 }
958
959 const SharedLinkConfigurationPtr config = serialLink->linkConfiguration();
960 if (!config) {
961 return false;
962 }
963
964 const SerialConfiguration* const serialConfig = qobject_cast<const SerialConfiguration*>(config.get());
965 if (serialConfig && serialConfig->usbDirect()) {
966 return link;
967 }
968#endif
969
970 return false;
971}
972
973#ifndef QGC_NO_SERIAL_LINK // Serial Only Functions
974
975void LinkManager::_updateSerialPorts()
976{
977 QStringList portList;
978 QStringList displayList;
979 const auto inventory = SerialPortManager::instance()->availablePorts();
980 for (const SerialPortManager::Port& info : inventory) {
981 portList += SerialPortManager::instance()->persistentName(info.systemLocation);
982 displayList += info.displayName.isEmpty() ? info.portName : info.displayName;
983 }
984 const bool portsChanged = _commPortList != portList;
985 const bool displayChanged = _commPortDisplayList != displayList;
986 _commPortList = std::move(portList);
987 _commPortDisplayList = std::move(displayList);
988 if (portsChanged) {
989 emit commPortsChanged();
990 }
991 if (displayChanged) {
993 }
994}
995
996bool LinkManager::_usePersistentPortName(LinkConfiguration* config)
997{
998 auto* const serialConfig = qobject_cast<SerialConfiguration*>(config);
999 // A dynamic configuration is not saved: automatic connection makes one for a port each time it finds it.
1000 if (!serialConfig || serialConfig->isDynamic()) {
1001 return false;
1002 }
1003
1004 // Asked of the last scan, which is recent: the inventory is scanned every second, and on Android also when
1005 // the user lets QGC open a device.
1006 const QString persistentName = SerialPortManager::instance()->persistentName(serialConfig->portName());
1007 if (persistentName == serialConfig->portName()) {
1008 return false;
1009 }
1010 serialConfig->setPortName(persistentName);
1011 return true;
1012}
1013
1015{
1016 if (_commPortDisplayList.isEmpty()) {
1017 _updateSerialPorts();
1018 }
1019
1020 return _commPortDisplayList;
1021}
1022
1024{
1025 if (_commPortList.isEmpty()) {
1026 _updateSerialPorts();
1027 }
1028
1029 return _commPortList;
1030}
1031
1036
1037bool LinkManager::serialPortHasFlowControl(const QString& portName) const
1038{
1039 const std::optional<SerialPortManager::Port> port = SerialPortManager::instance()->port(portName);
1040 return !port || port->hardwareFlowControl;
1041}
1042
1043#endif // QGC_NO_SERIAL_LINK
Q_APPLICATION_STATIC(ADSBVehicleManager, _adsbVehicleManager, SettingsManager::instance() ->adsbVehicleManagerSettings())
std::shared_ptr< LinkConfiguration > SharedLinkConfigurationPtr
std::shared_ptr< LinkInterface > SharedLinkInterfacePtr
mavlink_status_t * mavlink_get_channel_status(uint8_t chan)
Definition QGCMAVLink.cc:53
#define MAVLINK_COMM_NUM_BUFFERS
#define QGC_LOGGING_CATEGORY(name, categoryStr)
A Fact is used to hold a single value within the system.
Definition Fact.h:15
void rawValueChanged(const QVariant &value)
Interface holding link specific settings.
@ TypeSerial
Serial Link.
@ TypeBluetooth
Bluetooth Link.
virtual void loadSettings(QSettings &settings, const QString &root)=0
static LinkConfiguration * duplicateSettings(const LinkConfiguration *source)
virtual void copyFrom(const LinkConfiguration *source)
void setDynamic(bool dynamic=true)
Set if this is this a dynamic configuration. (decided at runtime).
void setHighLatency(bool hl=false)
Set if this is this an High Latency configuration.
static LinkConfiguration * createSettings(int type, const QString &name)
void setForwarding(bool forwarding=true)
Set if this is this a forwarding link configuration. (decided at runtime).
static QString settingsRoot()
LinkInterface * link() const
void nameChanged(const QString &name)
void setSuppressAutoReconnect(bool suppress)
void setName(const QString &name)
QString name() const
void setAutoConnect(bool autoc=true)
Set if this is this an Auto Connect configuration.
The link interface defines the interface for all links used to communicate with the ground station ap...
void bytesReceived(LinkInterface *link, const QByteArray &data)
void disconnected()
virtual void _freeMavlinkChannel()
virtual Q_INVOKABLE void disconnect()=0
void communicationError(const QString &title, const QString &error)
void bytesSent(LinkInterface *link, const QByteArray &data)
void connected()
SharedLinkConfigurationPtr linkConfiguration()
Manage communication links The Link Manager organizes the physical Links. It can manage arbitrary lin...
Definition LinkManager.h:31
void commPortStringsChanged()
Q_INVOKABLE void createConnectedLink(const LinkConfiguration *config)
This should only be used by Qml code.
Q_INVOKABLE bool serialPortHasFlowControl(const QString &portName) const
SharedLinkInterfacePtr sharedLinkInterfacePointerForLink(const LinkInterface *link)
QStringList serialPorts()
bool containsConfiguration(const QString &name) const
Q_INVOKABLE void endConfigurationEditing(LinkConfiguration *config, LinkConfiguration *editedConfig)
SharedLinkConfigurationPtr addConfiguration(LinkConfiguration *config)
QStringList linkTypeStrings() const
void loadLinkConfigurationList()
static bool isLinkUSBDirect(const LinkInterface *link)
uint8_t allocateMavlinkChannel()
Q_INVOKABLE void createMavlinkForwardingSupportLink()
Q_INVOKABLE LinkConfiguration * createConfiguration(int type, const QString &name)
Create/Edit Link Configuration.
void startAutoConnectedLinks()
Q_INVOKABLE void endCreateConfiguration(LinkConfiguration *config)
Q_INVOKABLE void shutdown()
Called to signal app shutdown. Disconnects all links while turning off auto-connect.
LinkManager(QObject *parent=nullptr)
static LinkManager * instance()
void freeMavlinkChannel(uint8_t channel)
Q_INVOKABLE void removeConfiguration(LinkConfiguration *config)
QList< SharedLinkInterfacePtr > links()
static constexpr uint8_t invalidMavlinkChannel()
void setConnectionsSuspended(const QString &reason)
Definition LinkManager.h:78
void disconnectAll()
Q_INVOKABLE LogReplayLink * startLogReplay(const QString &logFile)
void commPortsChanged()
QStringList serialPortStrings()
Q_INVOKABLE void disconnectLink(LinkInterface *link)
static QStringList serialBaudRates()
SharedLinkInterfacePtr mavlinkForwardingSupportLink()
Returns pointer to the mavlink support forwarding link, or nullptr if it does not exist.
Q_INVOKABLE void disconnectLinkConfiguration(LinkConfiguration *config)
Stop a link and suppress auto-reconnect, working whether or not a live link currently exists.
Q_INVOKABLE LinkConfiguration * startConfigurationEditing(LinkConfiguration *config)
bool containsLink(const LinkInterface *link)
SharedLinkInterfacePtr mavlinkForwardingLink()
Returns pointer to the mavlink forwarding link, or nullptr if it does not exist.
static bool isBluetoothAvailable()
void saveLinkConfigurationList()
void mavlinkSupportForwardingEnabledChanged()
QString logFilenameShort() const
void setLogFilename(const QString &logFilename)
void receiveBytes(LinkInterface *link, const QByteArray &data)
void logSentBytes(const LinkInterface *link, const QByteArray &data)
static MAVLinkProtocol * instance()
void resetMetadataForLink(LinkInterface *link)
static MultiVehicleManager * instance()
QObject * removeOne(const QObject *object) override final
bool usbDirect() const
Definition SerialLink.h:76
static QStringList supportedBaudRates()
static SerialPortManager * instance()
QList< Port > availablePorts()
std::optional< Port > port(const QString &name) const
void portsEnumerated(const QStringList &availablePorts)
Emitted only after a fresh scan, with every name of the ports it lists.
ReservationPtr reservePort(const QString &systemLocation, const QString &owner={})
void rescan()
As availablePorts(), without reusing a scan made less than a second ago.
QString persistentName(const QString &name) const
QString reservationOwner(const QString &systemLocation) const
The owner the port is reserved with; empty when it is not reserved or its holder gave none.
AutoConnectSettings * autoConnectSettings() const
static SettingsManager * instance()
AppSettings * appSettings() const
QStringList hostList() const
Definition UDPLink.h:83
void setLocalPort(quint16 port)
Definition UDPLink.h:95
Q_INVOKABLE void addHost(const QString &host)
Definition UDPLink.cc:129
void setRequireResolvedHosts(bool require)
Definition UDPLink.h:92
void setUsePosixSerial(bool use)
constexpr const char * toString(HwVideoBufferPath path) noexcept
Definition GstHwTypes.h:37
QList< Port > ports(const QList< Function > &functions)
Every port any function can run on, in port id order.
bool isBluetoothAvailable()
Check if Bluetooth is available on this device.
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