当前位置: 首页 > news >正文

Python脚本实现通过Vector VN1630A CAN盒子与ECU通信

1 安装 python-can 包

安装命令如下:

pip install python-can

安装完成后可用下面命令查看是否安装成功及版本。

pip show python-can
Name: python-can
Version: 4.4.2
Summary: Controller Area Network interface module for Python
Home-page: https://github.com/hardbyte/python-can
Author: python-can contributors
Author-email:
License: LGPL v3
Location: D:\python3\Lib\site-packages
Requires: packaging, pywin32, typing-extensions, wrapt
Required-by:

2 创建 Vector Hardware Application

Vector VN1630A 硬件如下图:
在这里插入图片描述




打开控制面板,找到Vector Hardware选项,点击进入配置界面。
在这里插入图片描述
当硬件设备VN 1630A未插入电脑时,
在这里插入图片描述
插入硬件设备插入时,
在这里插入图片描述

创建一个新的 Application.
在这里插入图片描述
在这里插入图片描述
输入Application Name,然后点击OK即可。例如 创建了一个名为 FctTool 的Application,包含两个CAN通道。

3 分配硬件设备通道给 Application

将 VN1630A 的 channel 1分配给 FctTool 的 CAN 1(下图因为已经分配过了,所以只显示 CAN 2),将 VN1630A 的 channel 2分配给 FctTool 的 CAN 2。
在这里插入图片描述
最终如下:
在这里插入图片描述

4 编程实现

完整代码如下:

import can
from can.interfaces.vector import VectorBusdef prase_can_msg(msg):message_str = str(msg)parts = message_str.split()# print("parts:", parts)try:err_frame = parts.index('E')# print("Error frame found at index:", err_frame)return None, None, Noneexcept Exception as e:# print("Error frame not found:", e)pass# 提取Timestamptimestamp = float(parts[1])# 提取IDmsg_id = int(parts[3].strip(), 16)# 提取DLC(数据长度)dlc_index = parts.index('DL:') + 1dlc = int(parts[dlc_index].strip())# 提取数据字段data_index = parts.index('DL:') + 2data1 = parts[data_index:data_index+dlc]data = [int(x, 16) for x in data1]# 提取Channelchannel_index = parts.index('Channel:') + 1channel = int(parts[channel_index].strip())hex_data = ' '.join('0x%02x' % i for i in data)print("Timestamp          channel   msg_id   dlc                   data")print(f"{timestamp:10.6f} {channel:5d} {msg_id:9X} {dlc:6d}     {hex_data}")return msg_id, dlc, datadef detect_device_exist():# 检测Vector 1603A设备是否存在device_exist = Falsetry:configs = can.detect_available_configs(interfaces=['vector'])for config in configs:if config['vector_channel_config'].name == 'VN1630A Channel 1':device_exist = Truebreakexcept Exception as e:print("Detect available configs Error:", e)app_exits = Falsetry:app_cfg = VectorBus.get_application_config(app_name='FctTool', app_channel=0)if app_cfg is not None:app_exits = Trueprint("app_cfg:", app_cfg)except can.interfaces.vector.exceptions.VectorInitializationError as e:print("Get application config Error:", e)if device_exist and app_exits:return True# 如果没有找到Vector 1603A设备,则返回Falsereturn Falsedef vector_init():if not detect_device_exist():print("Vector 1603A device not found.")return None# 创建CAN总线对象,指定Vector 1603A接口try:# app_name 要和控制面板 Vector Hardware里面配置的名字一致,这里的 channel 要配置为0, 对应实际的 CAN 1 通道bus = can.Bus(interface='vector', channel=0, bitrate=500000, app_name="FctTool")print("bus type:", type(bus))except Exception as e:print("Create CAN bus object Error:", e)try:return busexcept UnboundLocalError as e:print("Return CAN bus object Error:", e)print("Error: CAN bus channel is used by other application.")return Noneelse:print("Other error.")def vector_send_msg(bus, msg_id, message, dlc):# 发送CAN消息msg = can.Message(arbitration_id=msg_id, dlc=dlc, data=message, is_extended_id=False)bus.send(msg)def vector_recv_msg(bus):# 接收CAN消息msg = bus.recv(timeout=0.1)if msg is not None:# 解析CAN消息msg_id, dlc, data = prase_can_msg(msg)if msg_id is None:# print("Error frame received.")return False, None, None, Nonereturn True, msg_id, dlc, dataelse:return False, None, None, Nonedef vector_close(bus):# 关闭CAN总线bus.shutdown()if __name__ == '__main__':bus = vector_init()if bus is None:print("CAN bus initialized failed.")exit(1)print("CAN bus initialized successfully.")msg_id = 0x7F1dlc = 8message = [0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]vector_send_msg(bus, msg_id, message, dlc)have_msg, msg_id, dlc, data = vector_recv_msg(bus)if have_msg:print("Received message:")print(f"ID: 0x{msg_id:04X}")print(f"DL: {dlc}")print("Data: {data}".format(data=' '.join('0x%02x' % i for i in data)))vector_close(bus)

创建bus总线对象时需要注意下面这个点,
在这里插入图片描述

5 效果演示

Vector VN1630A插入电脑,另一端连接ECU,然后运行python脚本。

app_cfg: (<XL_HardwareType.XL_HWTYPE_VN1630: 57>, 0, 0)
bus type: <class 'can.interfaces.vector.canlib.VectorBus'>
CAN bus initialized successfully.
Timestamp          channel   msg_id   dlc                   data
1735904698.304546     0       7F2      8     0x1f 0x01 0x02 0x00 0x00 0x00 0x00 0x00
Received message:
ID: 0x07F2
DL: 8
Data: 0x1f 0x01 0x02 0x00 0x00 0x00 0x00 0x00

参考资料:https://python-can.readthedocs.io/en/stable/interfaces/vector.html

http://www.lryc.cn/news/515548.html

相关文章:

  • Spring实现Logback日志模板设置动态参数
  • 内部类 --- (寄生的哲学)
  • Python深度学习GRU、LSTM 、BiLSTM-CNN神经网络空气质量指数AQI时间序列预测及机器学习分析|数据分享...
  • JSP基础
  • 基于Springboot +Vue 在线考试管理系统
  • Node.js 函数
  • JVM学习指南(9)-JVM运行时数据区
  • 2025/1/4期末复习 密码学 按老师指点大纲复习
  • 关于嵌入式系统的知识课堂(二)
  • 基于ETAS工具的AutoConnect实现方案
  • BGP基础配置实验
  • 基于单片机的人体健康指标采集系统设计
  • Go语言性能优化-字符串格式化优化
  • UE5失真材质
  • SAP 01-初识AMDP(ABAP-Managed Database Procedure)
  • 关于视频审核,内容风控在“控”什么?
  • 5G NTN(七) 高层(1)
  • 专家混合(MoE)大语言模型:免费的嵌入模型新宠
  • 《柴油遗产-无耻时代》V98375官方版
  • 科技云报到:洞见2025年科技潮流,技术大融合开启“智算时代”
  • 【openwrt】OpenWrt 路由器的 802.1X 动态 VLAN
  • [coredump] 生成管理
  • CSS——5. 外部样式
  • 检查字符是否相同
  • casaos安装最新版homeassistant-arm
  • openwrt host方式编译ffmpeg尝试及问题分析
  • 【three.js】搭建环境
  • SQLite AND/OR 运算符
  • 《普通逻辑》学习记录——命题的判定与自然推理
  • 道可云人工智能元宇宙每日资讯|崂山区政务服务虚拟大厅启用