使用 PassThruCAN 插件
Pass-Thru CAN 插件通过 SAE J2534 Pass-Thru API 访问 CAN 适配器。SAE J2534 是通过 x86 Windows PC 访问车辆总线的标准。虽然该 API 仅针对 32 位 Windows,但一些供应商也提供了针对 64 位 Windows 和其他操作系统(如 Linux)的实现。
PassThruCAN 的使用
要使用 PassThruCAN,必须安装 CAN 适配器的相应供应商驱动程序。供应商还必须通过共享库提供 J2534 API 的实现。目前,只支持 04.04 版本的 Pass-Thru API。
在使用 x64 版本的 Qt 时,只有当 CAN 设备供应商也提供 64 位版本的 J2534 Pass-Thru 接口库时,该插件才能工作。如果供应商只提供 32 位 J2534 接口,则需要 32 位 Qt 版本才能使用。
要自动发现设备,供应商软件还必须在 Windows 注册表中列出并描述可用的适配器。在 Windows 以外的系统中,目前还不支持自动发现功能。
创建 CAN 总线设备
首先需要检查QCanBus 是否提供了所需插件:
if (QCanBus::instance()->plugins().contains(QStringLiteral("passthrucan"))) { // plugin available }
其中passthrucan是插件名称。
在 Windows 系统上,应使用自动设备发现功能列出可通过 Pass-Thru API 访问的可用 CAN 适配器:
const auto adapters = QCanBus::instance()-> availableDevices(QStringLiteral("passthrucan")); for (const QCanBusDeviceInfo &info : adapters) { // List available adapter in the user interface. uiListBox->addItem(info.name()); }
在其他操作系统上,发现的适配器列表将是空的。相反,应提供供应商提供的 J2534 接口库的完整路径来代替设备名称:
QCanBusDevice *device = QCanBus::instance()->createDevice( QStringLiteral("passthrucan"), QStringLiteral("/path/to/libj2534-vendor.so"));
为满足特殊需要,也可以在打开 Pass-Thru 适配卡时传递特定于供应商的设备名称参数:
QCanBusDevice *device = QCanBus::instance()->createDevice( QStringLiteral("passthrucan"), info.name() + QChar::fromLatin1('%') + deviceName);
Pass-Thru CAN 总线设备上的所有操作都是异步执行的,包括连接和断开。为了在设备准备好读写 CAN 帧时获得通知,请连接到stateChanged (QCanBusDevice::CanBusDeviceState 状态)信号:
if (!device) { // Error handling goes here } else { connect(device, &QCanBusDevice::stateChanged, this, &MyClass::canStateChanged); device->connectDevice(); }
state(一旦成功连接 CAN 适配器,()将返回ConnectedState 。然后,该设备就可用于写入和读取 CAN 帧:
QCanBusFrame frame; frame.setFrameId(8); frame.setPayload(QByteArray("\xA3\x6E\x74\x9C", 4)); device->writeFrame(frame);
读取可使用readFrame() 方法完成。当至少有一个新帧可供读取时,就会发出framesReceived() 信号:
QCanBusFrame frame = device->readFrame();
Pass-Thru CAN 插件支持以下配置选项,可通过setConfigurationParameter() 进行控制:
配置参数键 | 说明 |
---|---|
QCanBusDevice::LoopbackKey | 启用后,如果 CAN 总线上传输了 CAN 帧,CAN 适配器将接收到该帧的本地回声。回音帧用QCanBusFrame::hasLocalEcho() 标记。默认情况下,环回模式被禁用。 |
QCanBusDevice::RawFilterKey | 通过该选项可以为接收到的 CAN 总线报文设置过滤器。如果提供,其值应为QList<QCanBusDevice::Filter>。仅支持数据帧 ID 过滤器。默认情况下,接受任何 ID 的数据帧。 |
QCanBusDevice::BitRateKey | CAN 总线的比特率,无符号整数,单位为比特/秒。默认比特率为 500000(500 kbit/s)。在连接设备后设置比特率可能会触发 CAN 接口的隐式重新初始化。 |
Pass-Thru CAN 插件支持扩展帧格式(29 位 ID),但不支持灵活数据速率(CAN FD)。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.