本页内容

使用 VirtualCAN 插件

VirtualCAN 插件允许在无需 CAN 硬件的情况下,通过本地 TCP/IP 连接对 CAN 应用程序进行测试。 当第一个客户端调用 createDevice() 时,会创建一个 TCP 服务器。默认的 TCP 端口为 35468,可以通过向 createDevice() 提供完全限定的 URL 来更改该端口。一旦服务器运行,同一系统上就不会再启动其他服务器。

此后,所有客户端都会将 CAN 帧发送至服务器,由服务器将其分发给其他客户端。

创建 CAN 总线设备

首先需要检查QCanBus 是否提供了所需的插件:

if (QCanBus::instance()->plugins().contains(QStringLiteral("virtualcan"))) {
    // plugin available
}

其中virtualcan是插件名称。

接下来,可以建立与特定接口的连接:

QCanBusDevice *device = QCanBus::instance()->createDevice(
    QStringLiteral("virtualcan"), QStringLiteral("can0"));
device->connectDevice();

其中can0是活动的 CAN 通道名称。VirtualCAN 插件提供从“can0”到“can9”的十个通道。所有通道均可作为 CAN 2.0 或 CAN FD 通道使用。连接到这些通道之一的应用程序都会接收发送到该通道的所有消息。

要连接到远程服务器,请使用以下完全限定 URL 作为接口名称:

tcp://server:port/canX

例如:

tcp://192.168.1.2:35468/can0

现在,该设备已开放 CAN 帧的读写功能:

QCanBusFrame frame;
frame.setFrameId(8);
QByteArray payload("A36E");
frame.setPayload(payload);
device->writeFrame(frame);

读取操作可通过 `readFrame()` 方法实现。当至少有一个新帧可供读取时,将触发 `framesReceived()` 信号:

QCanBusFrame frame = device->readFrame();

VirtualCAN 支持以下配置,可通过setConfigurationParameter() 进行控制:

配置参数键描述
QCanBusDevice::CanFdKey确定虚拟 CAN 总线是否以 CAN FD 模式运行。此选项默认处于禁用状态。
QCanBusDevice::ReceiveOwnKey默认情况下,禁止在发送 CAN 帧的同一设备上接收 CAN 帧。启用此选项后,发送到 CAN 总线的所有 CAN 帧会立即出现在接收缓冲区中。这可用于检查发送是否成功。如果启用此选项,所接收的帧将通过QCanBusFrame::hasLocalEcho() 进行标记

© 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.