17#ifndef QGC_NO_SERIAL_LINK
27#include <QtCore/QDeadlineTimer>
37 case GPSConnectionError::OpenFailed:
38 qCWarning(GPSReceiverLog) <<
"Failed to open GPS receiver transport:" << detail;
40 case GPSConnectionError::ConfigFailed:
41 case GPSConnectionError::ConsentRequired:
42 qCWarning(GPSReceiverLog) <<
"GPS receiver did not accept configuration";
44 case GPSConnectionError::ProtocolError:
45 qCWarning(GPSReceiverLog) <<
"GPS receiver protocol error, connection lost:" << detail;
47 case GPSConnectionError::DeviceError:
48 qCWarning(GPSReceiverLog) <<
"GPS device error, connection lost:" << detail;
50 case GPSConnectionError::None:
59 , _correctionManager(dependencies.corrections)
60 , _positionManager(dependencies.positions)
63 , _outputOverflowTask(_scheduler, this)
64 , _pollTask(_scheduler, this)
65#ifndef QGC_NO_SERIAL_LINK
66 , _serialPorts(dependencies.serialPorts)
69 qCDebug(GPSReceiverLog) <<
this;
73 _clearStaleSolution();
76 _connection = std::make_unique<GPSReceiverConnectionPolicy>(
static_cast<GPSReceiverConnector&
>(*
this),
77 _configuration, _scheduler);
79 for (
Fact* fact : {_facts->fixType(), _facts->active()}) {
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));
102#ifndef QGC_NO_SERIAL_LINK
103 const bool deviceChanged = previous.
serialDevice != _configuration.serialDevice;
106 if (_serialPorts && _serialPorts->isSamePort(previous.
serialDevice, _configuration.serialDevice)) {
111 _setPersistentChangesAllowed(
false);
113 _connection->configurationChanged(previous);
114 ++_configurationRevision;
116#ifndef QGC_NO_SERIAL_LINK
118 if (deviceChanged && _serialPorts && !_serialPortEntries.isEmpty()) {
119 _updateSerialPortEntries();
126 _setPersistentChangesAllowed(allowed);
130void GPSReceiver::_setPersistentChangesAllowed(
bool allowed)
133 _persistentChangesAllowed = allowed;
145 capabilitiesFor(_configuration.receiverRole, _configuration.baseReceiverManufacturer);
150 [&presentation]<
typename Mode>(
const Mode&) {
151 if constexpr (std::is_same_v<Mode, GPSBaseStationConfig::Fixed>) {
153 }
else if constexpr (std::is_same_v<Mode, GPSBaseStationConfig::SurveyIn>) {
159 _configuration.base.mode);
165 capabilitiesFor(_configuration.receiverRole, _configuration.baseReceiverManufacturer);
175 qCWarning(GPSReceiverLog) <<
"Inject the worker factory before connecting a receiver";
178 _workerFactory = std::move(factory);
188 qCDebug(GPSReceiverLog) <<
this;
191GPSReceiver::ReceiverState GPSReceiver::_receiverState()
const
204void GPSReceiver::_emitChanges()
210 if (
reconnecting() != _notified.receiver.reconnecting) {
211 _setPersistentChangesAllowed(
false);
213 if (std::exchange(_notified.configurationRevision, _configurationRevision) != _configurationRevision) {
216 if (std::exchange(_notified.persistentChangesAllowed, _persistentChangesAllowed) != _persistentChangesAllowed) {
220 if (std::exchange(_notified.errorMessage, error) != error) {
223 const ReceiverState receiver = _receiverState();
224 if (std::exchange(_notified.receiver, receiver) != receiver) {
229void GPSReceiver::_resetStatus()
232 _outputOverflowUs = 0;
233 _outputOverflowTask.cancel();
234 _outputOverflowWarning.clear();
237void GPSReceiver::_clearStaleSolution()
239 _facts->_clearSolution();
245 return _errorMessage.isEmpty() ? _outputOverflowWarning : _errorMessage;
248void GPSReceiver::_updateOutputOverflow(uint64_t receiptUs)
250 if (receiptUs == 0 || std::exchange(_outputOverflowUs, receiptUs) == receiptUs) {
253 _outputOverflowWarning =
256 _outputOverflowWarning.clear();
261void GPSReceiver::_onGPSConnect()
264 _connection->receiverReady();
265 _facts->_setConfigured(
true);
266 _setPersistentChangesAllowed(
false);
268 _session->registerPosition(_positionManager, _positionHealth);
271#ifndef QGC_NO_SERIAL_LINK
272 _usePersistentSerialDevice();
276void GPSReceiver::_onReceiverDetected()
278 _setPersistentChangesAllowed(
false);
289void GPSReceiver::_endSession(
GPSConnectionError error,
const QString& detail,
bool portRemoved)
295 _setPersistentChangesAllowed(
false);
298 qCDebug(GPSReceiverLog) <<
"Receiver serial device removed";
302 !detail.isEmpty() && family) {
303 qCWarning(GPSReceiverLog) <<
"GPS receiver did not accept configuration";
308 qCWarning(GPSReceiverLog) <<
"GPS receiver session ended:" << error << detail;
310 logConnectionError(error, detail);
317 _facts->_setSurvey(status);
321#ifndef QGC_NO_SERIAL_LINK
322void GPSReceiver::_onSerialPortsEnumerated(
const QStringList& devices)
327 if (_session && !_session->serialDevice().isEmpty() && !devices.contains(_session->serialDevice())) {
328 _endSession(GPSConnectionError::DeviceError, {},
true);
331 _updateSerialPortEntries();
332 _usePersistentSerialDevice();
335bool GPSReceiver::serialPortAvailable(
const QString& device)
const
337 if (
device.isEmpty() || !_serialPorts) {
340 (void) _serialPorts->availablePorts();
341 const std::optional<SerialPortManager::Port>
port = _serialPorts->port(device);
345QString GPSReceiver::serialPortLabel(
const QString& device)
const
350 const bool named = !_serialPorts || _serialPorts->port(device) || _serialPorts->hasAccess(device);
351 return named ? _serialLocation(device) : QString();
354bool GPSReceiver::serialPortAllowed(
const QString& device)
const
356 return !_serialPorts || _serialPorts->hasAccess(device);
359QString GPSReceiver::_serialLocation(
const QString& device)
const
361 const std::optional<SerialPortManager::Port>
port = _serialPorts ? _serialPorts->port(device) : std::nullopt;
365void GPSReceiver::_usePersistentSerialDevice()
370 if (!_serialPorts || !_session || !_facts->telemetryAvailable()) {
373 const QString saved = _configuration.serialDevice.trimmed();
375 if (!_serialPorts->isSamePort(saved, _session->serialDevice())) {
378 const QString persistent = _serialPorts->persistentName(_session->serialDevice());
379 if (persistent != saved) {
386 QStringList receivers;
390 QSet<QString> seenDevices;
391 for (
const auto& port : _serialPorts->availablePorts()) {
397 if ((primary ||
port.description.contains(QStringLiteral(
"NMEA"))) &&
398 _serialPorts->canReservePort(
port.systemLocation)) {
399 receivers.append(
port.systemLocation);
408 const QString owner = tr(
"the GPS receiver");
411 const QString location = _serialLocation(device);
412 GPSSerialClaim claim = _serialPorts ? _serialPorts->reservePort(location, owner) :
nullptr;
414 _serialClaims.insert(location, claim);
419void GPSReceiver::_updateSerialPortEntries()
422 const QList<SerialPortManager::Port> available = _serialPorts->availablePorts();
423 QList<GPSSerialPortEntry> entries;
424 entries.reserve(available.size());
425 for (
const auto& port : available) {
427 const QString name =
port.description.trimmed().isEmpty() ?
port.boardName :
port.description.trimmed();
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()) {
432 label = tr(
"%1 (in use)").arg(label);
436 const bool savedPort = _serialPorts->isSamePort(_configuration.serialDevice,
port.systemLocation);
438 {.value = savedPort ? _configuration.serialDevice : _serialPorts->persistentName(
port.systemLocation),
441 if (entries != _serialPortEntries) {
442 _serialPortEntries = std::move(entries);
447bool GPSReceiver::connectSerial(
const QString& device,
GPSType type, uint32_t baudRate,
bool allowPersistentChanges,
450 const QString endpoint = _serialLocation(device);
451 return _connectReceiver(
453 [endpoint, claim = std::move(claim), factory = _serialTransportFactory](GPSCancelToken cancelToken) {
454 return factory(endpoint, std::move(cancelToken));
456 QStringLiteral(
"serial:%1").arg(endpoint), baudRate, allowPersistentChanges, endpoint, endpoint);
460bool GPSReceiver::connectTcp(
const QString& host, quint16 port,
GPSType type,
bool allowPersistentChanges)
462 const QString endpoint = QStringLiteral(
"%1:%2").arg(host).arg(port);
463 return _connectReceiver(
465 [host, port](GPSCancelToken cancelToken) {
466 return std::make_unique<TCPGPSTransport>(host, port, std::move(cancelToken));
471bool GPSReceiver::connectUdp(quint16 port,
GPSType type)
474 const QString endpoint = tr(
"UDP port %1").arg(port);
475 return _connectReceiver(
477 [port](GPSCancelToken cancelToken) {
return std::make_unique<UDPGPSTransport>(port, std::move(cancelToken)); },
484#ifndef QGC_NO_SERIAL_LINK
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));
503 return _session && _session->hasWorker();
506int GPSReceiver::_activeManufacturer()
const
513 return _session ? _session->baseMode() : -1;
518 return _session ? _session->endpoint() : QString();
523 return _session ? _session->identity() : QString();
528 const std::optional<GPSType> detected = _session ? _session->detectedType() : std::nullopt;
542 return _session && _session->forwardsCorrections();
556 _persistentChangesAllowed &&
558 _setPersistentChangesAllowed(
false);
559#ifndef QGC_NO_SERIAL_LINK
560 const QString device = _configuration.serialDevice.trimmed();
565 !device.isEmpty() && _serialPorts->requestAccess(device);
566 if (asked && !serialPortAvailable(device)) {
569 _setError(tr(
"Allow QGroundControl to open the receiver's USB device, then connect."));
574 const bool connected = _connection->connectConfigured(allowed);
584 _setPersistentChangesAllowed(
false);
585 _connection->disconnectConfigured();
594 (void) _pollTask.scheduleRepeating(
POLL_INTERVAL, [
this, suspended = std::move(suspended)]() {
595 if (!suspended || !suspended()) {
606 _connection->update();
612 return _connection && _connection->reconnecting();
617 return _positionHealth->acceptedObservation(use);
621 const QString& sourceInstance, uint32_t baudRate,
bool allowPersistentChanges,
622 const QString& serialDevice,
const QString& endpoint)
627 if (!configError.isEmpty()) {
628 _setError(configError);
636 auto*
const session =
new GPSReceiverSession(
641 .config = std::move(config),
642 .serialDevice = serialDevice,
643 .endpoint = endpoint},
645 session->registerCorrections(_correctionManager, sourceInstance);
654 _endSession(error, detail,
false);
657 if (!session->start(_workerFactory, std::move(transportFactory))) {
659 _setError(tr(
"Failed to create the receiver session."));
662 _setPersistentChangesAllowed(
false);
666void GPSReceiver::_retireSession()
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));
673 retired->deleteLater();
676 _positionHealth->reset();
685 _connection->reset();
686 endConnection(
false);
687 _joinRetiredWorkers();
691void GPSReceiver::_joinRetiredWorkers()
695 for (
const QPointer<GPSReceiverWorker>& worker : std::exchange(_retiredWorkers, {})) {
699 if (worker->wait(deadline)) {
700 delete worker.data();
702 qCWarning(GPSReceiverLog) <<
"GPS receiver worker did not stop within" <<
SHUTDOWN_TIMEOUT.count() <<
"s";
707void GPSReceiver::endConnection(
bool clearError)
711 _setPersistentChangesAllowed(
false);
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")
723 .arg(msg.
used ? QString::number(used) : QStringLiteral(
"unknown"));
724 _facts->_setSatellites(inView, used);
737 _positionHealth->updateObservation(_session->observation(report, _scheduler->nowUs()));
742void GPSReceiver::_updateLabels()
751 .surveyActive = _facts->active()->rawValue().toBool()});
752 if (std::exchange(_statusText, status) != status) {
758 label = _facts->active()->rawValue().toBool() ? tr(
"Survey",
"Base survey-in in progress") : tr(
"Base");
762 if (std::exchange(_summaryLabel, label) != label) {
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
#define QGC_LOGGING_CATEGORY(name, categoryStr)
void telemetryAvailableChanged(bool telemetryAvailable)
A Fact is used to hold a single value within the system.
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
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
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 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,...
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.
static constexpr unsigned BRIDGE_BAUDRATE
ReceiverRole
Persisted values of receiverRole. The storage type keeps any saved value a valid enum value.
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 ...
QCameraDevice device(const QString &description)
The attached camera of description description; a null device when none is.
uint64_t outputOverflowUs
GPSIntegrityReport integrity
GPSNavigationValues navigation
bool sameConnection(const GPSReceiverConfiguration &other) const
GPSBaseStationConfig base
bool automatic
The family is detected when connecting.
bool persistentConfiguration
std::optional< int > used
std::optional< int > inView