我想使用boost.asio检查串口上的传入数据包。 每个数据包将以一个字节长的标头开始,并指定已发送的消息类型。 每种不同类型的消息都有自己的长度。 我想写的函数应该不断地监听新的传入消息,当它找到它时应该读取它,并调用其他函数来解析它。 我目前的代码如下:
void check_for_incoming_messages()
{
boost::asio::streambuf response;
boost::system::error_code error;
std::string s1, s2;
if (boost::asio::read(port, response, boost::asio::transfer_at_least(0), error)) {
s1 = streambuf_to_string(response);
int msg_code = s1[0];
if (msg_code < 0 || msg_code >= NUM_MESSAGES) {
// Handle error, invalid message header
}
if (boost::asio::read(port, response, boost::asio::transfer_at_least(message_lengths[msg_code]-s1.length()), error)) {
s2 = streambuf_to_string(response);
// Handle the content of s1 and s2
}
else if (error != boost::asio::error::eof) {
throw boost::system::system_error(error);
}
}
else if (error != boost::asio::error::eof) {
throw boost::system::system_error(error);
}
}
boost::asio::streambuf是正确使用的工具吗? 如何从中提取数据以便我可以解析消息? 我也想知道我是否需要一个只调用此函数的单独线程,以便更频繁地调用它。 由于高流量和串口缓冲区耗尽,我是否应该担心两次调用函数之间的数据丢失? 我正在使用Qt的GUI用于GUI,我真的不知道处理所有事件需要多少时间。
编辑:有趣的问题是:如何检查串口上是否有传入数据? 如果没有传入数据,我不希望该功能阻止...