我要实现(希望如此)强大的异步串行 rs232 数据传输(通过 USB)- 适用于 windows 和 linux,包括 esp。那个叫做 beagle bone black 的漂亮嵌入式系统。
最后,我只是希望能够(兼容地)与 rs232 进行可靠的截止超时、cancel() reset() 等通信,以免在例如运行时崩溃/挂起。 tx 或 rx 线意外断开。当然,我可以简单地复制/粘贴/采用现有示例。但我也想变得更加开明;-)
我决定使用 boost:asio::serial_port .现在在阅读文档时,我对这两个类感到困惑(三个带有 typedef serial_port):
serial_port_service - 串行端口的默认服务实现。
class serial_port_service : public io_service::service
basic_serial_port - 提供串口功能。
template< typename SerialPortService = serial_port_service>
class basic_serial_port :
public basic_io_object< SerialPortService >,
public serial_port_base
我明白了,我需要一个 boost::asio::io_service
来构造 boost::asio::serial_port
或 serial_port_service
。
我想我已经了解了 asio 如何完成这项工作的基本方法,例如在this examples .
OK serial_port_service
派生自io_service,它的ctor 接受了一个io_service
,它的接口(interface)也提供了basic_serial_port
的memberfuncs。
对我来说,它看起来像是一个 io_service,它也实现了一个 basic_serial_port - 为什么要有两个类?什么时候用一个,什么时候用另一个?不确定可能的用例,以及这个 serial_port
typedef 怎么样。也许(很明显)我错过了一些东西 - 有人可以给我更多的启发吗?
最佳答案
通常,应用程序应该使用 I/O 对象。在这种情况下,这将是 boost::asio::serial_port
.
各种类用于分离职责和抽象。名称的相似性可能会造成混淆,因此文档在命名时非常谨慎。 documentation状态:
Class
io_service
implements an extensible, type-safe, polymorphic set of I/O services, indexed by service type. An object of classio_service
must be initialised before I/O objects such as sockets, resolvers and timers can be used. These I/O objects are distinguished by having constructors that accept anio_service&
parameter.I/O services exist to manage the logical interface to the operating system on behalf of the I/O objects. In particular, there are resources that are shared across a class of I/O objects. For example, timers may be implemented in terms of a single timer queue. The I/O services manage these shared resources.
在串行端口的上下文中解释这一点:
io_service
提供事件处理循环并管理 I/O 服务,例如serial_port_service
.serial_port
是一个 I/O 对象,它提供了一个接口(interface)来执行串行端口相关的操作。实现非常基本:- 确定如何将信息返回给调用者:如果发生错误则抛出,填充
std::future
, 暂停 coroutine等 - 将实际工作推迟到
serial_port_service
,它的 I/O 服务。 - 提供RAII语义。当
serial_port
被销毁时,它会取消未完成的异步操作并关闭serial_port
。
- 确定如何将信息返回给调用者:如果发生错误则抛出,填充
serial_port_service
是一个 I/O 服务:- 它提供抽象并实现特定于平台的 API。
- 它在使用相同
io_service
的serial_port
之间共享。当使用io_service
创建serial_port
时,serial_port
将使用注册到的现有
或使用serial_port_service
io_serviceio_service
创建并注册一个新的serial_port_service
。 - 它充当 I/O 对象的工厂
implementation
.对于serial_port
,这可能是基本文件描述符或句柄。
关于c++ - boost asio serial_port_service 和 serial_port 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26562965/