linux asio 读取串口,c++ - 使用Boost Asio从串口读取 - 堆栈内存溢出

我想使用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,我真的不知道处理所有事件需要多少时间。

编辑:有趣的问题是:如何检查串口上是否有传入数据? 如果没有传入数据,我不希望该功能阻止...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想在 C++使用 MySQL,并且不依赖于 Boost 库,你可以考虑使用第三方库 mysql-async。mysql-async 提供了一个基于非阻塞的异步操作接口,使用 asio 库进行底层网络通信。 以下是一个简单的示例代码,展示了如何使用 mysql-async 连接到 MySQL 数据库并执行查询操作: ```cpp #include <iostream> #include <mysql_async/mysql_async.h> int main() { boost::asio::io_service io_service; // 创建 MySQL 连接对象 mysql_async::connection conn(io_service); // 异步连接到数据库 conn.async_connect("tcp://127.0.0.1:3306", "user", "password", [](const boost::system::error_code& ec) { if (!ec) { std::cout << "Connected to MySQL server" << std::endl; // 异步执行查询操作 conn.async_query("SELECT * FROM table_name", [](const boost::system::error_code& ec, mysql_async::resultset_ref result) { if (!ec) { std::cout << "Query executed successfully" << std::endl; // 遍历结果集 while (result->next()) { std::cout << "Column 1: " << result->get_string(0) << std::endl; std::cout << "Column 2: " << result->get_string(1) << std::endl; // ... } } else { std::cout << "Error executing query: " << ec.message() << std::endl; } }); } else { std::cout << "Error connecting to MySQL server: " << ec.message() << std::endl; } }); // 运行异步操作 io_service.run(); return 0; } ``` 请注意,你需要在代码中包含 `mysql_async/mysql_async.h` 头文件,并将 mysql-async 库链接到你的项目中。 这只是一个简单的示例,你可以根据 mysql-async 的文档和示例进行更复杂的操作,如插入、更新、删除等。你可以在 mysql-async 的 GitHub 仓库中找到更多的信息和用法示例:https://github.com/mysql-net/mysql-async

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值