Metadata-Version: 2.4
Name: canfd
Version: 2.0.1
Summary: USB-CANFD adapter library
Author-email: codenocold <codenocold@gmail.com>
Project-URL: Homepage, https://item.taobao.com/item.htm?id=610739408298&pisk=gk1ibhvShOJs2NZpp6O_UqNW8L2L1COXmihvDIK4LH-I6id9MB7ePElZgAJqL9b5mhUbCCBHmMSHbibb5E-V0ixABJFR5NOXguK0w7Q_KdFldGcwbBz2PEkaJd8WeRtwguE8wv3eCldVDhKkTWkePH8wuh84-p86zI8wQFzHYEYS3cSV0yxe5U8q3jJZYv8XYx8wgf-UTUTq0EkZgybeAER20iJa-wlW80K5Q1CUvc3ZsyTX16YMI373FjlcPbpw4sKEgu5HSQtP7Hcqg3xvIkQhWlc5JC1lqUITTfjlP6sH8gP0xIsC3i8cY7iv1TI1NpbQUX7BsH9P3p4a_wAMjLYpKqM9stS1id6ilz_e_M6WVdyQAefOwKxWKDrNJwxwEtjTAj-OEwSHe6nKwIsC3i8cYcjPQvkySdlX8rCEhx9wRexJG15mT3zKtXa3-Y3DQeTyJy4nh9vwReGT-yD5Md8B5-C..&spm=a21xtw.29178619.0.0
Requires-Python: >=3.5
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyserial>=3.5
Dynamic: license-file

# 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

```bash
pip install canfd
```

*Dependencies:* `pyserial`.

## Quick Start

### 1. Scanning and Connecting to a Device

```python
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

```python
# 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

```python
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.

```python
# 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

```python
# 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.
