- Qt 6.9
- Qt Serial Bus
- Qt CAN Bus
- Using VirtualCAN Plugin
- Qt 6.9.2 Reference Documentation

Using VectorCAN Plugin ◦ Qt Modbus

# Using VirtualCAN Plugin

The VirtualCAN plugin allows testing of CAN applications with a local TCP/IP connection without CAN hardware. The TCP server is created, when the first client calls createDevice(). The default TCP port is 35468, which can be changed by giving the fully qualified URL to createDevice(). Once the server is running, no further server is started on the same system.

Afterwards, all clients send their CAN frames to the server, which distributes them to the other clients.

## Creating CAN Bus Devices

At first it is necessary to check that QCanBus provides the desired plugin:

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

Where virtualcan is the plugin name.

Next, a connection to a specific interface can be established:

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

Where can0 is the active CAN channel name. The VirtualCAN plugin provides two channels "can0" and "can1". Both can be used as CAN 2.0 or CAN FD channels. All applications connected to one of these channels receive all messages that are sent to this channel.

To connect to a remote server, use the following fully qualified URL as interface name:

     tcp://server:port/canX

for example:

     tcp://192.168.1.2:35468/can0

The device is now open for writing and reading CAN frames:

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

The reading can be done using the readFrame() method. The framesReceived() signal is emitted when at least one new frame is available for reading:

     QCanBusFrame frame = device->readFrame();

VirtualCAN supports the following configurations that can be controlled through setConfigurationParameter():

Configuration parameter key | Description
--- | ---
QCanBusDevice::CanFdKey | Determines whether the virtual CAN bus operates in CAN FD mode or not. This option is disabled by default.
QCanBusDevice::ReceiveOwnKey | The reception of the CAN frames on the same device that was sending the CAN frame is disabled by default. When enabling this option, all CAN frames sent to the CAN bus immediately appear in the receive buffer. This can be used to check if sending was successful. If this option is enabled, the therefore received frames are marked with QCanBusFrame::hasLocalEcho()