CAN BUS tools

41.3.0 · active · verified Sun Apr 12

cantools is a Python 3 library for working with CAN (Controller Area Network) bus data. It provides extensive functionalities for parsing and interacting with various CAN database file formats, including DBC, KCD, SYM, ARXML (versions 3&4), and CDD. Key features include encoding and decoding CAN messages, handling simple and extended signal multiplexing, diagnostic DID encoding and decoding, and command-line tools for monitoring CAN bus traffic, generating C source code from databases, and visualizing signals. The library is actively maintained with regular updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a CAN database (either from a string or file), encode Python dictionary data into a CAN message payload, and then decode a CAN message payload back into human-readable signal values. For actual CAN bus communication, the `python-can` library is commonly used in conjunction with `cantools`.

import cantools
import os

# A minimal DBC file content for demonstration
dbc_content = """
VERSION """

NS_ :
BS_:

BU_: Vector__XXX

BO_ 256 EXAMPLE_MESSAGE: 8 Vector__XXX
 SG_ Signal1 : 0|8@1+ (1,0) [0|255] "Unit" Vector__XXX
 SG_ Signal2 : 8|8@1+ (0.1,0) [0|25.5] "V" Vector__XXX
"""

# Load the database from a string (or use cantools.database.load_file('path/to/your.dbc'))
try:
    db = cantools.database.load_string(dbc_content, database_format='dbc')
    print("Database loaded successfully.")

    # Get a message from the database
    example_message = db.get_message_by_name('EXAMPLE_MESSAGE')

    # Encode a message
    data = example_message.encode({'Signal1': 100, 'Signal2': 12.5})
    print(f"Encoded data for EXAMPLE_MESSAGE: {data.hex()}")

    # Decode a message
    decoded_data = db.decode_message(example_message.frame_id, data)
    print(f"Decoded data: {decoded_data}")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Note: For real-world usage, provide a valid .dbc file path.")

view raw JSON →