8#include <QtCore/QCoreApplication>
9#include <QtCore/QMetaObject>
10#include <QtCore/QMutex>
18QString withDetail(
const QString& text,
const QString& detail)
20 return detail.isEmpty() ? text : text + QStringLiteral(
": ") + detail;
27 return QSerialPort::tr(
"Device disconnected");
29 return QSerialPort::tr(
"Reading from the device failed");
31 return QSerialPort::tr(
"Writing to the device failed");
35 return QSerialPort::tr(
"Device stopped transferring data");
69 QSerialPort::tr(
"USB permission was denied. Replug the device or connect to it by hand to be "
73 QSerialPort::tr(
"USB permission has not been granted. You have been asked to allow it")};
76 QSerialPort::tr(
"USB permission has not been granted. The request has not been answered yet")};
79 QSerialPort::tr(
"USB permission has not been granted. The device was just attached, and "
80 "Android asks first")};
84 QSerialPort::tr(
"USB permission has not been granted. %1 asks once its window has the focus")
85 .arg(QCoreApplication::applicationName())};
93 QSerialPort::tr(
"More than one attached USB device has this name. Unplug the others, or choose "
110 explicit UsbSerialBackend(AndroidSerialBackendHost port)
114 ~UsbSerialBackend()
override {
close(); }
116 bool open(QIODevice::OpenMode mode)
override;
117 void close()
override;
119 int descriptor()
const override {
return _descriptor; }
122 bool waitForInput(
const QDeadlineTimer& deadline)
override;
123 qint64 startWrite(
const char* data, qint64 maxSize)
override;
124 bool waitForWritable(
const QDeadlineTimer& deadline)
override;
128 bool setBreakEnabled(
bool set)
override;
129 bool clear(QSerialPort::Directions directions)
override;
130 QSerialPort::PinoutSignals pinoutSignals()
override;
135 bool newDataArrived(
const char* bytes,
int length)
override;
136 void bytesWritten(
int count)
override;
147 void _setDeviceGoneError();
149 struct DeviceParameters
156 bool operator==(
const DeviceParameters&)
const =
default;
166 AndroidSerialBackendHost _port;
169 int _descriptor = -1;
173 std::optional<DeviceParameters> _deviceParameters;
176 bool _readThreadStarted =
false;
179 std::atomic<bool> _readingPaused{
false};
182 bool _deviceGone =
false;
186 std::optional<Loss> _loss;
189bool UsbSerialBackend::open(QIODevice::OpenMode)
196 OpenFailure error = openFailure(openResult);
198 if (isPermissionRefusal(openResult)) {
201 qCDebug(AndroidSerialPortLog) <<
"No permission to open" << _port.
systemLocation() <<
":" << error.text;
203 qCWarning(AndroidSerialPortLog) <<
"Error opening" << _port.
systemLocation() <<
":" << error.text;
207 _port.
setError(error.code, error.text);
211 _descriptor = opened;
215void UsbSerialBackend::close()
227 _readThreadStarted =
false;
228 _readingPaused.store(
false);
230 _deviceParameters.reset();
239 qCDebug(AndroidSerialPortLog) <<
"Device of" << _port.
systemLocation() <<
"was gone before it was closed";
243 (void) _commandSucceeded(closeResult, QSerialPort::tr(
"Closing device failed"));
246bool UsbSerialBackend::startReading()
248 const bool paused = _readingPaused.exchange(
false);
249 if (_readThreadStarted && !paused) {
264 qCDebug(AndroidSerialPortLog) <<
"Device is gone, cannot read port" << _port.
systemLocation();
265 _setDeviceGoneError();
271 return _commandSucceeded(result, QSerialPort::tr(
"Failed to start async read"));
274bool UsbSerialBackend::waitForInput(
const QDeadlineTimer& deadline)
279 return !_reportLoss();
282qint64 UsbSerialBackend::startWrite(
const char* data, qint64 maxSize)
286 constexpr qint64 kMaxChunkBytes = 16 * 1024;
288 const int length =
static_cast<int>(std::min(maxSize, kMaxChunkBytes));
291 return std::min(result, length);
299 qCDebug(AndroidSerialPortLog) <<
"Device is gone, failed to write to port" << _port.
systemLocation();
301 _setDeviceGoneError();
305 qCWarning(AndroidSerialPortLog).noquote()
306 << withDetail(QStringLiteral(
"Failed to write to port ") + _port.
systemLocation(), detail);
313bool UsbSerialBackend::waitForWritable(
const QDeadlineTimer& deadline)
316 return !_reportLoss();
322 const DeviceParameters requested{baudRate, dataBits, stopBits, parity};
323 if (_deviceParameters == requested) {
329 _deviceParameters = requested;
331 _deviceParameters.reset();
334 return _commandSucceeded(result, failureText);
340 QSerialPort::tr(
"Failed to set flow control"));
343bool UsbSerialBackend::setBreakEnabled(
bool set)
348bool UsbSerialBackend::clear(QSerialPort::Directions directions)
351 QSerialPort::tr(
"Failed to purge buffers"));
354QSerialPort::PinoutSignals UsbSerialBackend::pinoutSignals()
359bool UsbSerialBackend::setDataTerminalReady(
bool set)
364bool UsbSerialBackend::setRequestToSend(
bool set)
369bool UsbSerialBackend::newDataArrived(
const char* bytes,
int length)
375 _readingPaused.store(
true);
379 _readingPaused.store(
false);
386void UsbSerialBackend::bytesWritten(
int count)
394 QMutexLocker locker(&_lossMutex);
395 _loss = Loss{_handle, reason, detail};
402 QMetaObject::invokeMethod(&_port.
serialPort(), [
this]() { (void) _reportLoss(); }, Qt::QueuedConnection);
405bool UsbSerialBackend::_reportLoss()
407 std::optional<Loss> loss;
409 QMutexLocker locker(&_lossMutex);
410 loss = std::exchange(_loss, std::nullopt);
412 if (!loss || (loss->handle != _handle)) {
419 const QString text = resourceErrorText(loss->reason);
420 qCWarning(AndroidSerialPortLog) <<
"Resource error on" << _port.
systemLocation() <<
":"
421 << withDetail(text, loss->detail);
423 _readThreadStarted =
false;
428void UsbSerialBackend::_setDeviceGoneError()
442 qCDebug(AndroidSerialPortLog).noquote()
443 <<
"Device is gone:" << failureText <<
"on" << _port.
systemLocation();
445 if (!_reportLoss()) {
446 _setDeviceGoneError();
474 qCWarning(AndroidSerialPortLog).noquote()
475 << withDetail(failureText + QStringLiteral(
" on ") + _port.
systemLocation(), detail);
476 _port.
setError(errorCode, withDetail(failureText, detail));
484 return std::make_unique<UsbSerialBackend>(port);
std::unique_ptr< AndroidSerialBackend > createUsbSerialBackend(AndroidSerialBackendHost port)
A USB serial adapter, which Java drives (AndroidSerial).
A QSerialPort as its backend sees it: what the backend asks of the port and reports to it.
void waitForArrivedInput(const QDeadlineTimer &deadline)
void setError(QSerialPort::SerialPortError error, const QString &text=QString())
bool newDataArrived(const char *bytes, int length)
void writeCompleted(qint64 bytes)
bool hasRoomForInput()
Returns whether the port has room for more input, on any thread.
void waitForWriteProgress(const QDeadlineTimer &deadline)
QSerialPort & serialPort() const
The port itself, for its settings, its error and its thread.
QString systemLocation() const
@ UnsupportedOperationError
SerialPortError error() const
qint64 PortHandle
Names an open port in every call to Java and in Java's callbacks. registerPort() makes one.
QString getLastErrorDetail()
PortHandle registerPort(PortListener *listener)
Returns a handle under which Java's callbacks reach the listener until unregisterPort() has returned.
constexpr PortHandle kNoPort
Result setDataTerminalReady(PortHandle handle, bool set)
Result setRequestToSend(PortHandle handle, bool set)
Result startReading(PortHandle handle)
QSerialPort::PinoutSignals getControlLines(PortHandle handle)
The control lines that are active.
Result purgeBuffers(PortHandle handle, QSerialPort::Directions directions)
Result setFlowControl(PortHandle handle, QSerialPort::FlowControl flowControl)
Result setBreak(PortHandle handle, bool set)
Result close(PortHandle handle)
ResourceErrorReason
Why a port can no longer transfer data. QGCUsbSerialResourceError.java lists the same values.
@ WriteFailed
A write to the device failed.
@ ReadFailed
A read from the device failed.
@ DeviceDetached
The device was unplugged.
int open(const QString &portName, PortHandle handle)
Result setParameters(PortHandle handle, qint32 baudRate, QSerialPort::DataBits dataBits, QSerialPort::StopBits stopBits, QSerialPort::Parity parity)
@ AlreadyOpen
Opening: the port is already open.
@ AmbiguousName
Opening: several attached devices share this stable name, so it opens none.
@ PermissionPending
The user was asked before, and has not answered yet.
@ PermissionDenied
Opening: QGC may not use the device, and the user denied the request to allow it.
@ PermissionAwaitsAndroid
The device was just attached, and Android asks the user first.
@ Unsupported
The port or its driver cannot do this.
@ NotOpen
No port is open under this handle.
@ DeviceNotFound
Opening: there is no such device.
@ PermissionRequested
This open has asked the user to allow it.
@ Failed
The call could not be made, or failed for a reason not listed here.
@ PermissionAwaitsFocus
The user is not asked while another window has the focus.
@ IoError
The device did not carry it out, and may be gone.
void unregisterPort(PortHandle handle)
int writeAsync(PortHandle handle, const char *data, int length)
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 ...