Last active
June 27, 2019 04:56
-
-
Save ebroecker/f9a9d9ca3063469905605d0348d25e3f to your computer and use it in GitHub Desktop.
dbc to scapy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import canmatrix.formats | |
import sys | |
import os | |
if len(sys.argv) < 2: | |
exit() | |
file_name = sys.argv[1] | |
cm = canmatrix.formats.loadp_flat(file_name) | |
scapy_decoder = """ | |
from scapy.packet import Packet | |
from scapy.packet import bind_layers | |
from scapy.fields import * | |
from scapy.layers.can import * | |
class DBC(CAN): | |
name = 'DBC' | |
fields_desc = [ | |
FlagsField('flags', 0, 3, ['error', | |
'remote_transmission_request', | |
'extended']), | |
XBitField('arbitration_id', 0, 29), | |
ByteField('length', None), | |
ThreeBytesField('reserved', 0), | |
] | |
""" | |
def get_fmt(signal): | |
if signal.is_little_endian: | |
if signal.is_float: | |
fmt = "<f" | |
elif signal.is_signed: | |
fmt = "<b" | |
else: | |
fmt = "<B" | |
else: | |
if signal.is_float: | |
fmt = ">f" | |
elif signal.is_signed: | |
fmt = ">b" | |
else: | |
fmt = ">B" | |
return fmt | |
for frame in cm.frames: | |
scapy_decoder += "class " + frame.name + "(Packet):\n" | |
scapy_decoder += " fields_desc = [ \n" | |
signal_collection = [] | |
for signal_group in frame.signalGroups: | |
for signal in signal_group.signals: | |
signal_collection.append(signal) | |
for signal in frame.signals: | |
signal_collection.append(signal) | |
for signal in signal_collection: | |
scapy_decoder += ' SignalField("{}", default=0, start={}, size={}, scaling={}, offset={}, unit="{}", fmt="{}"),\n'.format( | |
signal.name, signal.get_startbit(bit_numbering=1), signal.size, signal.factor, signal.offset, signal.unit, get_fmt(signal)) | |
scapy_decoder += " ]\n\n" | |
for frame in cm.frames: | |
if frame.arbitration_id.extended: | |
scapy_decoder += "bind_layers(DBC, " + frame.name + ", arbitration_id = " + hex(frame.arbitration_id.id) + ", flags = extended)\n" | |
else: | |
scapy_decoder += "bind_layers(DBC, " + frame.name + ", arbitration_id = " + hex(frame.arbitration_id.id) + ")\n" | |
out_file_name,_ = os.path.splitext(file_name) | |
out_file_name += ".py" | |
with open(out_file_name, "w") as fd: | |
fd.write(scapy_decoder) | |
fd.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment