Canmatrix
Canmatrix implements a "Python Can Matrix Object" which describes CAN communication and related objects such as Boardunits, Frames, Signals, and Values. It serves as a versatile tool for reading, writing, and manipulating various CAN database formats including .dbc, .dbf, .kcd, .arxml, .yaml, and .xls(x). The library also provides command-line utilities, `canconvert` for format conversion and `cancompare` for comparing CAN databases.
Warnings
- breaking Major internal refactoring and module reorganization in versions leading up to 1.0 (specifically around 0.8 and 0.9) introduced breaking changes. Direct imports of modules like `canmatrix.convert` or `canmatrix.formats.<format>` from earlier versions (pre-0.8) are likely to fail, as many components were moved to `canmatrix.cli` and `canmatrix.formats` submodules. Python 2 support was officially dropped with the 1.0 release.
- gotcha To work with specific CAN database formats (e.g., ARXML, KCD, XLSX, YAML), you often need to install `canmatrix` with additional optional dependencies. A basic `pip install canmatrix` will not include these, leading to `ModuleNotFoundError` when trying to load or save those formats.
- gotcha Older versions of `canmatrix` might have compatibility issues with Python 3.12 and newer due to an incompatible `future` dependency. An issue regarding this (`#742`) was resolved in May 2024.
Install
-
pip install canmatrix -
pip install 'canmatrix[arxml,kcd,fibex,odx]' # For XML-based formats -
pip install 'canmatrix[xls,xlsx]' # For Excel formats
Imports
- CanMatrix
from canmatrix import CanMatrix
- dbc_load
from canmatrix.formats import dbc
- dbc_dump
from canmatrix.formats import dbc
- cli_convert
from canmatrix.cli import convert
Quickstart
import os
from canmatrix.formats import dbc
# Create a dummy DBC file for demonstration
dummy_dbc_content = '''
BO_ 100 MSG_1: 8 Vector__XXX
SG_ Sig1 : 0|8@1+ (1,0) [0|255] "" Vector__XXX
SG_ Sig2 : 8|16@1+ (0.1,0) [0|6553.5] "" Vector__XXX
'''
dbc_file_path = 'dummy.dbc'
with open(dbc_file_path, 'w') as f:
f.write(dummy_dbc_content)
# Load the CAN matrix from the DBC file
db = dbc.load(dbc_file_path)
# Access frames and signals
for frame_name in db:
frame = db.frames[frame_name]
print(f"Frame: {frame.name} (ID: {frame.arbitration_id.id}, DLC: {frame.size} bytes)")
for signal_name in frame.signals:
signal = frame.signals[signal_name]
print(f" Signal: {signal.name} (StartBit: {signal.start_bit}, Length: {signal.size} bits)")
# Clean up the dummy file
os.remove(dbc_file_path)