如何在Linux上创建虚拟CAN端口?(C++)

22

我想创建一个程序,用于模拟CAN端口以进行另一个大型应用程序的测试。该程序应通过虚拟CAN发送先前记录的数据。有人有这样的经验吗?

我正在考虑建立虚拟COM,并通过它发送CAN帧中打包的数据。这可行吗?如何在Linux上建立虚拟串口?找到了这个讨论线程Virtual Serial Port for Linux,但不幸的是,我不知道如何将其实现到程序源代码中(作为一个Linux初学者和程序员)。

期待阅读您的经验和建议。


1
AF_CANдёҺAF_UNIXйқһеёёзӣёдјј....жӮЁеҸҜд»ҘдҪҝз”ЁеҘ—жҺҘеӯ—... - Basile Starynkevitch
2个回答

50

您需要SocketCAN驱动程序,该驱动程序在现代Linux发行版(如Ubuntu等)中可用。 SocketCAN提供了虚拟CAN端口驱动程序:

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

现在,您可以通过vcan0设备发送和接收CAN帧。维基百科文章提供了一个简单的代码示例来说明如何使用SocketCAN。
为了测试,您还需要can-utils
您可以在eLinux.org上找到有关SocketCAN及其使用方法的更多信息。

2

教程

第一部分 - 创建一个仿真CAN的程序


  • Install the required dependencies:

    sudo apt install net-tools iproute2 can-utils linux-modules-extra-$(uname -r)
    
  • You can use the following bash program to create a virtual CAN port (vcan) in Linux:

    setup_vcan.sh

    #!/bin/bash
    
    # Using can1 as an example
    CAN_PORT="can1"
    
    sudo modprobe vcan
    sudo ip link add dev $CAN_PORT type vcan
    sudo ip link set up $CAN_PORT
    
  • Make the bash program executable:

    chmod +x setup_vcan.sh
    
  • Run the bash program:

    ./setup_vcan.sh
    

第二部分 - CAN消息的记录和播放


  • Record the CAN messages into a log file (Replace $CAN_PORT with the name of your CAN port):

    candump -L $CAN_PORT > myfile.log
    
  • Playback the CAN messages from the log file:

    canplayer -I myfile.log
    
  • You can verify the playback by checking the output of candump:

    candump $CAN_PORT
    

参考文献


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接