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
BitTimingparameters. - 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 providedBitTimingandWorkModeconfigurations.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.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| canfd-2.0.2.tar.gz | 21.1 kB | Without provenance | Details for canfd-2.0.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| canfd-2.0.2-py3-none-any.whl | Python 3 | none | any | Details for canfd-2.0.2-py3-none-any.whl |
Total release size: 39.8 kB
Release files / canfd-2.0.2.tar.gz
| Download URL | canfd-2.0.2.tar.gz |
|---|---|
| Size | 21.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
138c02524d9818e69207a0c1cf20cb9e4af3ef87278880449f0883bc1e66dcfb
|
|
BLAKE2b-256 checksum How to use checksums |
616fd9eee63d0079e7577d892d25887847192bdb934c5c68885aba216b133805
|
| 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.2-py3-none-any.whl
| Download URL | canfd-2.0.2-py3-none-any.whl |
|---|---|
| Size | 18.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e72ce6d04d51eae5b8abefb71f9181deda565f3bb8bcdaeafc1409c811026767
|
|
BLAKE2b-256 checksum How to use checksums |
be415191350c986f4dfde5de547294b49ebf89fda9479c5d6705501def7c4278
|
| 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.2
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.