Boost Asio串口如何找出读取队列中缓冲区的大小C++

Boost Asio Serial port How to find out the size of the buffer in the queue for reading C++

在Arduino中可以读取数据如下:

void setup() {
    Serial.begin(9600);
}

String Comand = "";
void loop() {
    if (Serial.available() > 0) //If there is data read 
        {
        char c = Serial.read(); //get byte
        if(c!='\n')
        {
          Comand+=c;
        }
        else
        {
          if(Comand == "MyComand")
          {
            Serial.println("Comand 1");
          }
          //else
          //...
          Comand = "";
        }
    }
}

С++ 提升 asio 这里有一个c++从端口回放数据的例子,但是有什么函数可以检查是否有可读的?

#include <boost/asio.hpp>
#include <windows.h>

//....

int main(int, char**)
{
    {
        boost::asio::io_service io;
        boost::asio::serial_port serial(io,"COM5");
        serial.set_option(boost::asio::serial_port_base::baud_rate(9600));

        std::string s = "MyComand\n";
        boost::asio::write(serial,boost::asio::buffer(s.c_str(),s.size()));
        std::string result;

        //while serial data > 0 ???  How to check
        {
            using namespace boost;
            char c;
            asio::read(serial,asio::buffer(&c,1));
            result+=c;
        }

        std::cout<<result.c_str();

    }

return 0;
}

如果我循环读取,没有数据,程序就会停下来等待数据,不适合我。如何在尝试读取之前检查是否有数据。

异步IO的思想是不检查数据是否可用。相反,您可以推迟读取的完成,直到出现这种情况。

现在,您仍在使用 Asio 进行同步 IO。而你的要求是:

If I read in a cycle, and there is no data, the program will stop and wait for the data, it does not suit me.

同步 IO 意味着 阻塞读取。你可以return任何可用的:

while (auto n = serial.read_some(asio::buffer(buf))) {
    result.append(buf.data(), n);
    std::cout << "Received " << n
              << " bytes, total length: " << result.length() << "\n";
}

但是read_some还在阻塞:

This function is used to read data from the serial port. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

因此,串行端口唯一真正的替代方法是使用异步接口:

std::string result;
std::array<char, 32> buf;

std::function<void(error_code, size_t)> read_loop;
read_loop = [&](error_code ec, size_t n) {
    if (ec.failed())
        return;
    std::cout << "Received " << n
              << " bytes, total length: " << result.length() << "\n";
    result.append(buf.data(), n);
    serial.async_read_some(asio::buffer(buf), read_loop);
};
read_loop(error_code{}, 0);

现在你有一个新的“问题”:如何将你的应用程序逻辑集成到这里。您正在打印请求这一事实向我表明您没有收到无限制的二进制数据流。 相反,考虑简化您的应用程序逻辑以仅读取您需要的内容,也许有超时。参见例如asio_read_some countinue reading to get all data