当在串行端口中接收到字节时发出信号
Emitting signal when bytes are received in serial port
我正在尝试使用boost库连接C++中的一个信号和一个插槽。我的代码目前打开一个文件并从中读取数据。然而,我正在努力改进代码,使其能够使用串行端口实时读取和分析数据。我想做的是只有在串行端口中有数据可用时才调用分析函数。
我该怎么做?我以前在Qt中做过,但我不能在Qt使用信号和插槽,因为这段代码没有使用他们的moc工具。
您的操作系统(Linux)在处理串行端口时为您提供了以下机制。
您可以将串行端口设置为非匿名模式(通过在termios
结构中取消设置ICANON
标志)。然后,如果c_cc[]
中的MIN
和TIME
参数为零,则当且仅当串行端口输入缓冲区中有新数据时,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
类。只要使用同步读取函数,结果就会是一样的。
相关文章:
- Qt VTK交互风格的信号到小部件
- 使用 swig 追加到字节数组
- Ascii .txt文件到字节数组 - C++
- 将 CByteArray 复制到字节数组中会导致访问冲突
- 将QPush按钮::单击信号到插槽时出错
- 将HICON / HCURSOR复制到字节数组中
- 将 QImage 保存到字节数组
- 如何将数据复制到字节数组的某些部分
- 将数据流到字节数组中
- QT5 C 信号到QML插槽不起作用
- 如何将任何值转换为字节数组并将其附加到字节列表
- 以C++(Arduino)为单位比较指针到字节
- QT:C 信号到QML连接
- C++BigInteger到字节数组
- 从套接字到字节数组的读取数据中的意外字符
- C++结构到字节*引发错误
- std ::字符串到字节[]
- 如何从iStream的开头便移到字节中的偏移
- 将结构添加到字节向量,然后添加另一个
- 当在串行端口中接收到字节时发出信号