字节[256]的Boost::serial_port和asio::async_write超过200ms

Boost::serial_port and asio::async_write for byte[256] exceeds 200ms

本文关键字:asio async 200ms 超过 write port serial Boost 字节      更新时间:2023-10-16

我正在通过串行端口实现一些基本的通信。

根据协议,我必须在收到请求后的 225 毫秒内回复。最大封装尺寸为 256B。

因此,当我收到请求时,我创建了响应[header, lenght, payload, crc16](总共 256 B(,平均需要 30 - 40 毫秒。然后当我将该响应(字节数组(放入asio::async_write时,实际问题就会出现。该函数平均需要大约 240 毫秒来处理该字节数组。

除了我发送最大长度的包裹外,一切正常。大约需要240ms(asio::async_write(+ 40ms(封装组装(约280~300ms。

端口:9600波特,长度8,一个停止位

知道我怎样才能加快速度吗?

    void Example::do_write()
{
    if (pimpl_->WriteBuffer == nullptr)
    {
        boost::lock_guard<boost::mutex> l(pimpl_->WriteQueueMutex);
        pimpl_->WriteBufferSize = pimpl_->WriteQueue.size();
        pimpl_->WriteBuffer.reset(new byte[pimpl_->WriteQueue.size()]);
        std::move(pimpl_->WriteQueue.begin(), pimpl_->WriteQueue.end(), pimpl_->WriteBuffer.get());
        pimpl_->WriteQueue.clear();
        begin = boost::chrono::steady_clock::now();
        async_write(pimpl_->Port, asio::buffer(pimpl_->WriteBuffer.get(), pimpl_->WriteBufferSize), boost::bind(&Example::write_end, this, asio::placeholders::error));
    }
}
void Example::write_end(const system::error_code& error)
{
    if (!error)
    {
        boost::lock_guard<boost::mutex> l(pimpl_->WriteQueueMutex);
        if (pimpl_->WriteQueue.empty())
        {
            pimpl_->WriteBuffer.reset();
            pimpl_->WriteBufferSize = 0;
            end = boost::chrono::steady_clock::now();
            OutputDebugString(string("nWRITE TIME: " + to_string(boost::chrono::duration_cast<boost::chrono::milliseconds>(end - begin).count()) + "n").c_str());
            return;
        }
        pimpl_->WriteBufferSize = pimpl_->WriteQueue.size();
        pimpl_->WriteBuffer.reset(new byte[pimpl_->WriteQueue.size()]);
        std::move(pimpl_->WriteQueue.begin(), pimpl_->WriteQueue.end(), pimpl_->WriteBuffer.get());
        pimpl_->WriteQueue.clear();
        async_write(pimpl_->Port, asio::buffer(pimpl_->WriteBuffer.get(), pimpl_->WriteBufferSize), boost::bind(&Example::write_end, this, asio::placeholders::error));
    }
    else
    {
        set_error_status(true);
        do_close();
    }
}

根据我的经验,boost::asio本身需要几分之一微秒。您使用 40 毫秒来获取数据,通信需要 220 毫秒(通过 9600 波特发送 256 字节大约是最小值(,而在某个地方你浪费了更多的 20-40 毫秒,总和为 280 - 300 毫秒。

怎么办?

  1. 最有利可图的是将波特率提高到 115200 波特(9600 波特为 0.85 毫秒/字节,而 115200 波特为 0.07 毫秒/字节(。
  2. 下一个想法是分析出这 20-40 毫秒的去向(可能是您编写的消息循环中不需要的东西(。
  3. 最后,还可能减少获取 40 毫秒的数据。