12#include <QtCore/QDeadlineTimer>
13#include <QtCore/QPointer>
14#include <QtCore/QSocketNotifier>
20speed_t baudRateToSpeed(qint32 baudRate)
102constexpr unsigned long kGetTermios2 = _IOR(
'T', 0x2A, KernelTermios2);
103constexpr unsigned long kSetTermios2 = _IOW(
'T', 0x2B, KernelTermios2);
105constexpr tcflag_t kOtherBaudRate = 0010000;
107int pollTimeoutMs(
const QDeadlineTimer& deadline)
109 return deadline.isForever() ? -1 :
static_cast<int>(qMax<qint64>(0, deadline.remainingTime()));
115 explicit PosixSerialBackend(AndroidSerialBackendHost port)
119 ~PosixSerialBackend()
override {
close(); }
121 bool open(QIODevice::OpenMode mode)
override;
122 void close()
override;
124 int descriptor()
const override {
return _descriptor; }
127 bool waitForInput(
const QDeadlineTimer& deadline)
override;
128 qint64 startWrite(
const char* data, qint64 maxSize)
override;
129 bool waitForWritable(
const QDeadlineTimer& deadline)
override;
133 bool setBreakEnabled(
bool set)
override;
134 bool clear(QSerialPort::Directions directions)
override;
135 QSerialPort::PinoutSignals pinoutSignals()
override;
141 bool _setCustomBaudRate(qint32 baudRate);
145 bool _setControlLine(
int line,
bool set,
const char* lineName,
const QString& failureText);
147 bool _readActivated();
149 void _writeActivated();
150 void _readFailed(
int readError);
152 AndroidSerialBackendHost _port;
153 int _descriptor = -1;
154 QPointer<QSocketNotifier> _readNotifier;
157 bool _readPaused =
false;
159 QPointer<QSocketNotifier> _writeNotifier;
162bool PosixSerialBackend::open(QIODevice::OpenMode mode)
164 int flags = O_NOCTTY | O_NONBLOCK;
165 if ((mode & QIODevice::ReadWrite) == QIODevice::ReadWrite) {
167 }
else if (mode & QIODevice::WriteOnly) {
177 const int descriptor = ::open(_port.
systemLocation().toLocal8Bit().constData(), flags);
178 if (descriptor == -1) {
179 const int openErrno = errno;
180 qCWarning(AndroidSerialPortLog) <<
"Error opening" << _port.
systemLocation() <<
":" << strerror(openErrno);
182 : (openErrno == EACCES) ? QSerialPort::PermissionError
183 : QSerialPort::OpenError;
184 _port.
setError(openError, QString::fromLocal8Bit(strerror(openErrno)));
188 if (::isatty(descriptor) == 0) {
189 qCWarning(AndroidSerialPortLog) << _port.
systemLocation() <<
"is not a tty device";
190 (void) ::close(descriptor);
196 if (::ioctl(descriptor, TIOCEXCL) == -1) {
197 qCDebug(AndroidSerialPortLog) <<
"Failed to set exclusive access on" << _port.
systemLocation() <<
":"
201 _descriptor = descriptor;
204 if (mode & QIODevice::ReadOnly) {
205 _readNotifier =
new QSocketNotifier(descriptor, QSocketNotifier::Read, q);
207 _readNotifier->setEnabled(
false);
208 QObject::connect(_readNotifier, &QSocketNotifier::activated, q, [
this]() { (void) _readActivated(); });
210 if (mode & QIODevice::WriteOnly) {
211 _writeNotifier =
new QSocketNotifier(descriptor, QSocketNotifier::Write, q);
212 _writeNotifier->setEnabled(
false);
213 QObject::connect(_writeNotifier, &QSocketNotifier::activated, q, [
this]() { _writeActivated(); });
219void PosixSerialBackend::close()
221 delete _readNotifier.data();
222 delete _writeNotifier.data();
225 if (_descriptor != -1) {
228 (void) ::ioctl(_descriptor, TIOCNXCL);
229 if (::close(_descriptor) == -1) {
230 qCWarning(AndroidSerialPortLog) <<
"Failed to close" << _port.
systemLocation() <<
":" << strerror(errno);
236bool PosixSerialBackend::startReading()
240 _readNotifier->setEnabled(
true);
246bool PosixSerialBackend::waitForInput(
const QDeadlineTimer& deadline)
249 const bool writeBlocked = _writeNotifier && _writeNotifier->isEnabled();
251 const short events =
static_cast<short>((_readPaused ? 0 : POLLIN) | (writeBlocked ? POLLOUT : 0));
252 struct pollfd pfd = {_descriptor, events, 0};
253 const int ready = ::poll(&pfd, 1, pollTimeoutMs(deadline));
255 if (errno == EINTR) {
258 const int pollErrno = errno;
259 qCWarning(AndroidSerialPortLog) <<
"Poll error on" << _port.
systemLocation() <<
":" << strerror(pollErrno);
266 if (pfd.revents & POLLOUT) {
269 if (!(pfd.revents & ~POLLOUT)) {
274 const bool hungUp = pfd.revents & (POLLERR | POLLHUP | POLLNVAL);
275 const bool readSucceeded = _readActivated();
279 if (!readSucceeded) {
291bool PosixSerialBackend::_readActivated()
294 bool gotData =
false;
297 const ssize_t bytesRead = ::read(_descriptor, readBuf,
sizeof(readBuf));
300 if (!_port.
newDataArrived(readBuf,
static_cast<int>(bytesRead))) {
303 _readNotifier->setEnabled(
false);
307 if (bytesRead <
static_cast<ssize_t
>(
sizeof(readBuf))) {
313 if ((bytesRead < 0) && (errno == EINTR)) {
318 if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
334void PosixSerialBackend::_readFailed(
int readError)
336 const bool deviceGone =
337 (readError == 0) || (readError == EIO) || (readError == ENODEV) || (readError == ENXIO) || (readError == EBADF);
339 qCWarning(AndroidSerialPortLog) <<
"Read error on" << _port.
systemLocation() <<
":" << strerror(readError);
347 _readNotifier->setEnabled(
false);
349 qCWarning(AndroidSerialPortLog) <<
"Device lost on" << _port.
systemLocation() <<
":"
350 << (readError == 0 ?
"hung up" : strerror(readError));
354qint64 PosixSerialBackend::startWrite(
const char* data, qint64 maxSize)
358 written = ::write(_descriptor, data,
static_cast<size_t>(maxSize));
359 }
while ((written < 0) && (errno == EINTR));
361 if ((written < 0) && (errno != EAGAIN) && (errno != EWOULDBLOCK)) {
362 const int writeErrno = errno;
363 qCWarning(AndroidSerialPortLog) <<
"Write error on" << _port.
systemLocation() <<
":" << strerror(writeErrno);
365 const bool deviceGone = (writeErrno == EIO) || (writeErrno == ENODEV) || (writeErrno == ENXIO);
374 const qint64 taken = (written > 0) ? written : 0;
375 if ((taken < maxSize) && _writeNotifier) {
377 _writeNotifier->setEnabled(
true);
386void PosixSerialBackend::_writeActivated()
388 if (_writeNotifier) {
389 _writeNotifier->setEnabled(
false);
394bool PosixSerialBackend::waitForWritable(
const QDeadlineTimer& deadline)
396 struct pollfd pfd = {_descriptor, POLLOUT, 0};
397 if (::poll(&pfd, 1, pollTimeoutMs(deadline)) > 0) {
413 return _applySettings(
port.baudRate(),
port.dataBits(),
port.stopBits(),
port.parity(), flowControl);
420 if (::tcgetattr(_descriptor, &tio) == -1) {
421 const int getErrno = errno;
422 qCWarning(AndroidSerialPortLog) <<
"tcgetattr failed on" << _port.
systemLocation() <<
":" << strerror(getErrno);
430 tio.c_iflag &= ~INPCK;
431 tio.c_iflag |= IGNPAR;
432 tio.c_cflag |= (CLOCAL | CREAD);
439 qCWarning(AndroidSerialPortLog) <<
"Unsupported baud rate" << baudRate <<
"on" << _port.
systemLocation();
445 const speed_t speed = baudRateToSpeed(baudRate);
447 (void) ::cfsetispeed(&tio, speed);
448 (void) ::cfsetospeed(&tio, speed);
451 tio.c_cflag &= ~CSIZE;
466 qCWarning(AndroidSerialPortLog) <<
"Unsupported data bits:" << dataBits;
472 tio.c_cflag &= ~(PARENB | PARODD | CMSPAR);
477 tio.c_cflag |= PARENB;
480 tio.c_cflag |= (PARENB | PARODD);
483 tio.c_cflag |= (PARENB | CMSPAR);
486 tio.c_cflag |= (PARENB | CMSPAR | PARODD);
489 qCWarning(AndroidSerialPortLog) <<
"Unsupported parity:" << parity;
496 tio.c_cflag &= ~CSTOPB;
499 tio.c_cflag |= CSTOPB;
502 qCWarning(AndroidSerialPortLog) <<
"Unsupported stop bits:" << stopBits;
507 switch (flowControl) {
509 tio.c_cflag &= ~CRTSCTS;
510 tio.c_iflag &= ~(IXON | IXOFF);
513 tio.c_cflag |= CRTSCTS;
514 tio.c_iflag &= ~(IXON | IXOFF);
517 tio.c_cflag &= ~CRTSCTS;
518 tio.c_iflag |= (IXON | IXOFF);
521 qCWarning(AndroidSerialPortLog) <<
"Unsupported flow control:" << flowControl;
526 if (::tcsetattr(_descriptor, TCSANOW, &tio) == -1) {
527 const int setErrno = errno;
528 qCWarning(AndroidSerialPortLog) <<
"tcsetattr failed on" << _port.
systemLocation() <<
":" << strerror(setErrno);
533 return (speed != B0) || _setCustomBaudRate(baudRate);
536bool PosixSerialBackend::_setCustomBaudRate(qint32 baudRate)
539 if (::ioctl(_descriptor, kGetTermios2, &tio) != -1) {
540 tio.c_cflag &= ~CBAUD;
541 tio.c_cflag |= kOtherBaudRate;
542 tio.c_ispeed =
static_cast<speed_t
>(baudRate);
543 tio.c_ospeed =
static_cast<speed_t
>(baudRate);
544 if (::ioctl(_descriptor, kSetTermios2, &tio) != -1) {
549 const int setErrno = errno;
550 qCWarning(AndroidSerialPortLog) <<
"Unsupported baud rate" << baudRate <<
"on" << _port.
systemLocation() <<
":"
551 << strerror(setErrno);
556bool PosixSerialBackend::clear(QSerialPort::Directions directions)
569 if (::tcflush(_descriptor, queues) == -1) {
570 const int flushErrno = errno;
571 qCWarning(AndroidSerialPortLog) <<
"tcflush failed on" << _port.
systemLocation() <<
":" << strerror(flushErrno);
579QSerialPort::PinoutSignals PosixSerialBackend::pinoutSignals()
582 if (::ioctl(_descriptor, TIOCMGET, &arg) == -1) {
583 const int getErrno = errno;
584 qCWarning(AndroidSerialPortLog) <<
"TIOCMGET failed on" << _port.
systemLocation() <<
":" << strerror(getErrno);
590 if (arg & TIOCM_DTR) {
593 if (arg & TIOCM_RTS) {
596 if (arg & TIOCM_CTS) {
599 if (arg & TIOCM_DSR) {
602 if (arg & TIOCM_CAR) {
605 if (arg & TIOCM_RNG) {
608 if (arg & TIOCM_ST) {
611 if (arg & TIOCM_SR) {
618bool PosixSerialBackend::_setControlLine(
int line,
bool set,
const char* lineName,
const QString& failureText)
620 if (::ioctl(_descriptor, set ? TIOCMBIS : TIOCMBIC, &line) != -1) {
624 const int lineErrno = errno;
627 qCDebug(AndroidSerialPortLog) <<
"Failed to set" << lineName <<
"on" << _port.
systemLocation() <<
":"
628 << strerror(lineErrno);
633bool PosixSerialBackend::setDataTerminalReady(
bool set)
635 return _setControlLine(TIOCM_DTR, set,
"DTR", QSerialPort::tr(
"Failed to set DTR"));
638bool PosixSerialBackend::setRequestToSend(
bool set)
640 return _setControlLine(TIOCM_RTS, set,
"RTS", QSerialPort::tr(
"Failed to set RTS"));
643bool PosixSerialBackend::setBreakEnabled(
bool set)
645 if (::ioctl(_descriptor, set ? TIOCSBRK : TIOCCBRK) == -1) {
646 qCWarning(AndroidSerialPortLog) <<
"Failed to set break on" << _port.
systemLocation() <<
":" << strerror(errno);
658 return std::make_unique<PosixSerialBackend>(port);
std::unique_ptr< AndroidSerialBackend > createPosixSerialBackend(AndroidSerialBackendHost port)
A serial device node, such as /dev/ttyS1.
A QSerialPort as its backend sees it: what the backend asks of the port and reports to it.
void setError(QSerialPort::SerialPortError error, const QString &text=QString())
bool newDataArrived(const char *bytes, int length)
void writeCompleted(qint64 bytes)
bool inputArrived()
Returns whether input has arrived that the port's owner has not been told of and can be told of now.
QSerialPort & serialPort() const
The port itself, for its settings, its error and its thread.
QString systemLocation() const
FlowControl flowControl() const
@ UnsupportedOperationError
@ DataTerminalReadySignal
@ DataCarrierDetectSignal
@ SecondaryTransmittedDataSignal
@ SecondaryReceivedDataSignal
Result setDataTerminalReady(PortHandle handle, bool set)
Result setRequestToSend(PortHandle handle, bool set)
Result startReading(PortHandle handle)
Result setFlowControl(PortHandle handle, QSerialPort::FlowControl flowControl)
Result close(PortHandle handle)
int open(const QString &portName, PortHandle handle)
Result setParameters(PortHandle handle, qint32 baudRate, QSerialPort::DataBits dataBits, QSerialPort::StopBits stopBits, QSerialPort::Parity parity)
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 ...