使用 PassThruCAN 插件
Pass-Thru CAN 插件通过 SAE J2534 Pass-Thru API 访问 CAN 适配器。 SAE J2534 是一项从 x86 Windows 个人电脑访问车辆总线的标准。尽管该 API 仅针对 32 位 Windows 进行了规范,但部分供应商也提供了适用于 64 位 Windows 以及 Linux 等其他操作系统的实现方案。
PassThruCAN 的使用
要使用 PassThruCAN,必须安装 CAN 适配器的相应厂商驱动程序。厂商还必须通过共享库提供 J2534 API 的实现。目前仅支持 Pass-Thru API 的 04.04 版本。
当使用 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 state)信号:
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总线的比特率,以无符号整数表示,单位为bit/s。默认比特率为500000(500 kbit/s)。在设备已连接后设置比特率可能会触发CAN接口的隐式重新初始化。 |
Pass-Thru CAN 插件支持扩展帧格式(29 位 ID),但不支持灵活数据速率(CAN FD)。
© 2026 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.