使用python cantools模块解析dbc。
python3 -m pip install cantools
>>> import cantools
>>> from pprint import pprint
>>> db = cantools.database.load_file('tests/files/dbc/motohawk.dbc')
>>> db.messages
[message('ExampleMessage', 0x1f0, False, 8, 'Example message used as template in MotoHawk models.')]
>>> example_message = db.get_message_by_name('ExampleMessage')
>>> pprint(example_message.signals)
[signal('Enable', 7, 1, 'big_endian', False, 1.0, 0, 0.0, 0.0, '-', False, None, {0: 'Disabled', 1: 'Enabled'}, None),
signal('AverageRadius', 6, 6, 'big_endian', False, 0.1, 0, 0.0, 5.0, 'm', False, None, None, ''),
signal('Temperature', 0, 12, 'big_endian', True, 0.01, 250, 229.53, 270.47, 'degK', False, None, None, None)]
>>> import can
>>> can_bus = can.interface.Bus('vcan0', bustype='socketcan')
# example_message 为上例中的example_message
>>> data = example_message.encode({'Temperature': 250.1, 'AverageRadius': 3.2, 'Enable': 1})
>>> message = can.Message(arbitration_id=example_message.frame_id, data=data)
>>> can_bus.send(message)
或者,可以在数据库对象上使用 encode_message() 方法对消息进行编码。
>>> message = can_bus.recv()
>>> db.decode_message(message.arbitration_id, message.data)
{'AverageRadius': 3.2, 'Enable': 'Enabled', 'Temperature': 250.09}
cantools.database.load_file(filename, database_format=None, encoding=None, frame_id_mask=None, prune_choices=False, strict=True, cache_dir=None, sort_signals=
该函数打开、读取和分析给定的数据库文件,并返回一个can.database或diagnostics.database对象及其内容。
cantools.database.dump_file(database, filename, database_format=None, encoding=None, sort_signals='default')
将给定的数据库转储到给定的文件名。示例如下:
>>> db = cantools.database.load_file('foo.dbc')
>>> cantools.database.dump_file(db, 'bar.dbc')
cantools.database.load_string(string, database_format=None, frame_id_mask=None, prune_choices=False, strict=True, sort_signals=
分析给定的数据库字符串并返回can.database或diagnostics.database对象及其内容。示例如下:
>>> with open('foo.dbc') as fin:
... db = cantools.database.load_string(fin.read())
>>> db.version
'1.0'
cantools.database.load(fp, database_format=None, frame_id_mask=None, prune_choices=False, strict=True, sort_signals=
读取并解析给定的类似数据库文件的对象,并返回一个can.database或diagnostics.database对象及其内容。示例如下:
>>> with open('foo.kcd') as fin:
... db = cantools.database.load(fin)
>>> db.version
None