1// Copyright (C) 2011-2012 Denis Shienkov <denis.shienkov@gmail.com>
2// Copyright (C) 2011 Sergey Belyashov <Sergey.Belyashov@gmail.com>
3// Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
4// Copyright (C) 2012 Andre Hartmann <aha_1980@gmx.de>
5// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
6
7#include "qserialport.h"
8#include "qserialportinfo.h"
9#include "qserialportinfo_p.h"
10
11#include "qserialport_p.h"
12
13#include <QtCore/qdebug.h>
14
15QT_BEGIN_NAMESPACE
16
17QSerialPortErrorInfo::QSerialPortErrorInfo(QSerialPort::SerialPortError newErrorCode,
18 const QString &newErrorString)
19 : errorCode(newErrorCode)
20 , errorString(newErrorString)
21{
22 if (errorString.isNull()) {
23 switch (errorCode) {
24 case QSerialPort::NoError:
25 errorString = QSerialPort::tr(s: "No error");
26 break;
27 case QSerialPort::OpenError:
28 errorString = QSerialPort::tr(s: "Device is already open");
29 break;
30 case QSerialPort::NotOpenError:
31 errorString = QSerialPort::tr(s: "Device is not open");
32 break;
33 case QSerialPort::TimeoutError:
34 errorString = QSerialPort::tr(s: "Operation timed out");
35 break;
36 case QSerialPort::ReadError:
37 errorString = QSerialPort::tr(s: "Error reading from device");
38 break;
39 case QSerialPort::WriteError:
40 errorString = QSerialPort::tr(s: "Error writing to device");
41 break;
42 case QSerialPort::ResourceError:
43 errorString = QSerialPort::tr(s: "Device disappeared from the system");
44 break;
45 default:
46 // an empty string will be interpreted as "Unknown error"
47 // from the QIODevice::errorString()
48 break;
49 }
50 }
51}
52
53QSerialPortPrivate::QSerialPortPrivate()
54#if defined(Q_OS_WIN32)
55 : readChunkBuffer(QSERIALPORT_BUFFERSIZE, 0)
56#endif
57{
58 writeBufferChunkSize = QSERIALPORT_BUFFERSIZE;
59 readBufferChunkSize = QSERIALPORT_BUFFERSIZE;
60}
61
62void QSerialPortPrivate::setError(const QSerialPortErrorInfo &errorInfo)
63{
64 Q_Q(QSerialPort);
65
66 q->setErrorString(errorInfo.errorString);
67 error.setValue(errorInfo.errorCode);
68 error.notify();
69 emit q->errorOccurred(error);
70}
71
72/*!
73 \class QSerialPort
74
75 \brief Provides functions to access serial ports.
76
77 \reentrant
78 \ingroup serialport-main
79 \inmodule QtSerialPort
80 \since 5.1
81
82 You can get information about the available serial ports using the
83 QSerialPortInfo helper class, which allows an enumeration of all the serial
84 ports in the system. This is useful to obtain the correct name of the
85 serial port you want to use. You can pass an object
86 of the helper class as an argument to the setPort() or setPortName()
87 methods to assign the desired serial device.
88
89 After setting the port, you can open it in read-only (r/o), write-only
90 (w/o), or read-write (r/w) mode using the open() method.
91
92 \note The serial port is always opened with exclusive access
93 (that is, no other process or thread can access an already opened serial port).
94
95 Use the close() method to close the port and cancel the I/O operations.
96
97 Having successfully opened, QSerialPort tries to determine the current
98 configuration of the port and initializes itself. You can reconfigure the
99 port to the desired setting using the setBaudRate(), setDataBits(),
100 setParity(), setStopBits(), and setFlowControl() methods.
101
102 There are a couple of properties to work with the pinout signals namely:
103 QSerialPort::dataTerminalReady, QSerialPort::requestToSend. It is also
104 possible to use the pinoutSignals() method to query the current pinout
105 signals set.
106
107 Once you know that the ports are ready to read or write, you can
108 use the read() or write() methods. Alternatively the
109 readLine() and readAll() convenience methods can also be invoked.
110 If not all the data is read at once, the remaining data will
111 be available for later as new incoming data is appended to the
112 QSerialPort's internal read buffer. You can limit the size of the read
113 buffer using setReadBufferSize().
114
115 QSerialPort provides a set of functions that suspend the
116 calling thread until certain signals are emitted. These functions
117 can be used to implement blocking serial ports:
118
119 \list
120
121 \li waitForReadyRead() blocks calls until new data is available for
122 reading.
123
124 \li waitForBytesWritten() blocks calls until one payload of data has
125 been written to the serial port.
126
127 \endlist
128
129 See the following example:
130
131 \code
132 qint64 numReadTotal = 0;
133 char buffer[50];
134
135 for (;;) {
136 const qint64 numRead = serial.read(buffer, 50);
137
138 // Do whatever with the array
139
140 numReadTotal += numRead;
141 if (numRead == 0 && !serial.waitForReadyRead())
142 break;
143 }
144 \endcode
145
146 If \l{QIODevice::}{waitForReadyRead()} returns \c false, the
147 connection has been closed or an error has occurred.
148
149 If an error occurs at any point in time, QSerialPort will emit the
150 errorOccurred() signal. You can also call error() to find the type of
151 error that occurred last.
152
153 Programming with a blocking serial port is radically different from
154 programming with a non-blocking serial port. A blocking serial port
155 does not require an event loop and typically leads to simpler code.
156 However, in a GUI application, blocking serial port should only be
157 used in non-GUI threads, to avoid freezing the user interface.
158
159 For more details about these approaches, refer to the
160 \l {Qt Serial Port Examples}{example} applications.
161
162 The QSerialPort class can also be used with QTextStream and QDataStream's
163 stream operators (operator<<() and operator>>()). There is one issue to be
164 aware of, though: make sure that enough data is available before attempting
165 to read by using the operator>>() overloaded operator.
166
167 \sa QSerialPortInfo
168*/
169
170/*!
171 \enum QSerialPort::Direction
172
173 This enum describes the possible directions of the data transmission.
174
175 \note This enumeration is used for setting the baud rate of the device
176 separately for each direction on some operating systems (for example,
177 POSIX-like).
178
179 \value Input Input direction.
180 \value Output Output direction.
181 \value AllDirections Simultaneously in two directions.
182*/
183
184/*!
185 \enum QSerialPort::BaudRate
186
187 This enum describes the baud rate which the communication device operates
188 with.
189
190 \note Only the most common standard baud rates are listed in this enum.
191
192 \value Baud1200 1200 baud.
193 \value Baud2400 2400 baud.
194 \value Baud4800 4800 baud.
195 \value Baud9600 9600 baud.
196 \value Baud19200 19200 baud.
197 \value Baud38400 38400 baud.
198 \value Baud57600 57600 baud.
199 \value Baud115200 115200 baud.
200
201 \sa QSerialPort::baudRate
202*/
203
204/*!
205 \enum QSerialPort::DataBits
206
207 This enum describes the number of data bits used.
208
209 \value Data5 The number of data bits in each character is 5. It
210 is used for Baudot code. It generally only makes
211 sense with older equipment such as teleprinters.
212 \value Data6 The number of data bits in each character is 6. It
213 is rarely used.
214 \value Data7 The number of data bits in each character is 7. It
215 is used for true ASCII. It generally only makes
216 sense with older equipment such as teleprinters.
217 \value Data8 The number of data bits in each character is 8. It
218 is used for most kinds of data, as this size matches
219 the size of a byte. It is almost universally used in
220 newer applications.
221
222 \sa QSerialPort::dataBits
223*/
224
225/*!
226 \enum QSerialPort::Parity
227
228 This enum describes the parity scheme used.
229
230 \value NoParity No parity bit it sent. This is the most common
231 parity setting. Error detection is handled by the
232 communication protocol.
233 \value EvenParity The number of 1 bits in each character, including
234 the parity bit, is always even.
235 \value OddParity The number of 1 bits in each character, including
236 the parity bit, is always odd. It ensures that at
237 least one state transition occurs in each character.
238 \value SpaceParity Space parity. The parity bit is sent in the space
239 signal condition. It does not provide error
240 detection information.
241 \value MarkParity Mark parity. The parity bit is always set to the
242 mark signal condition (logical 1). It does not
243 provide error detection information.
244
245 \sa QSerialPort::parity
246*/
247
248/*!
249 \enum QSerialPort::StopBits
250
251 This enum describes the number of stop bits used.
252
253 \value OneStop 1 stop bit.
254 \value OneAndHalfStop 1.5 stop bits. This is only for the Windows platform.
255 \value TwoStop 2 stop bits.
256
257 \sa QSerialPort::stopBits
258*/
259
260/*!
261 \enum QSerialPort::FlowControl
262
263 This enum describes the flow control used.
264
265 \value NoFlowControl No flow control.
266 \value HardwareControl Hardware flow control (RTS/CTS).
267 \value SoftwareControl Software flow control (XON/XOFF).
268
269 \sa QSerialPort::flowControl
270*/
271
272/*!
273 \enum QSerialPort::PinoutSignal
274
275 This enum describes the possible RS-232 pinout signals.
276
277 \value NoSignal No line active
278 \value DataTerminalReadySignal DTR (Data Terminal Ready).
279 \value DataCarrierDetectSignal DCD (Data Carrier Detect).
280 \value DataSetReadySignal DSR (Data Set Ready).
281 \value RingIndicatorSignal RNG (Ring Indicator).
282 \value RequestToSendSignal RTS (Request To Send).
283 \value ClearToSendSignal CTS (Clear To Send).
284 \value SecondaryTransmittedDataSignal STD (Secondary Transmitted Data).
285 \value SecondaryReceivedDataSignal SRD (Secondary Received Data).
286
287 \sa pinoutSignals(), QSerialPort::dataTerminalReady,
288 QSerialPort::requestToSend
289*/
290
291/*!
292 \enum QSerialPort::SerialPortError
293
294 This enum describes the errors that may be contained by the
295 QSerialPort::error property.
296
297 \value NoError No error occurred.
298
299 \value DeviceNotFoundError An error occurred while attempting to
300 open an non-existing device.
301
302 \value PermissionError An error occurred while attempting to
303 open an already opened device by another
304 process or a user not having enough permission
305 and credentials to open.
306
307 \value OpenError An error occurred while attempting to open an
308 already opened device in this object.
309
310 \value NotOpenError This error occurs when an operation is executed
311 that can only be successfully performed if the
312 device is open. This value was introduced in
313 QtSerialPort 5.2.
314
315 \value WriteError An I/O error occurred while writing the data.
316
317 \value ReadError An I/O error occurred while reading the data.
318
319 \value ResourceError An I/O error occurred when a resource becomes
320 unavailable, e.g. when the device is
321 unexpectedly removed from the system.
322
323 \value UnsupportedOperationError The requested device operation is not
324 supported or prohibited by the running operating
325 system.
326
327 \value TimeoutError A timeout error occurred. This value was
328 introduced in QtSerialPort 5.2.
329
330 \value UnknownError An unidentified error occurred.
331 \sa QSerialPort::error
332*/
333
334
335
336/*!
337 Constructs a new serial port object with the given \a parent.
338*/
339QSerialPort::QSerialPort(QObject *parent)
340 : QIODevice(*new QSerialPortPrivate, parent)
341{
342}
343
344/*!
345 Constructs a new serial port object with the given \a parent
346 to represent the serial port with the specified \a name.
347
348 The name should have a specific format; see the setPort() method.
349*/
350QSerialPort::QSerialPort(const QString &name, QObject *parent)
351 : QIODevice(*new QSerialPortPrivate, parent)
352{
353 setPortName(name);
354}
355
356/*!
357 Constructs a new serial port object with the given \a parent
358 to represent the serial port with the specified helper class
359 \a serialPortInfo.
360*/
361QSerialPort::QSerialPort(const QSerialPortInfo &serialPortInfo, QObject *parent)
362 : QIODevice(*new QSerialPortPrivate, parent)
363{
364 setPort(serialPortInfo);
365}
366
367/*!
368 Closes the serial port, if necessary, and then destroys object.
369*/
370QSerialPort::~QSerialPort()
371{
372 /**/
373 if (isOpen())
374 close();
375}
376
377/*!
378 Sets the \a name of the serial port.
379
380 The name of the serial port can be passed as either a short name or
381 the long system location if necessary.
382
383 \sa portName(), QSerialPortInfo
384*/
385void QSerialPort::setPortName(const QString &name)
386{
387 Q_D(QSerialPort);
388 d->systemLocation = QSerialPortInfoPrivate::portNameToSystemLocation(source: name);
389}
390
391/*!
392 Sets the port stored in the serial port info instance \a serialPortInfo.
393
394 \sa portName(), QSerialPortInfo
395*/
396void QSerialPort::setPort(const QSerialPortInfo &serialPortInfo)
397{
398 Q_D(QSerialPort);
399 d->systemLocation = serialPortInfo.systemLocation();
400}
401
402/*!
403 Returns the name set by setPort() or passed to the QSerialPort constructor.
404 This name is short, i.e. it is extracted and converted from the internal
405 variable system location of the device. The conversion algorithm is
406 platform specific:
407 \table
408 \header
409 \li Platform
410 \li Brief Description
411 \row
412 \li Windows
413 \li Removes the prefix "\\\\.\\" or "//./" from the system location
414 and returns the remainder of the string.
415 \row
416 \li Unix, BSD
417 \li Removes the prefix "/dev/" from the system location
418 and returns the remainder of the string.
419 \endtable
420
421 \sa setPort(), QSerialPortInfo::portName()
422*/
423QString QSerialPort::portName() const
424{
425 Q_D(const QSerialPort);
426 return QSerialPortInfoPrivate::portNameFromSystemLocation(source: d->systemLocation);
427}
428
429/*!
430 \reimp
431
432 Opens the serial port using OpenMode \a mode, and then returns \c true if
433 successful; otherwise returns \c false and sets an error code which can be
434 obtained by calling the error() method.
435
436 If the port is opened, but setting the desired port parameters fails, the
437 method returns \c false and closes the port automatically.
438
439 \warning The \a mode has to be QIODeviceBase::ReadOnly, QIODeviceBase::WriteOnly,
440 or QIODeviceBase::ReadWrite. Other modes are unsupported.
441
442 \note Due to historical reasons, upon a successful open the
443 \l errorOccurred() signal is emitted with the \l {QSerialPort::}{NoError}
444 error code. This behavior is preserved to keep backwards compatibility.
445
446 \sa QIODeviceBase::OpenMode, setPort()
447*/
448bool QSerialPort::open(OpenMode mode)
449{
450 Q_D(QSerialPort);
451
452 if (isOpen()) {
453 d->setError(QSerialPortErrorInfo(QSerialPort::OpenError));
454 return false;
455 }
456
457 // Define while not supported modes.
458 static const OpenMode unsupportedModes = Append | Truncate | Text | Unbuffered;
459 if ((mode & unsupportedModes) || mode == NotOpen) {
460 d->setError(QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError, tr(s: "Unsupported open mode")));
461 return false;
462 }
463
464 clearError();
465 if (!d->open(mode))
466 return false;
467
468 QIODevice::open(mode);
469 return true;
470}
471
472/*!
473 \reimp
474
475 \note The serial port has to be open before trying to close it; otherwise
476 sets the NotOpenError error code.
477
478 \sa QIODevice::close()
479*/
480void QSerialPort::close()
481{
482 Q_D(QSerialPort);
483 if (!isOpen()) {
484 d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
485 return;
486 }
487
488 d->close();
489 d->isBreakEnabled.setValue(false);
490 QIODevice::close();
491}
492
493/*!
494 \property QSerialPort::baudRate
495 \brief the data baud rate for the desired direction
496
497 If the setting is successful or set before opening the port, returns \c true;
498 otherwise returns \c false and sets an error code which can be obtained by
499 accessing the value of the QSerialPort::error property. To set the baud
500 rate, use the enumeration QSerialPort::BaudRate or any positive qint32
501 value.
502
503 \note If the setting is set before opening the port, the actual serial port
504 setting is done automatically in the \l{QSerialPort::open()} method right
505 after that the opening of the port succeeds.
506
507 \warning Setting the AllDirections flag is supported on all platforms.
508 Windows supports only this mode.
509
510 \warning Returns equal baud rate in any direction on Windows.
511
512 The default value is Baud9600, i.e. 9600 bits per second.
513*/
514bool QSerialPort::setBaudRate(qint32 baudRate, Directions directions)
515{
516 Q_D(QSerialPort);
517
518 if (!isOpen() || d->setBaudRate(baudRate, directions)) {
519 if (directions & QSerialPort::Input) {
520 if (d->inputBaudRate != baudRate)
521 d->inputBaudRate = baudRate;
522 else
523 directions &= ~QSerialPort::Input;
524 }
525
526 if (directions & QSerialPort::Output) {
527 if (d->outputBaudRate != baudRate)
528 d->outputBaudRate = baudRate;
529 else
530 directions &= ~QSerialPort::Output;
531 }
532
533 if (directions)
534 emit baudRateChanged(baudRate, directions);
535
536 return true;
537 }
538
539 return false;
540}
541
542qint32 QSerialPort::baudRate(Directions directions) const
543{
544 Q_D(const QSerialPort);
545 if (directions == QSerialPort::AllDirections)
546 return d->inputBaudRate == d->outputBaudRate ?
547 d->inputBaudRate : -1;
548 return directions & QSerialPort::Input ? d->inputBaudRate : d->outputBaudRate;
549}
550
551/*!
552 \fn void QSerialPort::baudRateChanged(qint32 baudRate, Directions directions)
553
554 This signal is emitted after the baud rate has been changed. The new baud
555 rate is passed as \a baudRate and directions as \a directions.
556
557 \sa QSerialPort::baudRate
558*/
559
560/*!
561 \property QSerialPort::dataBits
562 \brief the data bits in a frame
563
564 If the setting is successful or set before opening the port, returns
565 \c true; otherwise returns \c false and sets an error code which can be obtained
566 by accessing the value of the QSerialPort::error property.
567
568 \note If the setting is set before opening the port, the actual serial port
569 setting is done automatically in the \l{QSerialPort::open()} method right
570 after that the opening of the port succeeds.
571
572 The default value is Data8, i.e. 8 data bits.
573*/
574bool QSerialPort::setDataBits(DataBits dataBits)
575{
576 Q_D(QSerialPort);
577 d->dataBits.removeBindingUnlessInWrapper();
578 const auto currentDataBits = d->dataBits.valueBypassingBindings();
579 if (!isOpen() || d->setDataBits(dataBits)) {
580 d->dataBits.setValueBypassingBindings(dataBits);
581 if (currentDataBits != dataBits) {
582 d->dataBits.notify();
583 emit dataBitsChanged(dataBits);
584 }
585 return true;
586 }
587 return false;
588}
589
590QSerialPort::DataBits QSerialPort::dataBits() const
591{
592 Q_D(const QSerialPort);
593 return d->dataBits;
594}
595
596QBindable<QSerialPort::DataBits> QSerialPort::bindableDataBits()
597{
598 return &d_func()->dataBits;
599}
600
601/*!
602 \fn void QSerialPort::dataBitsChanged(DataBits dataBits)
603
604 This signal is emitted after the data bits in a frame has been changed. The
605 new data bits in a frame is passed as \a dataBits.
606
607 \sa QSerialPort::dataBits
608*/
609
610
611/*!
612 \property QSerialPort::parity
613 \brief the parity checking mode
614
615 If the setting is successful or set before opening the port, returns \c true;
616 otherwise returns \c false and sets an error code which can be obtained by
617 accessing the value of the QSerialPort::error property.
618
619 \note If the setting is set before opening the port, the actual serial port
620 setting is done automatically in the \l{QSerialPort::open()} method right
621 after that the opening of the port succeeds.
622
623 The default value is NoParity, i.e. no parity.
624
625 \warning Some UNIX operating systems (i.e. \macOS) do not support
626 \l {https://www.man7.org/linux/man-pages/man3/termios.3.html#DESCRIPTION}
627 {the CMSPAR flag}. On such systems, setting \l {QSerialPort::Parity}
628 {Mark or Space} parity is not supported.
629*/
630bool QSerialPort::setParity(Parity parity)
631{
632 Q_D(QSerialPort);
633 d->parity.removeBindingUnlessInWrapper();
634 const auto currentParity = d->parity.valueBypassingBindings();
635 if (!isOpen() || d->setParity(parity)) {
636 d->parity.setValueBypassingBindings(parity);
637 if (currentParity != parity) {
638 d->parity.notify();
639 emit parityChanged(parity);
640 }
641 return true;
642 }
643 return false;
644}
645
646QSerialPort::Parity QSerialPort::parity() const
647{
648 Q_D(const QSerialPort);
649 return d->parity;
650}
651
652QBindable<QSerialPort::Parity> QSerialPort::bindableParity()
653{
654 return &d_func()->parity;
655}
656
657/*!
658 \fn void QSerialPort::parityChanged(Parity parity)
659
660 This signal is emitted after the parity checking mode has been changed. The
661 new parity checking mode is passed as \a parity.
662
663 \sa QSerialPort::parity
664*/
665
666/*!
667 \property QSerialPort::stopBits
668 \brief the number of stop bits in a frame
669
670 If the setting is successful or set before opening the port, returns \c true;
671 otherwise returns \c false and sets an error code which can be obtained by
672 accessing the value of the QSerialPort::error property.
673
674 \note If the setting is set before opening the port, the actual serial port
675 setting is done automatically in the \l{QSerialPort::open()} method right
676 after that the opening of the port succeeds.
677
678 The default value is OneStop, i.e. 1 stop bit.
679*/
680bool QSerialPort::setStopBits(StopBits stopBits)
681{
682 Q_D(QSerialPort);
683 d->stopBits.removeBindingUnlessInWrapper();
684 const auto currentStopBits = d->stopBits.valueBypassingBindings();
685 if (!isOpen() || d->setStopBits(stopBits)) {
686 d->stopBits.setValueBypassingBindings(stopBits);
687 if (currentStopBits != stopBits) {
688 d->stopBits.notify();
689 emit stopBitsChanged(stopBits);
690 }
691 return true;
692 }
693 return false;
694}
695
696QSerialPort::StopBits QSerialPort::stopBits() const
697{
698 Q_D(const QSerialPort);
699 return d->stopBits;
700}
701
702QBindable<QSerialPort::StopBits> QSerialPort::bindableStopBits(QT6_IMPL_NEW_OVERLOAD)
703{
704 return &d_func()->stopBits;
705}
706
707/*!
708 \fn void QSerialPort::stopBitsChanged(StopBits stopBits)
709
710 This signal is emitted after the number of stop bits in a frame has been
711 changed. The new number of stop bits in a frame is passed as \a stopBits.
712
713 \sa QSerialPort::stopBits
714*/
715
716/*!
717 \property QSerialPort::flowControl
718 \brief the desired flow control mode
719
720 If the setting is successful or set before opening the port, returns \c true;
721 otherwise returns \c false and sets an error code which can be obtained by
722 accessing the value of the QSerialPort::error property.
723
724 \note If the setting is set before opening the port, the actual serial port
725 setting is done automatically in the \l{QSerialPort::open()} method right
726 after that the opening of the port succeeds.
727
728 The default value is NoFlowControl, i.e. no flow control.
729*/
730bool QSerialPort::setFlowControl(FlowControl flowControl)
731{
732 Q_D(QSerialPort);
733 d->flowControl.removeBindingUnlessInWrapper();
734 const auto currentFlowControl = d->flowControl.valueBypassingBindings();
735 if (!isOpen() || d->setFlowControl(flowControl)) {
736 d->flowControl.setValueBypassingBindings(flowControl);
737 if (currentFlowControl != flowControl) {
738 d->flowControl.notify();
739 emit flowControlChanged(flowControl);
740 }
741 return true;
742 }
743 return false;
744}
745
746QSerialPort::FlowControl QSerialPort::flowControl() const
747{
748 Q_D(const QSerialPort);
749 return d->flowControl;
750}
751
752QBindable<QSerialPort::FlowControl> QSerialPort::bindableFlowControl()
753{
754 return &d_func()->flowControl;
755}
756
757/*!
758 \fn void QSerialPort::flowControlChanged(FlowControl flow)
759
760 This signal is emitted after the flow control mode has been changed. The
761 new flow control mode is passed as \a flow.
762
763 \sa QSerialPort::flowControl
764*/
765
766/*!
767 \property QSerialPort::dataTerminalReady
768 \brief the state (high or low) of the line signal DTR
769
770 Returns \c true on success, \c false otherwise.
771 If the flag is \c true then the DTR signal is set to high; otherwise low.
772
773 \note The serial port has to be open before trying to set or get this
774 property; otherwise \c false is returned and the error code is set to
775 NotOpenError.
776
777 \sa pinoutSignals()
778*/
779bool QSerialPort::setDataTerminalReady(bool set)
780{
781 Q_D(QSerialPort);
782
783 if (!isOpen()) {
784 d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
785 qWarning(msg: "%s: device not open", Q_FUNC_INFO);
786 return false;
787 }
788
789 const bool dataTerminalReady = isDataTerminalReady();
790 const bool retval = d->setDataTerminalReady(set);
791 if (retval && (dataTerminalReady != set))
792 emit dataTerminalReadyChanged(set);
793
794 return retval;
795}
796
797bool QSerialPort::isDataTerminalReady()
798{
799 Q_D(QSerialPort);
800 return d->pinoutSignals() & QSerialPort::DataTerminalReadySignal;
801}
802
803/*!
804 \fn void QSerialPort::dataTerminalReadyChanged(bool set)
805
806 This signal is emitted after the state (high or low) of the line signal DTR
807 has been changed. The new the state (high or low) of the line signal DTR is
808 passed as \a set.
809
810 \sa QSerialPort::dataTerminalReady
811*/
812
813/*!
814 \property QSerialPort::requestToSend
815 \brief the state (high or low) of the line signal RTS
816
817 Returns \c true on success, \c false otherwise.
818 If the flag is \c true then the RTS signal is set to high; otherwise low.
819
820 \note The serial port has to be open before trying to set or get this
821 property; otherwise \c false is returned and the error code is set to
822 NotOpenError.
823
824 \note An attempt to control the RTS signal in the HardwareControl mode
825 will fail with error code set to UnsupportedOperationError, because
826 the signal is automatically controlled by the driver.
827
828 \sa pinoutSignals()
829*/
830bool QSerialPort::setRequestToSend(bool set)
831{
832 Q_D(QSerialPort);
833
834 if (!isOpen()) {
835 d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
836 qWarning(msg: "%s: device not open", Q_FUNC_INFO);
837 return false;
838 }
839
840 if (d->flowControl == QSerialPort::HardwareControl) {
841 d->setError(QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError));
842 return false;
843 }
844
845 const bool requestToSend = isRequestToSend();
846 const bool retval = d->setRequestToSend(set);
847 if (retval && (requestToSend != set))
848 emit requestToSendChanged(set);
849
850 return retval;
851}
852
853bool QSerialPort::isRequestToSend()
854{
855 Q_D(QSerialPort);
856 return d->pinoutSignals() & QSerialPort::RequestToSendSignal;
857}
858
859/*!
860 \fn void QSerialPort::requestToSendChanged(bool set)
861
862 This signal is emitted after the state (high or low) of the line signal RTS
863 has been changed. The new the state (high or low) of the line signal RTS is
864 passed as \a set.
865
866 \sa QSerialPort::requestToSend
867*/
868
869/*!
870 Returns the state of the line signals in a bitmap format.
871
872 From this result, it is possible to allocate the state of the
873 desired signal by applying a mask "AND", where the mask is
874 the desired enumeration value from QSerialPort::PinoutSignals.
875
876 \note This method performs a system call, thus ensuring that the line signal
877 states are returned properly. This is necessary when the underlying
878 operating systems cannot provide proper notifications about the changes.
879
880 \note The serial port has to be open before trying to get the pinout
881 signals; otherwise returns NoSignal and sets the NotOpenError error code.
882
883 \sa QSerialPort::dataTerminalReady, QSerialPort::requestToSend
884*/
885QSerialPort::PinoutSignals QSerialPort::pinoutSignals()
886{
887 Q_D(QSerialPort);
888
889 if (!isOpen()) {
890 d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
891 qWarning(msg: "%s: device not open", Q_FUNC_INFO);
892 return QSerialPort::NoSignal;
893 }
894
895 return d->pinoutSignals();
896}
897
898/*!
899 This function writes as much as possible from the internal write
900 buffer to the underlying serial port without blocking. If any data
901 was written, this function returns \c true; otherwise returns \c false.
902
903 Call this function for sending the buffered data immediately to the serial
904 port. The number of bytes successfully written depends on the operating
905 system. In most cases, this function does not need to be called, because the
906 QSerialPort class will start sending data automatically once control is
907 returned to the event loop. In the absence of an event loop, call
908 waitForBytesWritten() instead.
909
910 \note The serial port has to be open before trying to flush any buffered
911 data; otherwise returns \c false and sets the NotOpenError error code.
912
913 \sa write(), waitForBytesWritten()
914*/
915bool QSerialPort::flush()
916{
917 Q_D(QSerialPort);
918
919 if (!isOpen()) {
920 d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
921 qWarning(msg: "%s: device not open", Q_FUNC_INFO);
922 return false;
923 }
924
925 return d->flush();
926}
927
928/*!
929 Discards all characters from the output or input buffer, depending on
930 given directions \a directions. This includes clearing the internal class buffers and
931 the UART (driver) buffers. Also terminate pending read or write operations.
932 If successful, returns \c true; otherwise returns \c false.
933
934 \note The serial port has to be open before trying to clear any buffered
935 data; otherwise returns \c false and sets the NotOpenError error code.
936*/
937bool QSerialPort::clear(Directions directions)
938{
939 Q_D(QSerialPort);
940
941 if (!isOpen()) {
942 d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
943 qWarning(msg: "%s: device not open", Q_FUNC_INFO);
944 return false;
945 }
946
947 if (directions & Input)
948 d->buffer.clear();
949 if (directions & Output)
950 d->writeBuffer.clear();
951 return d->clear(directions);
952}
953
954/*!
955 \property QSerialPort::error
956 \brief the error status of the serial port
957
958 The I/O device status returns an error code. For example, if open()
959 returns \c false, or a read/write operation returns \c -1, this property can
960 be used to figure out the reason why the operation failed.
961
962 The error code is set to the default QSerialPort::NoError after a call to
963 clearError()
964*/
965QSerialPort::SerialPortError QSerialPort::error() const
966{
967 Q_D(const QSerialPort);
968 return d->error;
969}
970
971void QSerialPort::clearError()
972{
973 Q_D(QSerialPort);
974 d->setError(QSerialPortErrorInfo(QSerialPort::NoError));
975}
976
977QBindable<QSerialPort::SerialPortError> QSerialPort::bindableError() const
978{
979 return &d_func()->error;
980}
981
982/*!
983 \fn void QSerialPort::errorOccurred(SerialPortError error)
984 \since 5.8
985
986 This signal is emitted when an error occurs in the serial port.
987 The specified \a error describes the type of error that occurred.
988
989 \sa QSerialPort::error
990*/
991
992/*!
993 Returns the size of the internal read buffer. This limits the
994 amount of data that the client can receive before calling the read()
995 or readAll() methods.
996
997 A read buffer size of \c 0 (the default) means that the buffer has
998 no size limit, ensuring that no data is lost.
999
1000 \sa setReadBufferSize(), read()
1001*/
1002qint64 QSerialPort::readBufferSize() const
1003{
1004 Q_D(const QSerialPort);
1005 return d->readBufferMaxSize;
1006}
1007
1008/*!
1009 Sets the size of QSerialPort's internal read buffer to be \a
1010 size bytes.
1011
1012 If the buffer size is limited to a certain size, QSerialPort
1013 will not buffer more than this size of data. The special case of a buffer
1014 size of \c 0 means that the read buffer is unlimited and all
1015 incoming data is buffered. This is the default.
1016
1017 This option is useful if the data is only read at certain points
1018 in time (for instance in a real-time streaming application) or if the serial
1019 port should be protected against receiving too much data, which may
1020 eventually cause the application to run out of memory.
1021
1022 \sa readBufferSize(), read()
1023*/
1024void QSerialPort::setReadBufferSize(qint64 size)
1025{
1026 Q_D(QSerialPort);
1027 d->readBufferMaxSize = size;
1028 if (isReadable())
1029 d->startAsyncRead();
1030}
1031
1032/*!
1033 \since 6.10
1034
1035 Returns the size of the internal write buffer.
1036
1037 A write buffer size of \c 0 (the default) means that the buffer has
1038 no size limit.
1039
1040 \sa setWriteBufferSize(), write()
1041*/
1042qint64 QSerialPort::writeBufferSize() const
1043{
1044 Q_D(const QSerialPort);
1045 return d->writeBufferMaxSize;
1046}
1047
1048/*!
1049 \since 6.10
1050
1051 Sets the size of QSerialPort's internal write buffer to be \a
1052 size bytes.
1053
1054 Sending the data over serial port is relatively slow, so in practice, when
1055 \l write() is called, the data is not sent immediately. It is first stored
1056 in an intermediate buffer and later written in chunks.
1057
1058 Thus, an attempt to write too much data or write data at a higher rate than
1059 the underlying serial port can handle, can lead to a situation when the
1060 internal buffer will grow. This can eventually cause the application to
1061 run out of memory, specially on a device with low memory resources.
1062
1063 This method allows to limit the internal buffer to a certain size. If the
1064 next write attempt exceeds the capacity of the buffer, the \l write()
1065 method will return the amount of bytes that were actually stored in the
1066 buffer. It's the user's responsibility to repeat the write attempt with the
1067 rest of the bytes after the \l bytesWritten() signal was received, or after
1068 the \l waitForBytesWritten() method returns \c true.
1069
1070 Passing \c 0 to this method means that the input buffer is not limited, and
1071 all the incoming data is buffered. This is the default.
1072
1073 \sa writeBufferSize(), write()
1074*/
1075void QSerialPort::setWriteBufferSize(qint64 size)
1076{
1077 Q_D(QSerialPort);
1078 if (size < 0)
1079 size = 0;
1080 d->writeBufferMaxSize = size;
1081 if (isWritable())
1082 d->flush();
1083}
1084
1085/*!
1086 \reimp
1087
1088 Always returns \c true. The serial port is a sequential device.
1089*/
1090bool QSerialPort::isSequential() const
1091{
1092 return true;
1093}
1094
1095/*!
1096 \reimp
1097
1098 Returns the number of incoming bytes that are waiting to be read.
1099
1100 \sa bytesToWrite(), read()
1101*/
1102qint64 QSerialPort::bytesAvailable() const
1103{
1104 return QIODevice::bytesAvailable();
1105}
1106
1107/*!
1108 \reimp
1109
1110 Returns the number of bytes that are waiting to be written. The
1111 bytes are written when control goes back to the event loop or
1112 when flush() is called.
1113
1114 \sa bytesAvailable(), flush()
1115*/
1116qint64 QSerialPort::bytesToWrite() const
1117{
1118 qint64 pendingBytes = QIODevice::bytesToWrite();
1119#if defined(Q_OS_WIN32)
1120 pendingBytes += d_func()->writeChunkBuffer.size();
1121#endif
1122 return pendingBytes;
1123}
1124
1125/*!
1126 \reimp
1127
1128 Returns \c true if a line of data can be read from the serial port;
1129 otherwise returns \c false.
1130
1131 \sa readLine()
1132*/
1133bool QSerialPort::canReadLine() const
1134{
1135 return QIODevice::canReadLine();
1136}
1137
1138/*!
1139 \reimp
1140
1141 This function blocks until new data is available for reading and the
1142 \l{QIODevice::}{readyRead()} signal has been emitted. The function
1143 will timeout after \a msecs milliseconds; the default timeout is
1144 30000 milliseconds. If \a msecs is -1, this function will not time out.
1145
1146 The function returns \c true if the readyRead() signal is emitted and
1147 there is new data available for reading; otherwise it returns \c false
1148 (if an error occurred or the operation timed out).
1149
1150 \sa waitForBytesWritten()
1151*/
1152bool QSerialPort::waitForReadyRead(int msecs)
1153{
1154 Q_D(QSerialPort);
1155 return d->waitForReadyRead(msec: msecs);
1156}
1157
1158/*!
1159 \fn Handle QSerialPort::handle() const
1160 \since 5.2
1161
1162 If the platform is supported and the serial port is open, returns the native
1163 serial port handle; otherwise returns \c -1.
1164
1165 \warning This function is for expert use only; use it at your own risk.
1166 Furthermore, this function carries no compatibility promise between minor
1167 Qt releases.
1168*/
1169
1170/*!
1171 \reimp
1172
1173 This function blocks until at least one byte has been written to the serial
1174 port and the \l{QIODevice::}{bytesWritten()} signal has been emitted. The
1175 function will timeout after \a msecs milliseconds; the default timeout is
1176 30000 milliseconds. If \a msecs is -1, this function will not time out.
1177
1178 The function returns \c true if the bytesWritten() signal is emitted; otherwise
1179 it returns \c false (if an error occurred or the operation timed out).
1180*/
1181bool QSerialPort::waitForBytesWritten(int msecs)
1182{
1183 Q_D(QSerialPort);
1184 return d->waitForBytesWritten(msec: msecs);
1185}
1186
1187/*!
1188 \property QSerialPort::breakEnabled
1189 \since 5.5
1190 \brief the state of the transmission line in break
1191
1192 Returns \c true on success, \c false otherwise.
1193 If the flag is \c true then the transmission line is in break state;
1194 otherwise is in non-break state.
1195
1196 \note The serial port has to be open before trying to set or get this
1197 property; otherwise returns \c false and sets the NotOpenError error code.
1198 This is a bit unusual as opposed to the regular Qt property settings of
1199 a class. However, this is a special use case since the property is set
1200 through the interaction with the kernel and hardware. Hence, the two
1201 scenarios cannot be completely compared to each other.
1202*/
1203bool QSerialPort::setBreakEnabled(bool set)
1204{
1205 Q_D(QSerialPort);
1206 d->isBreakEnabled.removeBindingUnlessInWrapper();
1207 const auto currentSet = d->isBreakEnabled.valueBypassingBindings();
1208 if (isOpen()) {
1209 if (d->setBreakEnabled(set)) {
1210 d->isBreakEnabled.setValueBypassingBindings(set);
1211 if (currentSet != set) {
1212 d->isBreakEnabled.notify();
1213 emit breakEnabledChanged(set);
1214 }
1215 return true;
1216 }
1217 } else {
1218 d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
1219 qWarning(msg: "%s: device not open", Q_FUNC_INFO);
1220 }
1221 return false;
1222}
1223
1224bool QSerialPort::isBreakEnabled() const
1225{
1226 Q_D(const QSerialPort);
1227 return d->isBreakEnabled;
1228}
1229
1230QBindable<bool> QSerialPort::bindableIsBreakEnabled()
1231{
1232 return &d_func()->isBreakEnabled;
1233}
1234
1235/*!
1236 \fn void QSerialPort::settingsRestoredOnCloseChanged(bool restore)
1237 \since 6.9
1238
1239 This signal is emitted after the settingsRestoredOnClose property is
1240 changed. The \a restore parameter contains the new value of the property.
1241
1242 \sa QSerialPort::settingsRestoredOnClose
1243*/
1244
1245/*!
1246 \property QSerialPort::settingsRestoredOnClose
1247 \since 6.9
1248 \brief This property defines if the port parameters should be restored on
1249 close or not
1250
1251 After the port is opened, the class caches its parameters before applying
1252 the parameters that are defined by the user.
1253
1254 If the property is \c true, the serial port tries to restore the cached
1255 parameters before closing the port; otherwise the caches parameters are
1256 discarded.
1257
1258 The default value is \c true.
1259
1260 \note This property may have no effect on some operating systems.
1261 For example, \macOS seems to always restore the default serial port settings
1262 when the port is closed.
1263*/
1264bool QSerialPort::settingsRestoredOnClose() const
1265{
1266 Q_D(const QSerialPort);
1267 return d->settingsRestoredOnClose;
1268}
1269
1270void QSerialPort::setSettingsRestoredOnClose(bool restore)
1271{
1272 Q_D(QSerialPort);
1273
1274 if (d->settingsRestoredOnClose == restore)
1275 return;
1276
1277 d->settingsRestoredOnClose = restore;
1278 emit settingsRestoredOnCloseChanged(restore);
1279}
1280
1281/*!
1282 \reimp
1283
1284 \omit
1285 This function does not really read anything, as we use QIODevicePrivate's
1286 buffer. The buffer will be read inside of QIODevice before this
1287 method will be called.
1288 \endomit
1289*/
1290qint64 QSerialPort::readData(char *data, qint64 maxSize)
1291{
1292 Q_UNUSED(data);
1293 Q_UNUSED(maxSize);
1294
1295 // In any case we need to start the notifications if they were
1296 // disabled by the read handler. If enabled, next call does nothing.
1297 d_func()->startAsyncRead();
1298
1299 // return 0 indicating there may be more data in the future
1300 return qint64(0);
1301}
1302
1303/*!
1304 \reimp
1305*/
1306qint64 QSerialPort::readLineData(char *data, qint64 maxSize)
1307{
1308 return QIODevice::readLineData(data, maxlen: maxSize);
1309}
1310
1311/*!
1312 \reimp
1313*/
1314qint64 QSerialPort::writeData(const char *data, qint64 maxSize)
1315{
1316 Q_D(QSerialPort);
1317 return d->writeData(data, maxSize);
1318}
1319
1320QT_END_NAMESPACE
1321
1322#include "moc_qserialport.cpp"
1323

source code of qtserialport/src/serialport/qserialport.cpp