当在串行端口中接收到字节时发出信号

Emitting signal when bytes are received in serial port

本文关键字:信号 到字节 串行端口      更新时间:2023-10-16

我正在尝试使用boost库连接C++中的一个信号和一个插槽。我的代码目前打开一个文件并从中读取数据。然而,我正在努力改进代码,使其能够使用串行端口实时读取和分析数据。我想做的是只有在串行端口中有数据可用时才调用分析函数。

我该怎么做?我以前在Qt中做过,但我不能在Qt使用信号和插槽,因为这段代码没有使用他们的moc工具。

您的操作系统(Linux)在处理串行端口时为您提供了以下机制。

您可以将串行端口设置为非匿名模式(通过在termios结构中取消设置ICANON标志)。然后,如果c_cc[]中的MINTIME参数为零,则当且仅当串行端口输入缓冲区中有新数据时,read()函数才会返回(有关详细信息,请参阅termios手册页)。因此,您可以运行一个单独的线程来负责获取传入的串行数据:

ssize_t count, bytesReceived = 0;
char myBuffer[1024];
while(1)
{
    if (count = read(portFD, 
        myBuffer + bytesReceived, 
        sizeof(myBuffer)-bytesReceived) > 0)
    {
     /*
       Here we check the arrived bytes. If they can be processed as a complete message,
       you can alert other thread in a way you choose, put them to some kind of 
       queue etc. The details depend greatly on communication protocol being used.
       If there is not enough bytes to process, you just store them in buffer
      */
         bytesReceived += count;
         if (MyProtocolMessageComplete(myBuffer, bytesReceived))
         {
              ProcessMyData(myBuffer, bytesReceived);
              AlertOtherThread(); //emit your 'signal' here
              bytesReceived = 0;  //going to wait for next message
         }
    }
    else
    {
     //process read() error
    }
}

这里的主要思想是,只有当新数据到达时,调用read()的线程才会处于活动状态。剩下的时间操作系统将使这个线程处于等待状态。因此,它不会消耗CPU时间。如何实现实际的signal部分取决于您。

上面的示例使用常规的read系统调用从端口获取数据,但您可以以相同的方式使用boost类。只要使用同步读取函数,结果就会是一样的。