繁体   English   中英

串口接收字节时发出信号

[英]Emitting signal when bytes are received in serial port

我正在尝试使用Boost库在C ++中连接信号和插槽。 我的代码当前打开一个文件并从中读取数据。 但是,我正在尝试改进代码,以便它可以使用串行端口实时读取和分析数据。 我想做的是只有当串行端口中有可用数据时才调用分析功能。

我将如何去做呢? 我之前在Qt中已经做过,但是我不能在Qt中使用信号和插槽,因为此代码未使用其moc工具。

在处理串行端口时,您的OS(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类。 只需使用同步读取功能,结果将是相同的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM