之前都是使用CANape解析充电桩报文,同时canape的function功能进行数据分析还挺好用的,可以统计充电桩功率和车载功率,还能积分算出充电桩输出电量和车的输入电量。于是琢磨着自己用Python去解析充电桩的报文。在次记录一下解析的弯弯绕绕,防止踩坑。
1、安装python环境及依赖库
安装python就不必多说了推荐使用anaconda,重点是需要哪些库,这里需要使用pip安装:
pip install python-can
pip install j1939
pip install cantools
1、读取DBC文件
dbc文件使用canoe自带的27930文件,可以通过以上链接下载。通过cantools读取dbc文件
import cantools
import can
dbc = cantools.database.load_file(R'D:\GBT_27930_2015.dbc',encoding="gbk")
3、将原始CAN报文转换为J1939报文。
如果直接使用原始报文的话,有些J1939的多帧报文是无法解析出来的。因此需要使用J1939库,把多帧报文转换为单帧,从而可以使用cantools工具将其解析出信号。
import cantools
import can
import sys
import j1939
import logging
logging.getLogger('j1939').setLevel(logging.DEBUG)
j1939msg = []
ecu = j1939.ElectronicControlUnit()
ecu.connect(bustype='virtual', bitrate=250000)
blf_file = r"D:\聊天数据\企业微信\WXWork\1688856102462474\Cache\File\2024-10\0914_2.blf"
logdata = list(can.BLFReader(blf_file))
decoded = {}
# sys.stdout = open('output.txt', 'w')
def on_message56(priority, pgn, sa,timestamp, data):
canid = (cantools.j1939.frame_id_pack(priority,0,0,int(pgn/256) ,0x56,sa))
j1939msg.append([timestamp,canid,data])
def on_messagef4(priority, pgn, sa,timestamp, data):
canid = (cantools.j1939.frame_id_pack(priority,0,0,int(pgn/256) ,0xF4,sa))
j1939msg.append([timestamp,canid,data])
ecu.subscribe(on_message56,0x56)
ecu.subscribe(on_messagef4,0xf4)
for msg in logdata:
dec = ecu.notify(msg.arbitration_id, msg.data,msg.timestamp)
# ecu.disconnect()
4、使用DBC解析J1939报文
decoded = {}
idlist = []
for msg in j1939msg:
# try:
if msg[1] in dbc._frame_id_to_message:
if msg[1] not in idlist:
idlist.append(msg[1])
dec = dbc.decode_message(msg[1], msg[2], allow_truncated=True, scaling=True)
if dec:
for key ,data in dec.items():
if key not in decoded:
decoded[key] = []
decoded[key].append([msg[0],data])
至此,就可以获取完整的充电数据,接下计划可能是用pyechart进行数据可视化