使用 SocketCAN 插件

The SocketCAN plugin encapsulates the Linux sockets API for accessing the CAN devices. This API is a set of open source CAN drivers and a networking stack contributed by Volkswagen Research to the Linux kernel.

This plugin requires a Linux Kernel with SocketCAN support and SocketCAN device drivers for the used CAN hardware.

SocketCAN 用法

To list all (including unconfigured) network interfaces, the command ifconfig -a 可以使用。

To use SocketCAN, the corresponding Linux Kernel modules must be loaded and the network interface must be configured.

设置真正的 CAN 硬件

This section assumes, that the device driver is already loaded (most likely automatically when connecting the CAN hardware).

默认设置

To set the device can0 to a bitrate of 250 kBit/s:

sudo ip link set up can0 type can bitrate 250000
					

To automatically recover from "bus off" errors after 100 milliseconds, the following command can be used:

sudo ip link set up can0 type can bitrate 250000 restart-ms 100
					

CAN FD 设置

To set the device can0 to an arbitration bitrate of 500 kBit/s and a data bitrate of 4 MBit/s (for frames with bitrate switch flag):

sudo ip link set can0 up type can bitrate 500000 dbitrate 4000000 fd on
					

设置虚拟 CAN 总线

注意: For CAN FD usage, the MTU (Maximum Transmission Unit) has to be set to 72 byte.

sudo modprobe vcan
sudo ip link add dev vcan0 type vcan
sudo ip link set up vcan0 mtu 72
					

The command line test programs used in the following are from the can-utils 包:

# Display received CAN messages with absolute timestamps and flags
candump -ta -x vcan0
# Send a CAN FD message with flags BRS and EFI set
cansend vcan0 123##3112233445566778899aabbccddeeff
# Generate random CAN messages
cangen vcan0
					

创建 CAN 总线设备

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

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

Where socketcan 是插件名称。

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

QString errorString;
QCanBusDevice *device = QCanBus::instance()->createDevice(
    QStringLiteral("socketcan"), QStringLiteral("can0"), &errorString);
if (!device) {
    // Error handling goes here
    qDebug << errorString;
} else {
    device->connectDevice();
}
					

Where can0 is the active CAN interface name. CAN interfaces act like regular network interfaces on Linux systems and can be discovered using ifconfig . Also, the availableDevices() method returns a list of currently available devices.

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() 方法。 framesReceived() signal is emitted when at least one new frame is available for reading:

QCanBusFrame frame = device->readFrame();
					

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

配置参数键 描述
QCanBusDevice::LoopbackKey To meet the multiple-user needs, the local loopback is enabled by default. This means, whenever a CAN frame is transmitted on the CAN bus, a local echo of this frame is sent to all applications connected to this CAN device. If this option is enabled, the therefore received frames are marked with QCanBusFrame::hasLocalEcho ()
QCanBusDevice::ReceiveOwnKey The reception of the CAN frames on the same socket 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 ()
QCanBusDevice::ErrorFilterKey A CAN interface driver can generate so called Error Message Frames that can optionally be passed to the user application in the same way as other CAN frames. The possible errors are divided into different error classes that may be filtered using the appropriate error mask. The values for the error mask are defined in linux/can/error.h .
QCanBusDevice::RawFilterKey This configuration can contain multiple filters of type QCanBusDevice::Filter . By default, the connection is configured to accept any CAN bus message.
QCanBusDevice::BitRateKey Determines the bit rate of the CAN bus connection. The following bit rates are supported: 5000, 10000, 20000, 33000, 47000, 50000, 83000, 95000, 100000, 125000, 250000, 500000, 800000, 1000000. Note that this configuration parameter can only be adjusted while the QCanBusDevice is not connected. To set this configuration parameter, the library libsocketcan is needed at runtime http://www.pengutronix.de/software/libsocketcan Usually, root rights are needed to set the CAN bus bitrate.
QCanBusDevice::CanFdKey This configuration option determines whether CANFD frames may be sent or received. By default, this option is disabled. It controls the CAN_RAW_FD_FRAMES option of the CAN socket.
QCanBusDevice::DataBitRateKey This configuration is not supported by the socketcan plugin. However it is possible to set the data rate when configuring the CAN network interface using the ip link 命令。
QCanBusDevice::ProtocolKey Allows to use another protocol inside the protocol family PF_CAN. The default value for this configuration option is CAN_RAW (1).

例如:

QList<QCanBusDevice::Filter> list;
QCanBusDevice::Filter f;
// only accept odd numbered frame id of type remote request
// frame can utilize extended or base format
f.frameId = 0x1;
f.frameIdMask = 0x1;
f.format = QCanBusDevice::Filter::MatchBaseAndExtendedFormat;
f.type = QCanBusFrame::RemoteRequestFrame;
list.append(f);
device->setConfigurationParameter(QCanBusDevice::RawFilterKey, QVariant::fromValue(list));
device->setConfigurationParameter(QCanBusDevice::ErrorFilterKey,
                                  QVariant::fromValue(QCanBusFrame::FrameErrors(QCanBusFrame::AnyError)));
					

Extended frame format and flexible data-rate are supported in SocketCAN.

SocketCAN supports the following additional functions: