Skip to main content

CANFD Python Library

This is a Python interface library designed for CAN and CAN FD communication via a USB-to-CAN module. It provides a streamlined API to manage CAN device connections, configure bit timing, transmit and receive CAN/CAN FD data frames, and supports bus status monitoring.

Features

  • Hardware Scanning & Connection: Automatically scans for available CANFD serial devices on the system and establishes connections.
  • CAN & CAN FD Support: Fully supports standard CAN and CAN FD protocols, including extended frames, remote frames (RTR), and Bit Rate Switching (BRS).
  • Flexible Baud Rate Configuration: Precise control over arbitration and data phase baud rates through custom BitTiming parameters.
  • Multiple Work Modes: Supports Normal, Loopback, Silent, and Silent Loopback operating modes.

Installation

pip install canfd

Dependencies: pyserial.

Quick Start

1. Scanning and Connecting to a Device

from canfd import CanFD, BitTiming, WorkMode

# Initialize the CanFD controller
can = CanFD()

# Scan for available CANFD ports
ports = can.scan()
if not ports:
    print("No CANFD devices found.")
    exit()

print(f"Devices found: {ports}")

# Open connection to the first discovered device
# Note: The port parameter expects a partial serial number string
if not can.open(ports[0]):
    print("Failed to connect to the device.")
    exit()

print("Device connected successfully.")

2. Configuring and Enabling the CAN Controller

# Configure bit timing parameters (BitTiming) hardware can clock = 60MHz
timing = BitTiming(
    can_prescaler=1, can_seg1=47, can_seg2=12, can_sjw=8,   # 1Mbps 80%
    data_prescaler=1, data_seg1=11, data_seg2=3, data_sjw=3 # 4Mbps 80%
)

# Enable the CAN module in NORMAL mode
success = can.enable(
    timing=timing,
    mode=WorkMode.NORMAL,
    termination=True,      # Enable internal termination resistor (if supported)
    auto_retransmit=True,  # Enable auto-retransmission on error
    fd_bosch=False         # False for ISO CAN FD, True for non-ISO (Bosch)
)

if success:
    print("CAN module enabled successfully.")

3. Transmitting Data Frames

from canfd import CanFrame

# Create and send a Standard CAN frame
frame_std = CanFrame(
    id=0x123,
    len=8,
    data=b'\x01\x02\x03\x04\x05\x06\x07\x08',
    ext=False,
    fd=False
)
can.tx_frame(frame_std)

# Create and send a CAN FD frame with BRS (Bit Rate Switching)
frame_fd = CanFrame(
    id=0x123456,
    len=64,   # Supported DLC lengths: 0-8, 12, 16, 20, 24, 32, 48, 64
    data=b'\xAA' * 64,
    ext=True, # Extended 29-bit ID
    fd=True,  # CAN FD format
    brs=True  # Enable Bit Rate Switching
)
can.tx_frame(frame_fd)

4. Receiving Data Frames

Data reception is handled asynchronously by an internal queue. You can retrieve frames using the rx_frame() method.

# Check if there are any frames waiting in the queue
if can.rx_frame_in_waiting() > 0:
    print(f"{can.rx_frame_in_waiting()} frames waiting to be read.")

# Attempt to receive a data frame (with a 1.0-second timeout)
ret, frame = can.rx_frame(timeout=1.0)
if ret and frame:
    print(f"Received Frame: ID={hex(frame.id)}, DLC={frame.len}, Data={frame.data.hex()}")

5. Retrieving Bus Status and Closing

# Retrieve CAN bus status and error counters
ret, status = can.get_status()
if ret and status:
    print(f"Bus Status: Error Active={not status.error_passive}, Bus Off={status.bus_off}")
    print(f"TX Errors: {status.tx_error_count}, RX Errors: {status.rx_error_count}")

# Disable the CAN controller and safely close the serial port
can.disable()
can.close()

Core API Reference

CanFD

The primary controller class for managing serial connections, executing commands, and routing data.

  • scan(): Scans the system for available CANFD serial COM ports.
  • open(serial_number: str): Opens a connection to the device matching the provided serial number.
  • close(): Terminates the background polling thread and closes the serial port.
  • enable(...): Starts the CAN controller with the provided BitTiming and WorkMode configurations.
  • disable(): Stops the CAN controller.
  • tx_frame(frame: CanFrame): Transmits a CAN frame over the bus.
  • rx_frame(timeout: float): Retrieves the next available CAN frame from the RX queue.

CanFrame

Data class representing a CAN/CAN FD message frame.

  • id: The frame identifier (11-bit standard or 29-bit extended).
  • data: The payload bytes.
  • len: Data length (strictly validated against standard DLC maps).
  • ext: Boolean flag for Extended Frame format.
  • fd: Boolean flag for CAN FD frame format.
  • brs: Boolean flag to enable Bit Rate Switching.
  • rtr: Boolean flag for Remote Transmission Request (payload must be empty).

BitTiming

Configuration class for bit timing registers. It includes the prescaler, time segment 1 (seg1), time segment 2 (seg2), and synchronization jump width (sjw) for both the arbitration phase (can_) and the data phase (data_).

WorkMode

An enumeration of supported operational modes:

  • NORMAL: Standard bus communication.
  • LOOPBACK: Internal loopback mode for self-testing.
  • SILENT: Listen-only mode without ACKing frames.
  • SILENT_LOOPBACK: Combines silent and loopback characteristics.

Metadata

Release files for canfd 2.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for canfd 2.0.3
File Size Uploaded Provenance Actions
canfd-2.0.3.tar.gz 22.0 kB Without provenance Details for canfd-2.0.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for canfd 2.0.3
File Interpreter ABI Platform Actions
canfd-2.0.3-py3-none-any.whl Python 3 none any Details for canfd-2.0.3-py3-none-any.whl

Total release size: 41.5 kB

Release files / canfd-2.0.3.tar.gz

Download URL canfd-2.0.3.tar.gz
Size 22.0 kB
Tags Source
SHA-256 checksum
How to use checksums
8c6e0aaad4b1bd7a4fa349bfd4852f4e4367a6da28e35387f3f4eaa4c6a87003
BLAKE2b-256 checksum
How to use checksums
5d6a3d7e069dc8b3a5c2b1a4159b8df7ed9bef500cca4fd5c83f7439546e563d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Release files / canfd-2.0.3-py3-none-any.whl

Download URL canfd-2.0.3-py3-none-any.whl
Size 19.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7520db3139a4494ec6f8a0d884caee9e364c0ecff6ad9e2f90d0ad7fb2dfdae1
BLAKE2b-256 checksum
How to use checksums
91650fc2a0bb2e1cf0dee448957ab6a662cfa50e4d1228dcf6733a551f6bcea4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Security for canfd 2.0.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page