/libs/serialport/qserialport.cpp

https://github.com/isluzhishen/qgroundcontrol · C++ · 1167 lines · 371 code · 108 blank · 688 comment · 54 complexity · 2821fa9bfe53a84306e6fab795b9b147 MD5 · raw file

  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2011-2012 Denis Shienkov <denis.shienkov@gmail.com>
  4. ** Copyright (C) 2011 Sergey Belyashov <Sergey.Belyashov@gmail.com>
  5. ** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
  6. ** Copyright (C) 2012 Andre Hartmann <aha_1980@gmx.de>
  7. ** Contact: http://www.qt-project.org/legal
  8. **
  9. ** This file is part of the QtSerialPort module of the Qt Toolkit.
  10. **
  11. ** $QT_BEGIN_LICENSE:LGPL$
  12. ** Commercial License Usage
  13. ** Licensees holding valid commercial Qt licenses may use this file in
  14. ** accordance with the commercial license agreement provided with the
  15. ** Software or, alternatively, in accordance with the terms contained in
  16. ** a written agreement between you and Digia. For licensing terms and
  17. ** conditions see http://qt.digia.com/licensing. For further information
  18. ** use the contact form at http://qt.digia.com/contact-us.
  19. **
  20. ** GNU Lesser General Public License Usage
  21. ** Alternatively, this file may be used under the terms of the GNU Lesser
  22. ** General Public License version 2.1 as published by the Free Software
  23. ** Foundation and appearing in the file LICENSE.LGPL included in the
  24. ** packaging of this file. Please review the following information to
  25. ** ensure the GNU Lesser General Public License version 2.1 requirements
  26. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  27. **
  28. ** In addition, as a special exception, Digia gives you certain additional
  29. ** rights. These rights are described in the Digia Qt LGPL Exception
  30. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  31. **
  32. ** GNU General Public License Usage
  33. ** Alternatively, this file may be used under the terms of the GNU
  34. ** General Public License version 3.0 as published by the Free Software
  35. ** Foundation and appearing in the file LICENSE.GPL included in the
  36. ** packaging of this file. Please review the following information to
  37. ** ensure the GNU General Public License version 3.0 requirements will be
  38. ** met: http://www.gnu.org/copyleft/gpl.html.
  39. **
  40. **
  41. ** $QT_END_LICENSE$
  42. **
  43. ****************************************************************************/
  44. #include "qserialport.h"
  45. #include "qserialportinfo.h"
  46. #ifdef Q_OS_WIN
  47. #include "qserialport_win_p.h"
  48. #elif defined (Q_OS_SYMBIAN)
  49. #include "qserialport_symbian_p.h"
  50. #elif defined (Q_OS_UNIX)
  51. #include "qserialport_unix_p.h"
  52. #else
  53. #error Unsupported OS
  54. #endif
  55. #ifndef SERIALPORT_BUFFERSIZE
  56. # define SERIALPORT_BUFFERSIZE 16384
  57. #endif
  58. QT_BEGIN_NAMESPACE
  59. QSerialPortPrivateData::QSerialPortPrivateData(QSerialPort *q)
  60. : readBufferMaxSize(0)
  61. , readBuffer(SERIALPORT_BUFFERSIZE)
  62. , writeBuffer(SERIALPORT_BUFFERSIZE)
  63. , error(QSerialPort::NoError)
  64. , inputBaudRate(0)
  65. , outputBaudRate(0)
  66. , dataBits(QSerialPort::UnknownDataBits)
  67. , parity(QSerialPort::UnknownParity)
  68. , stopBits(QSerialPort::UnknownStopBits)
  69. , flow(QSerialPort::UnknownFlowControl)
  70. , policy(QSerialPort::IgnorePolicy)
  71. , settingsRestoredOnClose(true)
  72. , q_ptr(q)
  73. {
  74. }
  75. int QSerialPortPrivateData::timeoutValue(int msecs, int elapsed)
  76. {
  77. if (msecs == -1)
  78. return msecs;
  79. msecs -= elapsed;
  80. return qMax(msecs, 0);
  81. }
  82. /*!
  83. \class QSerialPort
  84. \brief Provides functions to access serial ports.
  85. \reentrant
  86. \ingroup serialport-main
  87. \inmodule QtSerialPort
  88. \since 5.1
  89. You can get information about the available serial ports using the
  90. QSerialPortInfo helper class, which allows an enumeration of all the serial
  91. ports in the system. This is useful to obtain the correct name of the
  92. serial port you want to use. You can pass an object
  93. of the helper class as an argument to the setPort() or setPortName()
  94. methods to assign the desired serial device.
  95. After setting the port, you can open it in read-only (r/o), write-only
  96. (w/o), or read-write (r/w) mode using the open() method.
  97. \note The serial port is always opened with exclusive access
  98. (that is, no other process or thread can access an already opened serial port).
  99. Having successfully opened, QSerialPort tries to determine the current
  100. configuration of the port and initializes itself. You can reconfigure the
  101. port to the desired setting using the setBaudRate(), setDataBits(),
  102. setParity(), setStopBits(), and setFlowControl() methods.
  103. The status of the control pinout signals is determined with the
  104. isDataTerminalReady(), isRequestToSend, and pinoutSignals() methods. To
  105. change the control line status, use the setDataTerminalReady(), and
  106. setRequestToSend() methods.
  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. Use the close() method to close the port and cancel the I/O operations.
  115. See the following example:
  116. \code
  117. int numRead = 0, numReadTotal = 0;
  118. char buffer[50];
  119. forever {
  120. numRead = serial.read(buffer, 50);
  121. // Do whatever with the array
  122. numReadTotal += numRead;
  123. if (numRead == 0 && !serial.waitForReadyRead())
  124. break;
  125. }
  126. \endcode
  127. If \l{QIODevice::}{waitForReadyRead()} returns false, the
  128. connection has been closed or an error has occurred.
  129. Programming with a blocking serial port is radically different from
  130. programming with a non-blocking serial port. A blocking serial port
  131. does not require an event loop and typically leads to simpler code.
  132. However, in a GUI application, blocking serial port should only be
  133. used in non-GUI threads, to avoid freezing the user interface.
  134. For more details about these approaches, refer to the
  135. \l {Examples}{example} applications.
  136. The QSerialPort class can also be used with QTextStream and QDataStream's
  137. stream operators (operator<<() and operator>>()). There is one issue to be
  138. aware of, though: make sure that enough data is available before attempting
  139. to read by using the operator>>() overloaded operator.
  140. \sa QSerialPortInfo
  141. */
  142. /*!
  143. \enum QSerialPort::Direction
  144. This enum describes the possible directions of the data transmission.
  145. \note This enumeration is used for setting the baud rate of the device
  146. separately for each direction on some operating systems (for example,
  147. POSIX-like).
  148. \value Input Input direction.
  149. \value Output Output direction.
  150. \value AllDirections Simultaneously in two directions.
  151. */
  152. /*!
  153. \enum QSerialPort::BaudRate
  154. This enum describes the baud rate which the communication device operates
  155. with. Note: only the most common standard baud rates are listed in this
  156. enum.
  157. \value Baud1200 1200 baud.
  158. \value Baud2400 2400 baud.
  159. \value Baud4800 4800 baud.
  160. \value Baud9600 9600 baud.
  161. \value Baud19200 19200 baud.
  162. \value Baud38400 38400 baud.
  163. \value Baud57600 57600 baud.
  164. \value Baud115200 115200 baud.
  165. \value UnknownBaud Unknown baud.
  166. \sa QSerialPort::baudRate
  167. */
  168. /*!
  169. \enum QSerialPort::DataBits
  170. This enum describes the number of data bits used.
  171. \value Data5 Five bits.
  172. \value Data6 Six bits.
  173. \value Data7 Seven bits
  174. \value Data8 Eight bits.
  175. \value UnknownDataBits Unknown number of bits.
  176. \sa QSerialPort::dataBits
  177. */
  178. /*!
  179. \enum QSerialPort::Parity
  180. This enum describes the parity scheme used.
  181. \value NoParity No parity.
  182. \value EvenParity Even parity.
  183. \value OddParity Odd parity.
  184. \value SpaceParity Space parity.
  185. \value MarkParity Mark parity.
  186. \value UnknownParity Unknown parity.
  187. \sa QSerialPort::parity
  188. */
  189. /*!
  190. \enum QSerialPort::StopBits
  191. This enum describes the number of stop bits used.
  192. \value OneStop 1 stop bit.
  193. \value OneAndHalfStop 1.5 stop bits.
  194. \value TwoStop 2 stop bits.
  195. \value UnknownStopBits Unknown number of stop bit.
  196. \sa QSerialPort::stopBits
  197. */
  198. /*!
  199. \enum QSerialPort::FlowControl
  200. This enum describes the flow control used.
  201. \value NoFlowControl No flow control.
  202. \value HardwareControl Hardware flow control (RTS/CTS).
  203. \value SoftwareControl Software flow control (XON/XOFF).
  204. \value UnknownFlowControl Unknown flow control.
  205. \sa QSerialPort::flowControl
  206. */
  207. /*!
  208. \enum QSerialPort::PinoutSignal
  209. This enum describes the possible RS-232 pinout signals.
  210. \value NoSignal No line active
  211. \value TransmittedDataSignal TxD (Transmitted Data).
  212. \value ReceivedDataSignal RxD (Received Data).
  213. \value DataTerminalReadySignal DTR (Data Terminal Ready).
  214. \value DataCarrierDetectSignal DCD (Data Carrier Detect).
  215. \value DataSetReadySignal DSR (Data Set Ready).
  216. \value RingIndicatorSignal RNG (Ring Indicator).
  217. \value RequestToSendSignal RTS (Request To Send).
  218. \value ClearToSendSignal CTS (Clear To Send).
  219. \value SecondaryTransmittedDataSignal STD (Secondary Transmitted Data).
  220. \value SecondaryReceivedDataSignal SRD (Secondary Received Data).
  221. \sa pinoutSignals(), QSerialPort::dataTerminalReady,
  222. QSerialPort::requestToSend
  223. */
  224. /*!
  225. \enum QSerialPort::DataErrorPolicy
  226. This enum describes the policies for the received symbols
  227. while parity errors were detected.
  228. \value SkipPolicy Skips the bad character.
  229. \value PassZeroPolicy Replaces bad character to zero.
  230. \value IgnorePolicy Ignores the error for a bad character.
  231. \value StopReceivingPolicy Stops data reception on error.
  232. \value UnknownPolicy Unknown policy.
  233. \sa QSerialPort::dataErrorPolicy
  234. */
  235. /*!
  236. \enum QSerialPort::SerialPortError
  237. This enum describes the errors that may be contained by the
  238. QSerialPort::error property.
  239. \value NoError No error occurred.
  240. \value DeviceNotFoundError An error occurred while attempting to
  241. open an non-existing device.
  242. \value PermissionError An error occurred while attempting to
  243. open an already opened device by another process or a user not
  244. having enough permission and credentials to open.
  245. \value OpenError An error occurred while attempting to
  246. open an already opened device in this object.
  247. \value ParityError Parity error detected by the hardware while reading data.
  248. \value FramingError Framing error detected by the hardware while reading data.
  249. \value BreakConditionError Break condition detected by the hardware on
  250. the input line.
  251. \value WriteError An I/O error occurred while writing the data.
  252. \value ReadError An I/O error occurred while reading the data.
  253. \value ResourceError An I/O error occurred when a resource becomes unavailable,
  254. e.g. when the device is unexpectedly removed from the system.
  255. \value UnsupportedOperationError The requested device operation is
  256. not supported or prohibited by the running operating system.
  257. \value UnknownError An unidentified error occurred.
  258. \sa QSerialPort::error
  259. */
  260. /*!
  261. Constructs a new serial port object with the given \a parent.
  262. */
  263. QSerialPort::QSerialPort(QObject *parent)
  264. : QIODevice(parent)
  265. , d_ptr(new QSerialPortPrivate(this))
  266. {}
  267. /*!
  268. Constructs a new serial port object with the given \a parent
  269. to represent the serial port with the specified \a name.
  270. The name should have a specific format; see the setPort() method.
  271. */
  272. QSerialPort::QSerialPort(const QString &name, QObject *parent)
  273. : QIODevice(parent)
  274. , d_ptr(new QSerialPortPrivate(this))
  275. {
  276. setPortName(name);
  277. }
  278. /*!
  279. Constructs a new serial port object with the given \a parent
  280. to represent the serial port with the specified helper class
  281. \a serialPortInfo.
  282. */
  283. QSerialPort::QSerialPort(const QSerialPortInfo &serialPortInfo, QObject *parent)
  284. : QIODevice(parent)
  285. , d_ptr(new QSerialPortPrivate(this))
  286. {
  287. setPort(serialPortInfo);
  288. }
  289. /*!
  290. Closes the serial port, if necessary, and then destroys object.
  291. */
  292. QSerialPort::~QSerialPort()
  293. {
  294. /**/
  295. close();
  296. delete d_ptr;
  297. }
  298. /*!
  299. Sets the \a name of the serial port.
  300. The name of the serial port can be passed on as either a short name or
  301. the long system location if necessary.
  302. \sa portName(), QSerialPortInfo
  303. */
  304. void QSerialPort::setPortName(const QString &name)
  305. {
  306. Q_D(QSerialPort);
  307. d->systemLocation = QSerialPortPrivate::portNameToSystemLocation(name);
  308. }
  309. /*!
  310. Sets the port stored in the serial port info instance \a serialPortInfo.
  311. \sa portName(), QSerialPortInfo
  312. */
  313. void QSerialPort::setPort(const QSerialPortInfo &serialPortInfo)
  314. {
  315. Q_D(QSerialPort);
  316. d->systemLocation = QSerialPortPrivate::portNameToSystemLocation(serialPortInfo.systemLocation());
  317. }
  318. /*!
  319. Returns the name set by setPort() or to the QSerialPort constructors.
  320. This name is short, i.e. it extract and convert out from the internal
  321. variable system location of the device. Conversion algorithm is
  322. platform specific:
  323. \table
  324. \header
  325. \li Platform
  326. \li Brief Description
  327. \row
  328. \li Windows
  329. \li Removes the prefix "\\\\.\\" from the system location
  330. and returns the remainder of the string.
  331. \row
  332. \li Windows CE
  333. \li Removes the postfix ":" from the system location
  334. and returns the remainder of the string.
  335. \row
  336. \li Symbian
  337. \li Returns the system location as it is,
  338. as it is equivalent to the port name.
  339. \row
  340. \li GNU/Linux
  341. \li Removes the prefix "/dev/" from the system location
  342. and returns the remainder of the string.
  343. \row
  344. \li Mac OSX
  345. \li Removes the prefix "/dev/cu." and "/dev/tty." from the
  346. system location and returns the remainder of the string.
  347. \row
  348. \li Other *nix
  349. \li The same as for GNU/Linux.
  350. \endtable
  351. \sa setPort(), QSerialPortInfo::portName()
  352. */
  353. QString QSerialPort::portName() const
  354. {
  355. Q_D(const QSerialPort);
  356. return QSerialPortPrivate::portNameFromSystemLocation(d->systemLocation);
  357. }
  358. /*!
  359. \reimp
  360. Opens the serial port using OpenMode \a mode, and then returns true if
  361. successful; otherwise returns false with and sets an error code which can be
  362. obtained by calling the error() method.
  363. \warning The \a mode has to be QIODevice::ReadOnly, QIODevice::WriteOnly,
  364. or QIODevice::ReadWrite. Other modes are unsupported.
  365. \sa QIODevice::OpenMode, setPort()
  366. */
  367. bool QSerialPort::open(OpenMode mode)
  368. {
  369. Q_D(QSerialPort);
  370. if (isOpen()) {
  371. setError(QSerialPort::OpenError);
  372. return false;
  373. }
  374. // Define while not supported modes.
  375. static const OpenMode unsupportedModes = Append | Truncate | Text | Unbuffered;
  376. if ((mode & unsupportedModes) || mode == NotOpen) {
  377. setError(QSerialPort::UnsupportedOperationError);
  378. return false;
  379. }
  380. clearError();
  381. if (d->open(mode)) {
  382. QIODevice::open(mode);
  383. d->dataTerminalReady = isDataTerminalReady();
  384. d->requestToSend = isRequestToSend();
  385. return true;
  386. }
  387. return false;
  388. }
  389. /*!
  390. \reimp
  391. \sa QIODevice::close()
  392. */
  393. void QSerialPort::close()
  394. {
  395. Q_D(QSerialPort);
  396. if (!isOpen()) {
  397. return;
  398. }
  399. QIODevice::close();
  400. d->close();
  401. }
  402. /*!
  403. \property QSerialPort::settingsRestoredOnClose
  404. \brief the flag which allows to restore the previous settings while closing
  405. the serial port.
  406. If this flag is true, the settings will be restored; otherwise not.
  407. The default state of the QSerialPort class is configured to restore the
  408. settings.
  409. */
  410. void QSerialPort::setSettingsRestoredOnClose(bool restore)
  411. {
  412. Q_D(QSerialPort);
  413. if (d->settingsRestoredOnClose != restore) {
  414. d->settingsRestoredOnClose = restore;
  415. emit settingsRestoredOnCloseChanged(d->settingsRestoredOnClose);
  416. }
  417. }
  418. bool QSerialPort::settingsRestoredOnClose() const
  419. {
  420. Q_D(const QSerialPort);
  421. return d->settingsRestoredOnClose;
  422. }
  423. /*!
  424. \fn void QSerialPort::settingsRestoredOnCloseChanged(bool restore)
  425. This signal is emitted after the flag which allows to restore the
  426. previous settings while closing the serial port has been changed. The new
  427. flag which allows to restore the previous settings while closing the serial
  428. port is passed as \a restore.
  429. \sa QSerialPort::settingsRestoredOnClose
  430. */
  431. /*!
  432. \property QSerialPort::baudRate
  433. \brief the data baud rate for the desired direction
  434. If the setting is successful, returns true; otherwise returns false and sets
  435. an error code which can be obtained by accessing the value of the
  436. QSerialPort::error property. To set the baud rate, use the enumeration
  437. QSerialPort::BaudRate or any positive qint32 value.
  438. \warning Only the AllDirections flag is support for setting this property on
  439. Windows, Windows CE, and Symbian.
  440. \warning Returns equal baud rate in any direction on Windows, Windows CE, and
  441. Symbian.
  442. */
  443. bool QSerialPort::setBaudRate(qint32 baudRate, Directions dir)
  444. {
  445. Q_D(QSerialPort);
  446. if (d->setBaudRate(baudRate, dir)) {
  447. if (dir & QSerialPort::Input) {
  448. if (d->inputBaudRate != baudRate)
  449. d->inputBaudRate = baudRate;
  450. else
  451. dir &= ~QSerialPort::Input;
  452. }
  453. if (dir & QSerialPort::Output) {
  454. if (d->outputBaudRate != baudRate)
  455. d->outputBaudRate = baudRate;
  456. else
  457. dir &= ~QSerialPort::Output;
  458. }
  459. if (dir)
  460. emit baudRateChanged(baudRate, dir);
  461. return true;
  462. }
  463. return false;
  464. }
  465. qint32 QSerialPort::baudRate(Directions dir) const
  466. {
  467. Q_D(const QSerialPort);
  468. if (dir == QSerialPort::AllDirections)
  469. return d->inputBaudRate == d->outputBaudRate ?
  470. d->inputBaudRate : QSerialPort::UnknownBaud;
  471. return dir & QSerialPort::Input ? d->inputBaudRate : d->outputBaudRate;
  472. }
  473. /*!
  474. \fn void QSerialPort::baudRateChanged(qint32 baudRate, Directions dir)
  475. This signal is emitted after the baud rate has been changed. The new baud
  476. rate is passed as \a baudRate and directions as \a dir.
  477. \sa QSerialPort::baudRate
  478. */
  479. /*!
  480. \property QSerialPort::dataBits
  481. \brief the data bits in a frame
  482. If the setting is successful, returns true; otherwise returns false and sets
  483. an error code which can be obtained by accessing the value of the
  484. QSerialPort::error property.
  485. */
  486. bool QSerialPort::setDataBits(DataBits dataBits)
  487. {
  488. Q_D(QSerialPort);
  489. if (d->setDataBits(dataBits)) {
  490. if (d->dataBits != dataBits) {
  491. d->dataBits = dataBits;
  492. emit dataBitsChanged(d->dataBits);
  493. }
  494. return true;
  495. }
  496. return false;
  497. }
  498. QSerialPort::DataBits QSerialPort::dataBits() const
  499. {
  500. Q_D(const QSerialPort);
  501. return d->dataBits;
  502. }
  503. /*!
  504. \fn void QSerialPort::dataBitsChanged(DataBits dataBits)
  505. This signal is emitted after the data bits in a frame has been changed. The
  506. new data bits in a frame is passed as \a dataBits.
  507. \sa QSerialPort::dataBits
  508. */
  509. /*!
  510. \property QSerialPort::parity
  511. \brief the parity checking mode
  512. If the setting is successful, returns true; otherwise returns false and sets
  513. an error code which can be obtained by accessing the value of the
  514. QSerialPort::error property.
  515. */
  516. bool QSerialPort::setParity(Parity parity)
  517. {
  518. Q_D(QSerialPort);
  519. if (d->setParity(parity)) {
  520. if (d->parity != parity) {
  521. d->parity = parity;
  522. emit parityChanged(d->parity);
  523. }
  524. return true;
  525. }
  526. return false;
  527. }
  528. QSerialPort::Parity QSerialPort::parity() const
  529. {
  530. Q_D(const QSerialPort);
  531. return d->parity;
  532. }
  533. /*!
  534. \fn void QSerialPort::parityChanged(Parity parity)
  535. This signal is emitted after the parity checking mode has been changed. The
  536. new parity checking mode is passed as \a parity.
  537. \sa QSerialPort::parity
  538. */
  539. /*!
  540. \property QSerialPort::stopBits
  541. \brief the number of stop bits in a frame
  542. If the setting is successful, returns true; otherwise returns false and
  543. sets an error code which can be obtained by accessing the value of the
  544. QSerialPort::error property.
  545. */
  546. bool QSerialPort::setStopBits(StopBits stopBits)
  547. {
  548. Q_D(QSerialPort);
  549. if (d->setStopBits(stopBits)) {
  550. if (d->stopBits != stopBits) {
  551. d->stopBits = stopBits;
  552. emit stopBitsChanged(d->stopBits);
  553. }
  554. return true;
  555. }
  556. return false;
  557. }
  558. QSerialPort::StopBits QSerialPort::stopBits() const
  559. {
  560. Q_D(const QSerialPort);
  561. return d->stopBits;
  562. }
  563. /*!
  564. \fn void QSerialPort::stopBitsChanged(StopBits stopBits)
  565. This signal is emitted after the number of stop bits in a frame has been
  566. changed. The new number of stop bits in a frame is passed as \a stopBits.
  567. \sa QSerialPort::stopBits
  568. */
  569. /*!
  570. \property QSerialPort::flowControl
  571. \brief the desired flow control mode
  572. If the setting is successful, returns true; otherwise returns false and sets
  573. an error code which can be obtained by accessing the value of the
  574. QSerialPort::error property.
  575. */
  576. bool QSerialPort::setFlowControl(FlowControl flow)
  577. {
  578. Q_D(QSerialPort);
  579. if (d->setFlowControl(flow)) {
  580. if (d->flow != flow) {
  581. d->flow = flow;
  582. emit flowControlChanged(d->flow);
  583. }
  584. return true;
  585. }
  586. return false;
  587. }
  588. QSerialPort::FlowControl QSerialPort::flowControl() const
  589. {
  590. Q_D(const QSerialPort);
  591. return d->flow;
  592. }
  593. /*!
  594. \fn void QSerialPort::flowControlChanged(FlowControl flow)
  595. This signal is emitted after the flow control mode has been changed. The
  596. new flow control mode is passed as \a flow.
  597. \sa QSerialPort::flowControl
  598. */
  599. /*!
  600. \property QSerialPort::dataTerminalReady
  601. \brief the state (high or low) of the line signal DTR
  602. If the setting is successful, returns true; otherwise returns false.
  603. If the flag is true then the DTR signal is set to high; otherwise low.
  604. \sa pinoutSignals()
  605. */
  606. bool QSerialPort::setDataTerminalReady(bool set)
  607. {
  608. Q_D(QSerialPort);
  609. bool retval = d->setDataTerminalReady(set);
  610. if (retval && (d->dataTerminalReady != set)) {
  611. d->dataTerminalReady = set;
  612. emit dataTerminalReadyChanged(set);
  613. }
  614. return retval;
  615. }
  616. bool QSerialPort::isDataTerminalReady()
  617. {
  618. Q_D(const QSerialPort);
  619. return d->pinoutSignals() & QSerialPort::DataTerminalReadySignal;
  620. }
  621. /*!
  622. \fn void QSerialPort::dataTerminalReadyChanged(bool set)
  623. This signal is emitted after the state (high or low) of the line signal DTR
  624. has been changed. The new the state (high or low) of the line signal DTR is
  625. passed as \a set.
  626. \sa QSerialPort::dataTerminalReady
  627. */
  628. /*!
  629. \property QSerialPort::requestToSend
  630. \brief the state (high or low) of the line signal RTS
  631. If the setting is successful, returns true; otherwise returns false.
  632. If the flag is true then the RTS signal is set to high; otherwise low.
  633. \sa pinoutSignals()
  634. */
  635. bool QSerialPort::setRequestToSend(bool set)
  636. {
  637. Q_D(QSerialPort);
  638. bool retval = d->setRequestToSend(set);
  639. if (retval && (d->requestToSend != set)) {
  640. d->requestToSend = set;
  641. emit requestToSendChanged(set);
  642. }
  643. return retval;
  644. }
  645. bool QSerialPort::isRequestToSend()
  646. {
  647. Q_D(const QSerialPort);
  648. return d->pinoutSignals() & QSerialPort::RequestToSendSignal;
  649. }
  650. /*!
  651. \fn void QSerialPort::requestToSendChanged(bool set)
  652. This signal is emitted after the state (high or low) of the line signal RTS
  653. has been changed. The new the state (high or low) of the line signal RTS is
  654. passed as \a set.
  655. \sa QSerialPort::requestToSend
  656. */
  657. /*!
  658. Returns the state of the line signals in a bitmap format.
  659. From this result, it is possible to allocate the state of the
  660. desired signal by applying a mask "AND", where the mask is
  661. the desired enumeration value from QSerialPort::PinoutSignals.
  662. Note that, this method performs a system call, thus ensuring that the line
  663. signal states are returned properly. This is necessary when the underlying
  664. operating systems cannot provide proper notifications about the changes.
  665. \sa isDataTerminalReady(), isRequestToSend, setDataTerminalReady(),
  666. setRequestToSend()
  667. */
  668. QSerialPort::PinoutSignals QSerialPort::pinoutSignals()
  669. {
  670. Q_D(const QSerialPort);
  671. return d->pinoutSignals();
  672. }
  673. /*!
  674. This function writes as much as possible from the internal write
  675. buffer to the underlying serial port without blocking. If any data
  676. was written, this function returns true; otherwise returns false.
  677. Call this function for sending the buffered data immediately to the serial
  678. port. The number of bytes successfully written depends on the operating
  679. system. In most cases, this function does not need to be called, because the
  680. QSerialPort class will start sending data automatically once control is
  681. returned to the event loop. In the absence of an event loop, call
  682. waitForBytesWritten() instead.
  683. \sa write(), waitForBytesWritten()
  684. */
  685. bool QSerialPort::flush()
  686. {
  687. Q_D(QSerialPort);
  688. return d->flush();
  689. }
  690. /*!
  691. Discards all characters from the output or input buffer, depending on
  692. a given direction \a dir. Including clear an internal class buffers and
  693. the UART (driver) buffers. Also terminate pending read or write operations.
  694. If successful, returns true; otherwise returns false.
  695. */
  696. bool QSerialPort::clear(Directions dir)
  697. {
  698. Q_D(QSerialPort);
  699. if (dir & Input)
  700. d->readBuffer.clear();
  701. if (dir & Output)
  702. d->writeBuffer.clear();
  703. return d->clear(dir);
  704. }
  705. /*!
  706. \reimp
  707. Returns true if no more data is currently available for reading; otherwise
  708. returns false.
  709. This function is most commonly used when reading data from the
  710. serial port in a loop. For example:
  711. \code
  712. // This slot is connected to QSerialPort::readyRead()
  713. void QSerialPortClass::readyReadSlot()
  714. {
  715. while (!port.atEnd()) {
  716. QByteArray data = port.read(100);
  717. ....
  718. }
  719. }
  720. \endcode
  721. \sa bytesAvailable(), readyRead()
  722. */
  723. bool QSerialPort::atEnd() const
  724. {
  725. Q_D(const QSerialPort);
  726. return QIODevice::atEnd() && (!isOpen() || (d->bytesAvailable() == 0));
  727. }
  728. /*!
  729. \property QSerialPort::dataErrorPolicy
  730. \brief the error policy how the process receives the character in case of
  731. parity error detection.
  732. If the setting is successful, returns true; otherwise returns false. The
  733. default policy set is IgnorePolicy.
  734. */
  735. bool QSerialPort::setDataErrorPolicy(DataErrorPolicy policy)
  736. {
  737. Q_D(QSerialPort);
  738. const bool ret = d->policy == policy || d->setDataErrorPolicy(policy);
  739. if (ret && (d->policy != policy)) {
  740. d->policy = policy;
  741. emit dataErrorPolicyChanged(d->policy);
  742. }
  743. return ret;
  744. }
  745. QSerialPort::DataErrorPolicy QSerialPort::dataErrorPolicy() const
  746. {
  747. Q_D(const QSerialPort);
  748. return d->policy;
  749. }
  750. /*!
  751. \fn void QSerialPort::dataErrorPolicyChanged(DataErrorPolicy policy)
  752. This signal is emitted after the error policy how the process receives the
  753. character in case of parity error detection has been changed. The new error
  754. policy how the process receives the character in case of parity error
  755. detection is passed as \a policy.
  756. \sa QSerialPort::dataErrorPolicy
  757. */
  758. /*!
  759. \property QSerialPort::error
  760. \brief the error status of the serial port
  761. The I/O device status returns an error code. For example, if open()
  762. returns false, or a read/write operation returns -1, this property can
  763. be used to figure out the reason why the operation failed.
  764. The error code is set to the default QSerialPort::NoError after a call to
  765. clearError()
  766. */
  767. QSerialPort::SerialPortError QSerialPort::error() const
  768. {
  769. Q_D(const QSerialPort);
  770. return d->error;
  771. }
  772. void QSerialPort::clearError()
  773. {
  774. setError(QSerialPort::NoError);
  775. }
  776. /*!
  777. \fn void QSerialPort::error(SerialPortError error)
  778. This signal is emitted after the error has been changed. The new erroris
  779. passed as \a error.
  780. \sa QSerialPort::error
  781. */
  782. /*!
  783. Returns the size of the internal read buffer. This limits the
  784. amount of data that the client can receive before calling the read()
  785. or readAll() methods.
  786. A read buffer size of 0 (the default) means that the buffer has
  787. no size limit, ensuring that no data is lost.
  788. \sa setReadBufferSize(), read()
  789. */
  790. qint64 QSerialPort::readBufferSize() const
  791. {
  792. Q_D(const QSerialPort);
  793. return d->readBufferMaxSize;
  794. }
  795. /*!
  796. Sets the size of QSerialPort's internal read buffer to be \a
  797. size bytes.
  798. If the buffer size is limited to a certain size, QSerialPort
  799. will not buffer more than this size of data. Exceptionally, a buffer
  800. size of 0 means that the read buffer is unlimited and all
  801. incoming data is buffered. This is the default.
  802. This option is useful if the data is only read at certain points
  803. in time (for instance in a real-time streaming application) or if the serial
  804. port should be protected against receiving too much data, which may
  805. eventually causes that the application runs out of memory.
  806. \sa readBufferSize(), read()
  807. */
  808. void QSerialPort::setReadBufferSize(qint64 size)
  809. {
  810. Q_D(QSerialPort);
  811. if (d->readBufferMaxSize == size)
  812. return;
  813. d->readBufferMaxSize = size;
  814. }
  815. /*!
  816. \reimp
  817. Always returns true. The serial port is a sequential device.
  818. */
  819. bool QSerialPort::isSequential() const
  820. {
  821. return true;
  822. }
  823. /*!
  824. \reimp
  825. Returns the number of incoming bytes that are waiting to be read.
  826. \sa bytesToWrite(), read()
  827. */
  828. qint64 QSerialPort::bytesAvailable() const
  829. {
  830. Q_D(const QSerialPort);
  831. return d->bytesAvailable() + QIODevice::bytesAvailable();
  832. }
  833. /*!
  834. \reimp
  835. Returns the number of bytes that are waiting to be written. The
  836. bytes are written when control goes back to the event loop or
  837. when flush() is called.
  838. \sa bytesAvailable(), flush()
  839. */
  840. qint64 QSerialPort::bytesToWrite() const
  841. {
  842. Q_D(const QSerialPort);
  843. return d->writeBuffer.size() + QIODevice::bytesToWrite();
  844. }
  845. /*!
  846. \reimp
  847. Returns true if a line of data can be read from the serial port;
  848. otherwise returns false.
  849. \sa readLine()
  850. */
  851. bool QSerialPort::canReadLine() const
  852. {
  853. Q_D(const QSerialPort);
  854. const bool hasLine = (d->bytesAvailable() > 0) && d->readBuffer.canReadLine();
  855. return hasLine || QIODevice::canReadLine();
  856. }
  857. /*!
  858. \reimp
  859. This function blocks until new data is available for reading and the
  860. \l{QIODevice::}{readyRead()} signal has been emitted. The function
  861. will timeout after \a msecs milliseconds.
  862. The function returns true if the readyRead() signal is emitted and
  863. there is new data available for reading; otherwise it returns false
  864. (if an error occurred or the operation timed out).
  865. \sa waitForBytesWritten()
  866. */
  867. bool QSerialPort::waitForReadyRead(int msecs)
  868. {
  869. Q_D(QSerialPort);
  870. return d->waitForReadyRead(msecs);
  871. }
  872. /*!
  873. \reimp
  874. */
  875. bool QSerialPort::waitForBytesWritten(int msecs)
  876. {
  877. Q_D(QSerialPort);
  878. return d->waitForBytesWritten(msecs);
  879. }
  880. /*!
  881. Sends a continuous stream of zero bits during a specified period
  882. of time \a duration in msec if the terminal is using asynchronous
  883. serial data. If successful, returns true; otherwise returns false.
  884. If the duration is zero then zero bits are transmitted by at least
  885. 0.25 seconds, but no more than 0.5 seconds.
  886. If the duration is non zero then zero bits are transmitted within a certain
  887. period of time depending on the implementation.
  888. \sa setBreakEnabled()
  889. */
  890. bool QSerialPort::sendBreak(int duration)
  891. {
  892. Q_D(QSerialPort);
  893. return d->sendBreak(duration);
  894. }
  895. /*!
  896. Controls the signal break, depending on the flag \a set.
  897. If successful, returns true; otherwise returns false.
  898. If \a set is true then enables the break transmission; otherwise disables.
  899. \sa sendBreak()
  900. */
  901. bool QSerialPort::setBreakEnabled(bool set)
  902. {
  903. Q_D(QSerialPort);
  904. return d->setBreakEnabled(set);
  905. }
  906. /*!
  907. \reimp
  908. */
  909. qint64 QSerialPort::readData(char *data, qint64 maxSize)
  910. {
  911. Q_D(QSerialPort);
  912. return d->readFromBuffer(data, maxSize);
  913. }
  914. /*!
  915. \reimp
  916. */
  917. qint64 QSerialPort::readLineData(char *data, qint64 maxSize)
  918. {
  919. return QIODevice::readLineData(data, maxSize);
  920. }
  921. /*!
  922. \reimp
  923. */
  924. qint64 QSerialPort::writeData(const char *data, qint64 maxSize)
  925. {
  926. Q_D(QSerialPort);
  927. return d->writeToBuffer(data, maxSize);
  928. }
  929. void QSerialPort::setError(QSerialPort::SerialPortError serialPortError, const QString &errorString)
  930. {
  931. Q_D(QSerialPort);
  932. d->error = serialPortError;
  933. if (errorString.isNull())
  934. setErrorString(qt_error_string(-1));
  935. else
  936. setErrorString(errorString);
  937. emit error(serialPortError);
  938. }
  939. #include "moc_qserialport.cpp"
  940. QT_END_NAMESPACE