QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
UsbSerialBackend.cc
Go to the documentation of this file.
1// The USB backend of QSerialPort: a serial adapter that Java drives, reached through AndroidSerial.
2
3#include <algorithm>
4#include <atomic>
5#include <optional>
6#include <utility>
7
8#include <QtCore/QCoreApplication>
9#include <QtCore/QMetaObject>
10#include <QtCore/QMutex>
11
13#include "AndroidSerialJni.h"
14
15namespace {
16
18QString withDetail(const QString& text, const QString& detail)
19{
20 return detail.isEmpty() ? text : text + QStringLiteral(": ") + detail;
21}
22
23QString resourceErrorText(AndroidSerial::ResourceErrorReason reason)
24{
25 switch (reason) {
27 return QSerialPort::tr("Device disconnected");
29 return QSerialPort::tr("Reading from the device failed");
31 return QSerialPort::tr("Writing to the device failed");
32 }
33
34 // A reason that only a newer Java side lists.
35 return QSerialPort::tr("Device stopped transferring data");
36}
37
40bool isPermissionRefusal(AndroidSerial::Result openResult)
41{
42 switch (openResult) {
48 return true;
49 default:
50 return false;
51 }
52}
53
54struct OpenFailure
55{
57 QString text;
58};
59
60OpenFailure openFailure(AndroidSerial::Result openResult)
61{
62 switch (openResult) {
64 return {QSerialPort::DeviceNotFoundError, QSerialPort::tr("No such device")};
65 // The port's owner shows the text to the user, so each refusal for lack of permission has a whole text
66 // of its own, and Java keeps no detail of it, which would follow the text untranslated.
69 QSerialPort::tr("USB permission was denied. Replug the device or connect to it by hand to be "
70 "asked again")};
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")};
83 //: %1 is the name of the app, such as QGroundControl
84 QSerialPort::tr("USB permission has not been granted. %1 asks once its window has the focus")
85 .arg(QCoreApplication::applicationName())};
87 // Desktop QSerialPort reports a device that another owner holds as PermissionError too.
88 return {QSerialPort::PermissionError, QSerialPort::tr("Device is already open")};
90 // Adapters of a kind that report the same serial number, or none. One of them alone has the name
91 // to itself, and each is listed under the name that Android gave it.
93 QSerialPort::tr("More than one attached USB device has this name. Unplug the others, or choose "
94 "the port again")};
100 break;
101 }
102
103 // Also a result that only a newer Java side lists.
104 return {QSerialPort::UnknownError, QSerialPort::tr("Failed to open the USB device")};
105}
106
107class UsbSerialBackend final : public AndroidSerialBackend, private AndroidSerial::PortListener
108{
109public:
110 explicit UsbSerialBackend(AndroidSerialBackendHost port)
111 : _port(port)
112 {}
113
114 ~UsbSerialBackend() override { close(); }
115
116 bool open(QIODevice::OpenMode mode) override;
117 void close() override;
118
119 int descriptor() const override { return _descriptor; }
120
121 bool startReading() override;
122 bool waitForInput(const QDeadlineTimer& deadline) override;
123 qint64 startWrite(const char* data, qint64 maxSize) override;
124 bool waitForWritable(const QDeadlineTimer& deadline) override;
125 bool setParameters(qint32 baudRate, QSerialPort::DataBits dataBits, QSerialPort::StopBits stopBits,
126 QSerialPort::Parity parity, const QString& failureText) override;
127 bool setFlowControl(QSerialPort::FlowControl flowControl) override;
128 bool setBreakEnabled(bool set) override;
129 bool clear(QSerialPort::Directions directions) override;
130 QSerialPort::PinoutSignals pinoutSignals() override;
131 bool setDataTerminalReady(bool set) override;
132 bool setRequestToSend(bool set) override;
133
134private:
135 bool newDataArrived(const char* bytes, int length) override;
136 void bytesWritten(int count) override;
137 void resourceErrorArrived(AndroidSerial::ResourceErrorReason reason, const QString& detail) override;
138
142 bool _commandSucceeded(AndroidSerial::Result result, const QString& failureText);
145 bool _reportLoss();
147 void _setDeviceGoneError();
148
149 struct DeviceParameters
150 {
151 qint32 baudRate;
152 QSerialPort::DataBits dataBits;
153 QSerialPort::StopBits stopBits;
154 QSerialPort::Parity parity;
155
156 bool operator==(const DeviceParameters&) const = default;
157 };
158
159 struct Loss
160 {
163 QString detail;
164 };
165
166 AndroidSerialBackendHost _port;
167 // Names the port to Java while the device is open.
169 int _descriptor = -1;
170 // What the device was last set to since it was opened. Each QSerialPort setter passes all four parameters
171 // down again, and setting the device costs USB transfers, so an unchanged set is not resent. Nothing after a
172 // set that failed: a chip that takes the baud rate and the framing in separate transfers may have taken one.
173 std::optional<DeviceParameters> _deviceParameters;
174 // Whether Java's read thread was started and has not since been stopped or reported a resource error. Kept
175 // here because every read that empties the port's buffer asks, and asking Java is a JNI call.
176 bool _readThreadStarted = false;
177 // Whether Java's read thread was told that the port has no room for more input, on which it waits to be
178 // started again. That thread writes it.
179 std::atomic<bool> _readingPaused{false};
180 // Whether Java has answered that it no longer has the port open. It is not asked to read again, since it
181 // logs every such call.
182 bool _deviceGone = false;
183 // The loss of the device that Java has reported, on its own thread, and of which the port's thread has not
184 // told the port yet.
185 QMutex _lossMutex;
186 std::optional<Loss> _loss;
187};
188
189bool UsbSerialBackend::open(QIODevice::OpenMode)
190{
191 _handle = AndroidSerial::registerPort(this);
192
193 const int opened = AndroidSerial::open(_port.systemLocation(), _handle);
194 if (opened < 0) {
195 const auto openResult = static_cast<AndroidSerial::Result>(opened);
196 OpenFailure error = openFailure(openResult);
197 error.text = withDetail(error.text, AndroidSerial::getLastErrorDetail());
198 if (isPermissionRefusal(openResult)) {
199 // Auto-connect opens the port again and again while its device waits for the user's permission. Java
200 // warns of the first refusal.
201 qCDebug(AndroidSerialPortLog) << "No permission to open" << _port.systemLocation() << ":" << error.text;
202 } else {
203 qCWarning(AndroidSerialPortLog) << "Error opening" << _port.systemLocation() << ":" << error.text;
204 }
206 _handle = AndroidSerial::kNoPort;
207 _port.setError(error.code, error.text);
208 return false;
209 }
210
211 _descriptor = opened;
212 return true;
213}
214
215void UsbSerialBackend::close()
216{
217 if (_handle == AndroidSerial::kNoPort) {
218 return;
219 }
220
221 // Closing the device also stops its read thread.
222 const AndroidSerial::Result closeResult = AndroidSerial::close(_handle);
223 // Java reports nothing more to this backend once this returns.
225 _handle = AndroidSerial::kNoPort;
226 _descriptor = -1;
227 _readThreadStarted = false;
228 _readingPaused.store(false);
229 _deviceGone = false;
230 _deviceParameters.reset();
231
232 if (closeResult == AndroidSerial::Result::Ok) {
233 return;
234 }
235
236 // A device whose loss the port has reported may fail to close: its owner, which closes the port over that
237 // loss, hears of no other.
239 qCDebug(AndroidSerialPortLog) << "Device of" << _port.systemLocation() << "was gone before it was closed";
240 return;
241 }
242
243 (void) _commandSucceeded(closeResult, QSerialPort::tr("Closing device failed"));
244}
245
246bool UsbSerialBackend::startReading()
247{
248 const bool paused = _readingPaused.exchange(false);
249 if (_readThreadStarted && !paused) {
250 return true;
251 }
252
253 if (_deviceGone) {
254 return false;
255 }
256
258 if (result == AndroidSerial::Result::NotOpen) {
259 // Java closed its side of the port when the device was detached, and said so. If its report of the loss
260 // has not reached the port yet, the port hears that. An owner that leaves the port open comes here on
261 // every read(), so it hears of the loss again only if it cleared that error.
262 _deviceGone = true;
263 if (!_reportLoss() && (_port.serialPort().error() != QSerialPort::ResourceError)) {
264 qCDebug(AndroidSerialPortLog) << "Device is gone, cannot read port" << _port.systemLocation();
265 _setDeviceGoneError();
266 }
267 return false;
268 }
269
270 _readThreadStarted = (result == AndroidSerial::Result::Ok);
271 return _commandSucceeded(result, QSerialPort::tr("Failed to start async read"));
272}
273
274bool UsbSerialBackend::waitForInput(const QDeadlineTimer& deadline)
275{
276 // Java's threads deliver the input and report what was written; there is no descriptor to poll. They also end
277 // the wait when the device is lost.
278 _port.waitForArrivedInput(deadline);
279 return !_reportLoss();
280}
281
282qint64 UsbSerialBackend::startWrite(const char* data, qint64 maxSize)
283{
284 // Java reports a chunk only once all of it is written, so a large one would be a long time without
285 // progress, and it is copied whole for the call.
286 constexpr qint64 kMaxChunkBytes = 16 * 1024;
287
288 const int length = static_cast<int>(std::min(maxSize, kMaxChunkBytes));
289 const int result = AndroidSerial::writeAsync(_handle, data, length);
290 if (result >= 0) {
291 return std::min(result, length);
292 }
293
294 if (result == static_cast<int>(AndroidSerial::Result::IoError) ||
295 result == static_cast<int>(AndroidSerial::Result::NotOpen)) {
296 // Like desktop QSerialPort when the device disappears; the port's owner is expected to close it. The
297 // port hears Java's own report of the loss if that has not reached it yet, and nothing more of a loss that
298 // it has been told of: Java refuses output from then on.
299 qCDebug(AndroidSerialPortLog) << "Device is gone, failed to write to port" << _port.systemLocation();
300 if (!_reportLoss() && (_port.serialPort().error() != QSerialPort::ResourceError)) {
301 _setDeviceGoneError();
302 }
303 } else {
304 const QString detail = AndroidSerial::getLastErrorDetail();
305 qCWarning(AndroidSerialPortLog).noquote()
306 << withDetail(QStringLiteral("Failed to write to port ") + _port.systemLocation(), detail);
307 _port.setError(QSerialPort::WriteError, withDetail(QSerialPort::tr("Failed to write to port"), detail));
308 }
309
310 return -1;
311}
312
313bool UsbSerialBackend::waitForWritable(const QDeadlineTimer& deadline)
314{
315 _port.waitForWriteProgress(deadline);
316 return !_reportLoss();
317}
318
319bool UsbSerialBackend::setParameters(qint32 baudRate, QSerialPort::DataBits dataBits, QSerialPort::StopBits stopBits,
320 QSerialPort::Parity parity, const QString& failureText)
321{
322 const DeviceParameters requested{baudRate, dataBits, stopBits, parity};
323 if (_deviceParameters == requested) {
324 return true;
325 }
326
327 const AndroidSerial::Result result = AndroidSerial::setParameters(_handle, baudRate, dataBits, stopBits, parity);
328 if (result == AndroidSerial::Result::Ok) {
329 _deviceParameters = requested;
330 } else {
331 _deviceParameters.reset();
332 }
333
334 return _commandSucceeded(result, failureText);
335}
336
337bool UsbSerialBackend::setFlowControl(QSerialPort::FlowControl flowControl)
338{
339 return _commandSucceeded(AndroidSerial::setFlowControl(_handle, flowControl),
340 QSerialPort::tr("Failed to set flow control"));
341}
342
343bool UsbSerialBackend::setBreakEnabled(bool set)
344{
345 return _commandSucceeded(AndroidSerial::setBreak(_handle, set), QSerialPort::tr("Failed to set break"));
346}
347
348bool UsbSerialBackend::clear(QSerialPort::Directions directions)
349{
350 return _commandSucceeded(AndroidSerial::purgeBuffers(_handle, directions),
351 QSerialPort::tr("Failed to purge buffers"));
352}
353
354QSerialPort::PinoutSignals UsbSerialBackend::pinoutSignals()
355{
356 return AndroidSerial::getControlLines(_handle);
357}
358
359bool UsbSerialBackend::setDataTerminalReady(bool set)
360{
361 return _commandSucceeded(AndroidSerial::setDataTerminalReady(_handle, set), QSerialPort::tr("Failed to set DTR"));
362}
363
364bool UsbSerialBackend::setRequestToSend(bool set)
365{
366 return _commandSucceeded(AndroidSerial::setRequestToSend(_handle, set), QSerialPort::tr("Failed to set RTS"));
367}
368
369bool UsbSerialBackend::newDataArrived(const char* bytes, int length)
370{
371 if (_port.newDataArrived(bytes, length)) {
372 return true;
373 }
374
375 _readingPaused.store(true);
376 // The port's thread may have made room, and asked to read on, before the note above was there to tell it
377 // that Java pauses. Nothing would then end the pause, so Java pauses only if there is still no room.
378 if (_port.hasRoomForInput()) {
379 _readingPaused.store(false);
380 return true;
381 }
382
383 return false;
384}
385
386void UsbSerialBackend::bytesWritten(int count)
387{
388 _port.writeCompleted(count);
389}
390
391void UsbSerialBackend::resourceErrorArrived(AndroidSerial::ResourceErrorReason reason, const QString& detail)
392{
393 {
394 QMutexLocker locker(&_lossMutex);
395 _loss = Loss{_handle, reason, detail};
396 }
397 // A blocking wait on the port's thread runs no event loop, so the wait is ended and reports the loss itself.
398 _port.interruptWait();
399
400 // Queued for the port's thread, in case it is not waiting. This one is Java's, and AndroidSerial holds its
401 // registry lock while it reports, which the close that this error prompts has to take.
402 QMetaObject::invokeMethod(&_port.serialPort(), [this]() { (void) _reportLoss(); }, Qt::QueuedConnection);
403}
404
405bool UsbSerialBackend::_reportLoss()
406{
407 std::optional<Loss> loss;
408 {
409 QMutexLocker locker(&_lossMutex);
410 loss = std::exchange(_loss, std::nullopt);
411 }
412 if (!loss || (loss->handle != _handle)) {
413 // Nothing to tell, or the port closed, and may have opened again, before the loss reached its thread.
414 return false;
415 }
416
417 // The port's owner shows the text to the user, so Java's detail, which is not translated, goes to the log
418 // only.
419 const QString text = resourceErrorText(loss->reason);
420 qCWarning(AndroidSerialPortLog) << "Resource error on" << _port.systemLocation() << ":"
421 << withDetail(text, loss->detail);
422 // Java reports this when its read thread has ended, so the next read starts it again.
423 _readThreadStarted = false;
425 return true;
426}
427
428void UsbSerialBackend::_setDeviceGoneError()
429{
431}
432
433bool UsbSerialBackend::_commandSucceeded(AndroidSerial::Result result, const QString& failureText)
434{
436 switch (result) {
438 return true;
440 // Java closes its side of the port when the device is detached, and reports the loss on a thread of
441 // its own. A command that gets ahead of that report tells the port of the loss in its place.
442 qCDebug(AndroidSerialPortLog).noquote()
443 << "Device is gone:" << failureText << "on" << _port.systemLocation();
444 _deviceGone = true;
445 if (!_reportLoss()) {
446 _setDeviceGoneError();
447 }
448 return false;
450 // The device did not carry the command out. If Java has reported its loss, that is why, and all
451 // that the owner needs to hear. Otherwise the owner hears what failed: a link closes its port
452 // without a word over a ResourceError, which would hide a device that only refuses this command.
453 if (_reportLoss()) {
454 return false;
455 }
456 break;
459 break;
469 // Java's other failures say nothing a caller could act on differently.
470 break;
471 }
472
473 const QString detail = AndroidSerial::getLastErrorDetail();
474 qCWarning(AndroidSerialPortLog).noquote()
475 << withDetail(failureText + QStringLiteral(" on ") + _port.systemLocation(), detail);
476 _port.setError(errorCode, withDetail(failureText, detail));
477 return false;
478}
479
480} // namespace
481
482std::unique_ptr<AndroidSerialBackend> createUsbSerialBackend(AndroidSerialBackendHost port)
483{
484 return std::make_unique<UsbSerialBackend>(port);
485}
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.
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 ...
Definition SBFPlan.cc:34