Skip to content

Instantly share code, notes, and snippets.

@I0x0I
Created April 9, 2022 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save I0x0I/5db43dc7d96706d71af1b2ff2516c52f to your computer and use it in GitHub Desktop.
Save I0x0I/5db43dc7d96706d71af1b2ff2516c52f to your computer and use it in GitHub Desktop.
Convert pcapng with CAN messages to CAN log
import struct
import argparse
import pcapng.blocks
from pcapng import FileScanner
def unpackCANFrame(frame,reverse=False):
#https://github.com/hardbyte/python-can/blob/ae0bc1746c04b3c1ccd8b56aba99895d50c87d2d/can/interfaces/socketcan/socketcan.py#L511
CAN_FRAME_HEADER_STRUCT = struct.Struct(">IBB2x") if reverse == False else struct.Struct("=IBB2x")
can_id, can_dlc, flags = CAN_FRAME_HEADER_STRUCT.unpack_from(frame)
data = frame[8 : 8 + can_dlc]
arbitration_id = '%08x'%(can_id & 0x1FFFFFFF) if bool(can_id & 0x80000000) else '%03x'%(can_id & 0x000007FF)
return arbitration_id, data.hex()
parser = argparse.ArgumentParser(description='Convert pcapng with CAN messages to CAN log')
parser.add_argument('FILE', metavar='FILE', type=str, help='File path')
FILE = parser.parse_args().FILE
with open(FILE,'rb') as f:
scanner = FileScanner(f)
blocks = [block for block in scanner if type(block)==pcapng.blocks.EnhancedPacket]
with open(FILE[:-7]+'.log','w') as f:
for block in blocks:
arbitration_id, data = unpackCANFrame(block.packet_data)
line = '(%.6f) %s %s#%s\n'%(block.timestamp,block.interface.options['if_name'],arbitration_id,data)
print(line)
f.write(line)
f.flush()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment