【问题标题】:Truncated data (if more than 512 bytes) when using boost::asio::async_read_until from serial port从串口使用 boost::asio::async_read_until 时截断的数据(如果超过 512 字节)
【发布时间】:2020-08-05 09:24:01
【问题描述】:

我正在使用 boost::asio::async_read_until 函数从 Windows 10 中的串行端口读取。分隔符是正则表达式模式。只要接收到的数据不超过 512 字节,它就可以正常工作。

如果接收到的数据大于512字节,则简单截断,不再调用“readComplete”函数。但是,如果我发送更多数据,1 个字节就足够了,丢失的数据将与新数据一起接收。

我在 tcp/socket 上使用了相同的实现,并且可以完美运行。 Windows 中的本机串行接口是否有任何限制导致此行为?

编辑 1:我注意到如果波特率从 115200 降低到 28800,则不会丢失任何数据。

// from .h-file: boost::asio::streambuf streamBuf_;

void RS232Instrument::readAsyncChars()
{
   boost::asio::async_read_until(
      serial_,
      streamBuf_,
      boost::regex(regexStr_.substr(6, regexStr_.length() - 7)),
      boost::bind(
         &RS232Instrument::readComplete,
         this,
         boost::asio::placeholders::error,
         boost::asio::placeholders::bytes_transferred));
}

void RS232Instrument::readComplete(const boost::system::error_code& error, size_t bytes_transferred)
{   
   if(error)
   {
     // Error handling
   }
   else
   {
      std::string rawStr(
         boost::asio::buffers_begin(streamBuf_.data()),
         boost::asio::buffers_begin(streamBuf_.data()) + bytes_transferred);

      // Log the data in rawStr....

      // Remove data from beginning until all data sent to log
      streamBuf_.consume(bytes_transferred);

      if(abort_ == false)
      {
         readAsyncChars();
      }
   }
}

【问题讨论】:

    标签: c++ windows serial-port boost-asio


    【解决方案1】:

    既然我发现是这个问题引起的,我会自己回答这个问题。

    为了清楚起见,我在上面省略了一些代码,我没有意识到的代码实际上是问题所在。 省略的代码示例:

    LOG_DEBUG("Rs232Data收到");

    我使用了 boost:log 功能,并在日志框架中添加了更多“接收器”。本例中使用的接收器记录到 ram 中的向量,并在用户输入触发时打印到控制台。

    事实证明,日志框架在调用 sink 中的“consume”函数之前消耗了大约 1 ms。这足以在使用 async_read_until 时导致串口数据丢失。

    经验教训:不要在 async_read_until 的处理函数中调用任何耗时的任务

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 2016-12-22
      • 2018-07-21
      • 2015-02-25
      • 2011-02-17
      • 1970-01-01
      相关资源
      最近更新 更多