【Python】python-can使用记录

📅 发布时间:2026/7/12 0:20:33 👁️ 浏览次数:
【Python】python-can使用记录
python-can是目前 Python 生态中最成熟、通用的CAN 总线通信库支持多种硬件接口PCAN、Vector、Kvaser、SocketCAN、slcan、USB2CAN 等同时也支持虚拟 CANvcan和 PCAN 等。下面整理一份实用的python-can 使用记录基于 2025–2026 年最新版本 4.6.x 系列包含安装、基本用法、常见场景、注意事项等。1. 安装# 基本安装推荐pipinstallpython-can# 如果需要 serial 接口如 slcan、arduino-canpipinstallpython-can[serial]# 某些特定接口可能还需要额外驱动如 PCAN 需要安装 Peak 驱动当前最新稳定版2025年8月后4.6.1官方文档https://python-can.readthedocs.io/en/stable/2. 快速入门 - 创建 Bus 并收发消息最经典的用法以 SocketCAN 为例Linux 常用importcanimporttime# 方式一使用 with 语句推荐自动关闭withcan.Bus(interfacesocketcan,channelvcan0,receive_own_messagesTrue)asbus:# 发送一条标准 CAN 消息 (ID0x123, 数据 8 字节)msgcan.Message(arbitration_id0x123,is_extended_idFalse,# False标准帧, True扩展帧data[0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88],is_fdFalse,# 是否 CAN-FD默认 Falsebitrate_switchFalse# FD 模式下是否切换速率)try:bus.send(msg,timeout0.2)print(Message sent on,bus.channel_info)exceptcan.CanError:print(Message NOT sent)# 接收消息阻塞式print(Waiting for messages...)formsginbus:print(fReceived:{msg})# msg.arbitration_id, msg.data, msg.timestamp, msg.dlc 等ifmsg.arbitration_id0x321:print(Target message found!)break带超时接收单条消息更常用msgbus.recv(timeout3.0)# 等待最多 3 秒ifmsgisnotNone:print(fGot: ID0x{msg.arbitration_id:x}Data{msg.data.hex()})else:print(Timeout - no message received)3. 常用接口类型interface 参数接口名称interface 值平台备注SocketCAN‘socketcan’Linux最常用虚拟 vcan0 / 真实 can0/can1PCAN‘pcan’Windows/Linux需要 Peak 驱动Vector‘vector’Windows需要 Vector XL DriverKvaser‘kvaser’Windows/Linux需要 Kvaser 驱动slcan‘slcan’跨平台USB转CAN如 Lawicel、Arduino CANvirtual‘virtual’跨平台纯内存虚拟总线用于测试cantact‘cantact’跨平台CANtact 设备创建 bus 几种等价写法# 最常用自动从配置读取buscan.Bus()# 需要提前配置 ~/.can 或环境变量# 显式指定推荐生产环境buscan.Bus(interfacesocketcan,channelcan0,bitrate500000)# CAN-FD 示例buscan.Bus(interfacepcan,channelPCAN_USBD,fdTrue,f_clock80000000,dbitrate2000000,bitrate500000)4. 过滤器设置提高接收效率# 只接收特定 ID 的消息filters[{can_id:0x7E0,can_mask:0x7FF,extended:False},# 精确匹配 0x7E0{can_id:0x18F,can_mask:0x1FF0000,extended:True}# 匹配 J1939 PGN]bus.set_filters(filters)5. 周期发送最常见需求defsend_periodic():buscan.Bus(socketcan,channelvcan0)msgcan.Message(arbitration_id0x100,data[0x01,0x02],is_extended_idFalse)# 每 200ms 发送一次持续运行taskbus.send_periodic(msg,period0.2)try:time.sleep(10)# 运行 10 秒finally:task.stop()# 或者使用线程方式fromcan.threadimportThreadSafeBus6. 配合 DBC 文件解析强烈推荐importcanfromcantoolsimportdb dbdb.load_file(your_database.dbc)withcan.Bus()asbus:formsginbus:decodeddb.decode_message(msg.arbitration_id,msg.data)print(decoded)需要额外安装pip install cantools7. 常用实用代码片段打印所有收到的消息带时间戳formsginbus:print(f{msg.timestamp:16.3f}{msg.arbitration_id:03X}{Xifmsg.is_extended_idelse }{msg.data.hex( )})发送 CAN-FD 消息msgcan.Message(arbitration_id0x123,data[iforiinrange(64)],# CAN-FD 支持最长 64 字节is_fdTrue,bitrate_switchTrue)bus.send(msg)8. 注意事项 常见问题bitrate参数只在初始化时有效后续不可改除非重开 busreceive_own_messagesTrue时自己发的消息也会被收到Linux SocketCAN 默认行为Windows 下 PCAN/Vector 需要安装官方驱动Linux 下 SocketCAN 需要先配置 can 接口sudo ip link set can0 up type can bitrate 500000虚拟测试sudo modprobe vcan; sudo ip link add dev vcan0 type vcan; sudo ip link set vcan0 up异常处理几乎所有操作都要try ... except can.CanError性能大量消息时推荐使用can.Notifier 回调函数异步处理9. 推荐学习路径先跑通虚拟 CANvcan0环境掌握发送单条 / 周期发送 / 接收循环学会设置过滤器结合cantools DBC做信号解析最后对接真实硬件PCAN / Vector / SocketCAN需要我针对某个具体硬件PCAN、USBCAN、Vector、CANalyzer 配合等给出详细示例或者帮你写某个特定功能的完整脚本吗直接告诉我需求