QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
SerialGPSTransport.cc
Go to the documentation of this file.
2
3#include <algorithm>
4#include <utility>
5
6#include <QtCore/QCoreApplication>
7#include <QtCore/QDeadlineTimer>
8#include <QtCore/QFileInfo>
9#include <QtSerialPort/QSerialPort>
10
11#include "QGCLoggingCategory.h"
12
13QGC_LOGGING_CATEGORY(SerialGPSTransportLog, "GPS.Transport.SerialGPSTransport")
14
15namespace {
16
18QString openFailure(const QSerialPort& serial, const QString& device)
19{
20 switch (serial.error()) {
22 //: %1 is a serial device, such as /dev/ttyACM0 or COM3
23 return QCoreApplication::translate("SerialGPSTransport", "%1 was not found").arg(device);
25#ifdef Q_OS_ANDROID
26 // The port tells which it is: QGC may not use the USB device yet, or the port is open already.
27 return serial.errorString();
28#else
29#ifdef Q_OS_UNIX
30 // A device held by another program reports a permission error too.
31 if (const QFileInfo file(device); file.exists() && !(file.isReadable() && file.isWritable())) {
32 //: %1 is a serial device, such as /dev/ttyACM0
33 return QCoreApplication::translate("SerialGPSTransport", "permission denied for %1").arg(device);
34 }
35#endif
36 //: %1 is a serial device, such as /dev/ttyACM0 or COM3
37 return QCoreApplication::translate("SerialGPSTransport", "%1 is in use by another program").arg(device);
38#endif
39 default:
40 return serial.errorString();
41 }
42}
43
44} // namespace
45
47 std::chrono::milliseconds openTimeout)
49 , _device(std::move(device))
50 , _openTimeout(openTimeout)
51{}
52
54
56{
57 if (isCancelled()) {
59 }
60 _serial = std::make_unique<QSerialPort>();
61 _inputOverflow = false;
62 _serial->setReadBufferSize(READ_BUFFER_BYTES);
63 QObject::connect(
64 _serial.get(), &QSerialPort::readyRead, _serial.get(),
65 [this]() {
66 // With no serial flow control, exhausting our budget makes stream continuity unverifiable.
67 // Retire the attempt rather than decode bytes across a possible overrun.
68 _inputOverflow = _inputOverflow || _serial->bytesAvailable() >= READ_BUFFER_BYTES;
69 },
70 Qt::DirectConnection);
71 _acceptedTotal = 0;
72 _writtenTotal = 0;
73 QObject::connect(
74 _serial.get(), &QSerialPort::bytesWritten, _serial.get(), [this](qint64 count) { _writtenTotal += count; },
75 Qt::DirectConnection);
76 _serial->setPortName(_device);
77 const QDeadlineTimer openDeadline(_openTimeout);
78 while (!_serial->open(QIODevice::ReadWrite)) {
79 if (isCancelled()) {
81 }
82 // Device can take 10-20s to become accessible after startup.
83 if (_serial->error() != QSerialPort::PermissionError || openDeadline.hasExpired()) {
84 qCWarning(SerialGPSTransportLog)
85 << "GPS: Failed to open Serial Device" << _device << _serial->errorString();
86 return {openDeadline.hasExpired() ? GPSOpenStatus::TimedOut : GPSOpenStatus::Error,
87 openFailure(*_serial, _device)};
88 }
89 qCDebug(SerialGPSTransportLog) << "Cannot open device... retrying";
90 const QDeadlineTimer retryDeadline(
91 (std::min) (std::chrono::milliseconds(openDeadline.remainingTime()), OPEN_RETRY));
92 (void) waitUntil([]() { return false; }, retryDeadline);
93 if (isCancelled()) {
95 }
96 }
97 _serial->clearError();
98
99 const bool configured = _serial->setBaudRate(QSerialPort::Baud9600) && _serial->setDataBits(QSerialPort::Data8) &&
100 _serial->setParity(QSerialPort::NoParity) && _serial->setStopBits(QSerialPort::OneStop) &&
101 _serial->setFlowControl(QSerialPort::NoFlowControl);
102 if (!configured || isCancelled()) {
104 _serial->errorString()};
105 _serial->close();
106 return result;
107 }
108 return {GPSOpenStatus::Opened};
109}
110
112{
113 return _inputBudgetExhausted() || !_serial || !_serial->isOpen() ||
114 ((_serial->error() != QSerialPort::NoError) && (_serial->error() != QSerialPort::TimeoutError));
115}
116
118{
119 return _serial.get();
120}
121
123{
124 return fatalError();
125}
126
127bool SerialGPSTransport::waitReadable(QDeadlineTimer deadline)
128{
129 // Unlike a socket, a serial port delivers no input once a stop or an overrun was seen.
130 return GPSDeviceTransport::waitReadable(deadline) && !isCancelled() && !fatalError();
131}
132
134{
135 return {_inputBudgetExhausted() ? GPSReadStatus::Overflow : GPSReadStatus::Error, 0, _errorDetail()};
136}
137
138bool SerialGPSTransport::_inputBudgetExhausted() const
139{
140 return _inputOverflow || (_serial && _serial->bytesAvailable() >= READ_BUFFER_BYTES);
141}
142
143QString SerialGPSTransport::_errorDetail() const
144{
145 return _inputBudgetExhausted()
146 ? QStringLiteral("Serial GPS input buffer exhausted; reconnect required to restore stream continuity")
147 : _serial ? _serial->errorString()
148 : QStringLiteral("Serial GPS connection is closed");
149}
150
151void SerialGPSTransport::waitWritten(QDeadlineTimer& deadline)
152{
153 _serial->waitForBytesWritten(static_cast<int>(
154 (deadline.isForever() ? CANCELLATION_POLL
155 : (std::min) (std::chrono::milliseconds(deadline.remainingTime()), CANCELLATION_POLL))
156 .count()));
157}
158
159qint64 SerialGPSTransport::confirmedWritten(int accepted, qint64 drained)
160{
161 Q_UNUSED(drained)
162 const qint64 previousAccepted = _acceptedTotal;
163 _acceptedTotal += accepted;
164 // Late bytesWritten signals belong to earlier connection-wide submissions.
165 const qint64 confirmed =
166 !fatalError() ? (std::max) (_writtenTotal, _acceptedTotal - _serial->bytesToWrite()) : _writtenTotal;
167 return confirmed - previousAccepted;
168}
169
170bool SerialGPSTransport::setBaudrate(unsigned baudrate)
171{
172 if (isCancelled() || fatalError()) {
173 return false;
174 }
175 if (_serial->setBaudRate(static_cast<qint32>(baudrate))) {
176 return true;
177 }
178 // A refused rate leaves the port open at its previous rate; only a lost device ends the link.
179 if (_serial->isOpen() && _serial->error() != QSerialPort::ResourceError) {
180 qCDebug(SerialGPSTransportLog) << "Link refused" << baudrate << "baud:" << _serial->errorString();
181 _serial->clearError();
182 }
183 return false;
184}
#define QGC_LOGGING_CATEGORY(name, categoryStr)
bool waitUntil(const std::function< bool()> &done, QDeadlineTimer deadline)
virtual bool waitReadable(QDeadlineTimer deadline)
Waits until input is buffered. Input reported buffered is delivered even after the link fails.
static constexpr qint64 READ_BUFFER_BYTES
bool isCancelled() const
const GPSCancelToken & cancelToken() const
SerialPortError error() const
bool setBaudrate(unsigned baudrate) override
void waitWritten(QDeadlineTimer &deadline) override
Waits for queued bytes to drain. May expire deadline to end the write.
bool fatalError() const override
True once the port hits an error the receive loop should stop retrying past.
GPSOpenResult open() override
SerialGPSTransport(QString device, GPSCancelToken cancelToken, std::chrono::milliseconds openTimeout=OPEN_TIMEOUT)
GPSReadResult readFailure() const override
Describes a failed link; by default, a closed connection with the device's error.
qint64 confirmedWritten(int accepted, qint64 drained) override
~SerialGPSTransport() override
bool waitReadable(QDeadlineTimer deadline) override
Waits until input is buffered. Input reported buffered is delivered even after the link fails.
bool readUnavailable() const override
Whether read() fails without waiting; by default, when there is no device.
QIODevice * device() const override
The open device, or null before open().