SSM框架实战:超市商品信息管理系统毕业设计全流程指南
2026/10/13 12:38:36
python-can是目前 Python 生态中最成熟、通用的CAN 总线通信库,支持多种硬件接口(PCAN、Vector、Kvaser、SocketCAN、slcan、USB2CAN 等),同时也支持虚拟 CAN(vcan)和 PCAN 等。
下面整理一份实用的python-can 使用记录(基于 2025–2026 年最新版本 4.6.x 系列),包含安装、基本用法、常见场景、注意事项等。
# 基本安装(推荐)pipinstallpython-can# 如果需要 serial 接口(如 slcan、arduino-can)pipinstallpython-can[serial]# 某些特定接口可能还需要额外驱动(如 PCAN 需要安装 Peak 驱动)当前最新稳定版(2025年8月后):4.6.1
官方文档:https://python-can.readthedocs.io/en/stable/
最经典的用法(以 SocketCAN 为例,Linux 常用):
importcanimporttime# 方式一:使用 with 语句(推荐,自动关闭)withcan.Bus(interface='socketcan',channel='vcan0',receive_own_messages=True)asbus:# 发送一条标准 CAN 消息 (ID=0x123, 数据 8 字节)msg=can.Message(arbitration_id=0x123,is_extended_id=False,# False=标准帧, True=扩展帧data=[0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88],is_fd=False,# 是否 CAN-FD(默认 False)bitrate_switch=False# FD 模式下是否切换速率)try:bus.send(msg,timeout=0.2)print("Message sent on",bus.channel_info)exceptcan.CanError:print("Message NOT sent")# 接收消息(阻塞式)print("Waiting for messages...")formsginbus:print(f"Received:{msg}")# msg.arbitration_id, msg.data, msg.timestamp, msg.dlc 等ifmsg.arbitration_id==0x321:print("Target message found!")break带超时接收单条消息(更常用):
msg=bus.recv(timeout=3.0)# 等待最多 3 秒ifmsgisnotNone:print(f"Got: ID=0x{msg.arbitration_id:x}Data={msg.data.hex()}")else:print("Timeout - no message received")| 接口名称 | interface= 值 | 平台 | 备注 |
|---|---|---|---|
| SocketCAN | ‘socketcan’ | Linux | 最常用,虚拟 vcan0 / 真实 can0/can1 |
| PCAN | ‘pcan’ | Windows/Linux | 需要 Peak 驱动 |
| Vector | ‘vector’ | Windows | 需要 Vector XL Driver |
| Kvaser | ‘kvaser’ | Windows/Linux | 需要 Kvaser 驱动 |
| slcan | ‘slcan’ | 跨平台 | USB转CAN(如 Lawicel、Arduino CAN) |
| virtual | ‘virtual’ | 跨平台 | 纯内存虚拟总线,用于测试 |
| cantact | ‘cantact’ | 跨平台 | CANtact 设备 |
创建 bus 几种等价写法:
# 最常用(自动从配置读取)bus=can.Bus()# 需要提前配置 ~/.can 或环境变量# 显式指定(推荐生产环境)bus=can.Bus(interface='socketcan',channel='can0',bitrate=500000)# CAN-FD 示例bus=can.Bus(interface='pcan',channel='PCAN_USBD',fd=True,f_clock=80000000,dbitrate=2000000,bitrate=500000)# 只接收特定 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)defsend_periodic():bus=can.Bus('socketcan',channel='vcan0')msg=can.Message(arbitration_id=0x100,data=[0x01,0x02],is_extended_id=False)# 每 200ms 发送一次,持续运行task=bus.send_periodic(msg,period=0.2)try:time.sleep(10)# 运行 10 秒finally:task.stop()# 或者使用线程方式fromcan.threadimportThreadSafeBusimportcanfromcantoolsimportdb db=db.load_file('your_database.dbc')withcan.Bus()asbus:formsginbus:decoded=db.decode_message(msg.arbitration_id,msg.data)print(decoded)(需要额外安装:pip install cantools)
打印所有收到的消息(带时间戳)
formsginbus:print(f"{msg.timestamp:>16.3f}{msg.arbitration_id:03X}{'X'ifmsg.is_extended_idelse' '}{msg.data.hex(' ')}")发送 CAN-FD 消息
msg=can.Message(arbitration_id=0x123,data=[iforiinrange(64)],# CAN-FD 支持最长 64 字节is_fd=True,bitrate_switch=True)bus.send(msg)sudo ip link set can0 up type can bitrate 500000sudo modprobe vcan; sudo ip link add dev vcan0 type vcan; sudo ip link set vcan0 uptry ... except can.CanErrorcan.Notifier+ 回调函数异步处理需要我针对某个具体硬件(PCAN、USBCAN、Vector、CANalyzer 配合等)给出详细示例,或者帮你写某个特定功能的完整脚本吗?直接告诉我需求~