我使用boost来从串口读/写。设备通过USB(ttyACM0)连接。我的代码可以工作,但我不确定我是否正确处理文件结束时的错误,这是在读取过程中拆卸USB电缆时得到的。打开串口看起来像这样(我在这里只是代码中最重要的部分):
//this thread tries to open a serial port
if(serialPort_.is_open())
{
serialPort_.close();
}
try
{
serialPort_.open(port);
}
catch(std::exception& e)
{
//some code
continue;
}
if (serialPort_.is_open())
{
serialPort_.set_option(/*baud rate etc. */);
startRead();
}
else
{
//some code
continue;
}
/////Handling end of file (or open other port), works but I'm not sure if it is correct
if(ioServiceRun)
{
ioServiceThread_.interrupt();
if(ioServiceThread_.joinable())
{
ioServiceThread_.join();
ioServiceRun = false;
ioService_.reset();
}
}
////////////////////////////////////////////////////////////////
if(!ioServiceRun)
{
try
{
ioServiceThread_ = boost::thread(boost::bind(&boost::asio::io_service::run, &ioService_));
}
catch (std::exception&)
{
//some code
continue;
}
ioServiceRun = true;
}
以下是阅读功能:
void startRead()
{
serialPort_.async_read_some(boost::asio::buffer(readSerialPortData_),
boost::bind(&SerialPortAccess::readComplete, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void readComplete(const boost::system::error_code& error, size_t bytesTransferred)
{
if (!error)
{
if (bytesTransferred > 0 && !readSerialPortData_.empty())
{
//handle data
}
startRead();
}
else
{
if(error == boost::asio::error::eof)
{
//async try to open serial port (someone may connect usb cable again), notify other thread (code presented above)
open("/dev/ttyACM0");
}
else
{
close();
}
}
}
实施是否正确?