serial  1.2.1
Cross-platform, serial port library written in C++
Data Structures | Public Member Functions
serial::Serial Class Reference

#include <serial.h>

Data Structures

class  ScopedReadLock
 
class  ScopedWriteLock
 

Public Member Functions

 Serial (const std::string &port="", uint32_t baudrate=9600, Timeout timeout=Timeout(), bytesize_t bytesize=eightbits, parity_t parity=parity_none, stopbits_t stopbits=stopbits_one, flowcontrol_t flowcontrol=flowcontrol_none)
 
virtual ~Serial ()
 
void open ()
 
bool isOpen () const
 
void close ()
 
size_t available ()
 
bool waitReadable ()
 
void waitByteTimes (size_t count)
 
size_t read (uint8_t *buffer, size_t size)
 
size_t read (std::vector< uint8_t > &buffer, size_t size=1)
 
size_t read (std::string &buffer, size_t size=1)
 
std::string read (size_t size=1)
 
size_t readline (std::string &buffer, size_t size=65536, std::string eol="\n")
 
std::string readline (size_t size=65536, std::string eol="\n")
 
std::vector< std::string > readlines (size_t size=65536, std::string eol="\n")
 
size_t write (const uint8_t *data, size_t size)
 
size_t write (const std::vector< uint8_t > &data)
 
size_t write (const std::string &data)
 
void setPort (const std::string &port)
 
std::string getPort () const
 
void setTimeout (Timeout &timeout)
 
void setTimeout (uint32_t inter_byte_timeout, uint32_t read_timeout_constant, uint32_t read_timeout_multiplier, uint32_t write_timeout_constant, uint32_t write_timeout_multiplier)
 
Timeout getTimeout () const
 
void setBaudrate (uint32_t baudrate)
 
uint32_t getBaudrate () const
 
void setBytesize (bytesize_t bytesize)
 
bytesize_t getBytesize () const
 
void setParity (parity_t parity)
 
parity_t getParity () const
 
void setStopbits (stopbits_t stopbits)
 
stopbits_t getStopbits () const
 
void setFlowcontrol (flowcontrol_t flowcontrol)
 
flowcontrol_t getFlowcontrol () const
 
void flush ()
 
void flushInput ()
 
void flushOutput ()
 
void sendBreak (int duration)
 
void setBreak (bool level=true)
 
void setRTS (bool level=true)
 
void setDTR (bool level=true)
 
bool waitForChange ()
 
bool getCTS ()
 
bool getDSR ()
 
bool getRI ()
 
bool getCD ()
 

Detailed Description

Class that provides a portable serial port interface.

Constructor & Destructor Documentation

serial::Serial::Serial ( const std::string &  port = "",
uint32_t  baudrate = 9600,
Timeout  timeout = Timeout(),
bytesize_t  bytesize = eightbits,
parity_t  parity = parity_none,
stopbits_t  stopbits = stopbits_one,
flowcontrol_t  flowcontrol = flowcontrol_none 
)

Creates a Serial object and opens the port if a port is specified, otherwise it remains closed until serial::Serial::open is called.

Parameters
portA std::string containing the address of the serial port, which would be something like 'COM1' on Windows and '/dev/ttyS0' on Linux.
baudrateAn unsigned 32-bit integer that represents the baudrate
timeoutA serial::Timeout struct that defines the timeout conditions for the serial port.
See also
serial::Timeout
Parameters
bytesizeSize of each byte in the serial transmission of data, default is eightbits, possible values are: fivebits, sixbits, sevenbits, eightbits
parityMethod of parity, default is parity_none, possible values are: parity_none, parity_odd, parity_even
stopbitsNumber of stop bits used, default is stopbits_one, possible values are: stopbits_one, stopbits_one_point_five, stopbits_two
flowcontrolType of flowcontrol used, default is flowcontrol_none, possible values are: flowcontrol_none, flowcontrol_software, flowcontrol_hardware
Exceptions
serial::PortNotOpenedException
serial::IOException
std::invalid_argument
Serial::~Serial ( )
virtual

Destructor

76 {
77  delete pimpl_;
78 }

Member Function Documentation

size_t Serial::available ( )

Return the number of characters in the buffer.

100 {
101  return pimpl_->available ();
102 }
size_t available()
Definition: unix.cc:478
void Serial::close ( )

Closes the serial port.

88 {
89  pimpl_->close ();
90 }
void close()
Definition: unix.cc:455
void Serial::flush ( )

Flush the input and output buffers

353 {
354  ScopedReadLock rlock(this->pimpl_);
355  ScopedWriteLock wlock(this->pimpl_);
356  pimpl_->flush ();
357 }
void flush()
Definition: unix.cc:789
void Serial::flushInput ( )

Flush only the input buffer

360 {
361  ScopedReadLock lock(this->pimpl_);
362  pimpl_->flushInput ();
363 }
void flushInput()
Definition: unix.cc:798
void Serial::flushOutput ( )

Flush only the output buffer

366 {
367  ScopedWriteLock lock(this->pimpl_);
368  pimpl_->flushOutput ();
369 }
void flushOutput()
Definition: unix.cc:807
uint32_t Serial::getBaudrate ( ) const

Gets the baudrate for the serial port.

Returns
An integer that sets the baud rate for the serial port.
See also
Serial::setBaudrate
Exceptions
std::invalid_argument
300 {
301  return uint32_t(pimpl_->getBaudrate ());
302 }
unsigned long getBaudrate() const
Definition: unix.cc:727
bytesize_t Serial::getBytesize ( ) const

Gets the bytesize for the serial port.

See also
Serial::setBytesize
Exceptions
std::invalid_argument
312 {
313  return pimpl_->getBytesize ();
314 }
bytesize_t getBytesize() const
Definition: unix.cc:741
bool Serial::getCD ( )

Returns the current status of the CD line.

412 {
413  return pimpl_->getCD ();
414 }
bool getCD()
Definition: unix.cc:1007
bool Serial::getCTS ( )

Returns the current status of the CTS line.

397 {
398  return pimpl_->getCTS ();
399 }
bool getCTS()
Definition: unix.cc:944
bool Serial::getDSR ( )

Returns the current status of the DSR line.

402 {
403  return pimpl_->getDSR ();
404 }
bool getDSR()
Definition: unix.cc:965
flowcontrol_t Serial::getFlowcontrol ( ) const

Gets the flow control for the serial port.

See also
Serial::setFlowcontrol
Exceptions
std::invalid_argument
348 {
349  return pimpl_->getFlowcontrol ();
350 }
flowcontrol_t getFlowcontrol() const
Definition: unix.cc:783
parity_t Serial::getParity ( ) const

Gets the parity for the serial port.

See also
Serial::setParity
Exceptions
std::invalid_argument
324 {
325  return pimpl_->getParity ();
326 }
parity_t getParity() const
Definition: unix.cc:755
string Serial::getPort ( ) const

Gets the serial port identifier.

See also
Serial::setPort
Exceptions
std::invalid_argument
277 {
278  return pimpl_->getPort ();
279 }
string getPort() const
Definition: unix.cc:701
bool Serial::getRI ( )

Returns the current status of the RI line.

407 {
408  return pimpl_->getRI ();
409 }
bool getRI()
Definition: unix.cc:986
stopbits_t Serial::getStopbits ( ) const

Gets the stopbits for the serial port.

See also
Serial::setStopbits
Exceptions
std::invalid_argument
336 {
337  return pimpl_->getStopbits ();
338 }
stopbits_t getStopbits() const
Definition: unix.cc:769
serial::Timeout Serial::getTimeout ( ) const

Gets the timeout for reads in seconds.

Returns
A Timeout struct containing the inter_byte_timeout, and read and write timeout constants and multipliers.
See also
Serial::setTimeout
288  {
289  return pimpl_->getTimeout ();
290 }
Timeout getTimeout() const
Definition: unix.cc:713
bool Serial::isOpen ( ) const

Gets the open status of the serial port.

Returns
Returns true if the port is open, false otherwise.
94 {
95  return pimpl_->isOpen ();
96 }
bool isOpen() const
Definition: unix.cc:472
void Serial::open ( )

Opens the serial port as long as the port is set and the port isn't already open.

If the port is provided to the constructor then an explicit call to open is not needed.

See also
Serial::Serial
Exceptions
std::invalid_argument
serial::SerialException
serial::IOException
82 {
83  pimpl_->open ();
84 }
void open()
Definition: unix.cc:130
size_t Serial::read ( uint8_t *  buffer,
size_t  size 
)

Read a given amount of bytes from the serial port into a given buffer.

The read function will return in one of three cases:

  • The number of requested bytes was read.
    • In this case the number of bytes requested will match the size_t returned by read.
  • A timeout occurred, in this case the number of bytes read will not match the amount requested, but no exception will be thrown. One of two possible timeouts occurred:
    • The inter byte timeout expired, this means that number of milliseconds elapsed between receiving bytes from the serial port exceeded the inter byte timeout.
    • The total timeout expired, which is calculated by multiplying the read timeout multiplier by the number of requested bytes and then added to the read timeout constant. If that total number of milliseconds elapses after the initial call to read a timeout will occur.
  • An exception occurred, in this case an actual exception will be thrown.
Parameters
bufferAn uint8_t array of at least the requested size.
sizeA size_t defining how many bytes to be read.
Returns
A size_t representing the number of bytes read as a result of the call to read.
Exceptions
serial::PortNotOpenedException
serial::SerialException
125 {
126  ScopedReadLock lock(this->pimpl_);
127  return this->pimpl_->read (buffer, size);
128 }
size_t read(uint8_t *buf, size_t size=1)
Definition: unix.cc:530
size_t Serial::read ( std::vector< uint8_t > &  buffer,
size_t  size = 1 
)

Read a given amount of bytes from the serial port into a give buffer.

Parameters
bufferA reference to a std::vector of uint8_t.
sizeA size_t defining how many bytes to be read.
Returns
A size_t representing the number of bytes read as a result of the call to read.
Exceptions
serial::PortNotOpenedException
serial::SerialException
132 {
133  ScopedReadLock lock(this->pimpl_);
134  uint8_t *buffer_ = new uint8_t[size];
135  size_t bytes_read = this->pimpl_->read (buffer_, size);
136  buffer.insert (buffer.end (), buffer_, buffer_+bytes_read);
137  delete[] buffer_;
138  return bytes_read;
139 }
size_t read(uint8_t *buf, size_t size=1)
Definition: unix.cc:530
size_t Serial::read ( std::string &  buffer,
size_t  size = 1 
)

Read a given amount of bytes from the serial port into a give buffer.

Parameters
bufferA reference to a std::string.
sizeA size_t defining how many bytes to be read.
Returns
A size_t representing the number of bytes read as a result of the call to read.
Exceptions
serial::PortNotOpenedException
serial::SerialException
143 {
144  ScopedReadLock lock(this->pimpl_);
145  uint8_t *buffer_ = new uint8_t[size];
146  size_t bytes_read = this->pimpl_->read (buffer_, size);
147  buffer.append (reinterpret_cast<const char*>(buffer_), bytes_read);
148  delete[] buffer_;
149  return bytes_read;
150 }
size_t read(uint8_t *buf, size_t size=1)
Definition: unix.cc:530
string Serial::read ( size_t  size = 1)

Read a given amount of bytes from the serial port and return a string containing the data.

Parameters
sizeA size_t defining how many bytes to be read.
Returns
A std::string containing the data read from the port.
Exceptions
serial::PortNotOpenedException
serial::SerialException
154 {
155  std::string buffer;
156  this->read (buffer, size);
157  return buffer;
158 }
size_t read(uint8_t *buffer, size_t size)
Definition: serial.cc:124
size_t serial::Serial::readline ( std::string &  buffer,
size_t  size = 65536,
std::string  eol = "\n" 
)

Reads in a line or until a given delimiter has been processed.

Reads from the serial port until a single line has been read.

Parameters
bufferA std::string reference used to store the data.
sizeA maximum length of a line, defaults to 65536 (2^16)
eolA string to match against for the EOL.
Returns
A size_t representing the number of bytes read.
Exceptions
serial::PortNotOpenedException
serial::SerialException
std::string serial::Serial::readline ( size_t  size = 65536,
std::string  eol = "\n" 
)

Reads in a line or until a given delimiter has been processed.

Reads from the serial port until a single line has been read.

Parameters
sizeA maximum length of a line, defaults to 65536 (2^16)
eolA string to match against for the EOL.
Returns
A std::string containing the line.
Exceptions
serial::PortNotOpenedException
serial::SerialException
vector< string > Serial::readlines ( size_t  size = 65536,
std::string  eol = "\n" 
)

Reads in multiple lines until the serial port times out.

This requires a timeout > 0 before it can be run. It will read until a timeout occurs and return a list of strings.

Parameters
sizeA maximum length of combined lines, defaults to 65536 (2^16)
eolA string to match against for the EOL.
Returns
A vector<string> containing the lines.
Exceptions
serial::PortNotOpenedException
serial::SerialException
197 {
198  ScopedReadLock lock(this->pimpl_);
199  std::vector<std::string> lines;
200  size_t eol_len = eol.length ();
201  uint8_t *buffer_ = static_cast<uint8_t*>
202  (alloca (size * sizeof (uint8_t)));
203  size_t read_so_far = 0;
204  size_t start_of_line = 0;
205  while (read_so_far < size) {
206  size_t bytes_read = this->read_ (buffer_+read_so_far, 1);
207  read_so_far += bytes_read;
208  if (bytes_read == 0) {
209  if (start_of_line != read_so_far) {
210  lines.push_back (
211  string (reinterpret_cast<const char*> (buffer_ + start_of_line),
212  read_so_far - start_of_line));
213  }
214  break; // Timeout occured on reading 1 byte
215  }
216  if (string (reinterpret_cast<const char*>
217  (buffer_ + read_so_far - eol_len), eol_len) == eol) {
218  // EOL found
219  lines.push_back(
220  string(reinterpret_cast<const char*> (buffer_ + start_of_line),
221  read_so_far - start_of_line));
222  start_of_line = read_so_far;
223  }
224  if (read_so_far == size) {
225  if (start_of_line != read_so_far) {
226  lines.push_back(
227  string(reinterpret_cast<const char*> (buffer_ + start_of_line),
228  read_so_far - start_of_line));
229  }
230  break; // Reached the maximum read length
231  }
232  }
233  return lines;
234 }
void Serial::sendBreak ( int  duration)

Sends the RS-232 break signal. See tcsendbreak(3).

372 {
373  pimpl_->sendBreak (duration);
374 }
void sendBreak(int duration)
Definition: unix.cc:816
void Serial::setBaudrate ( uint32_t  baudrate)

Sets the baudrate for the serial port.

Possible baudrates depends on the system but some safe baudrates include: 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 56000, 57600, 115200 Some other baudrates that are supported by some comports: 128000, 153600, 230400, 256000, 460800, 921600

Parameters
baudrateAn integer that sets the baud rate for the serial port.
Exceptions
std::invalid_argument
294 {
295  pimpl_->setBaudrate (baudrate);
296 }
void setBaudrate(unsigned long baudrate)
Definition: unix.cc:719
void Serial::setBreak ( bool  level = true)

Set the break condition to a given level. Defaults to true.

377 {
378  pimpl_->setBreak (level);
379 }
void setBreak(bool level)
Definition: unix.cc:825
void Serial::setBytesize ( bytesize_t  bytesize)

Sets the bytesize for the serial port.

Parameters
bytesizeSize of each byte in the serial transmission of data, default is eightbits, possible values are: fivebits, sixbits, sevenbits, eightbits
Exceptions
std::invalid_argument
306 {
307  pimpl_->setBytesize (bytesize);
308 }
void setBytesize(bytesize_t bytesize)
Definition: unix.cc:733
void Serial::setDTR ( bool  level = true)

Set the DTR handshaking line to the given level. Defaults to true.

387 {
388  pimpl_->setDTR (level);
389 }
void setDTR(bool level)
Definition: unix.cc:875
void Serial::setFlowcontrol ( flowcontrol_t  flowcontrol)

Sets the flow control for the serial port.

Parameters
flowcontrolType of flowcontrol used, default is flowcontrol_none, possible values are: flowcontrol_none, flowcontrol_software, flowcontrol_hardware
Exceptions
std::invalid_argument
342 {
343  pimpl_->setFlowcontrol (flowcontrol);
344 }
void setFlowcontrol(flowcontrol_t flowcontrol)
Definition: unix.cc:775
void Serial::setParity ( parity_t  parity)

Sets the parity for the serial port.

Parameters
parityMethod of parity, default is parity_none, possible values are: parity_none, parity_odd, parity_even
Exceptions
std::invalid_argument
318 {
319  pimpl_->setParity (parity);
320 }
void setParity(parity_t parity)
Definition: unix.cc:747
void Serial::setPort ( const std::string &  port)

Sets the serial port identifier.

Parameters
portA const std::string reference containing the address of the serial port, which would be something like 'COM1' on Windows and '/dev/ttyS0' on Linux.
Exceptions
std::invalid_argument
266 {
267  ScopedReadLock rlock(this->pimpl_);
268  ScopedWriteLock wlock(this->pimpl_);
269  bool was_open = pimpl_->isOpen ();
270  if (was_open) close();
271  pimpl_->setPort (port);
272  if (was_open) open ();
273 }
void close()
Definition: serial.cc:87
void open()
Definition: serial.cc:81
bool isOpen() const
Definition: unix.cc:472
void setPort(const string &port)
Definition: unix.cc:695
void Serial::setRTS ( bool  level = true)

Set the RTS handshaking line to the given level. Defaults to true.

382 {
383  pimpl_->setRTS (level);
384 }
void setRTS(bool level)
Definition: unix.cc:849
void Serial::setStopbits ( stopbits_t  stopbits)

Sets the stopbits for the serial port.

Parameters
stopbitsNumber of stop bits used, default is stopbits_one, possible values are: stopbits_one, stopbits_one_point_five, stopbits_two
Exceptions
std::invalid_argument
330 {
331  pimpl_->setStopbits (stopbits);
332 }
void setStopbits(stopbits_t stopbits)
Definition: unix.cc:761
void Serial::setTimeout ( serial::Timeout timeout)

Sets the timeout for reads and writes using the Timeout struct.

There are two timeout conditions described here:

  • The inter byte timeout:
    • The inter_byte_timeout component of serial::Timeout defines the maximum amount of time, in milliseconds, between receiving bytes on the serial port that can pass before a timeout occurs. Setting this to zero will prevent inter byte timeouts from occurring.
  • Total time timeout:
    • The constant and multiplier component of this timeout condition, for both read and write, are defined in serial::Timeout. This timeout occurs if the total time since the read or write call was made exceeds the specified time in milliseconds.
    • The limit is defined by multiplying the multiplier component by the number of requested bytes and adding that product to the constant component. In this way if you want a read call, for example, to timeout after exactly one second regardless of the number of bytes you asked for then set the read_timeout_constant component of serial::Timeout to 1000 and the read_timeout_multiplier to zero. This timeout condition can be used in conjunction with the inter byte timeout condition with out any problems, timeout will simply occur when one of the two timeout conditions is met. This allows users to have maximum control over the trade-off between responsiveness and efficiency.

Read and write functions will return in one of three cases. When the reading or writing is complete, when a timeout occurs, or when an exception occurs.

A timeout of 0 enables non-blocking mode.

Parameters
timeoutA serial::Timeout struct containing the inter byte timeout, and the read and write timeout constants and multipliers.
See also
serial::Timeout
283 {
284  pimpl_->setTimeout (timeout);
285 }
void setTimeout(Timeout &timeout)
Definition: unix.cc:707
void serial::Serial::setTimeout ( uint32_t  inter_byte_timeout,
uint32_t  read_timeout_constant,
uint32_t  read_timeout_multiplier,
uint32_t  write_timeout_constant,
uint32_t  write_timeout_multiplier 
)
inline

Sets the timeout for reads and writes.

468  {
469  Timeout timeout(inter_byte_timeout, read_timeout_constant,
470  read_timeout_multiplier, write_timeout_constant,
471  write_timeout_multiplier);
472  return setTimeout(timeout);
473  }
void setTimeout(Timeout &timeout)
Definition: serial.cc:282
void Serial::waitByteTimes ( size_t  count)

Block for a period of time corresponding to the transmission time of count characters at present serial settings. This may be used in con- junction with waitReadable to read larger blocks of data from the port.

113 {
114  pimpl_->waitByteTimes(count);
115 }
void waitByteTimes(size_t count)
Definition: unix.cc:523
bool Serial::waitForChange ( )

Blocks until CTS, DSR, RI, CD changes or something interrupts it.

Can throw an exception if an error occurs while waiting. You can check the status of CTS, DSR, RI, and CD once this returns. Uses TIOCMIWAIT via ioctl if available (mostly only on Linux) with a resolution of less than +-1ms and as good as +-0.2ms. Otherwise a polling method is used which can give +-2ms.

Returns
Returns true if one of the lines changed, false if something else occurred.
Exceptions
SerialException
392 {
393  return pimpl_->waitForChange();
394 }
bool waitForChange()
Definition: unix.cc:901
bool Serial::waitReadable ( )

Block until there is serial data to read or read_timeout_constant number of milliseconds have elapsed. The return value is true when the function exits with the port in a readable state, false otherwise (due to timeout or select interruption).

106 {
107  serial::Timeout timeout(pimpl_->getTimeout ());
108  return pimpl_->waitReadable(timeout.read_timeout_constant);
109 }
bool waitReadable(uint32_t timeout)
Definition: unix.cc:492
Definition: serial.h:98
Timeout getTimeout() const
Definition: unix.cc:713
size_t Serial::write ( const uint8_t *  data,
size_t  size 
)

Write a string to the serial port.

Parameters
dataA const reference containing the data to be written to the serial port.
sizeA size_t that indicates how many bytes should be written from the given data buffer.
Returns
A size_t representing the number of bytes actually written to the serial port.
Exceptions
serial::PortNotOpenedException
serial::SerialException
serial::IOException
253 {
254  ScopedWriteLock lock(this->pimpl_);
255  return this->write_(data, size);
256 }
size_t Serial::write ( const std::vector< uint8_t > &  data)

Write a string to the serial port.

Parameters
dataA const reference containing the data to be written to the serial port.
Returns
A size_t representing the number of bytes actually written to the serial port.
Exceptions
serial::PortNotOpenedException
serial::SerialException
serial::IOException
246 {
247  ScopedWriteLock lock(this->pimpl_);
248  return this->write_ (&data[0], data.size());
249 }
size_t serial::Serial::write ( const std::string &  data)

Write a string to the serial port.

Parameters
dataA const reference containing the data to be written to the serial port.
Returns
A size_t representing the number of bytes actually written to the serial port.
Exceptions
serial::PortNotOpenedException
serial::SerialException
serial::IOException

The documentation for this class was generated from the following files: