The SerialPort class provides functions to access serial ports. More...
#include <SerialPort>Inherits: QIODevice.
Note: All functions in this class are reentrant.
This class was introduced in SerialPort 5.0.
| enum | DataBits { Data5, Data6, Data7, Data8, UnknownDataBits } |
| enum | DataErrorPolicy { SkipPolicy, PassZeroPolicy, IgnorePolicy, StopReceivingPolicy, UnknownPolicy } |
| enum | Direction { Input, Output, AllDirections } |
| flags | Directions |
| enum | FlowControl { NoFlowControl, HardwareControl, SoftwareControl, UnknownFlowControl } |
| enum | Line { Le, Dtr, Rts, St, ..., Dsr } |
| flags | Lines |
| enum | Parity { EvenParity, OddParity, SpaceParity, MarkParity, UnknownParity } |
| enum | PortError { NoError, NoSuchDeviceError, PermissionDeniedError, DeviceAlreadyOpenedError, ..., UnknownPortError } |
| enum | Rate { Rate1200, Rate2400, Rate4800, Rate9600, ..., UnknownRate } |
| enum | StopBits { OneStop, OneAndHalfStop, TwoStop, UnknownStopBits } |
|
|
| SerialPort ( QObject * parent = 0 ) | |
| SerialPort ( const QString & name, QObject * parent = 0 ) | |
| SerialPort ( const SerialPortInfo & info, QObject * parent = 0 ) | |
| virtual | ~SerialPort () |
| bool | clear ( Directions dir = AllDirections ) |
| void | clearError () |
| DataBits | dataBits () const |
| DataErrorPolicy | dataErrorPolicy () const |
| bool | dtr () const |
| PortError | error () const |
| FlowControl | flowControl () const |
| bool | flush () |
| Lines | lines () const |
| virtual bool | open ( OpenMode mode ) |
| Parity | parity () const |
| QString | portName () const |
| qint32 | rate ( Directions dir = AllDirections ) const |
| qint64 | readBufferSize () const |
| bool | restoreSettingsOnClose () const |
| bool | rts () const |
| bool | setDataBits ( DataBits dataBits ) |
| bool | setDataErrorPolicy ( DataErrorPolicy policy = IgnorePolicy ) |
| bool | setFlowControl ( FlowControl flow ) |
| bool | setParity ( Parity parity ) |
| void | setPort ( const QString & name ) |
| void | setPort ( const SerialPortInfo & info ) |
| bool | setRate ( qint32 rate, Directions dir = AllDirections ) |
| void | setReadBufferSize ( qint64 size ) |
| void | setRestoreSettingsOnClose ( bool restore ) |
| bool | setStopBits ( StopBits stopBits ) |
| StopBits | stopBits () const |
| virtual bool | atEnd () const |
| virtual qint64 | bytesAvailable () const |
| virtual qint64 | bytesToWrite () const |
| virtual bool | canReadLine () const |
| virtual void | close () |
| virtual bool | isSequential () const |
| virtual bool | waitForBytesWritten ( int msecs ) |
| virtual bool | waitForReadyRead ( int msecs ) |
| bool | clearBreak ( bool clear = true ) |
| bool | sendBreak ( int duration = 0 ) |
| bool | setBreak ( bool set = true ) |
| bool | setDtr ( bool set ) |
| bool | setRts ( bool set ) |
| void | dataBitsChanged ( DataBits dataBits ) |
| void | dataErrorPolicyChanged ( DataErrorPolicy policy ) |
| void | dtrChanged ( bool set ) |
| void | errorChanged ( PortError error ) |
| void | flowControlChanged ( FlowControl flow ) |
| void | parityChanged ( Parity parity ) |
| void | rateChanged ( qint32 rate, Directions dir ) |
| void | restoreSettingsOnCloseChanged ( bool restore ) |
| void | rtsChanged ( bool set ) |
| void | stopBitsChanged ( StopBits stopBits ) |
| virtual qint64 | readData ( char * data, qint64 maxSize ) |
| virtual qint64 | readLineData ( char * data, qint64 maxSize ) |
| virtual qint64 | writeData ( const char * data, qint64 maxSize ) |
The SerialPort class provides functions to access serial ports.
This class resembles the functionality and behavior of the QAbstractSocket class in many aspects, for instance the I/O operations, the implementation of the wait methods, the internal architecture and so forth. Certain SerialPort method implementations were taken directly from QAbstractSocket with only minor changes.
The features of the implementation and the conduct of the class are listed below:
To get started with the SerialPort class, first create an object of that.
Then, call the setPort() method in order to assign the object with the name of the desired serial port (which has to be present in the system). The name has to follow a certain format, which is platform dependent.
The helper class SerialPortInfo allows the enumeration of all the serial ports in the system. This is useful to obtain the correct serial port name.
The SerialPortInfo class can also be used as an input parameter for the setPort() method (to retrieve the currently assigned name, use the portName() method).
After that, the serial port can be opened in read-only (r/o), write-only (w/o) or read-write (r/w) mode using the open() method.
Note: The serial port is always opened with exclusive access (i.e. no other process or thread can access an already opened serial port).
Having successfully opened, the SerialPort determines its current configuration and initializes itself to that. To access the current configuration use the rate(), dataBits(), parity(), stopBits(), and flowControl() methods.
If these settings are satisfying, the I/O operation can be proceed with. Otherwise the port can be reconfigured to the desired setting using the setRate(), setDataBits(), setParity(), setStopBits(), and setFlowControl() methods.
Read or write the data by calling read() or write(). Alternatively the readLine() and readAll() convenience methods can also be invoked. The SerialPort class also inherits the getChar(), putChar(), and ungetChar() methods from the QIODevice class. Those methods work on single bytes. The bytesWritten() signal is emitted when data has been written to the serial port. Note that, Qt does not limit the write buffer size, which can be monitored by listening to this signal.
The readyRead() signal is emitted every time a new chunk of data has arrived. The bytesAvailable() method then returns the number of bytes that are available for reading. Typically, the readyRead() signal would be connected to a slot and all data available could be read in there.
If not all the data is read at once, the remaining data will still be available later. Any new incoming data will be appended to the SerialPort's internal read buffer. In order to limit the size of the read buffer, call setReadBufferSize().
The status of the control lines is determined with the dtr(), rts(), and lines() methods. To change the control line status, use the setDtr(), and setRts() methods.
To close the serial port, call the close() method. After all the pending data has been written to the serial port, the SerialPort class actually closes the descriptor.
SerialPort provides a set of functions that suspend the calling thread until certain signals are emitted. These functions can be used to implement blocking serial ports:
See the following example:
int numRead = 0, numReadTotal = 0; char buffer[50]; forever { numRead = serial.read(buffer, 50); // Do whatever with the array numReadTotal += numRead; if (numRead == 0 && !serial.waitForReadyRead()) break; }
If waitForReadyRead() returns false, the connection has been closed or an error has occurred.
Programming with a blocking serial port is radically different from programming with a non-blocking serial port. A blocking serial port does not require an event loop and typically leads to simpler code. However, in a GUI application, blocking serial port should only be used in non-GUI threads, to avoid freezing the user interface.
See the examples/terminal and examples/blockingterminal examples for an overview of both approaches.
The use of blocking functions is discouraged together with signals. One of the two possibilities should be used.
The SerialPort class can be used with QTextStream and QDataStream's stream operators (operator<<() and operator>>()). There is one issue to be aware of, though: make sure that enough data is available before attempting to read by using the operator>>() overloaded operator.
See also SerialPortInfo.
This enum describes the number of data bits used.
| Constant | Value | Description |
|---|---|---|
| SerialPort::Data5 | 5 | Five bits. |
| SerialPort::Data6 | 6 | Six bits. |
| SerialPort::Data7 | 7 | Seven bits |
| SerialPort::Data8 | 8 | Eight bits. |
| SerialPort::UnknownDataBits | -1 | Unknown number of bits. |
See also setDataBits() and dataBits().
This enum describes the policies for the received symbols while parity errors were detected.
| Constant | Value | Description |
|---|---|---|
| SerialPort::SkipPolicy | 0 | Skips the bad character. |
| SerialPort::PassZeroPolicy | 1 | Replaces bad character to zero. |
| SerialPort::IgnorePolicy | 2 | Ignores the error for a bad character. |
| SerialPort::StopReceivingPolicy | 3 | Stops data reception on error. |
| SerialPort::UnknownPolicy | -1 | Unknown policy. |
See also setDataErrorPolicy() and dataErrorPolicy().
This enum describes the possible directions of the data transmission. Note: This enumeration is used for setting the baud rate of the device separately for each direction in case some operating systems (i.e. POSIX-like).
| Constant | Value | Description |
|---|---|---|
| SerialPort::Input | 1 | Input direction. |
| SerialPort::Output | 2 | Output direction. |
| SerialPort::AllDirections | Input | Output | Simultaneously in two directions. |
The Directions type is a typedef for QFlags<Direction>. It stores an OR combination of Direction values.
This enum describes the flow control used.
| Constant | Value | Description |
|---|---|---|
| SerialPort::NoFlowControl | 0 | No flow control. |
| SerialPort::HardwareControl | 1 | Hardware flow control (RTS/CTS). |
| SerialPort::SoftwareControl | 2 | Software flow control (XON/XOFF). |
| SerialPort::UnknownFlowControl | -1 | Unknown flow control. |
See also setFlowControl() and flowControl().
This enum describes the possible RS-232 pinout signals.
| Constant | Value | Description |
|---|---|---|
| SerialPort::Le | ? | DSR (data set ready/line enable). |
| SerialPort::Dtr | ? | DTR (data terminal ready). |
| SerialPort::Rts | ? | RTS (request to send). |
| SerialPort::St | ? | Secondary TXD (transmit). |
| SerialPort::Sr | ? | Secondary RXD (receive). |
| SerialPort::Cts | ? | CTS (clear to send). |
| SerialPort::Dcd | ? | DCD (data carrier detect). |
| SerialPort::Ri | ? | RNG (ring). |
| SerialPort::Dsr | ? | DSR (data set ready). |
The Lines type is a typedef for QFlags<Line>. It stores an OR combination of Line values.
See also lines(), setDtr(), setRts(), dtr(), and rts().
This enum describes the parity scheme used.
\ValueNoParity No parity.
| Constant | Value | Description |
|---|---|---|
| SerialPort::EvenParity | 2 | Even parity. |
| SerialPort::OddParity | 3 | Odd parity. |
| SerialPort::SpaceParity | 4 | Space parity. |
| SerialPort::MarkParity | 5 | Mark parity. |
| SerialPort::UnknownParity | -1 | Unknown parity. |
See also setParity() and parity().
This enum describes the errors that may be returned by the error() method.
| Constant | Value | Description |
|---|---|---|
| SerialPort::NoError | 0 | No error occurred. |
| SerialPort::NoSuchDeviceError | 1 | An error occurred while attempting to open an non-existing device. |
| SerialPort::PermissionDeniedError | 2 | An error occurred while attempting to open an already opened device by another process or a user not having enough permission and credentials to open. |
| SerialPort::DeviceAlreadyOpenedError | 3 | An error occurred while attempting to open an already opened device in this object. |
| SerialPort::DeviceIsNotOpenedError | 4 | An error occurred while attempting to control a device still closed. |
| SerialPort::ParityError | 5 | Parity error detected by the hardware while reading data. |
| SerialPort::FramingError | 6 | Framing error detected by the hardware while reading data. |
| SerialPort::BreakConditionError | 7 | Break condition detected by the hardware on the input line. |
| SerialPort::IoError | 8 | An I/O error occurred while reading or writing the data. |
| SerialPort::UnsupportedPortOperationError | 9 | The requested device operation is not supported or prohibited by the running operating system. |
| SerialPort::UnknownPortError | 10 | An unidentified error occurred. |
See also error() and clearError().
This enum describes the baud rate which the communication device operates with. Note: only the most common standard rates are listed in this enum.
| Constant | Value | Description |
|---|---|---|
| SerialPort::Rate1200 | 1200 | 1200 baud. |
| SerialPort::Rate2400 | 2400 | 2400 baud. |
| SerialPort::Rate4800 | 4800 | 4800 baud. |
| SerialPort::Rate9600 | 9600 | 9600 baud. |
| SerialPort::Rate19200 | 19200 | 19200 baud. |
| SerialPort::Rate38400 | 38400 | 38400 baud. |
| SerialPort::Rate57600 | 57600 | 57600 baud. |
| SerialPort::Rate115200 | 115200 | 115200 baud. |
| SerialPort::UnknownRate | -1 | Unknown baud. |
See also setRate() and rate().
This enum describes the number of stop bits used.
| Constant | Value | Description |
|---|---|---|
| SerialPort::OneStop | 1 | 1 stop bit. |
| SerialPort::OneAndHalfStop | 3 | 1.5 stop bits. |
| SerialPort::TwoStop | 2 | 2 stop bits. |
| SerialPort::UnknownStopBits | -1 | Unknown number of stop bit. |
See also setStopBits() and stopBits().
This property holds the data bits in a frame.
If the setting is successful, returns true; otherwise returns false and sets an error code which can be obtained by calling the error() method.
Access functions:
| DataBits | dataBits () const |
| bool | setDataBits ( DataBits dataBits ) |
Notifier signal:
| void | dataBitsChanged ( DataBits dataBits ) |
This property holds the error policy how the process receives the character in case of parity error detection.
If the setting is successful, returns true; otherwise returns false. The default policy set is IgnorePolicy.
Access functions:
| DataErrorPolicy | dataErrorPolicy () const |
| bool | setDataErrorPolicy ( DataErrorPolicy policy = IgnorePolicy ) |
Notifier signal:
| void | dataErrorPolicyChanged ( DataErrorPolicy policy ) |
This property holds the state (high or low) of the line signal DTR.
If the setting is successful, returns true; otherwise returns false. If the flag is true then the DTR signal is set to high; otherwise low.
Access functions:
| bool | dtr () const |
| bool | setDtr ( bool set ) |
Notifier signal:
| void | dtrChanged ( bool set ) |
See also lines().
This property holds the error status of the serial port.
The I/O device status returns an error code. For example, if open() returns false, or a read/write operation returns -1, this property can be used to figure out the reason why the operation failed.
The error code is set to the default SerialPort::NoError after a call to clearError()
Access functions:
| PortError | error () const |
| void | clearError () |
Notifier signal:
| void | errorChanged ( PortError error ) |
This property holds the desired flow control mode.
If the setting is successful, returns true; otherwise returns false and sets an error code which can be obtained by calling the error() method.
Access functions:
| FlowControl | flowControl () const |
| bool | setFlowControl ( FlowControl flow ) |
Notifier signal:
| void | flowControlChanged ( FlowControl flow ) |
This property holds the parity checking mode.
If the setting is successful, returns true; otherwise returns false and sets an error code which can be obtained by calling the error() method.
Access functions:
| Parity | parity () const |
| bool | setParity ( Parity parity ) |
Notifier signal:
| void | parityChanged ( Parity parity ) |
This property holds the data rate for the desired direction.
If the setting is successful, returns true; otherwise returns false and sets an error code which can be obtained by calling error(). To set the baud rate, use the enumeration SerialPort::Rate or any positive qint32 value.
Warning: Only the AllDirections flag is support for setting this property on Windows, Windows CE, and Symbian.
Warning: Returns equal rate in any direction on Windows, Windows CE, and Symbian.
Access functions:
| qint32 | rate ( Directions dir = AllDirections ) const |
| bool | setRate ( qint32 rate, Directions dir = AllDirections ) |
Notifier signal:
| void | rateChanged ( qint32 rate, Directions dir ) |
This property holds the flag which allows to restore the previous settings while closing the serial port.
If this flag is true, the settings will be restored; otherwise not. The default state of the SerialPort class is configured to restore the settings.
Access functions:
| bool | restoreSettingsOnClose () const |
| void | setRestoreSettingsOnClose ( bool restore ) |
Notifier signal:
| void | restoreSettingsOnCloseChanged ( bool restore ) |
See also restoreSettingsOnClose().
This property holds the state (high or low) of the line signal RTS.
If the setting is successful, returns true; otherwise returns false. If the flag is true then the RTS signal is set to high; otherwise low.
Access functions:
| bool | rts () const |
| bool | setRts ( bool set ) |
Notifier signal:
| void | rtsChanged ( bool set ) |
See also lines().
This property holds the number of stop bits in a frame.
If the setting is successful, returns true; otherwise returns false and sets an error code which can be obtained by calling the error() method.
Access functions:
| StopBits | stopBits () const |
| bool | setStopBits ( StopBits stopBits ) |
Notifier signal:
| void | stopBitsChanged ( StopBits stopBits ) |
Constructs a new serial port object with the given parent.
Constructs a new serial port object with the given parent to represent the serial port with the specified name.
The name should have a specific format; see the setPort() method.
Constructs a new serial port object with the given parent to represent the serial port with the specified a helper class info.
Closes the serial port, if neccessary, and then destroys object.
Reimplemented from QIODevice::atEnd().
Returns true if no more data is currently available for reading; otherwise returns false.
This function is most commonly used when reading data from the serial port in a loop. For example:
// This slot is connected to SerialPort::readyRead() void SerialPortClass::readyReadSlot() { while (!port.atEnd()) { QByteArray data = port.read(100); .... } }
See also bytesAvailable() and readyRead().
Reimplemented from QIODevice::bytesAvailable().
Returns the number of incoming bytes that are waiting to be read.
See also bytesToWrite() and read().
Reimplemented from QIODevice::bytesToWrite().
Returns the number of bytes that are waiting to be written. The bytes are written when control goes back to the event loop or when flush() is called.
See also bytesAvailable() and flush().
Reimplemented from QIODevice::canReadLine().
Returns true if a line of data can be read from the serial port; otherwise returns false.
See also readLine().
Discards all characters from the output or input buffer, depending on a given direction dir. Including clear an internal class buffers and the UART (driver) buffers. Also terminate pending read or write operations. If successful, returns true; otherwise returns false.
Controls the signal break, depending on the flag clear. If successful, returns true; otherwise returns false.
If clear is false then enables the break transmission; otherwise disables.
See also setBreak() and sendBreak().
Reimplemented from QIODevice::close().
Calls SerialPort::flush() and closes the serial port. Errors from flush are ignored.
See also QIODevice::close().
This signal is emitted after the data bits in a frame has been changed. The new data bits in a frame is passed as \dataBits.
See also SerialPort::dataBits.
This signal is emitted after the state (high or low) of the line signal DTR has been changed. The new the state (high or low) of the line signal DTR is passed as set.
See also SerialPort::dtr.
This signal is emitted after the error has been changed. The new erroris passed as error.
See also SerialPort::error.
This signal is emitted after the flow control mode has been changed. The new flow control mode is passed as flow.
See also SerialPort::flowControl.
This function writes as much as possible from the internal write buffer to the underlying serial port without blocking. If any data was written, this function returns true; otherwise returns false.
Call this function for sending the buffered data immediately to the serial port. The number of bytes successfully written depends on the operating system. In most cases, this function does not need to be called, because the SerialPort class will start sending data automatically once control is returned to the event loop. In the absence of an event loop, call waitForBytesWritten() instead.
See also write() and waitForBytesWritten().
Reimplemented from QIODevice::isSequential().
Always returns true. The serial port is a sequential device.
Returns the bitmap states of the line signals. From this result, it is possible to allocate the state of the desired signal by applying a mask "AND", where the mask is the desired enumeration value from SerialPort::Lines.
See also dtr(), rts(), setDtr(), and setRts().
Opens the serial port using OpenMode mode, and then returns true if successful; otherwise returns false with and sets an error code which can be obtained by calling the error() method.
Warning: The mode has to be QIODevice::ReadOnly, QIODevice::WriteOnly, or QIODevice::ReadWrite. This may also have additional flags, such as QIODevice::Unbuffered. Other modes are unsupported.
See also QIODevice::OpenMode and setPort().
This signal is emitted after the parity checking mode has been changed. The new parity checking mode is passed as parity.
See also SerialPort::parity.
Returns the name set by setPort() or to the SerialPort constructors. This name is short, i.e. it extract and convert out from the internal variable system location of the device. Conversion algorithm is platform specific:
| Platform | Brief Description |
|---|---|
| Windows | Removes the prefix "\\.\" from the system location and returns the remainder of the string. |
| Windows CE | Removes the postfix ":" from the system location and returns the remainder of the string. |
| Symbian | Returns the system location as it is, as it is equivalent to the port name. |
| GNU/Linux | Removes the prefix "/dev/" from the system location and returns the remainder of the string. |
| Mac OSX | Removes the prefix "/dev/cu." and "/dev/tty." from the system location and returns the remainder of the string. |
| Other *nix | The same as for GNU/Linux. |
See also setPort() and SerialPortInfo::portName().
This signal is emitted after the rate has been changed. The new rate is passed as rate and directions as dir.
See also SerialPort::rate.
Returns the size of the internal read buffer. This limits the amount of data that the client can receive before calling the read() or readAll() methods.
A read buffer size of 0 (the default) means that the buffer has no size limit, ensuring that no data is lost.
See also setReadBufferSize() and read().
Reimplemented from QIODevice::readData().
Reimplemented from QIODevice::readLineData().
This signal is emitted after the flag which allows to restore the previous settings while closing the serial port has been changed. The new flag which allows to restore the previous settings while closing the serial port is passed as \restore.
See also SerialPort::restoreSettingsOnClose.
This signal is emitted after the state (high or low) of the line signal RTS has been changed. The new the state (high or low) of the line signal RTS is passed as set.
See also SerialPort::rts.
Sends a continuous stream of zero bits during a specified period of time duration in msec if the terminal is using asynchronous serial data. If successful, returns true; otherwise returns false.
If the duration is zero then zero bits are transmitted by at least 0.25 seconds, but no more than 0.5 seconds.
If the duration is non zero then zero bits are transmitted within a certain period of time depending on the implementation.
See also setBreak() and clearBreak().
Controls the signal break, depending on the flag set. If successful, returns true; otherwise returns false.
If set is true then enables the break transmission; otherwise disables.
See also clearBreak() and sendBreak().
Sets the name of the port. The name may be in any format; either short, or also as system location (with all the prefixes and postfixed). As a result, this name will be automatically written and converted into an internal variable as system location.
See also portName() and SerialPortInfo.
Sets the port stored in the serial port info instance info.
See also portName() and SerialPortInfo.
Sets the size of SerialPort's internal read buffer to be size bytes.
If the buffer size is limited to a certain size, SerialPort will not buffer more than this size of data. Exceptionally, a buffer size of 0 means that the read buffer is unlimited and all incoming data is buffered. This is the default.
This option is useful if the data is only read at certain points in time (for instance in a real-time streaming application) or if the serial port should be protected against receiving too much data, which may eventually causes that the application runs out of memory.
See also readBufferSize() and read().
This signal is emitted after the number of stop bits in a frame has been changed. The new number of stop bits in a frame is passed as stopBits.
See also SerialPort::stopBits.
Reimplemented from QIODevice::waitForBytesWritten().
Reimplemented from QIODevice::waitForReadyRead().
This function blocks until new data is available for reading and the readyRead() signal has been emitted. The function will timeout after msecs milliseconds.
The function returns true if the readyRead() signal is emitted and there is new data available for reading; otherwise it returns false (if an error occurred or the operation timed out).
See also waitForBytesWritten().
Reimplemented from QIODevice::writeData().