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
CANFDidentifier and returns a list of device serial numbers. - Smart Length Alignment: When constructing a
CanFramewith 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 callingdisable()andclose()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
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:
"""
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:
"""
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 validatesCanFramefields before enqueuing (e.g.,brs=Truerequiresfd=True,fd=Truerequiresrtr=False, andrtr=Truerequiresdata == b""), returningFalseif validation fails. - Disconnect Detection: If a
SerialExceptionoccurs on the underlying serial port (such as an unplugged USB cable), the background threads exit safely andis_open()becomesFalse. - Status Queue Clearing: Calling
get_status()clears any buffered asynchronousBusStatusentries 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). 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 file or the official GNU GPL v3.0 text 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 及以上
pip install canfd
快速开始
1. 发送示例 (tx_demo.py)
以下示例打开扫描到的第 1 台设备,基于 60 MHz CAN 时钟配置仲裁段与数据段均为 1 Mbps(采样点 80%),每 0.5 秒发送一帧 CAN FD 报文:
"""
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%),并持续接收总线报文:
"""
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 文件或访问 GNU GPL v3.0 官方文本。
Metadata
Release files for canfd 2.0.4
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.4.tar.gz | 30.5 kB | Without provenance | Details for canfd-2.0.4.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| canfd-2.0.4-py3-none-any.whl | Python 3 | none | any | Details for canfd-2.0.4-py3-none-any.whl |
Total release size: 46.5 kB
Release files / canfd-2.0.4.tar.gz
| Download URL | canfd-2.0.4.tar.gz |
|---|---|
| Size | 30.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e13a4ed8c54206c432faa7213c4ffa8172791a94ffa819703f14bfff251c1a7e
|
|
BLAKE2b-256 checksum How to use checksums |
83f0064a2d1e2addc9f258278c987180756f226bacdd42cf9c9b63bddca15a01
|
| 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.4-py3-none-any.whl
| Download URL | canfd-2.0.4-py3-none-any.whl |
|---|---|
| Size | 16.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2566130b03abcd85721e47e363f9b2eb547c4c3f92f01dba6ef55b7fc689e059
|
|
BLAKE2b-256 checksum How to use checksums |
86bf74dbfe9f8725f78cde70172664ca46a30c74a34da8a99b13b31379da5ce9
|
| 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.4
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.