基于Python的CAN报文分析(1)CAN报文DLC分析
前言:CAN报文分析忒费时间,下班晚老婆埋怨,因此写几个小脚本帮助快速分析CAN报文,下面是基于Python的CAN报文分析——CAN报文DLC分析
基于Python的CAN报文DLC分析
1. 读取CANoe导出的blf格式的文件,并循环读取每条报文
blf_file = 'canoe_log.blf'
trace = can.BLFReader(blf_file)
# 循环读取每个消息
for msg in trace:
# 打印报文dlc
print(msg.dlc)
运行结果如图1所示:
2. 创建字典用于保存不同ID的数据长度
id_lengths = {}
# 循环读取每个消息
for msg in trace:
# 获取当前消息的ID和dlc
msg_id = msg.arbitration_id
dlc = msg.dlc
# 更新字典中对应ID的dlc
if msg_id in id_lengths:
id_lengths[msg_id].append(dlc)
else:
id_lengths[msg_id] = [dlc]
# 打印每个ID的dlc
for msg_id, lengths in id_lengths.items():
print(f"ID: {msg_id}, dlc: {lengths}")
运行结果如图2所示:
(完整)3. 使用集合对结果去重,并将打印ID设置为十六进制
import can
blf_file = 'canoe_log.blf'
trace = can.BLFReader(blf_file)
id_lengths = {}
# 循环读取每个消息
for msg in trace:
# 获取当前消息的ID和dlc
msg_id = msg.arbitration_id
dlc = msg.dlc
# 更新字典中对应ID的dlc
if msg_id in id_lengths:
id_lengths[msg_id].add(dlc) # 使用set进行去重
else:
id_lengths[msg_id] = {dlc} # 初始化为包含一个dlc的set
# 打印每个ID的dlc
for msg_id, lengths in id_lengths.items():
unique_lengths = list(lengths) # 将set转换为列表打印
print(f"ID: {hex(msg_id)}, dlc: {unique_lengths}")
运行结果如图3所示:
后言:其实我没老婆,一切都是幻想罢辽。