C12Adapter Opensource C++ Interface
MSerialPort Class Reference

Serial port device. More...

Public Types

typedef HANDLE PortHandleType
 

Public Member Functions

 MSerialPort ()
 Constructor that creates an uninitialized serial port. More...
 
 ~MSerialPort ()
 Destructor. More...
 
void Open (const MStdString &portName)
 Open a serial port. More...
 
void Close ()
 Close the port. More...
 
unsigned Read (char *buffer, unsigned size)
 Receive a number of bytes available in the serial port. More...
 
unsigned Write (const char *buffer, unsigned size)
 Write the buffer into the port. More...
 
void ClearInputBuffer () const
 Discard the contents of the input buffer of the port. More...
 
void FlushOutputBuffer (unsigned numberOfCharsInBuffer=UINT_MAX)
 Ensure that the characters from the output buffer are sent. More...
 
unsigned GetBytesReadyToRead () const
 Returns the number of bytes in the serial port input buffer, which are not read yet.
 
bool IsOpen () const
 Whether the port is open.
 
bool GetDCD () const
 Get the current state of the DCD signal of the port. More...
 
void SetParameters (unsigned baud, int dataBits, char parity, int stopBits)
 Convenience method for setting related port parameters in a single call. More...
 
void SetTimeouts (unsigned intercharacterTimeout, unsigned readTimeout, unsigned writeTimeout)
 Convenience method for setting port timeouts in a single call. More...
 
void ConfigurePortParameters () const
 Force configuration of port parameters to properties of this class. More...
 
void ConfigurePortTimeouts () const
 Force configuration of port timeouts to properties of this class. More...
 
void UpdatePortParametersOrTimeoutsIfChanged () const
 If properties for parameters or timeouts are changed, change port. More...
 
const MStdStringGetPortName () const
 
void SetPortName (const MStdString &port)
 
unsigned GetBaud () const
 
void SetBaud (unsigned)
 
char GetParity () const
 
void SetParity (char)
 
int GetStopBits () const
 
void SetStopBits (int)
 
int GetDataBits () const
 
void SetDataBits (int)
 
bool GetCtsFlow () const
 
void SetCtsFlow (bool)
 
bool GetDsrFlow () const
 
void SetDsrFlow (bool)
 
bool GetDsrSensitivity () const
 
void SetDsrSensitivity (bool)
 
char GetDtrControl () const
 
void SetDtrControl (char)
 
char GetRtsControl () const
 
void SetRtsControl (char rtsControl)
 
unsigned GetIntercharacterTimeout () const
 
void SetIntercharacterTimeout (unsigned timeout)
 
unsigned GetReadTimeout () const
 
void SetReadTimeout (unsigned timeout)
 
unsigned GetWriteTimeout () const
 
void SetWriteTimeout (unsigned timeout)
 
PortHandleType GetHandle () const
 

Static Public Member Functions

static MStdStringVector GetAvailablePortNames (bool addExtraInfo=false)
 Return a collection of serial port names available at this computer. More...
 
static MStdString GetPortType (const MStdString &portName)
 Get type based on the port name. More...
 
static M_NORETURN_FUNC void ThrowInvalidBaudRate (unsigned baud)
 Throw an error that says the baud is invalid, giving the baud value as parameter. More...
 
static void CheckIsBaudValid (unsigned baud)
 Check if the given baud rate is valid. More...
 
static void CheckIsParityValid (char parity)
 Check if the given parity is valid. More...
 
static const unsigned * GetAcceptableBaudsArray ()
 Get a zero-terminated list of acceptable baud rates.
 
static const char * GetAcceptableParitiesArray ()
 Get a zero-terminated list of acceptable parity values.
 
static void CheckIsStopBitsValid (int stopBits)
 Check if the given number of stop bits is a valid value. More...
 
static void CheckIsDataBitsValid (int dataBits)
 Check if the given number of data bits is a valid value. More...
 
static void CheckIsDtrControlValid (char dtrControl)
 Check if the given character represents a valid value for DTR control. More...
 
static void CheckIsRtsControlValid (char rtsControl)
 Check if the given character represents a valid value for RTS control. More...
 

Detailed Description

Serial port device.

The services below can throw MException or MESystemError in the event of an erroneous serial port operation.

Member Typedef Documentation

Operating system dependent serial port handle type

Constructor & Destructor Documentation

MSerialPort::MSerialPort ( )

Constructor that creates an uninitialized serial port.

The serial is not open until Open is called.

MSerialPort::~MSerialPort ( )

Destructor.

No exceptions are thrown by this call.

Member Function Documentation

static void MSerialPort::CheckIsBaudValid ( unsigned  baud)
static

Check if the given baud rate is valid.

Parameters
baudBaud value to be checked. If the baud rate is not valid, an exception is thrown.
static void MSerialPort::CheckIsDataBitsValid ( int  dataBits)
static

Check if the given number of data bits is a valid value.

Parameters
dataBitsData bits to check. If the number of data bits is not 5, 6, 7 or 8, an exception is thrown.
static void MSerialPort::CheckIsDtrControlValid ( char  dtrControl)
static

Check if the given character represents a valid value for DTR control.

Parameters
dtrControlDTR control parameter to check. It shall either be 'E', 'D' or 'H', or an exception is thrown.
static void MSerialPort::CheckIsParityValid ( char  parity)
static

Check if the given parity is valid.

Parameters
parityParity value to be checked. If the parity is not valid, an exception is thrown.
static void MSerialPort::CheckIsRtsControlValid ( char  rtsControl)
static

Check if the given character represents a valid value for RTS control.

Parameters
rtsControlRTS control parameter to check. It shall either be 'E', 'D', 'H', or 'T', or an exception is thrown.
static void MSerialPort::CheckIsStopBitsValid ( int  stopBits)
static

Check if the given number of stop bits is a valid value.

Parameters
stopBitsStop bits to test. If the number of stop bits is not 1 or 2, an exception is thrown.
void MSerialPort::ClearInputBuffer ( ) const

Discard the contents of the input buffer of the port.

All characters in the receive buffer that are waiting to be read are lost.

Precondition
The port is open, otherwise the operation fails with the exception.
void MSerialPort::Close ( )

Close the port.

No exceptions are thrown by this function. If the port was not open, this method does nothing.

void MSerialPort::ConfigurePortParameters ( ) const

Force configuration of port parameters to properties of this class.

No action is performed in case communication is not yet established.

Precondition
There are few checks that relate to the communication port state. OS-related exceptions can be thrown in case the port parameters cannot be set.
See also
ConfigurePortTimeouts for timeout handling.
void MSerialPort::ConfigurePortTimeouts ( ) const

Force configuration of port timeouts to properties of this class.

No action is performed in case communication is not yet established.

Precondition
There are few checks that relate to the communication port state. OS-related exceptions can be thrown in case the port timeouts cannot be set.
See also
ConfigurePortParameters for parameter handling.
void MSerialPort::FlushOutputBuffer ( unsigned  numberOfCharsInBuffer = UINT_MAX)

Ensure that the characters from the output buffer are sent.

The parameter, if specified, should match the number of characters written into the serial port right before FlushOutputBuffer is called. If the parameter is missing, the biggest possible number of characters will be ensured to go away.

Precondition
The port is open, otherwise the operation fails with the exception.
static MStdStringVector MSerialPort::GetAvailablePortNames ( bool  addExtraInfo = false)
static

Return a collection of serial port names available at this computer.

Names returned can be given to Open. The returned names are operating system dependent.

  • On Windows the names are "COM1" or "COM12". When extra information is added they are like "COM11 {USB Optical Probe}".
  • On UNIX-like operating systems such as Linux, QNX (but not Android), it returns device names such as "/dev/ttyS0". Extra information will be "/dev/ttyS0 {USB Optical Probe}".
  • On Android the port name rules are more diverse as the standard Android does not expose serial port device files. Bluetooth serial port uses the name of the paired device, and FTDI USB probe accepts the device description. Extra information will include MAC address for Bluetooth or device index for FTDI USB device.
Parameters
addExtraInfowhether to add any extra information about the port, useful for users to select the port.
Returns
array of present port names
unsigned MSerialPort::GetBaud ( ) const
inline

Baud rate of the port.

If the port is connected, the baud rate switch will happen immediately within the function. If the port is not connected, the baud rate will be used to configure the port when Open is called.

Precondition
The baud rate has to be a valid value defined by the OS. That is 300, 600, 1200, 2400, 4800, and so on. When assigning a bad baud, an exception takes place.
bool MSerialPort::GetCtsFlow ( ) const
inline

CTS flow used for port handling.

If the port is connected, CTS flow handling changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

int MSerialPort::GetDataBits ( ) const
inline

Number of data bits.

If the port is connected, the number of data bits changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

Precondition
A valid number of data bits is to be given, 5, 6, 7 or 8. Otherwise an exception is thrown.
bool MSerialPort::GetDCD ( ) const

Get the current state of the DCD signal of the port.

Precondition
The port has to be open, otherwise a system error takes place.
bool MSerialPort::GetDsrFlow ( ) const
inline

DSR flow used for port handling.

If the port is connected, CTS flow handling changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

bool MSerialPort::GetDsrSensitivity ( ) const
inline

Sensitivity of the communication port to DSR signal.

If the port is connected, DSR sensitivity handling changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

char MSerialPort::GetDtrControl ( ) const
inline

Data Terminal Ready (DTR) control mode of the communication port.

'E' means Enable, 'D' means Disable, and 'H' means Handshake.

If the port is connected, DTR control changes immediately at the assignment. If the port is not connected, the property is used to configure port when Open is called.

Precondition
The allowed values for the character are 'E', 'D' or 'H', otherwise an exception will be thrown.
PortHandleType MSerialPort::GetHandle ( ) const
inline

Access operating system handle of the port.

On Windows this is file HANDLE type, while on Posix operating systems this is an integer file number.

unsigned MSerialPort::GetIntercharacterTimeout ( ) const
inline

Read intercharacter timeout in milliseconds.

Maximum amount of milliseconds between any two characters before timeout exception takes place.

char MSerialPort::GetParity ( ) const
inline

Port parity.

If the port is connected, the parity change happens immediately at the assignment. If the port is not connected, the parity setting is used to configure the port when Open is called.

Precondition
Parity has to be any of the following characters: 'N', 'O', 'E', 'M', or 'S'. Otherwise an exception takes place.
const MStdString& MSerialPort::GetPortName ( ) const
inline

Port name, whatever was used during Open.

Setting port name explicitly outside Open can be used to keep the port name associated with the object that will open it later.

static MStdString MSerialPort::GetPortType ( const MStdString portName)
static

Get type based on the port name.

Provides information about underlying port technology. When such information is not available, for example, the given port name is not present, an empty string is returned. Otherwise the string returned can be one of the following types:

  • "serial" wide range of different UART based serial drivers
  • "bluetooth" for bluetooth devices
  • "usb" USB serial devices
  • "remote" remote ports such as MOXA NPort
  • "" empty string can be returned only on Android when MeteringSDK could not determine the type of the port
  • Any other name will mean the type of the port is determined, but not recognized and classified. The name is still useful as it identifies the port type

All known port types will always appear in lowercase. Unknown port types will preserve the letter case defined by the operating system. The port will not be opened by the call.

This is a static method as it allows getting information without opening the port. A string is returned rather than an enumeration as it allows returning useful information even when the port type is not recognized and classified.

Parameters
portNameName of the port such as "COM11" on Windows or "/dev/ttyS0" on Linux
Returns
Port type string with contents described above
unsigned MSerialPort::GetReadTimeout ( ) const
inline

Read timeout in milliseconds.

Maximum amount of milliseconds for completion of the whole read operation.

char MSerialPort::GetRtsControl ( ) const
inline

Request To Send (RTS) control mode of the communication port.

'E' means Enable, 'D' means Disable, 'H' means Handshake, and 'T' means Toggle.

If the port is connected, RTS control changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

Precondition
The allowed values for the character are 'E', 'D' 'H', or 'T', otherwise an exception will be thrown.
int MSerialPort::GetStopBits ( ) const
inline

Number of stop bits.

If the port is connected, the number of stop bits changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

Precondition
A valid number of stop bits is to be given, 1 or 2. Otherwise an exception is thrown. Notice that one and a half stop bits is not supported.
unsigned MSerialPort::GetWriteTimeout ( ) const
inline

Write timeout in milliseconds.

Timeout is the time for which the write operation should complete.

void MSerialPort::Open ( const MStdString portName)

Open a serial port.

The valid name rules depend on the operating system. All available ports can be gotten using GetAvailablePortNames(bool addExtraInfo = false) call. When addExtraInfo is true, the port names returned have more human readable information that can help select the port name. The port name is operating system dependent:

  • On Windows this can be "COM1", "COM12", and so on. The call also accepts and ignores any information in curly braces such as "COM11 {USB Optical Probe}".
  • On UNIX-like operating systems such as Linux, QNX (but not Android) this is a device name such as "/dev/ttyS0". Information in curly braces such as "/dev/ttyS0 {USB Optical Probe}" is ignored.
  • On Android the port name rules are more diverse as the standard Android does not expose serial port device files. Bluetooth serial port uses the name of the paired device, and FTDI USB probe accepts the device description. Different from Windows or *NIX, Android does not ignore the information within the curly braces and it is used to distinguish between many devices with the same name if these are hooked up. For all operating systems, it is recommended to give the result of GetAvailablePortNames(true) call as the port name.
Precondition
IsOpen() should be false as the port should not be open already prior to this call, and there is a debug version check for this condition. Also, any operating system related exception can take place due to many reasons why the port cannot be open.
Parameters
portNamePort name to open.
unsigned MSerialPort::Read ( char *  buffer,
unsigned  size 
)

Receive a number of bytes available in the serial port.

return the actual number of bytes read.

Precondition
The connection is alive, otherwise the system exception is raised. The given length is bigger than zero, otherwise a debug version hits an assert.
void MSerialPort::SetBaud ( unsigned  )

Baud rate of the port.

If the port is connected, the baud rate switch will happen immediately within the function. If the port is not connected, the baud rate will be used to configure the port when Open is called.

Precondition
The baud rate has to be a valid value defined by the OS. That is 300, 600, 1200, 2400, 4800, and so on. When assigning a bad baud, an exception takes place.
void MSerialPort::SetCtsFlow ( bool  )

CTS flow used for port handling.

If the port is connected, CTS flow handling changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

void MSerialPort::SetDataBits ( int  )

Number of data bits.

If the port is connected, the number of data bits changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

Precondition
A valid number of data bits is to be given, 5, 6, 7 or 8. Otherwise an exception is thrown.
void MSerialPort::SetDsrFlow ( bool  )

DSR flow used for port handling.

If the port is connected, CTS flow handling changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

void MSerialPort::SetDsrSensitivity ( bool  )

Sensitivity of the communication port to DSR signal.

If the port is connected, DSR sensitivity handling changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

void MSerialPort::SetDtrControl ( char  )

Data Terminal Ready (DTR) control mode of the communication port.

'E' means Enable, 'D' means Disable, and 'H' means Handshake.

If the port is connected, DTR control changes immediately at the assignment. If the port is not connected, the property is used to configure port when Open is called.

Precondition
The allowed values for the character are 'E', 'D' or 'H', otherwise an exception will be thrown.
void MSerialPort::SetIntercharacterTimeout ( unsigned  timeout)

Read intercharacter timeout in milliseconds.

Maximum amount of milliseconds between any two characters before timeout exception takes place.

void MSerialPort::SetParameters ( unsigned  baud,
int  dataBits,
char  parity,
int  stopBits 
)

Convenience method for setting related port parameters in a single call.

Parameters
baudValid baud rate
dataBitsValid data bits value
parityValid parity value
stopBitsValid stop bits value
void MSerialPort::SetParity ( char  )

Port parity.

If the port is connected, the parity change happens immediately at the assignment. If the port is not connected, the parity setting is used to configure the port when Open is called.

Precondition
Parity has to be any of the following characters: 'N', 'O', 'E', 'M', or 'S'. Otherwise an exception takes place.
void MSerialPort::SetPortName ( const MStdString port)
inline

Port name, whatever was used during Open.

Setting port name explicitly outside Open can be used to keep the port name associated with the object that will open it later.

void MSerialPort::SetReadTimeout ( unsigned  timeout)

Read timeout in milliseconds.

Maximum amount of milliseconds for completion of the whole read operation.

void MSerialPort::SetRtsControl ( char  rtsControl)

Request To Send (RTS) control mode of the communication port.

'E' means Enable, 'D' means Disable, 'H' means Handshake, and 'T' means Toggle.

If the port is connected, RTS control changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

Precondition
The allowed values for the character are 'E', 'D' 'H', or 'T', otherwise an exception will be thrown.
void MSerialPort::SetStopBits ( int  )

Number of stop bits.

If the port is connected, the number of stop bits changes immediately at the assignment. If the port is not connected, the property is used to configure the port when Open is called.

Precondition
A valid number of stop bits is to be given, 1 or 2. Otherwise an exception is thrown. Notice that one and a half stop bits is not supported.
void MSerialPort::SetTimeouts ( unsigned  intercharacterTimeout,
unsigned  readTimeout,
unsigned  writeTimeout 
)

Convenience method for setting port timeouts in a single call.

Parameters
intercharacterTimeoutIntercharacter timeout in milliseconds
readTimeoutRead timeout in milliseconds
writeTimeoutWrite timeout in milliseconds
void MSerialPort::SetWriteTimeout ( unsigned  timeout)

Write timeout in milliseconds.

Timeout is the time for which the write operation should complete.

static M_NORETURN_FUNC void MSerialPort::ThrowInvalidBaudRate ( unsigned  baud)
static

Throw an error that says the baud is invalid, giving the baud value as parameter.

Precondition
The exception is thrown unconditionally
Parameters
baudReported bad baud
void MSerialPort::UpdatePortParametersOrTimeoutsIfChanged ( ) const

If properties for parameters or timeouts are changed, change port.

No action is performed in case communication is not yet established.

Precondition
There are few checks that relate to the communication port state. OS-related exceptions can be thrown in case the port parameters or timeouts cannot be set.
See also
ConfigurePortParameters for parameter handling.
ConfigurePortTimeouts for timeout handling.
unsigned MSerialPort::Write ( const char *  buffer,
unsigned  size 
)

Write the buffer into the port.

Precondition
The port is opened successfully, otherwise the system-specific exception is thrown.