C++ 尝试在unix系统上为串行设备ttys0生成定时连接

C++ 尝试在unix系统上为串行设备ttys0生成定时连接,c++,boost-asio,C++,Boost Asio,我试图生成一个类,用于从特定的串行设备读取数据 对于启动进程,必须发送字符“1”,然后我必须等待响应(254和255) 在10毫秒内,我必须向设备发送下一个命令,但这次命令长度为5个字符 当通信没有在正确的时间发送时,设备将超时并向我发送255255,2,4 因此,我需要不同大小的读取,对我来说最重要的是通信超时,否则系统将因丢失一些值而停止工作 因此,我尝试使用boost::asio::async\u read生成一个类 它的工作方式是正确的,我可以定义超时,也可以定义要读取的字节大小。当设备

我试图生成一个类,用于从特定的串行设备读取数据

对于启动进程,必须发送字符“1”,然后我必须等待响应(254和255)


在10毫秒内,我必须向设备发送下一个命令,但这次命令长度为5个字符

当通信没有在正确的时间发送时,设备将超时并向我发送255255,2,4

因此,我需要不同大小的读取,对我来说最重要的是通信超时,否则系统将因丢失一些值而停止工作

因此,我尝试使用boost::asio::async\u read生成一个类

它的工作方式是正确的,我可以定义超时,也可以定义要读取的字节大小。当设备发送的大小不正确时,例程将被保留

但只有第一次,当我第二次尝试时,设备没有向我发送任何信息。我已尝试再次使用.open,但它无法解决问题。另外,停用关闭功能也不能解决问题,那么例程就会出错

有人能就我的问题给我一点建议吗。也许我对自己的问题视而不见。。。。伯纳德

ConnectionWithTimeout::ConnectionWithTimeout(int timeout_)
    : timer_(io_service_, boost::posix_time::milliseconds(timeout_))
    , serial_port_(io_service_) {
    }

void ConnectionWithTimeout::ReadNumberOfChars(int numberOfCharactersToRead_)
{
    buffer_.resize(numberOfCharactersToRead_);
    for (int i = 0; i < numberOfCharactersToRead_; ++i) {
        std::cout << "Clear Buffer[" << i << "]" << std::endl;
        buffer_[i] = 0;
    }
    timer_.async_wait(boost::bind(&::ConnectionWithTimeout::Stop, this));
    //async read from serial port
    boost::asio::async_read(serial_port_, boost::asio::buffer(buffer_), 
    boost::bind(&ConnectionWithTimeout::ReadHandle, this, 
    boost::asio::placeholders::error));
    io_service_.run();
}

void ConnectionWithTimeout::Stop() {
    std::cout << "Connection is being closed." << std::endl;
    serial_port_.close();
    std::cout << "Connection has been closed." << std::endl;
}
void ConnectionWithTimeout::ReadHandle(const boost::system::error_code& ec) {
    if (ec) {
        std::cout << "The amount of data is to low: " << ec << std::endl;
        for (std::vector<char>::iterator it = buffer_.begin();
             it != buffer_.end(); ++it)
        {
            std::cout << int(*it) << std::endl;
        }
    }
    else {
        std::cout << "The amount of data is correct: " << ec << std::endl;
        for (std::vector<char>::iterator it = buffer_.begin(); it != 
             buffer_.end(); ++it)
         {
            std::cout << int(*it) << std::endl;
         }
    }
}
ConnectionWithTimeout::ConnectionWithTimeout(int timeout)
:timer_uu(io_u服务,boost::posix_u时间::毫秒(超时))
,串行端口(io\U服务){
}
无效连接WithTimeout::ReadNumberOfChars(int numberOfCharactersToRead)
{
缓冲区大小(numberOfCharactersToRead);
对于(int i=0;istd::cout“在10毫秒内”我只知道大多数操作系统在保证这类时间方面都有问题,例如,微软通常会说一些15毫秒左右的下限,特别是在用户代码中。因此,您只能尝试在一个缓冲区中给出char“1”和rest send命令,即一次对asio的调用,因此串行驱动程序领域应该在这一时间限制内。“在10毫秒内“我只知道大多数操作系统在保证这类时间方面都有问题,例如,微软像往常一样规定了15毫秒的下限,特别是在用户代码中。因此,您只能尝试在一个缓冲区中给出char'1'和rest send命令,即对asio的一次调用,因此串行驱动程序领域应该在这一时间限制内。