Metadata-Version: 2.4
Name: canfd
Version: 2.0.4
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(English)

A lightweight Python driver library for USB-to-CAN / CAN FD adapters, supporting classic CAN and CAN FD messaging as well as bus status monitoring.

## Key Features

- **Bus Diagnostics**: Supports firmware version queries as well as asynchronous and active bus error status reading (including Bus-Off, Error Passive, Error Warning, and TX/RX error counters).
- **Automatic Device Discovery**: Automatically scans system serial ports whose serial numbers contain the `CANFD` identifier and returns a list of device serial numbers.
- **Smart Length Alignment**: When constructing a `CanFrame` with a non-standard CAN FD payload length, the payload is automatically zero-padded (`0x00`) to the next valid length or truncated to the protocol maximum.
- **Automatic Context Management**: Supports the `with CanFD() as dev:` syntax, automatically calling `disable()` and `close()` upon exiting the block.
- **Flexible Controller Configuration**: Supports switching between ISO and Bosch non-ISO CAN FD standards, four operating modes (`NORMAL`, `LOOPBACK`, `SILENT`, `SILENT_LOOPBACK`), and software-configurable 120-ohm termination resistor and automatic retransmission.
- **Low-CPU Asynchronous TX/RX Engine**: Uses dedicated background TX and RX threads with event-driven blocking waits to minimize CPU usage; the transmitter automatically coalesces queued packets to reduce system calls, while the receiver performs batch splitting.
- **Full CAN / CAN FD Support**: Supports 11-bit standard and 29-bit extended frames, classic CAN (up to 8 bytes, including RTR remote frames), and CAN FD (up to 64 bytes with Bit Rate Switch / BRS acceleration).

## Requirements & Installation

- **Python**: Python 3.10 or later

```bash
pip install canfd
```

## Quick Start

### 1. Transmit Example (`tx_demo.py`)

The following example opens the first discovered device, configures both the arbitration and data phases to 1 Mbps (80% sample point) based on a 60 MHz CAN clock, and transmits a CAN FD frame every 0.5 seconds:

```python
"""
Standard CAN FD Transmit Example
Description: Scans and opens the 1st CANFD device, configures a 1 Mbps bit rate
             on a 60 MHz clock, and periodically transmits a CAN FD data frame every 0.5 s.
"""

import time

from canfd import BitTiming, CanFD, CanFrame, WorkMode

# Use a context manager to manage the device lifecycle:
# Automatically calls disable() and close() on exit (normal completion, exception, or Ctrl+C)
with CanFD() as dev:
    # 1. Scan and open the 1st CANFD device
    devices = dev.scan()  # Returns a list of serial numbers for all online CANFD devices
    if not devices:
        raise RuntimeError("No CANFD device found")
    if not dev.open(devices[0]):  # Open the 1st device in the list
        raise RuntimeError("Failed to open device")

    # 2. Configure bit timing and enable the CAN FD channel
    # Calculated for a 60 MHz CAN clock:
    #   - Arbitration phase: 60 MHz / 1 / (1 + 47 + 12) = 1 Mbps, sample point = (1 + 47) / 60 = 80%
    #   - Data phase:        60 MHz / 3 / (1 + 15 + 4)  = 1 Mbps, sample point = (1 + 15) / 20 = 80%
    timing = BitTiming(
        can_prescaler=1,   # Arbitration prescaler (range: 1 to 1024)
        can_seg1=47,       # Arbitration time segment 1 (range: 1 to 128)
        can_seg2=12,       # Arbitration time segment 2 (range: 1 to 32)
        can_sjw=8,         # Arbitration sync jump width (range: 1 to 8)
        data_prescaler=3,  # Data phase prescaler (range: 1 to 1024)
        data_seg1=15,      # Data phase time segment 1 (range: 1 to 16)
        data_seg2=4,       # Data phase time segment 2 (range: 1 to 8)
        data_sjw=4,        # Data phase sync jump width (range: 1 to 8)
    )
    if not dev.enable(
        timing,                 # Bit timing (bit rate) configuration
        mode=WorkMode.NORMAL,   # Work mode: NORMAL / LOOPBACK / SILENT / SILENT_LOOPBACK
        termination=True,       # Enable internal 120-ohm termination resistor
        auto_retransmit=False,  # Enable automatic retransmission on TX error or arbitration loss
        fd_bosch=False,         # CAN FD standard: False for ISO, True for Bosch non-ISO
    ):
        raise RuntimeError("Failed to enable CANFD")

    # 3. Periodically transmit CAN FD data frames
    print("Transmitting... Press Ctrl+C to stop.")
    try:
        while True:
            # Build the CAN FD data frame to send
            data = bytes([0x01, 0x02, 0x03, 0x04])
            frame = CanFrame(
                ext=False,      # ID format: False for 11-bit standard, True for 29-bit extended
                rtr=False,      # Frame type: False for data frame, True for remote frame (must be False for CAN FD)
                fd=True,        # Protocol: True for CAN FD frame, False for classic CAN frame
                brs=True,       # Bit Rate Switch: True enables fast data phase (requires fd=True)
                id=0x123,       # CAN ID (standard: 0x000-0x7FF, extended: 0x00000000-0x1FFFFFFF)
                len=len(data),  # Payload length in bytes (valid CAN FD lengths: 0-8, 12, 16, 20, 24, 32, 48, 64)
                data=data,      # Payload bytes to transmit
            )

            # Encode and enqueue the frame for transmission
            if dev.tx_frame(frame):
                print(
                    f"[TX] ID=0x{frame.id:03X} LEN={frame.len} DATA={frame.data.hex(' ').upper()}"
                )
            else:
                print("[TX] Transmission failed")

            # Wait 0.5 seconds between frames
            time.sleep(0.5)
    except KeyboardInterrupt:
        print("\nTransmission stopped.")
```

### 2. Receive Example (`rx_demo.py`)

The following example opens the second discovered device (for dual-adapter testing on a single host; change `devices[1]` to `devices[0]` for a single device), configures both the arbitration and data phases to 1 Mbps (80% sample point) based on a 60 MHz CAN clock, and continuously receives frames from the bus:

```python
"""
Standard CAN FD Receive Example
Description: Scans and opens the 2nd CANFD device, configures a 1 Mbps bit rate
             on a 60 MHz clock, and continuously receives and prints CAN / CAN FD frames.
"""

from canfd import BitTiming, CanFD, WorkMode

# Use a context manager to manage the device lifecycle:
# Automatically calls disable() and close() on exit (normal completion, exception, or Ctrl+C)
with CanFD() as dev:
    # 1. Scan and open the 2nd CANFD device (suitable for dual-adapter testing on one host)
    devices = dev.scan()  # Returns a list of serial numbers for all online CANFD devices
    if not devices:
        raise RuntimeError("No CANFD device found")
    if not dev.open(devices[1]):  # Open the 2nd device (change to devices[0] for a single device)
        raise RuntimeError("Failed to open device")

    # 2. Configure bit timing and enable the CAN FD channel (must match the transmitter settings)
    # Calculated for a 60 MHz CAN clock:
    #   - Arbitration phase: 60 MHz / 1 / (1 + 47 + 12) = 1 Mbps, sample point = (1 + 47) / 60 = 80%
    #   - Data phase:        60 MHz / 3 / (1 + 15 + 4)  = 1 Mbps, sample point = (1 + 15) / 20 = 80%
    timing = BitTiming(
        can_prescaler=1,   # Arbitration prescaler (range: 1 to 1024)
        can_seg1=47,       # Arbitration time segment 1 (range: 1 to 128)
        can_seg2=12,       # Arbitration time segment 2 (range: 1 to 32)
        can_sjw=8,         # Arbitration sync jump width (range: 1 to 8)
        data_prescaler=3,  # Data phase prescaler (range: 1 to 1024)
        data_seg1=15,      # Data phase time segment 1 (range: 1 to 16)
        data_seg2=4,       # Data phase time segment 2 (range: 1 to 8)
        data_sjw=4,        # Data phase sync jump width (range: 1 to 8)
    )
    if not dev.enable(
        timing,                 # Bit timing (bit rate) configuration
        mode=WorkMode.NORMAL,   # Work mode: NORMAL (sends ACK); use SILENT for passive sniffing
        termination=True,       # Enable internal 120-ohm termination resistor
        auto_retransmit=False,  # Enable automatic retransmission
        fd_bosch=False,         # CAN FD standard: False for ISO, True for Bosch non-ISO
    ):
        raise RuntimeError("Failed to enable CANFD")

    # 3. Continuously receive CAN / CAN FD data frames
    print("Waiting for frames... Press Ctrl+C to stop.")
    try:
        while True:
            # Block for up to 0.01 s to fetch a frame:
            # Avoids busy-waiting CPU usage while keeping Ctrl+C responsive
            ok, frame = dev.rx_frame(timeout=0.01)
            if ok and frame is not None:
                # Print hardware timestamp, frame ID, data length, and hex payload
                print(
                    f"[RX] ts={frame.ts} ID=0x{frame.id:X} "
                    f"LEN={frame.len} "
                    f"DATA={frame.data.hex(' ').upper()}"
                )
    except KeyboardInterrupt:
        print("\nReception stopped.")
```

## API Reference

### Data Types & Enums

#### 1. `WorkMode`

| Enum Member                | Value | Description                                              |
| :------------------------- | :---: | :------------------------------------------------------- |
| `WorkMode.NORMAL`          |  `0`  | Normal bus communication mode                            |
| `WorkMode.LOOPBACK`        |  `1`  | Internal loopback mode (transmit and receive internally) |
| `WorkMode.SILENT`          |  `2`  | Silent listen-only mode (receive only, no ACK sent)      |
| `WorkMode.SILENT_LOOPBACK` |  `3`  | Silent loopback mode                                     |

#### 2. `BitTiming`

Bit rate and sample point formulas:

$$\text{Bitrate} = \frac{F_{\text{clk}}}{\text{prescaler} \times (1 + \text{seg1} + \text{seg2})}$$

$$\text{Sample Point} = \frac{1 + \text{seg1}}{1 + \text{seg1} + \text{seg2}}$$

| Parameter        | Valid Range | Description                                  |
| :--------------- | :---------: | :------------------------------------------- |
| `can_prescaler`  | `1 - 1024`  | Arbitration phase clock prescaler            |
| `can_seg1`       |  `1 - 128`  | Arbitration phase time segment 1             |
| `can_seg2`       |  `1 - 32`   | Arbitration phase time segment 2             |
| `can_sjw`        |   `1 - 8`   | Arbitration phase synchronization jump width |
| `data_prescaler` | `1 - 1024`  | Data phase clock prescaler                   |
| `data_seg1`      |  `1 - 16`   | Data phase time segment 1                    |
| `data_seg2`      |   `1 - 8`   | Data phase time segment 2                    |
| `data_sjw`       |   `1 - 8`   | Data phase synchronization jump width        |

#### 3. `CanFrame`

| Field  |  Type   | Default | Constraints & Description                                    |
| :----- | :-----: | :-----: | :----------------------------------------------------------- |
| `ts`   |  `int`  |   `0`   | 16-bit timestamp, range `0 - 0xFFFF`                         |
| `ext`  | `bool`  | `False` | `False` for 11-bit standard frame, `True` for 29-bit extended frame |
| `rtr`  | `bool`  | `False` | Remote frame flag; when `True`, requires `fd=False`, `len <= 8`, and `data == b""` |
| `fd`   | `bool`  | `False` | CAN FD flag; when `False`, requires `len <= 8`               |
| `brs`  | `bool`  | `False` | Bit Rate Switch flag; can only be `True` when `fd=True`      |
| `id`   |  `int`  |   `0`   | Standard frame: `0 - 0x7FF`; extended frame: `0 - 0x1FFFFFFF` |
| `len`  |  `int`  |   `0`   | Valid lengths: `0-8, 12, 16, 20, 24, 32, 48, 64` (non-standard lengths are zero-padded or truncated automatically) |
| `data` | `bytes` |  `b""`  | Payload bytes; must match `len` for data frames              |

#### 4. `BusStatus`

| Field            |  Type  | Description                                                  |
| :--------------- | :----: | :----------------------------------------------------------- |
| `error_type`     | `int`  | Bus error type code (`0 - 7`)                                |
| `rx_error_count` | `int`  | Receive Error Counter (REC)                                  |
| `tx_error_count` | `int`  | Transmit Error Counter (TEC)                                 |
| `bus_off`        | `bool` | Indicates whether the controller is in the Bus-Off state     |
| `error_passive`  | `bool` | Indicates whether the controller is in the Error Passive state |
| `error_warning`  | `bool` | Indicates whether the Error Warning flag is triggered        |

### `CanFD` Methods

| Method Signature                                             | Return Type                            | Description                                                  |
| :----------------------------------------------------------- | :------------------------------------- | :----------------------------------------------------------- |
| `scan()`                                                     | `list[str]`                            | Scan for connected CANFD devices and return their serial numbers |
| `open(serial_number)`                                        | `bool`                                 | Open the serial port matching the serial number and start background TX/RX threads |
| `is_open()`                                                  | `bool`                                 | Check whether the device and background threads are currently active |
| `close()`                                                    | `bool`                                 | Stop background TX/RX threads and close the serial port      |
| `enable(timing, mode=WorkMode.NORMAL, termination=False, auto_retransmit=False, fd_bosch=False)` | `bool`                                 | Configure bit timing and controller options, then enable CAN FD |
| `disable()`                                                  | `bool`                                 | Disable the CAN FD controller                                |
| `get_firmware_version()`                                     | `tuple[bool, tuple[int, int] \| None]` | Query device firmware `(major, minor)` version               |
| `tx_frame(frame)`                                            | `bool`                                 | Validate, encode, and enqueue a `CanFrame` for transmission  |
| `rx_frame(timeout=0)`                                        | `tuple[bool, CanFrame \| None]`        | Read a received `CanFrame` from the RX queue with optional blocking timeout |
| `rx_frame_in_waiting()`                                      | `int`                                  | Return the number of frames waiting in the RX queue          |
| `get_status()`                                               | `tuple[bool, BusStatus \| None]`       | Actively query current bus status and clear buffered historical status entries |
| `rx_status(timeout=0)`                                       | `tuple[bool, BusStatus \| None]`       | Read an asynchronously reported `BusStatus` from the status queue |
| `rx_status_in_waiting()`                                     | `int`                                  | Return the number of queued asynchronous bus status entries  |

## Notes

- **Frame Validation**: `tx_frame()` strictly validates `CanFrame` fields before enqueuing (e.g., `brs=True` requires `fd=True`, `fd=True` requires `rtr=False`, and `rtr=True` requires `data == b""`), returning `False` if validation fails.
- **Disconnect Detection**: If a `SerialException` occurs on the underlying serial port (such as an unplugged USB cable), the background threads exit safely and `is_open()` becomes `False`.
- **Status Queue Clearing**: Calling `get_status()` clears any buffered asynchronous `BusStatus` entries in the internal queue before returning the latest queried bus status.

## License

This project is licensed under the [GNU General Public License v3.0 (GPL-3.0)](LICENSE). You may freely use, modify, and redistribute this software in accordance with its terms; derivative works distributed to others must also be licensed under the same license with source code made available. See the [LICENSE](LICENSE) file or the [official GNU GPL v3.0 text](https://www.gnu.org/licenses/gpl-3.0.html) for full details.

# canfd(中文)

轻量级 USB 转 CAN / CAN FD Python 驱动库，支持经典 CAN 与 CAN FD 报文收发、总线状态监控。

## 核心特性

- **总线诊断**：支持固件版本查询、异步及主动总线错误状态读取（含 Bus-Off、Error Passive、Error Warning 与收发错误计数）。
- **自动设备发现**：自动扫描系统中序列号包含 `CANFD` 标识的串口设备，并返回设备序列号列表。
- **智能长度对齐**：构造 `CanFrame` 时若传入非标准 CAN FD 载荷长度，会自动用 `0x00` 向上补齐到最近的合法长度或截断至协议上限。
- **上下文自动管理**：支持 `with CanFD() as dev:` 语法，退出代码块时自动执行失能（`disable`）与关闭（`close`）。
- **灵活的控制器配置**：支持 ISO 与 Bosch 非 ISO CAN FD 规范切换，支持 `NORMAL`、`LOOPBACK`、`SILENT`、`SILENT_LOOPBACK` 四种工作模式，并可软件配置 120 欧姆终端电阻与自动重传。
- **低占用异步收发引擎**：内置独立后台收发线程，采用事件驱动阻塞等待以降低 CPU 占用；发送端自动合并积压数据包减少系统调用，接收端批量切分。
- **完整 CAN / CAN FD 支持**：支持 11 位标准帧与 29 位扩展帧，支持经典 CAN（最长 8 字节，含远程帧 RTR）及 CAN FD（最长 64 字节，支持 BRS 数据段加速）。

## 环境要求与安装

- **Python 版本**：Python 3.10 及以上

```bash
pip install canfd
```

## 快速开始

### 1. 发送示例 (`tx_demo.py`)

以下示例打开扫描到的第 1 台设备，基于 60 MHz CAN 时钟配置仲裁段与数据段均为 1 Mbps（采样点 80%），每 0.5 秒发送一帧 CAN FD 报文：

```python
"""
CAN FD 标准发送例程
功能：扫描并打开第 1 台 CANFD 设备，按 60 MHz 时钟配置 1 Mbps 波特率，
      每 0.5 秒周期性发送一帧 CAN FD 数据帧。
"""

import time

from canfd import BitTiming, CanFD, CanFrame, WorkMode

# 使用 with 上下文管理器管理设备生命周期：
# 退出代码块（正常结束或触发异常/Ctrl+C）时，会自动调用 disable() 和 close() 释放资源
with CanFD() as dev:
    # 1. 扫描并打开第 1 个 CANFD 设备
    devices = dev.scan()  # 返回所有在线 CANFD 设备的序列号列表
    if not devices:
        raise RuntimeError("未找到 CANFD 设备")
    if not dev.open(devices[0]):  # 打开列表中的第 1 台设备
        raise RuntimeError("设备打开失败")

    # 2. 配置位时序并使能 CAN FD 通道
    # 基于 60 MHz CAN 时钟计算：
    #   - 仲裁段：60 MHz / 1 / (1 + 47 + 12) = 1 Mbps，采样点 = (1 + 47) / 60 = 80%
    #   - 数据段：60 MHz / 3 / (1 + 15 + 4)  = 1 Mbps，采样点 = (1 + 15) / 20 = 80%
    timing = BitTiming(
        can_prescaler=1,   # 仲裁段预分频系数（范围 1 ~ 1024）
        can_seg1=47,       # 仲裁段时间段 1（范围 1 ~ 128）
        can_seg2=12,       # 仲裁段时间段 2（范围 1 ~ 32）
        can_sjw=8,         # 仲裁段同步跳转宽度（范围 1 ~ 8）
        data_prescaler=3,  # 数据段预分频系数（范围 1 ~ 1024）
        data_seg1=15,      # 数据段时间段 1（范围 1 ~ 16）
        data_seg2=4,       # 数据段时间段 2（范围 1 ~ 8）
        data_sjw=4,        # 数据段同步跳转宽度（范围 1 ~ 8）
    )
    if not dev.enable(
        timing,                 # 位时序（波特率）配置
        mode=WorkMode.NORMAL,   # 工作模式：NORMAL 正常 / LOOPBACK 回环 / SILENT 静默 / SILENT_LOOPBACK 静默回环
        termination=True,       # 是否使能内部 120Ω 终端电阻
        auto_retransmit=False,  # 是否开启发送失败/丢仲裁时的自动重传
        fd_bosch=False,         # CAN FD 协议规范：False 为 ISO 标准，True 为 Bosch 非 ISO 标准
    ):
        raise RuntimeError("CANFD 使能失败")

    # 3. 循环发送 CAN FD 数据帧
    print("开始发送，按 Ctrl+C 停止...")
    try:
        while True:
            # 构造待发送的 CAN FD 数据帧
            data = bytes([0x01, 0x02, 0x03, 0x04])
            frame = CanFrame(
                ext=False,      # 帧 ID 类型：False 为 11 位标准帧，True 为 29 位扩展帧
                rtr=False,      # 帧类型：False 为数据帧，True 为远程帧（CAN FD 帧必须为 False）
                fd=True,        # 协议类型：True 为 CAN FD 帧，False 为经典 CAN 帧
                brs=True,       # 波特率切换：True 表示数据段使用高速率（需 fd=True）
                id=0x123,       # CAN 报文 ID（标准帧 0x000~0x7FF，扩展帧 0x00000000~0x1FFFFFFF）
                len=len(data),  # 数据字节长度（CAN FD 合法长度：0~8, 12, 16, 20, 24, 32, 48, 64）
                data=data,      # 实际发送的字节载荷
            )

            # 将报文编码并推入发送队列
            if dev.tx_frame(frame):
                print(
                    f"[TX] ID=0x{frame.id:03X} LEN={frame.len} DATA={frame.data.hex(' ').upper()}"
                )
            else:
                print("[TX] 发送失败")

            # 发送间隔延时 0.5 秒
            time.sleep(0.5)
    except KeyboardInterrupt:
        print("\n已停止发送")
```

### 2. 接收示例 (`rx_demo.py`)

以下示例打开扫描到的第 1 台设备，基于 60 MHz CAN 时钟配置仲裁段与数据段均为 1 Mbps（采样点 80%），并持续接收总线报文：

```python
"""
CAN FD 标准接收例程
功能：扫描并打开第 2 台 CANFD 设备，按 60 MHz 时钟配置 1 Mbps 波特率，
      持续阻塞接收总线上的 CAN / CAN FD 报文并打印。
"""

from canfd import BitTiming, CanFD, WorkMode

# 使用 with 上下文管理器管理设备生命周期：
# 退出代码块（正常结束或触发异常/Ctrl+C）时，会自动调用 disable() 和 close() 释放资源
with CanFD() as dev:
    # 1. 扫描并打开第 2 个 CANFD 设备（适用于同一台主机插两块卡对发测试）
    devices = dev.scan()  # 返回所有在线 CANFD 设备的序列号列表
    if not devices:
        raise RuntimeError("未找到 CANFD 设备")
    if not dev.open(devices[1]):  # 打开列表中的第 2 台设备（单设备运行时请改为 devices[0]）
        raise RuntimeError("设备打开失败")

    # 2. 配置位时序并使能 CAN FD 通道（须与发送端波特率及协议规范保持一致）
    # 基于 60 MHz CAN 时钟计算：
    #   - 仲裁段：60 MHz / 1 / (1 + 47 + 12) = 1 Mbps，采样点 = (1 + 47) / 60 = 80%
    #   - 数据段：60 MHz / 3 / (1 + 15 + 4)  = 1 Mbps，采样点 = (1 + 15) / 20 = 80%
    timing = BitTiming(
        can_prescaler=1,   # 仲裁段预分频系数（范围 1 ~ 1024）
        can_seg1=47,       # 仲裁段时间段 1（范围 1 ~ 128）
        can_seg2=12,       # 仲裁段时间段 2（范围 1 ~ 32）
        can_sjw=8,         # 仲裁段同步跳转宽度（范围 1 ~ 8）
        data_prescaler=3,  # 数据段预分频系数（范围 1 ~ 1024）
        data_seg1=15,      # 数据段时间段 1（范围 1 ~ 16）
        data_seg2=4,       # 数据段时间段 2（范围 1 ~ 8）
        data_sjw=4,        # 数据段同步跳转宽度（范围 1 ~ 8）
    )
    if not dev.enable(
        timing,                 # 位时序（波特率）配置
        mode=WorkMode.NORMAL,   # 工作模式：NORMAL 正常（回 ACK）；纯监听不干扰总线可用 SILENT
        termination=True,       # 是否使能内部 120Ω 终端电阻
        auto_retransmit=False,  # 是否开启自动重传
        fd_bosch=False,         # CAN FD 协议规范：False 为 ISO 标准，True 为 Bosch 非 ISO 标准
    ):
        raise RuntimeError("CANFD 使能失败")

    # 3. 循环接收 CAN / CAN FD 数据帧
    print("等待接收数据，按 Ctrl+C 停止...")
    try:
        while True:
            # 阻塞等待最多 0.01 秒获取一帧报文：
            # 无数据时释放 CPU 避免空转，同时保证按下 Ctrl+C 后能及时响应退出
            ok, frame = dev.rx_frame(timeout=0.01)
            if ok and frame is not None:
                # 打印硬件时间戳、帧 ID、数据长度及十六进制载荷
                print(
                    f"[RX] ts={frame.ts} ID=0x{frame.id:X} "
                    f"LEN={frame.len} "
                    f"DATA={frame.data.hex(' ').upper()}"
                )
    except KeyboardInterrupt:
        print("\n已停止接收")
```

## API 参考

### 数据类型与枚举

#### 1. `WorkMode`（工作模式）

| 枚举值                     | 数值 | 说明                               |
| :------------------------- | :--: | :--------------------------------- |
| `WorkMode.NORMAL`          | `0`  | 正常通信模式                       |
| `WorkMode.LOOPBACK`        | `1`  | 内部回环模式（自发自收）           |
| `WorkMode.SILENT`          | `2`  | 静默监听模式（只收不发，不回 ACK） |
| `WorkMode.SILENT_LOOPBACK` | `3`  | 静默回环模式                       |

#### 2. `BitTiming`（位时序参数）

波特率与采样点计算公式如下：

$$\text{Bitrate} = \frac{F_{\text{clk}}}{\text{prescaler} \times (1 + \text{seg1} + \text{seg2})}$$

$$\text{Sample Point} = \frac{1 + \text{seg1}}{1 + \text{seg1} + \text{seg2}}$$

| 参数             |  合法范围  | 说明               |
| :--------------- | :--------: | :----------------- |
| `can_prescaler`  | `1 ~ 1024` | 仲裁段预分频系数   |
| `can_seg1`       | `1 ~ 128`  | 仲裁段时间段 1     |
| `can_seg2`       |  `1 ~ 32`  | 仲裁段时间段 2     |
| `can_sjw`        |  `1 ~ 8`   | 仲裁段同步跳转宽度 |
| `data_prescaler` | `1 ~ 1024` | 数据段预分频系数   |
| `data_seg1`      |  `1 ~ 16`  | 数据段时间段 1     |
| `data_seg2`      |  `1 ~ 8`   | 数据段时间段 2     |
| `data_sjw`       |  `1 ~ 8`   | 数据段同步跳转宽度 |

#### 3. `CanFrame`（报文帧对象）

| 字段   |  类型   | 默认值  | 约束与说明                                                   |
| :----- | :-----: | :-----: | :----------------------------------------------------------- |
| `ts`   |  `int`  |   `0`   | 16 位时间戳，范围 `0 ~ 0xFFFF`                               |
| `ext`  | `bool`  | `False` | `False` 为 11 位标准帧，`True` 为 29 位扩展帧                |
| `rtr`  | `bool`  | `False` | 远程帧标志；`True` 时 `fd` 须为 `False`、`len <= 8` 且 `data` 须为 `b""` |
| `fd`   | `bool`  | `False` | CAN FD 标志；`False` 时 `len <= 8`                           |
| `brs`  | `bool`  | `False` | 数据段波特率切换标志；仅当 `fd=True` 时可设为 `True`         |
| `id`   |  `int`  |   `0`   | 标准帧 `0 ~ 0x7FF`，扩展帧 `0 ~ 0x1FFFFFFF`                  |
| `len`  |  `int`  |   `0`   | 合法值：`0~8, 12, 16, 20, 24, 32, 48, 64`（非标准长度自动补零或截断） |
| `data` | `bytes` |  `b""`  | 字节载荷；数据帧时长度须等于 `len`                           |

#### 4. `BusStatus`（总线状态对象）

| 字段             |  类型  | 说明                                  |
| :--------------- | :----: | :------------------------------------ |
| `error_type`     | `int`  | 总线错误类型码（`0 ~ 7`）             |
| `rx_error_count` | `int`  | 接收错误计数器（REC）                 |
| `tx_error_count` | `int`  | 发送错误计数器（TEC）                 |
| `bus_off`        | `bool` | 是否进入总线关闭（Bus-Off）状态       |
| `error_passive`  | `bool` | 是否处于被动错误（Error Passive）状态 |
| `error_warning`  | `bool` | 是否触发错误警告（Error Warning）标志 |

### `CanFD` 类常用方法

| 方法签名                                                     | 返回值                                 | 说明                                     |
| :----------------------------------------------------------- | :------------------------------------- | :--------------------------------------- |
| `scan()`                                                     | `list[str]`                            | 扫描在线的 CANFD 设备序列号列表          |
| `open(serial_number)`                                        | `bool`                                 | 按序列号打开串口并启动后台收发线程       |
| `is_open()`                                                  | `bool`                                 | 查询设备与收发线程是否处于运行状态       |
| `close()`                                                    | `bool`                                 | 停止收发线程并关闭串口                   |
| `enable(timing, mode=WorkMode.NORMAL, termination=False, auto_retransmit=False, fd_bosch=False)` | `bool`                                 | 配置位时序与工作参数并使能 CAN FD 控制器 |
| `disable()`                                                  | `bool`                                 | 失能 CAN FD 控制器                       |
| `get_firmware_version()`                                     | `tuple[bool, tuple[int, int] \| None]` | 查询设备固件 `(major, minor)` 版本号     |
| `tx_frame(frame)`                                            | `bool`                                 | 校验并编码 `CanFrame`，推入发送队列      |
| `rx_frame(timeout=0)`                                        | `tuple[bool, CanFrame \| None]`        | 从接收队列读取一帧报文，支持超时阻塞     |
| `rx_frame_in_waiting()`                                      | `int`                                  | 返回接收队列中待读取的报文数量           |
| `get_status()`                                               | `tuple[bool, BusStatus \| None]`       | 主动查询当前总线状态，并清空历史状态队列 |
| `rx_status(timeout=0)`                                       | `tuple[bool, BusStatus \| None]`       | 读取设备异步上报的总线状态               |
| `rx_status_in_waiting()`                                     | `int`                                  | 返回队列中待读取的异步总线状态数量       |

## 注意事项

- **帧参数校验**：`tx_frame()` 在入队前会严格校验 `CanFrame` 字段合法性（例如 `brs=True` 时 `fd` 必须为 `True`、`fd=True` 时 `rtr` 必须为 `False`、`rtr=True` 时 `data` 必须为空 `b""`），校验不通过将返回 `False`。
- **断线检测**：当底层串口通信出现 `SerialException`（如 USB 线缆被意外拔出）时，后台线程会安全退出并将 `is_open()` 置为 `False`。
- **状态队列清理**：主动调用 `get_status()` 会先清空内部积压的异步 `BusStatus` 队列，再返回本次命令查询到的最新总线状态。

## 开源协议

本项目基于 [GNU General Public License v3.0 (GPL-3.0)](LICENSE) 开源。你可以在遵守该协议条款的前提下自由使用、修改和重新分发本软件；基于本项目的衍生作品在对外分发时也须采用相同协议开源并公开源代码。完整协议内容请参阅 [LICENSE](LICENSE) 文件或访问 [GNU GPL v3.0 官方文本](https://www.gnu.org/licenses/gpl-3.0.html)。
