使用 VirtualCAN 插件

VirtualCAN 插件允许使用本地 TCP/IP 连接测试 CAN 应用程序,而无需 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 "和 "can1"。这两个通道均可用作 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() 标记。

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