QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GPSReceiver.cc
Go to the documentation of this file.
1#include "GPSReceiver.h"
2
4#include "GPSReceiverConfig.h"
10#include "GPSSourceHealth.h"
11#include "PositionManager.h"
12#include "QGCLoggingCategory.h"
13#include "RuntimeScheduler.h"
14#include "TCPGPSTransport.h"
15#include "UDPGPSTransport.h"
16
17#ifndef QGC_NO_SERIAL_LINK
18#include "SerialGPSTransport.h"
19#include "SerialPortManager.h"
20#endif
21
22#include <algorithm>
23#include <type_traits>
24#include <utility>
25#include <variant>
26
27#include <QtCore/QDeadlineTimer>
28#include <QtCore/QSet>
29
30QGC_LOGGING_CATEGORY(GPSReceiverLog, "GPS.Receiver.GPSReceiver")
31
32namespace {
33
34void logConnectionError(GPSConnectionError error, const QString& detail)
35{
36 switch (error) {
37 case GPSConnectionError::OpenFailed:
38 qCWarning(GPSReceiverLog) << "Failed to open GPS receiver transport:" << detail;
39 break;
40 case GPSConnectionError::ConfigFailed:
41 case GPSConnectionError::ConsentRequired:
42 qCWarning(GPSReceiverLog) << "GPS receiver did not accept configuration";
43 break;
44 case GPSConnectionError::ProtocolError:
45 qCWarning(GPSReceiverLog) << "GPS receiver protocol error, connection lost:" << detail;
46 break;
47 case GPSConnectionError::DeviceError:
48 qCWarning(GPSReceiverLog) << "GPS device error, connection lost:" << detail;
49 break;
50 case GPSConnectionError::None:
51 break;
52 }
53}
54
55} // namespace
56
57GPSReceiver::GPSReceiver(QObject* parent, RuntimeScheduler* scheduler, const Dependencies& dependencies)
58 : QObject(parent)
59 , _correctionManager(dependencies.corrections)
60 , _positionManager(dependencies.positions)
61 , _scheduler(RuntimeScheduler::orDefault(scheduler, this))
62 , _positionHealth(new GPSSourceHealth(this, _scheduler))
63 , _outputOverflowTask(_scheduler, this)
64 , _pollTask(_scheduler, this)
65#ifndef QGC_NO_SERIAL_LINK
66 , _serialPorts(dependencies.serialPorts)
67#endif
68{
69 qCDebug(GPSReceiverLog) << this;
70 // A silent receiver stays connected, so its last solution must not remain on display.
71 connect(_positionHealth, &GPSSourceHealth::positionChanged, this, [this]() {
72 if (_positionHealth->state() == GPSSourceHealth::State::Stale) {
73 _clearStaleSolution();
74 }
75 });
76 _connection = std::make_unique<GPSReceiverConnectionPolicy>(static_cast<GPSReceiverConnector&>(*this),
77 _configuration, _scheduler);
78 _facts = new GPSReceiverFactGroup(this);
79 for (Fact* fact : {_facts->fixType(), _facts->active()}) {
80 connect(fact, &Fact::rawValueChanged, this, &GPSReceiver::_updateLabels);
81 }
82 connect(_facts, &FactGroup::telemetryAvailableChanged, this, &GPSReceiver::_updateLabels);
83 connect(this, &GPSReceiver::receiverChanged, this, &GPSReceiver::_updateLabels);
84 _updateLabels();
85 _notified.receiver = _receiverState();
86#ifndef QGC_NO_SERIAL_LINK
87 _serialTransportFactory = [](const QString& device, GPSCancelToken cancelToken) {
88 return std::make_unique<SerialGPSTransport>(device, std::move(cancelToken));
89 };
90 if (_serialPorts) {
91 connect(_serialPorts, &SerialPortManager::portsEnumerated, this, &GPSReceiver::_onSerialPortsEnumerated);
92 }
93#endif
94}
95
97{
98 if (_configuration == configuration) {
99 return;
100 }
101 Configuration previous = std::exchange(_configuration, configuration);
102#ifndef QGC_NO_SERIAL_LINK
103 const bool deviceChanged = previous.serialDevice != _configuration.serialDevice;
104 // Another name of the port that the device was saved by is the same connection: the saved device takes the
105 // persistent name of its port while the receiver is connected on it.
106 if (_serialPorts && _serialPorts->isSamePort(previous.serialDevice, _configuration.serialDevice)) {
107 previous.serialDevice = _configuration.serialDevice;
108 }
109#endif
110 if (!previous.sameConnection(_configuration)) {
111 _setPersistentChangesAllowed(false);
112 }
113 _connection->configurationChanged(previous);
114 ++_configurationRevision;
115 _emitChanges();
116#ifndef QGC_NO_SERIAL_LINK
117 // The entry of the port that the saved device names goes by that name.
118 if (deviceChanged && _serialPorts && !_serialPortEntries.isEmpty()) {
119 _updateSerialPortEntries();
120 }
121#endif
122}
123
125{
126 _setPersistentChangesAllowed(allowed);
127 _emitChanges();
128}
129
130void GPSReceiver::_setPersistentChangesAllowed(bool allowed)
131{
132 if (!_destroying) {
133 _persistentChangesAllowed = allowed;
134 }
135}
136
138{
139 return _configuration.receiverRole != RTKSettings::ConfiguredBase || effectiveConnectionType() != RTKSettings::Udp;
140}
141
143{
144 const GPSReceiverPresentation presentation =
145 capabilitiesFor(_configuration.receiverRole, _configuration.baseReceiverManufacturer);
146 if (presentation.passive) {
147 return true;
148 }
149 return std::visit(
150 [&presentation]<typename Mode>(const Mode&) {
151 if constexpr (std::is_same_v<Mode, GPSBaseStationConfig::Fixed>) {
152 return presentation.rtkBase;
153 } else if constexpr (std::is_same_v<Mode, GPSBaseStationConfig::SurveyIn>) {
154 return presentation.surveyIn;
155 } else {
156 return presentation.receiverAveraging;
157 }
158 },
159 _configuration.base.mode);
160}
161
163{
164 const GPSReceiverPresentation presentation =
165 capabilitiesFor(_configuration.receiverRole, _configuration.baseReceiverManufacturer);
166 return (presentation.specificReceiver || presentation.automatic) && baseModeSupported() && connectionSupported();
167}
168
170{
171 if (_destroying) {
172 return;
173 }
174 if (hasReceiver()) {
175 qCWarning(GPSReceiverLog) << "Inject the worker factory before connecting a receiver";
176 return;
177 }
178 _workerFactory = std::move(factory);
179}
180
182{
183 _destroying = true;
184 // The policy must not run against a partially destroyed receiver.
185 _connection.reset();
186 _retireSession();
187
188 qCDebug(GPSReceiverLog) << this;
189}
190
191GPSReceiver::ReceiverState GPSReceiver::_receiverState() const
192{
193 return {.hasReceiver = hasReceiver(),
194 .baseMode = activeBaseMode(),
195 .endpoint = activeEndpoint(),
196 .identity = receiverIdentity(),
197 .detected = detectedReceiver(),
198 .reconnecting = reconnecting(),
199 .presentation = activePresentation(),
200 .role = activeRole(),
201 .forwardingCorrections = forwardingCorrections()};
202}
203
204void GPSReceiver::_emitChanges()
205{
206 if (_destroying) {
207 return;
208 }
209 // Starting or stopping to reconnect the saved receiver is a session change.
210 if (reconnecting() != _notified.receiver.reconnecting) {
211 _setPersistentChangesAllowed(false);
212 }
213 if (std::exchange(_notified.configurationRevision, _configurationRevision) != _configurationRevision) {
215 }
216 if (std::exchange(_notified.persistentChangesAllowed, _persistentChangesAllowed) != _persistentChangesAllowed) {
218 }
219 const QString error = errorMessage();
220 if (std::exchange(_notified.errorMessage, error) != error) {
221 emit errorMessageChanged();
222 }
223 const ReceiverState receiver = _receiverState();
224 if (std::exchange(_notified.receiver, receiver) != receiver) {
225 emit receiverChanged();
226 }
227}
228
229void GPSReceiver::_resetStatus()
230{
231 _facts->_reset();
232 _outputOverflowUs = 0;
233 _outputOverflowTask.cancel();
234 _outputOverflowWarning.clear();
235}
236
237void GPSReceiver::_clearStaleSolution()
238{
239 _facts->_clearSolution();
240 _emitChanges();
241}
242
244{
245 return _errorMessage.isEmpty() ? _outputOverflowWarning : _errorMessage;
246}
247
248void GPSReceiver::_updateOutputOverflow(uint64_t receiptUs)
249{
250 if (receiptUs == 0 || std::exchange(_outputOverflowUs, receiptUs) == receiptUs) {
251 return;
252 }
253 _outputOverflowWarning =
254 GPSReceiverMessages::outputOverflow(activeRole(), _session && _session->compactObservations());
255 _outputOverflowTask.schedule(OUTPUT_OVERFLOW_WARNING_DURATION, [this]() {
256 _outputOverflowWarning.clear();
257 _emitChanges();
258 });
259}
260
261void GPSReceiver::_onGPSConnect()
262{
263 _setError();
264 _connection->receiverReady();
265 _facts->_setConfigured(true);
266 _setPersistentChangesAllowed(false);
267 if (_session) {
268 _session->registerPosition(_positionManager, _positionHealth);
269 }
270 _emitChanges();
271#ifndef QGC_NO_SERIAL_LINK
272 _usePersistentSerialDevice();
273#endif
274}
275
276void GPSReceiver::_onReceiverDetected()
277{
278 _setPersistentChangesAllowed(false);
279 _emitChanges();
280}
281
282void GPSReceiver::_onInputProblem(GPSInputProblem problem)
283{
284 _setError(GPSReceiverMessages::inputProblem(problem, _session ? _session->detectedType() : std::nullopt,
286 _emitChanges();
287}
288
289void GPSReceiver::_endSession(GPSConnectionError error, const QString& detail, bool portRemoved)
290{
291 // The family an Automatic session detected, else the selected one.
292 const auto* family = _session ? gpsReceiverDescriptorForManufacturer(_session->manufacturer()) : nullptr;
293 _retireSession();
294 _resetStatus();
295 _setPersistentChangesAllowed(false);
296 const GPSReceiverSessionOutcome outcome = _connection->sessionEnded(portRemoved);
297 if (portRemoved) {
298 qCDebug(GPSReceiverLog) << "Receiver serial device removed";
299 }
300 // Automatic connections never pass the flash-save consent this receiver asked for.
301 if (outcome == GPSReceiverSessionOutcome::AutoRetrying && error == GPSConnectionError::ConsentRequired &&
302 !detail.isEmpty() && family) {
303 qCWarning(GPSReceiverLog) << "GPS receiver did not accept configuration";
304 _setError(GPSReceiverMessages::consentRefused(detail, family->type));
305 return;
306 }
308 qCWarning(GPSReceiverLog) << "GPS receiver session ended:" << error << detail;
309 } else if (outcome == GPSReceiverSessionOutcome::None && !portRemoved) {
310 logConnectionError(error, detail);
311 }
312 _setError(GPSReceiverMessages::sessionEnded(outcome, error, detail, portRemoved));
313}
314
315void GPSReceiver::_onGPSSurveyReport(const GPSSurveyReport& status)
316{
317 _facts->_setSurvey(status);
318 _emitChanges();
319}
320
321#ifndef QGC_NO_SERIAL_LINK
322void GPSReceiver::_onSerialPortsEnumerated(const QStringList& devices)
323{
324 if (_destroying) {
325 return;
326 }
327 if (_session && !_session->serialDevice().isEmpty() && !devices.contains(_session->serialDevice())) {
328 _endSession(GPSConnectionError::DeviceError, {}, true);
329 _emitChanges();
330 }
331 _updateSerialPortEntries();
332 _usePersistentSerialDevice();
333}
334
335bool GPSReceiver::serialPortAvailable(const QString& device) const
336{
337 if (device.isEmpty() || !_serialPorts) {
338 return false;
339 }
340 (void) _serialPorts->availablePorts();
341 const std::optional<SerialPortManager::Port> port = _serialPorts->port(device);
342 return port && !port->bootloader;
343}
344
345QString GPSReceiver::serialPortLabel(const QString& device) const
346{
347 // Only a USB port on Android is without access while it is not listed: its device is detached, or QGC may not
348 // open it. Its address is another one each time the device is attached and its stable name is made of IDs, so
349 // neither tells the user which device is meant.
350 const bool named = !_serialPorts || _serialPorts->port(device) || _serialPorts->hasAccess(device);
351 return named ? _serialLocation(device) : QString();
352}
353
354bool GPSReceiver::serialPortAllowed(const QString& device) const
355{
356 return !_serialPorts || _serialPorts->hasAccess(device);
357}
358
359QString GPSReceiver::_serialLocation(const QString& device) const
360{
361 const std::optional<SerialPortManager::Port> port = _serialPorts ? _serialPorts->port(device) : std::nullopt;
362 return port ? port->systemLocation : device.trimmed();
363}
364
365void GPSReceiver::_usePersistentSerialDevice()
366{
367 // Only once the receiver has answered on the port: the system location that an older build saved may be
368 // another device's by now. On Android the user has then let QGC open the device, if only after it was saved,
369 // and a scan gives the port its stable name.
370 if (!_serialPorts || !_session || !_facts->telemetryAvailable()) {
371 return;
372 }
373 const QString saved = _configuration.serialDevice.trimmed();
374 // Not the port of a discovered receiver, which has no saved device and is not given one.
375 if (!_serialPorts->isSamePort(saved, _session->serialDevice())) {
376 return;
377 }
378 const QString persistent = _serialPorts->persistentName(_session->serialDevice());
379 if (persistent != saved) {
380 emit serialDeviceRenamed(persistent);
381 }
382}
383
384QStringList GPSReceiver::rtkReceiverPorts() const
385{
386 QStringList receivers;
387 if (!_serialPorts) {
388 return receivers;
389 }
390 QSet<QString> seenDevices;
391 for (const auto& port : _serialPorts->availablePorts()) {
392 if (port.boardType != QGCSerialPortInfo::BoardTypeRTKGPS || port.bootloader) {
393 continue;
394 }
395 // A labelled NMEA interface remains a receiver candidate on composite GPS devices.
396 const bool primary = SerialPortManager::isPrimaryInterface(port, seenDevices);
397 if ((primary || port.description.contains(QStringLiteral("NMEA"))) &&
398 _serialPorts->canReservePort(port.systemLocation)) {
399 receivers.append(port.systemLocation);
400 }
401 }
402 return receivers;
403}
404
405GPSSerialClaim GPSReceiver::claimSerialPort(const QString& device)
406{
407 //: Ends the sentence "Cannot connect the link: the serial port is in use by ..."
408 const QString owner = tr("the GPS receiver");
409 // By the system location, which the session opens. A claim by a name that survives replugging would be on the
410 // port that the device comes back as, while the worker of the session that lost it may still hold the claim.
411 const QString location = _serialLocation(device);
412 GPSSerialClaim claim = _serialPorts ? _serialPorts->reservePort(location, owner) : nullptr;
413 if (claim) {
414 _serialClaims.insert(location, claim);
415 }
416 return claim;
417}
418
419void GPSReceiver::_updateSerialPortEntries()
420{
421 // Just after a scan the manager returns that inventory without scanning again.
422 const QList<SerialPortManager::Port> available = _serialPorts->availablePorts();
423 QList<GPSSerialPortEntry> entries;
424 entries.reserve(available.size());
425 for (const auto& port : available) {
426 // The USB product string, else the name of a known board.
427 const QString name = port.description.trimmed().isEmpty() ? port.boardName : port.description.trimmed();
428 //: %1 is a serial device's name, such as u-blox GNSS receiver; %2 its path, such as /dev/ttyACM0 or COM3
429 QString label = name.isEmpty() ? port.systemLocation : tr("%1 – %2").arg(name, port.systemLocation);
430 if (_serialPorts->isPortReserved(port.systemLocation) && _serialClaims.value(port.systemLocation).expired()) {
431 //: %1 is a serial device that another QGroundControl connection, such as a vehicle link, uses
432 label = tr("%1 (in use)").arg(label);
433 }
434 // The port that the saved device names by another name than the one to save it by takes the latter only
435 // once the receiver has connected on it. Until then the picker finds its selection by the saved name.
436 const bool savedPort = _serialPorts->isSamePort(_configuration.serialDevice, port.systemLocation);
437 entries.append(
438 {.value = savedPort ? _configuration.serialDevice : _serialPorts->persistentName(port.systemLocation),
439 .label = label});
440 }
441 if (entries != _serialPortEntries) {
442 _serialPortEntries = std::move(entries);
444 }
445}
446
447bool GPSReceiver::connectSerial(const QString& device, GPSType type, uint32_t baudRate, bool allowPersistentChanges,
448 GPSSerialClaim claim)
449{
450 const QString endpoint = _serialLocation(device);
451 return _connectReceiver(
452 type,
453 [endpoint, claim = std::move(claim), factory = _serialTransportFactory](GPSCancelToken cancelToken) {
454 return factory(endpoint, std::move(cancelToken));
455 },
456 QStringLiteral("serial:%1").arg(endpoint), baudRate, allowPersistentChanges, endpoint, endpoint);
457}
458#endif
459
460bool GPSReceiver::connectTcp(const QString& host, quint16 port, GPSType type, bool allowPersistentChanges)
461{
462 const QString endpoint = QStringLiteral("%1:%2").arg(host).arg(port);
463 return _connectReceiver(
464 type,
465 [host, port](GPSCancelToken cancelToken) {
466 return std::make_unique<TCPGPSTransport>(host, port, std::move(cancelToken));
467 },
468 QStringLiteral("tcp:%1").arg(endpoint), GPSTransport::BRIDGE_BAUDRATE, allowPersistentChanges, {}, endpoint);
469}
470
471bool GPSReceiver::connectUdp(quint16 port, GPSType type)
472{
473 //: %1 is the local UDP port the receiver's data arrives on
474 const QString endpoint = tr("UDP port %1").arg(port);
475 return _connectReceiver(
476 type,
477 [port](GPSCancelToken cancelToken) { return std::make_unique<UDPGPSTransport>(port, std::move(cancelToken)); },
478 QStringLiteral("udp:%1").arg(port), GPSTransport::BRIDGE_BAUDRATE, false, {}, endpoint);
479}
480
482{
483 QList<int> rates;
484#ifndef QGC_NO_SERIAL_LINK
485 for (const QString& text : SerialPortManager::supportedBaudRates()) {
486 const uint32_t rate = text.toUInt();
487 if (gpsValidBaudRate(rate, true) && !rates.contains(static_cast<int>(rate))) {
488 rates.append(static_cast<int>(rate));
489 }
490 }
491#endif
492 return rates;
493}
494
496{
498 role == RTKSettings::ConfiguredBase ? manufacturer : gpsReceiverManufacturerForType(GPSType::passive));
499}
500
502{
503 return _session && _session->hasWorker();
504}
505
506int GPSReceiver::_activeManufacturer() const
507{
508 return _session ? _session->manufacturer() : 0;
509}
510
512{
513 return _session ? _session->baseMode() : -1;
514}
515
517{
518 return _session ? _session->endpoint() : QString();
519}
520
522{
523 return _session ? _session->identity() : QString();
524}
525
527{
528 const std::optional<GPSType> detected = _session ? _session->detectedType() : std::nullopt;
529 if (!detected) {
530 return {};
531 }
532 return activeRole() == RTKSettings::Passive ? gpsInputProtocolName(*detected) : gpsReceiverName(*detected);
533}
534
536{
537 return _session ? _session->role() : RTKSettings::ConfiguredBase;
538}
539
541{
542 return _session && _session->forwardsCorrections();
543}
544
546{
547 return gpsReceiverPresentation(_activeManufacturer());
548}
549
551{
552 if (_destroying) {
553 return false;
554 }
555 const bool allowed =
556 _persistentChangesAllowed &&
557 capabilitiesFor(_configuration.receiverRole, _configuration.baseReceiverManufacturer).persistentConfiguration;
558 _setPersistentChangesAllowed(false);
559#ifndef QGC_NO_SERIAL_LINK
560 const QString device = _configuration.serialDevice.trimmed();
561 // The user asked for this connection, so they are asked again for a USB device that they have denied QGC:
562 // opening the port asks only once for each time the device is attached. The session keeps trying to open the
563 // port for a while, and so opens it once they allow it.
564 const bool asked = _serialPorts && !hasReceiver() && effectiveConnectionType() == RTKSettings::Serial &&
565 !device.isEmpty() && _serialPorts->requestAccess(device);
566 if (asked && !serialPortAvailable(device)) {
567 // A device that QGC may not open is listed without the name that survives replugging, so a device saved by
568 // that name is not found until the user allows it. An automatic connection that waits for it goes on waiting.
569 _setError(tr("Allow QGroundControl to open the receiver's USB device, then connect."));
570 _emitChanges();
571 return false;
572 }
573#endif
574 const bool connected = _connection->connectConfigured(allowed);
575 _emitChanges();
576 return connected;
577}
578
580{
581 if (_destroying) {
582 return;
583 }
584 _setPersistentChangesAllowed(false);
585 _connection->disconnectConfigured();
586 _emitChanges();
587}
588
589void GPSReceiver::startConnectionPolling(std::function<bool()> suspended)
590{
591 if (_destroying) {
592 return;
593 }
594 (void) _pollTask.scheduleRepeating(POLL_INTERVAL, [this, suspended = std::move(suspended)]() {
595 if (!suspended || !suspended()) {
596 tick();
597 }
598 });
599}
600
602{
603 if (_destroying) {
604 return;
605 }
606 _connection->update();
607 _emitChanges();
608}
609
611{
612 return _connection && _connection->reconnecting();
613}
614
616{
617 return _positionHealth->acceptedObservation(use);
618}
619
620bool GPSReceiver::_connectReceiver(GPSType type, GPSReceiverWorker::TransportFactory transportFactory,
621 const QString& sourceInstance, uint32_t baudRate, bool allowPersistentChanges,
622 const QString& serialDevice, const QString& endpoint)
623{
624 QString configError;
625 GPSReceiverConfig config =
626 gpsReceiverConfigFor(_configuration.base, type, baudRate, allowPersistentChanges, &configError);
627 if (!configError.isEmpty()) {
628 _setError(configError);
629 return false;
630 }
631 _retireSession();
632 _resetStatus();
633 _setError();
634 const RTKSettings::ReceiverRole role =
635 type == GPSType::passive ? RTKSettings::Passive : RTKSettings::ConfiguredBase;
636 auto* const session = new GPSReceiverSession(
637 ++_sessionCount,
638 {.type = type,
639 .role = role,
640 .forwardsCorrections = role == RTKSettings::ConfiguredBase || _configuration.forwardReceiverRtcm,
641 .config = std::move(config),
642 .serialDevice = serialDevice,
643 .endpoint = endpoint},
644 this);
645 session->registerCorrections(_correctionManager, sourceInstance);
646 _session = session;
647 connect(session, &GPSReceiverSession::satelliteInfoUpdated, this, &GPSReceiver::_onSatelliteInfoUpdated);
648 connect(session, &GPSReceiverSession::positionUpdated, this, &GPSReceiver::_onPositionUpdated);
649 connect(session, &GPSReceiverSession::surveyInStatusUpdated, this, &GPSReceiver::_onGPSSurveyReport);
650 connect(session, &GPSReceiverSession::receiverReady, this, &GPSReceiver::_onGPSConnect);
651 connect(session, &GPSReceiverSession::receiverDetected, this, &GPSReceiver::_onReceiverDetected);
652 connect(session, &GPSReceiverSession::inputProblem, this, &GPSReceiver::_onInputProblem);
653 connect(session, &GPSReceiverSession::ended, this, [this](GPSConnectionError error, const QString& detail) {
654 _endSession(error, detail, false);
655 _emitChanges();
656 });
657 if (!session->start(_workerFactory, std::move(transportFactory))) {
658 _retireSession();
659 _setError(tr("Failed to create the receiver session."));
660 return false;
661 }
662 _setPersistentChangesAllowed(false);
663 return true;
664}
665
666void GPSReceiver::_retireSession()
667{
668 if (auto* const retired = std::exchange(_session, nullptr)) {
669 _retiredWorkers.removeIf([](const QPointer<GPSReceiverWorker>& worker) { return worker.isNull(); });
670 if (QPointer<GPSReceiverWorker> worker = retired->worker()) {
671 _retiredWorkers.append(std::move(worker));
672 }
673 retired->deleteLater();
674 retired->retire();
675 }
676 _positionHealth->reset();
677}
678
680{
681 if (_destroying) {
682 return;
683 }
684 _pollTask.cancel();
685 _connection->reset();
686 endConnection(false);
687 _joinRetiredWorkers();
688 _emitChanges();
689}
690
691void GPSReceiver::_joinRetiredWorkers()
692{
693 // At application exit the event loop that deletes finished workers has stopped, so they are joined here.
694 const QDeadlineTimer deadline(SHUTDOWN_TIMEOUT);
695 for (const QPointer<GPSReceiverWorker>& worker : std::exchange(_retiredWorkers, {})) {
696 if (!worker) {
697 continue;
698 }
699 if (worker->wait(deadline)) {
700 delete worker.data();
701 } else {
702 qCWarning(GPSReceiverLog) << "GPS receiver worker did not stop within" << SHUTDOWN_TIMEOUT.count() << "s";
703 }
704 }
705}
706
707void GPSReceiver::endConnection(bool clearError)
708{
709 _retireSession();
710 _resetStatus();
711 _setPersistentChangesAllowed(false);
712 if (clearError) {
713 _setError();
714 }
715}
716
717void GPSReceiver::_onSatelliteInfoUpdated(const GPSSatelliteReport& msg)
718{
719 const int inView = msg.inView.value_or(-1);
720 const int used = msg.used.value_or(-1);
721 qCDebug(GPSReceiverLog) << QStringLiteral("%1 in view, %2 used")
722 .arg(inView)
723 .arg(msg.used ? QString::number(used) : QStringLiteral("unknown"));
724 _facts->_setSatellites(inView, used);
725 _emitChanges();
726}
727
728void GPSReceiver::_onPositionUpdated(const GPSPositionReport& report)
729{
730 if (gpsFixQualityFromValue(_facts->fixType()->rawValue().toInt()) != report.navigation.fixType) {
731 qCDebug(GPSReceiverLog) << "Receiver fix changed:" << report.navigation.fixType;
732 }
733 // Drivers project integrity to Unknown once it is older than its freshness window.
734 _facts->_setSolution(report.navigation.fixType, report.integrity);
735 _updateOutputOverflow(report.integrity.outputOverflowUs);
736 if (_session) {
737 _positionHealth->updateObservation(_session->observation(report, _scheduler->nowUs()));
738 }
739 _emitChanges();
740}
741
742void GPSReceiver::_updateLabels()
743{
744 const QString status = GPSReceiverMessages::receiverStatus({.configured = _facts->telemetryAvailable(),
745 .hasReceiver = hasReceiver(),
746 .identifying = activePresentation().automatic,
747 .reconnecting = reconnecting(),
748 .role = activeRole(),
749 .forwardingCorrections = forwardingCorrections(),
750 .baseMode = activeBaseMode(),
751 .surveyActive = _facts->active()->rawValue().toBool()});
752 if (std::exchange(_statusText, status) != status) {
753 emit statusTextChanged();
754 }
755
756 QString label;
758 label = _facts->active()->rawValue().toBool() ? tr("Survey", "Base survey-in in progress") : tr("Base");
759 } else {
760 label = GPSReceiverMessages::fixLabel(gpsFixQualityFromValue(_facts->fixType()->rawValue().toInt()));
761 }
762 if (std::exchange(_summaryLabel, label) != label) {
763 emit summaryLabelChanged();
764 }
765}
GPSConnectionErrors::GPSInputProblem GPSInputProblem
GPSConnectionErrors::GPSConnectionError GPSConnectionError
constexpr bool gpsValidBaudRate(uint32_t baudRate, bool passive)
GPSReceiverSessionOutcome
What the policy does after a receiver session ends; the receiver words the message for it.
@ None
Nothing reconnects; the receiver's own message for the error applies.
@ AutoRetrying
A discovered receiver failed or was lost; discovery retries it.
@ Retrying
The saved receiver's connection was lost; a retry is scheduled.
SerialPortManager::ReservationPtr GPSSerialClaim
Holds a serial device for one receiver session until the last copy is released.
const GPSReceiverDescriptor * gpsReceiverDescriptorForManufacturer(int manufacturer)
QString gpsInputProtocolName(GPSType type)
int gpsReceiverManufacturerForType(GPSType type)
The persisted manufacturer of type, or GPS_AUTOMATIC_MANUFACTURER when it has none.
QString gpsReceiverName(GPSType type)
The name of type's receiver family as shown to users; empty when no descriptor exists.
const GPSReceiverPresentation & gpsReceiverPresentation(int manufacturer)
constexpr GPSFixQuality gpsFixQualityFromValue(int value)
GPSReceiverConfig gpsReceiverConfigFor(const GPSBaseStationConfig &base, GPSType type, uint32_t baudRate, bool allowPersistentChanges, QString *error)
GPSTypes::GPSType GPSType
Definition GPSType.h:25
#define QGC_LOGGING_CATEGORY(name, categoryStr)
void telemetryAvailableChanged(bool telemetryAvailable)
A Fact is used to hold a single value within the system.
Definition Fact.h:15
void rawValueChanged(const QVariant &value)
virtual QStringList rtkReceiverPorts() const =0
void receiverReady(const QString &identity)
void ended(GPSConnectionError error, const QString &detail)
The worker failed or exited; the owner ends the session.
void surveyInStatusUpdated(const GPSSurveyReport &report)
Survey progress of a configured base.
void positionUpdated(const GPSPositionReport &report)
void receiverDetected(GPSType type)
The family an Automatic session detected, or the protocol a passive receiver's output carries.
int manufacturer() const
The detected family's once an Automatic session detected it; a passive receiver's stays passive.
void inputProblem(GPSInputProblem problem)
Why a passive receiver delivers no position; None once positions arrive.
void satelliteInfoUpdated(const GPSSatelliteReport &report)
std::function< std::unique_ptr< GPSTransport >(GPSCancelToken)> TransportFactory
Consumed on the worker thread, so transport construction, I/O and destruction share that thread.
void summaryLabelChanged()
static constexpr std::chrono::seconds POLL_INTERVAL
How often connection polling ticks the receiver.
void startConnectionPolling(std::function< bool()> suspended={})
Runs tick() every POLL_INTERVAL until shutdown(), skipping ticks while suspended returns true.
RTKSettings::ConnectionType effectiveConnectionType() const
QString detectedReceiver() const
static QList< int > serialBaudRates()
The application's serial rates that a receiver accepts as an explicit rate; empty without serial link...
GPSReceiver(QObject *parent=nullptr, RuntimeScheduler *scheduler=nullptr, const Dependencies &dependencies={})
const Configuration & configuration() const
void receiverChanged()
RTKSettings::ReceiverRole activeRole() const
bool connectionSupported() const
UDP only receives, so a receiver QGroundControl configures needs serial or TCP.
QString activeEndpoint() const
Serial device or TCP host:port of the active receiver.
void configurationChanged()
Q_INVOKABLE GPSReceiverPresentation capabilitiesFor(int role, int manufacturer) const
Editable settings for a role; configured bases also depend on the manufacturer.
bool hasReceiver() const override
void persistentChangesAllowedChanged()
void serialPortEntriesChanged()
bool forwardingCorrections() const
GPSReceiverWorkerFactory WorkerFactory
void shutdown()
static constexpr std::chrono::seconds SHUTDOWN_TIMEOUT
How long shutdown() waits for the workers of retired sessions.
int activeBaseMode() const
bool reconnecting() const
The saved receiver is being connected automatically, at startup or after its connection was lost.
void setWorkerFactory(WorkerFactory factory)
Inject before connecting; an empty factory restores the real worker.
void serialDeviceRenamed(const QString &device)
GPSReceiverPresentation activePresentation() const
Presentation capabilities of the connected receiver family.
GPSReceiverDependencies Dependencies
void statusTextChanged()
void errorMessageChanged()
static constexpr std::chrono::seconds OUTPUT_OVERFLOW_WARNING_DURATION
How long the warning about output the receiver dropped stays after the last report of it.
std::optional< GPSObservation > acceptedPositionObservation(GPSObservation::PositionUse use) const
Latest receiver solution that passes the consumer's gates; empty without a fresh fix.
QString errorMessage() const
The connection or input problem, else a recent report that the receiver dropped output.
GPSReceiverConfiguration Configuration
void setConfiguration(const Configuration &configuration)
Q_INVOKABLE bool connectReceiver()
void tick()
One step of automatic connection: connections due, reconnections, and USB discovery.
bool baseModeSupported() const
void setPersistentChangesAllowed(bool allowed)
Granting permission only lasts until the configuration changes, a session starts or ends,...
bool canConnect() const
Q_INVOKABLE void disconnectReceiver()
Disconnects and pauses automatic connection until the user connects again.
QString receiverIdentity() const
Session health is independent of transport readiness and RTK survey-in validity.
void positionChanged()
static constexpr unsigned BRIDGE_BAUDRATE
ReceiverRole
Persisted values of receiverRole. The storage type keeps any saved value a valid enum value.
Definition RTKSettings.h:36
static QStringList supportedBaudRates()
static bool isPrimaryInterface(const Port &port, QSet< QString > &seenDevices)
void portsEnumerated(const QStringList &availablePorts)
Emitted only after a fresh scan, with every name of the ports it lists.
QString consentRefused(const QString &detail, GPSType family)
The error of an automatic connection that the family receiver refused for lack of flash-save consent.
QString outputOverflow(RTKSettings::ReceiverRole role, bool compactObservations)
The warning that the receiver produces more output than its connection carries.
QString fixLabel(GPSFixQuality fixType)
The short label of a fix type; empty for an unknown one.
QString receiverStatus(const ReceiverStatus &status)
The receiver status sentence; empty when no receiver is connected or being connected.
QString sessionEnded(GPSReceiverSessionOutcome outcome, GPSConnectionError error, const QString &detail, bool portRemoved)
QString inputProblem(GPSInputProblem problem, std::optional< GPSType > detected, const QString &endpoint, bool forwardingCorrections)
GPSCommandSequence port(QByteArrayView port, unsigned baud)
Clears the SBF output of port, keeps a serial port at the link's baud, and selects SBF and the WGS84 ...
Definition SBFPlan.cc:34
QCameraDevice device(const QString &description)
The attached camera of description description; a null device when none is.
Definition UVCDevices.cc:21
GPSIntegrityReport integrity
GPSNavigationValues navigation
bool sameConnection(const GPSReceiverConfiguration &other) const
bool automatic
The family is detected when connecting.
std::optional< int > used
std::optional< int > inView