python-cantools 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_cantools-0.2.0/LICENSE +10 -0
- python_cantools-0.2.0/PKG-INFO +183 -0
- python_cantools-0.2.0/README.md +157 -0
- python_cantools-0.2.0/pyproject.toml +45 -0
- python_cantools-0.2.0/setup.cfg +4 -0
- python_cantools-0.2.0/src/canlink/__init__.py +34 -0
- python_cantools-0.2.0/src/canlink/asc.py +220 -0
- python_cantools-0.2.0/src/canlink/errors.py +19 -0
- python_cantools-0.2.0/src/canlink/mirror.py +361 -0
- python_cantools-0.2.0/src/canlink/tapped.py +144 -0
- python_cantools-0.2.0/src/python_cantools.egg-info/PKG-INFO +183 -0
- python_cantools-0.2.0/src/python_cantools.egg-info/SOURCES.txt +16 -0
- python_cantools-0.2.0/src/python_cantools.egg-info/dependency_links.txt +1 -0
- python_cantools-0.2.0/src/python_cantools.egg-info/requires.txt +7 -0
- python_cantools-0.2.0/src/python_cantools.egg-info/top_level.txt +1 -0
- python_cantools-0.2.0/tests/test_asc.py +114 -0
- python_cantools-0.2.0/tests/test_mirror.py +177 -0
- python_cantools-0.2.0/tests/test_tapped.py +104 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Copyright (c) 2026 HIL Platform Team. All rights reserved.
|
|
2
|
+
|
|
3
|
+
PROPRIETARY AND CONFIDENTIAL
|
|
4
|
+
|
|
5
|
+
This software and its source code are provided for internal use only by
|
|
6
|
+
authorized projects of the copyright holder. No part of it may be
|
|
7
|
+
redistributed, published, sublicensed, or disclosed to any third party
|
|
8
|
+
without prior written permission.
|
|
9
|
+
|
|
10
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-cantools
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: CAN bench core extracted from HIL frameworks: DBC signal mirror, tapped bus and ASC recorder
|
|
5
|
+
Author: HIL Platform Team
|
|
6
|
+
License-Expression: LicenseRef-Proprietary
|
|
7
|
+
Project-URL: Homepage, https://github.com/Ericcoool/python-cantools
|
|
8
|
+
Project-URL: Repository, https://github.com/Ericcoool/python-cantools.git
|
|
9
|
+
Project-URL: Issues, https://github.com/Ericcoool/python-cantools/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/Ericcoool/python-cantools/blob/main/README.md#变更记录
|
|
11
|
+
Keywords: can,dbc,cantools,python-can,hil,asc,automotive
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Topic :: Software Development :: Testing
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: python-can<6,>=4.4
|
|
20
|
+
Requires-Dist: cantools<50,>=22.0
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: pytest<10,>=8.0; extra == "dev"
|
|
23
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
24
|
+
Requires-Dist: twine>=6.0; extra == "dev"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# python-cantools(import 名 `canlink`)
|
|
28
|
+
|
|
29
|
+
CAN 台架通信内核,从 HIL 自动化测试框架的 `src/drv/drv_can.py` 与
|
|
30
|
+
`src/drv/drv_asc_logger.py` 抽取。纯 Python,仅依赖 `python-can` + `cantools`。
|
|
31
|
+
|
|
32
|
+
> 状态:`0.2.0` — 已发布 PyPI(`pip install python-cantools`),源码同步在 GitHub。
|
|
33
|
+
|
|
34
|
+
分发名与 import 名故意分开:`pip install python-cantools` → `import canlink`
|
|
35
|
+
(与 `python-can` → `import can` 的惯例一致,且避免与 `cantools` 混淆)。
|
|
36
|
+
|
|
37
|
+
## 范围(只这三块)
|
|
38
|
+
|
|
39
|
+
| 模块 | 主要 API | 职责 | 抽取源 |
|
|
40
|
+
|---|---|---|---|
|
|
41
|
+
| `tapped.py` | `TappedBus` / `TappedPeriodicTask` | 单总线搭线:收发广播、周期任务快照(PCAN 同进程只能开一条 bus,且不回显自发帧) | `drv_can.py` |
|
|
42
|
+
| `mirror.py` | `DbcSignalMirror` | DBC 编解码、周期发送/启停/恢复、裸帧收发、后台解码缓存与帧时间戳 | `drv_can.py::VehicleCanBus` |
|
|
43
|
+
| `asc.py` | `AscRecorder` + 4 个行格式函数 | ASC 录制:硬件时基对齐、周期 Tx 重放、按大小分卷 | `drv_asc_logger.py::CaseCanRecorder` |
|
|
44
|
+
|
|
45
|
+
**不在本包内**(留在业务项目):NTC 设压(0xA3/0xA4)、TH6301 电源串口、
|
|
46
|
+
下位机反馈等待(`MeasurementObserver`)、ISO-TP/UDS、信号名解析、中文关键字翻译、通道映射表。
|
|
47
|
+
本包**绝不 import 任何业务项目**。
|
|
48
|
+
|
|
49
|
+
## 业务约定 → 注入点
|
|
50
|
+
|
|
51
|
+
| 业务约定 | 注入点 |
|
|
52
|
+
|---|---|
|
|
53
|
+
| 哪些报文是模拟器自发帧 | `auto_start_predicate=lambda m: "Vector_XXX" in (m.senders or [])` |
|
|
54
|
+
| 不参与周期广播的报文(诊断请求等) | `skip_name_prefixes=("Diag_", "Tester_")` |
|
|
55
|
+
| 解码缓存要忽略的本端帧 | `ignore_frame_ids={0x2F9}` |
|
|
56
|
+
| DBC 无 `GenMsgCycleTime` 时的兜底周期 | `default_cycle_s=0.1` |
|
|
57
|
+
| ASC "每用例一个文件" 的命名规则 | `AscRecorder(namer=lambda case_id: ...)` |
|
|
58
|
+
|
|
59
|
+
## 安装
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
# PyPI(推荐)
|
|
63
|
+
python -m pip install python-cantools
|
|
64
|
+
|
|
65
|
+
# 固定版本
|
|
66
|
+
python -m pip install python-cantools==0.2.0
|
|
67
|
+
|
|
68
|
+
# 从 GitHub 源码安装(拉最新主干,调试用)
|
|
69
|
+
python -m pip install "git+https://github.com/Ericcoool/python-cantools.git@main"
|
|
70
|
+
|
|
71
|
+
# 本地开发
|
|
72
|
+
python -m pip install -e ".[dev]"
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### 发布新版本到 PyPI
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
# 1. 改 pyproject.toml 的 version,提交并打 tag
|
|
79
|
+
python -m build --sdist --wheel -o dist/
|
|
80
|
+
twine check dist/* # 元数据校验
|
|
81
|
+
twine upload dist/python_cantools-* # 上传(需要 PyPI 账号的 API token)
|
|
82
|
+
|
|
83
|
+
# 2. 上传成功后打 tag 推送
|
|
84
|
+
git tag -a vX.Y.Z -m "python-cantools X.Y.Z" && git push origin vX.Y.Z
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
> PyPI 版本号只能传一次:同一个 version 上传过就**不能重新上传**(哪怕删了文件),
|
|
88
|
+
> 修 bug 必须升版本号(如 0.2.1)。上传前先在
|
|
89
|
+
> [test.pypi.org](https://test.pypi.org) 用 `--repository testpypi` 走一遍最稳。
|
|
90
|
+
|
|
91
|
+
### 离线工控机
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
# 联网机器:产出本包 wheel(纯 Python → py3-none-any,跨平台)
|
|
95
|
+
python -m build --wheel -o dist/
|
|
96
|
+
|
|
97
|
+
# 依赖 wheel 必须一并带上,且必须在目标工控机相同 Python 版本 + 相同 OS/架构上下载
|
|
98
|
+
python -m pip download "python-can>=4.4,<6" "cantools>=22.0,<50" -d dist/
|
|
99
|
+
|
|
100
|
+
# 离线机器
|
|
101
|
+
python -m pip install --no-index --find-links=dist/ python-cantools
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
> `bitstruct` / `wrapt` 会解析成 `cp3XX-cp3XX-win_amd64` 平台专用 wheel,
|
|
105
|
+
> 从开发机随便拷大概率装不上。
|
|
106
|
+
|
|
107
|
+
## 快速示例
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
import can
|
|
111
|
+
from canlink import TappedBus, DbcSignalMirror, AscRecorder
|
|
112
|
+
|
|
113
|
+
bus = can.Bus(interface="pcan", channel="USBBUS1", bitrate=500000)
|
|
114
|
+
tap = TappedBus(bus, label="1")
|
|
115
|
+
|
|
116
|
+
vehicle = DbcSignalMirror(
|
|
117
|
+
"controller.dbc", tap,
|
|
118
|
+
auto_start_predicate=lambda m: "Vector_XXX" in (m.senders or []),
|
|
119
|
+
skip_name_prefixes=("Diag_", "Tester_"),
|
|
120
|
+
ignore_frame_ids={0x2F9},
|
|
121
|
+
)
|
|
122
|
+
vehicle.start() # 含无 DBC 周期的报文,按 0.1s 发
|
|
123
|
+
vehicle.update_signal("CCP_CFCAN_FrP02", "SysPwrMd", 2)
|
|
124
|
+
value = vehicle.read_signal("MSM_CFCAN_FrP03", "StrgWhlHeatLvl")
|
|
125
|
+
|
|
126
|
+
recorder = AscRecorder(
|
|
127
|
+
[tap], output_dir="can_logs",
|
|
128
|
+
namer=lambda case_id: case_id or "can",
|
|
129
|
+
)
|
|
130
|
+
recorder.start(case="WheelHeat_001")
|
|
131
|
+
...
|
|
132
|
+
recorder.stop()
|
|
133
|
+
vehicle.shutdown()
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## 与 `drv_can.py` 的行为对齐点
|
|
137
|
+
|
|
138
|
+
这三个坑都在台架上踩过,抽取时**原样保留**,改动前请先看对应注释:
|
|
139
|
+
|
|
140
|
+
1. **无 DBC 周期的报文也要发**:`start()` 对 `cycle_time` 为空/0 的报文按
|
|
141
|
+
`default_cycle_s`(0.1s)发送。整车 DBC 常把 EnRun/唤醒类报文写成无周期,
|
|
142
|
+
而它们是控制器工作的前置条件,缺发会导致控制器完全不响应。
|
|
143
|
+
2. **编码 `strict=False`**:OEM DBC 初始值常超物理范围(如座椅位置 127=SNA),
|
|
144
|
+
关掉范围断言后仍按 DBC 缩放/位打包,与真节点行为一致。
|
|
145
|
+
3. **写入前 coerce 数值字符串**:CSV/配置来源是 `"3"`、`"1.75"`,
|
|
146
|
+
直接编码整型/枚举信号会 `KeyError`,`update_signal(s)` 内部统一转 int/float。
|
|
147
|
+
|
|
148
|
+
## 替换到业务框架
|
|
149
|
+
|
|
150
|
+
| 业务框架现有实现 | 本包对应 |
|
|
151
|
+
|---|---|
|
|
152
|
+
| `src/drv/drv_can.py::TappedBus` / `_TappedPeriodicTask` | `TappedBus` / `TappedPeriodicTask` |
|
|
153
|
+
| `src/drv/drv_can.py::VehicleCanBus` | `DbcSignalMirror`(保留 `build_can_message` / `start_manual_periodic` / `stop_periodic_message` / `resume_periodic_message` / `send_raw_message` / `recv_frame` 旧名别名) |
|
|
154
|
+
| `src/drv/drv_asc_logger.py::CaseCanRecorder` | `AscRecorder(namer=...)`(提供 `CaseCanRecorder` 别名) |
|
|
155
|
+
|
|
156
|
+
策略:业务项目保留原文件改为薄适配器(继承 / 组合),对外方法签名不变,
|
|
157
|
+
逐个模块切换,每切一个跑一次全量回归。
|
|
158
|
+
|
|
159
|
+
## 测试
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
python -m pytest
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
单测基于内置最小 DBC 与 FakeBus,不依赖真实 PCAN 硬件、不依赖业务项目的 DBC / 用例表。
|
|
166
|
+
|
|
167
|
+
## 版本策略
|
|
168
|
+
|
|
169
|
+
- SemVer,tag 形如 `v0.2.0`,tag 不可变
|
|
170
|
+
- 破坏性变更升主/次版本并写 CHANGELOG
|
|
171
|
+
- 依赖上下限锁定,防 `python-can` / `cantools` 大版本 API 漂移
|
|
172
|
+
|
|
173
|
+
## 变更记录
|
|
174
|
+
|
|
175
|
+
- **0.2.0**:范围收缩为 `drv_can.py` + `drv_asc_logger.py` 两块来源;
|
|
176
|
+
删除 `FeedbackReader`(原 `MeasurementObserver`)与 `SignalResolver`(原 `app_real_bench`);
|
|
177
|
+
同步业务项目最新修复(无周期报文默认发送、`strict=False`、数值字符串 coerce、stop 排空);
|
|
178
|
+
分发名改为 `python-cantools`。
|
|
179
|
+
- **0.1.0**:首版,含 mirror / tapped / resolver / feedback / asc。
|
|
180
|
+
|
|
181
|
+
## 许可
|
|
182
|
+
|
|
183
|
+
内部专有,仅限授权项目使用,未经许可不得外传。详见 `LICENSE`。
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# python-cantools(import 名 `canlink`)
|
|
2
|
+
|
|
3
|
+
CAN 台架通信内核,从 HIL 自动化测试框架的 `src/drv/drv_can.py` 与
|
|
4
|
+
`src/drv/drv_asc_logger.py` 抽取。纯 Python,仅依赖 `python-can` + `cantools`。
|
|
5
|
+
|
|
6
|
+
> 状态:`0.2.0` — 已发布 PyPI(`pip install python-cantools`),源码同步在 GitHub。
|
|
7
|
+
|
|
8
|
+
分发名与 import 名故意分开:`pip install python-cantools` → `import canlink`
|
|
9
|
+
(与 `python-can` → `import can` 的惯例一致,且避免与 `cantools` 混淆)。
|
|
10
|
+
|
|
11
|
+
## 范围(只这三块)
|
|
12
|
+
|
|
13
|
+
| 模块 | 主要 API | 职责 | 抽取源 |
|
|
14
|
+
|---|---|---|---|
|
|
15
|
+
| `tapped.py` | `TappedBus` / `TappedPeriodicTask` | 单总线搭线:收发广播、周期任务快照(PCAN 同进程只能开一条 bus,且不回显自发帧) | `drv_can.py` |
|
|
16
|
+
| `mirror.py` | `DbcSignalMirror` | DBC 编解码、周期发送/启停/恢复、裸帧收发、后台解码缓存与帧时间戳 | `drv_can.py::VehicleCanBus` |
|
|
17
|
+
| `asc.py` | `AscRecorder` + 4 个行格式函数 | ASC 录制:硬件时基对齐、周期 Tx 重放、按大小分卷 | `drv_asc_logger.py::CaseCanRecorder` |
|
|
18
|
+
|
|
19
|
+
**不在本包内**(留在业务项目):NTC 设压(0xA3/0xA4)、TH6301 电源串口、
|
|
20
|
+
下位机反馈等待(`MeasurementObserver`)、ISO-TP/UDS、信号名解析、中文关键字翻译、通道映射表。
|
|
21
|
+
本包**绝不 import 任何业务项目**。
|
|
22
|
+
|
|
23
|
+
## 业务约定 → 注入点
|
|
24
|
+
|
|
25
|
+
| 业务约定 | 注入点 |
|
|
26
|
+
|---|---|
|
|
27
|
+
| 哪些报文是模拟器自发帧 | `auto_start_predicate=lambda m: "Vector_XXX" in (m.senders or [])` |
|
|
28
|
+
| 不参与周期广播的报文(诊断请求等) | `skip_name_prefixes=("Diag_", "Tester_")` |
|
|
29
|
+
| 解码缓存要忽略的本端帧 | `ignore_frame_ids={0x2F9}` |
|
|
30
|
+
| DBC 无 `GenMsgCycleTime` 时的兜底周期 | `default_cycle_s=0.1` |
|
|
31
|
+
| ASC "每用例一个文件" 的命名规则 | `AscRecorder(namer=lambda case_id: ...)` |
|
|
32
|
+
|
|
33
|
+
## 安装
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
# PyPI(推荐)
|
|
37
|
+
python -m pip install python-cantools
|
|
38
|
+
|
|
39
|
+
# 固定版本
|
|
40
|
+
python -m pip install python-cantools==0.2.0
|
|
41
|
+
|
|
42
|
+
# 从 GitHub 源码安装(拉最新主干,调试用)
|
|
43
|
+
python -m pip install "git+https://github.com/Ericcoool/python-cantools.git@main"
|
|
44
|
+
|
|
45
|
+
# 本地开发
|
|
46
|
+
python -m pip install -e ".[dev]"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### 发布新版本到 PyPI
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
# 1. 改 pyproject.toml 的 version,提交并打 tag
|
|
53
|
+
python -m build --sdist --wheel -o dist/
|
|
54
|
+
twine check dist/* # 元数据校验
|
|
55
|
+
twine upload dist/python_cantools-* # 上传(需要 PyPI 账号的 API token)
|
|
56
|
+
|
|
57
|
+
# 2. 上传成功后打 tag 推送
|
|
58
|
+
git tag -a vX.Y.Z -m "python-cantools X.Y.Z" && git push origin vX.Y.Z
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
> PyPI 版本号只能传一次:同一个 version 上传过就**不能重新上传**(哪怕删了文件),
|
|
62
|
+
> 修 bug 必须升版本号(如 0.2.1)。上传前先在
|
|
63
|
+
> [test.pypi.org](https://test.pypi.org) 用 `--repository testpypi` 走一遍最稳。
|
|
64
|
+
|
|
65
|
+
### 离线工控机
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
# 联网机器:产出本包 wheel(纯 Python → py3-none-any,跨平台)
|
|
69
|
+
python -m build --wheel -o dist/
|
|
70
|
+
|
|
71
|
+
# 依赖 wheel 必须一并带上,且必须在目标工控机相同 Python 版本 + 相同 OS/架构上下载
|
|
72
|
+
python -m pip download "python-can>=4.4,<6" "cantools>=22.0,<50" -d dist/
|
|
73
|
+
|
|
74
|
+
# 离线机器
|
|
75
|
+
python -m pip install --no-index --find-links=dist/ python-cantools
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
> `bitstruct` / `wrapt` 会解析成 `cp3XX-cp3XX-win_amd64` 平台专用 wheel,
|
|
79
|
+
> 从开发机随便拷大概率装不上。
|
|
80
|
+
|
|
81
|
+
## 快速示例
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
import can
|
|
85
|
+
from canlink import TappedBus, DbcSignalMirror, AscRecorder
|
|
86
|
+
|
|
87
|
+
bus = can.Bus(interface="pcan", channel="USBBUS1", bitrate=500000)
|
|
88
|
+
tap = TappedBus(bus, label="1")
|
|
89
|
+
|
|
90
|
+
vehicle = DbcSignalMirror(
|
|
91
|
+
"controller.dbc", tap,
|
|
92
|
+
auto_start_predicate=lambda m: "Vector_XXX" in (m.senders or []),
|
|
93
|
+
skip_name_prefixes=("Diag_", "Tester_"),
|
|
94
|
+
ignore_frame_ids={0x2F9},
|
|
95
|
+
)
|
|
96
|
+
vehicle.start() # 含无 DBC 周期的报文,按 0.1s 发
|
|
97
|
+
vehicle.update_signal("CCP_CFCAN_FrP02", "SysPwrMd", 2)
|
|
98
|
+
value = vehicle.read_signal("MSM_CFCAN_FrP03", "StrgWhlHeatLvl")
|
|
99
|
+
|
|
100
|
+
recorder = AscRecorder(
|
|
101
|
+
[tap], output_dir="can_logs",
|
|
102
|
+
namer=lambda case_id: case_id or "can",
|
|
103
|
+
)
|
|
104
|
+
recorder.start(case="WheelHeat_001")
|
|
105
|
+
...
|
|
106
|
+
recorder.stop()
|
|
107
|
+
vehicle.shutdown()
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## 与 `drv_can.py` 的行为对齐点
|
|
111
|
+
|
|
112
|
+
这三个坑都在台架上踩过,抽取时**原样保留**,改动前请先看对应注释:
|
|
113
|
+
|
|
114
|
+
1. **无 DBC 周期的报文也要发**:`start()` 对 `cycle_time` 为空/0 的报文按
|
|
115
|
+
`default_cycle_s`(0.1s)发送。整车 DBC 常把 EnRun/唤醒类报文写成无周期,
|
|
116
|
+
而它们是控制器工作的前置条件,缺发会导致控制器完全不响应。
|
|
117
|
+
2. **编码 `strict=False`**:OEM DBC 初始值常超物理范围(如座椅位置 127=SNA),
|
|
118
|
+
关掉范围断言后仍按 DBC 缩放/位打包,与真节点行为一致。
|
|
119
|
+
3. **写入前 coerce 数值字符串**:CSV/配置来源是 `"3"`、`"1.75"`,
|
|
120
|
+
直接编码整型/枚举信号会 `KeyError`,`update_signal(s)` 内部统一转 int/float。
|
|
121
|
+
|
|
122
|
+
## 替换到业务框架
|
|
123
|
+
|
|
124
|
+
| 业务框架现有实现 | 本包对应 |
|
|
125
|
+
|---|---|
|
|
126
|
+
| `src/drv/drv_can.py::TappedBus` / `_TappedPeriodicTask` | `TappedBus` / `TappedPeriodicTask` |
|
|
127
|
+
| `src/drv/drv_can.py::VehicleCanBus` | `DbcSignalMirror`(保留 `build_can_message` / `start_manual_periodic` / `stop_periodic_message` / `resume_periodic_message` / `send_raw_message` / `recv_frame` 旧名别名) |
|
|
128
|
+
| `src/drv/drv_asc_logger.py::CaseCanRecorder` | `AscRecorder(namer=...)`(提供 `CaseCanRecorder` 别名) |
|
|
129
|
+
|
|
130
|
+
策略:业务项目保留原文件改为薄适配器(继承 / 组合),对外方法签名不变,
|
|
131
|
+
逐个模块切换,每切一个跑一次全量回归。
|
|
132
|
+
|
|
133
|
+
## 测试
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
python -m pytest
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
单测基于内置最小 DBC 与 FakeBus,不依赖真实 PCAN 硬件、不依赖业务项目的 DBC / 用例表。
|
|
140
|
+
|
|
141
|
+
## 版本策略
|
|
142
|
+
|
|
143
|
+
- SemVer,tag 形如 `v0.2.0`,tag 不可变
|
|
144
|
+
- 破坏性变更升主/次版本并写 CHANGELOG
|
|
145
|
+
- 依赖上下限锁定,防 `python-can` / `cantools` 大版本 API 漂移
|
|
146
|
+
|
|
147
|
+
## 变更记录
|
|
148
|
+
|
|
149
|
+
- **0.2.0**:范围收缩为 `drv_can.py` + `drv_asc_logger.py` 两块来源;
|
|
150
|
+
删除 `FeedbackReader`(原 `MeasurementObserver`)与 `SignalResolver`(原 `app_real_bench`);
|
|
151
|
+
同步业务项目最新修复(无周期报文默认发送、`strict=False`、数值字符串 coerce、stop 排空);
|
|
152
|
+
分发名改为 `python-cantools`。
|
|
153
|
+
- **0.1.0**:首版,含 mirror / tapped / resolver / feedback / asc。
|
|
154
|
+
|
|
155
|
+
## 许可
|
|
156
|
+
|
|
157
|
+
内部专有,仅限授权项目使用,未经许可不得外传。详见 `LICENSE`。
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "python-cantools"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "CAN bench core extracted from HIL frameworks: DBC signal mirror, tapped bus and ASC recorder"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "LicenseRef-Proprietary"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "HIL Platform Team" }]
|
|
14
|
+
keywords = ["can", "dbc", "cantools", "python-can", "hil", "asc", "automotive"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Topic :: Software Development :: Testing",
|
|
20
|
+
]
|
|
21
|
+
dependencies = [
|
|
22
|
+
"python-can>=4.4,<6",
|
|
23
|
+
"cantools>=22.0,<50",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
dev = [
|
|
28
|
+
"pytest>=8.0,<10",
|
|
29
|
+
"build>=1.2",
|
|
30
|
+
"twine>=6.0",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Homepage = "https://github.com/Ericcoool/python-cantools"
|
|
35
|
+
Repository = "https://github.com/Ericcoool/python-cantools.git"
|
|
36
|
+
Issues = "https://github.com/Ericcoool/python-cantools/issues"
|
|
37
|
+
Changelog = "https://github.com/Ericcoool/python-cantools/blob/main/README.md#变更记录"
|
|
38
|
+
|
|
39
|
+
[tool.setuptools.packages.find]
|
|
40
|
+
where = ["src"]
|
|
41
|
+
|
|
42
|
+
[tool.pytest.ini_options]
|
|
43
|
+
testpaths = ["tests"]
|
|
44
|
+
addopts = "-q"
|
|
45
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""canlink — 可复用的 CAN 台架通信内核。
|
|
2
|
+
|
|
3
|
+
抽取自 HIL 测试框架的 `src/drv/drv_can.py` 与 `src/drv/drv_asc_logger.py`,
|
|
4
|
+
只保留与项目无关的三块通用能力:
|
|
5
|
+
|
|
6
|
+
TappedBus 单总线搭线(收/发广播 + 周期任务快照)
|
|
7
|
+
DbcSignalMirror DBC 信号镜像 + 周期发送 + 后台解码缓存
|
|
8
|
+
AscRecorder ASC 录制(硬件时基对齐 + 周期 Tx 重放 + 分卷)
|
|
9
|
+
|
|
10
|
+
业务约定(发送者过滤、报文前缀、单位换算、通道映射、NTC 设压、电源控制、
|
|
11
|
+
UDS 诊断、关键字翻译)一律由调用方注入或留在业务项目,本包不 import 任何业务项目。
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from .asc import AscRecorder, asc_channel, format_asc_data, format_frame_id, safe_filename
|
|
15
|
+
from .errors import CanLinkError, FrameDecodeError, MessageNotFound, SignalNotFound
|
|
16
|
+
from .mirror import DbcSignalMirror
|
|
17
|
+
from .tapped import TappedBus, TappedPeriodicTask
|
|
18
|
+
|
|
19
|
+
__version__ = "0.2.0"
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"TappedBus",
|
|
23
|
+
"TappedPeriodicTask",
|
|
24
|
+
"DbcSignalMirror",
|
|
25
|
+
"AscRecorder",
|
|
26
|
+
"asc_channel",
|
|
27
|
+
"format_frame_id",
|
|
28
|
+
"format_asc_data",
|
|
29
|
+
"safe_filename",
|
|
30
|
+
"CanLinkError",
|
|
31
|
+
"MessageNotFound",
|
|
32
|
+
"SignalNotFound",
|
|
33
|
+
"FrameDecodeError",
|
|
34
|
+
]
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""ASC 报文录制内核。
|
|
2
|
+
|
|
3
|
+
从 HIL 框架的 "CaseCanRecorder" 抽取,保留三个通用算法:
|
|
4
|
+
|
|
5
|
+
1. 硬件时基对齐:Rx 帧用驱动时间戳,Tx 帧用单调时钟;通过
|
|
6
|
+
offset = monotonic_now - msg.timestamp 的最小采样值估计两时钟偏差,
|
|
7
|
+
在收到第一帧 Rx 之前缓存 Tx,校准后统一重放,保证时间轴单调。
|
|
8
|
+
2. 周期 Tx 重放:PCAN 不回显自发帧,按 TappedBus.periodic_snapshot()
|
|
9
|
+
的周期在后台线程重放写入。
|
|
10
|
+
3. 按大小分卷:超过 max_file_mb 自动 "End Triggerblock" 并新建文件。
|
|
11
|
+
|
|
12
|
+
业务约定(每用例一个文件、caseId 提取规则)改为 namer 回调注入:
|
|
13
|
+
namer(case_name) -> 文件名主干(不含时间戳/分卷后缀)
|
|
14
|
+
不传时使用通用安全文件名。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
from datetime import datetime
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, Callable, List, Optional
|
|
25
|
+
|
|
26
|
+
# --------------------------------------------------------------------------- #
|
|
27
|
+
# 行格式(协议无关)
|
|
28
|
+
# --------------------------------------------------------------------------- #
|
|
29
|
+
def safe_filename(value: str, limit: int = 120) -> str:
|
|
30
|
+
value = re.sub(r"[^\w\u4e00-\u9fff.-]+", "_", str(value or ""))
|
|
31
|
+
return value.strip("._")[:limit] or "can"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def asc_channel(value: Any) -> str:
|
|
35
|
+
match = re.search(r"(\d+)$", str(value))
|
|
36
|
+
return match.group(1) if match else "1"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def format_frame_id(msg: Any) -> str:
|
|
40
|
+
frame_id = f"{msg.arbitration_id:X}"
|
|
41
|
+
return f"{frame_id}x" if msg.is_extended_id else frame_id
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def format_asc_data(data) -> str:
|
|
45
|
+
return " ".join(f"{byte:02X}" for byte in bytes(data))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def default_namer(case_name: Optional[str]) -> str:
|
|
49
|
+
return safe_filename(case_name or "can")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# --------------------------------------------------------------------------- #
|
|
53
|
+
class AscRecorder:
|
|
54
|
+
"""把若干搭线总线上的收发报文录制成 ASC 文件(支持多卷)。"""
|
|
55
|
+
|
|
56
|
+
_FLUSH_EVERY = 100
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
taps: List[Any],
|
|
61
|
+
*,
|
|
62
|
+
output_dir: Any = "can_logs",
|
|
63
|
+
namer: Optional[Callable[[Optional[str]], str]] = None,
|
|
64
|
+
case_name: Optional[str] = None,
|
|
65
|
+
enabled: bool = True,
|
|
66
|
+
max_file_mb: float = 20,
|
|
67
|
+
):
|
|
68
|
+
self.taps = list(taps)
|
|
69
|
+
self.output_dir = Path(output_dir)
|
|
70
|
+
self.namer = namer or default_namer
|
|
71
|
+
self.case_name = case_name
|
|
72
|
+
self.enabled = enabled
|
|
73
|
+
self.max_file_mb = max_file_mb
|
|
74
|
+
|
|
75
|
+
self.started = False
|
|
76
|
+
self.path: Optional[Path] = None
|
|
77
|
+
self.file = None
|
|
78
|
+
self.thread: Optional[threading.Thread] = None
|
|
79
|
+
self.stop_event = threading.Event()
|
|
80
|
+
self.write_lock = threading.Lock()
|
|
81
|
+
self.start_mono: Optional[float] = None
|
|
82
|
+
self.t0_hw: Optional[float] = None
|
|
83
|
+
self.offset: Optional[float] = None
|
|
84
|
+
self.pending_tx: list = []
|
|
85
|
+
self.next_emit: dict = {}
|
|
86
|
+
self.write_count = 0
|
|
87
|
+
self.part = 0
|
|
88
|
+
|
|
89
|
+
# ---- 生命周期 ------------------------------------------------------- #
|
|
90
|
+
def start(self, case: Optional[str] = None) -> Optional[Path]:
|
|
91
|
+
if case is not None:
|
|
92
|
+
self.case_name = case
|
|
93
|
+
if not self.enabled or self.started:
|
|
94
|
+
return self.path if self.started else None
|
|
95
|
+
self._start()
|
|
96
|
+
self.started = True
|
|
97
|
+
return self.path
|
|
98
|
+
|
|
99
|
+
def stop(self) -> Optional[Path]:
|
|
100
|
+
if not self.started:
|
|
101
|
+
return None
|
|
102
|
+
self.stop_event.set()
|
|
103
|
+
if self.thread is not None:
|
|
104
|
+
self.thread.join(timeout=2.0)
|
|
105
|
+
for tap in self.taps:
|
|
106
|
+
tap.remove_listener(self._on_message)
|
|
107
|
+
if self.file is not None:
|
|
108
|
+
self.file.write("End Triggerblock\n")
|
|
109
|
+
self.file.flush()
|
|
110
|
+
self.file.close()
|
|
111
|
+
self.file = None
|
|
112
|
+
self.started = False
|
|
113
|
+
return self.path
|
|
114
|
+
|
|
115
|
+
# ---- 文件与分卷 ----------------------------------------------------- #
|
|
116
|
+
def _new_file(self) -> None:
|
|
117
|
+
self.output_dir.mkdir(parents=True, exist_ok=True)
|
|
118
|
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
119
|
+
stem = safe_filename(self.namer(self.case_name))
|
|
120
|
+
suffix = f"_p{self.part}" if self.part else ""
|
|
121
|
+
self.path = self.output_dir / f"{stem}_{timestamp}{suffix}.asc"
|
|
122
|
+
self.file = self.path.open("w", newline="", encoding="utf-8")
|
|
123
|
+
self._write_header()
|
|
124
|
+
self.write_count = 0
|
|
125
|
+
|
|
126
|
+
def _start(self) -> None:
|
|
127
|
+
self.part = 0
|
|
128
|
+
self.stop_event.clear()
|
|
129
|
+
self._new_file()
|
|
130
|
+
self.start_mono = time.monotonic()
|
|
131
|
+
for tap in self.taps:
|
|
132
|
+
tap.add_listener(self._on_message)
|
|
133
|
+
self.thread = threading.Thread(target=self._run, name="asc-recorder", daemon=True)
|
|
134
|
+
self.thread.start()
|
|
135
|
+
|
|
136
|
+
def _rotate_if_needed(self) -> None:
|
|
137
|
+
if self.file is None:
|
|
138
|
+
return
|
|
139
|
+
if self.file.tell() >= self.max_file_mb * 1024 * 1024:
|
|
140
|
+
self.file.write("End Triggerblock\n")
|
|
141
|
+
self.file.flush()
|
|
142
|
+
self.file.close()
|
|
143
|
+
self.part += 1
|
|
144
|
+
self._new_file()
|
|
145
|
+
|
|
146
|
+
def _write_header(self) -> None:
|
|
147
|
+
started_at = datetime.now().strftime("%a %b %d %H:%M:%S.%f %Y")
|
|
148
|
+
self.file.write(f"date {started_at}\n")
|
|
149
|
+
self.file.write("base hex timestamps relative\n")
|
|
150
|
+
self.file.write("internal events logged\n")
|
|
151
|
+
self.file.write("Begin Triggerblock\n")
|
|
152
|
+
|
|
153
|
+
# ---- 时基对齐 ------------------------------------------------------- #
|
|
154
|
+
def _on_message(self, label: str, msg: Any, direction: str) -> None:
|
|
155
|
+
now = time.monotonic()
|
|
156
|
+
with self.write_lock:
|
|
157
|
+
if direction == "Rx":
|
|
158
|
+
sample = now - msg.timestamp
|
|
159
|
+
if self.offset is None or sample < self.offset:
|
|
160
|
+
self.offset = sample
|
|
161
|
+
if self.t0_hw is None:
|
|
162
|
+
self.t0_hw = self.start_mono - self.offset
|
|
163
|
+
for mono_time, pending_label, pending_msg in self.pending_tx:
|
|
164
|
+
self._write_line(
|
|
165
|
+
pending_label, pending_msg, "Tx", mono_time - self.offset
|
|
166
|
+
)
|
|
167
|
+
self.pending_tx.clear()
|
|
168
|
+
self._write_line(label, msg, "Rx", msg.timestamp)
|
|
169
|
+
else:
|
|
170
|
+
if self.t0_hw is None or self.offset is None:
|
|
171
|
+
self.pending_tx.append((now, label, msg))
|
|
172
|
+
return
|
|
173
|
+
self._write_line(label, msg, "Tx", now - self.offset)
|
|
174
|
+
|
|
175
|
+
def _write_line(self, label: str, msg: Any, direction: str, hw_time: float) -> None:
|
|
176
|
+
if self.t0_hw is None or self.file is None:
|
|
177
|
+
return
|
|
178
|
+
relative_time = hw_time - self.t0_hw
|
|
179
|
+
self.file.write(
|
|
180
|
+
f"{relative_time:12.6f} {asc_channel(label)} "
|
|
181
|
+
f"{format_frame_id(msg):<15} {direction} d {msg.dlc} "
|
|
182
|
+
f"{format_asc_data(msg.data)}\n"
|
|
183
|
+
)
|
|
184
|
+
self.write_count += 1
|
|
185
|
+
if self.write_count % self._FLUSH_EVERY == 0:
|
|
186
|
+
self.file.flush()
|
|
187
|
+
self._rotate_if_needed()
|
|
188
|
+
|
|
189
|
+
# ---- 周期 Tx 重放 --------------------------------------------------- #
|
|
190
|
+
def _run(self) -> None:
|
|
191
|
+
while not self.stop_event.is_set():
|
|
192
|
+
self._emit_due_periodic()
|
|
193
|
+
self.stop_event.wait(0.01)
|
|
194
|
+
|
|
195
|
+
def _emit_due_periodic(self) -> None:
|
|
196
|
+
now = time.monotonic()
|
|
197
|
+
with self.write_lock:
|
|
198
|
+
calibrated = self.t0_hw is not None and self.offset is not None
|
|
199
|
+
for tap in self.taps:
|
|
200
|
+
for arbitration_id, cycle_s, msg in tap.periodic_snapshot():
|
|
201
|
+
if not cycle_s or cycle_s <= 0:
|
|
202
|
+
continue
|
|
203
|
+
key = (tap.label, arbitration_id)
|
|
204
|
+
due = self.next_emit.get(key)
|
|
205
|
+
if due is None or now - due > max(1.0, cycle_s * 5):
|
|
206
|
+
self.next_emit[key] = now + cycle_s
|
|
207
|
+
continue
|
|
208
|
+
emitted = 0
|
|
209
|
+
while due <= now and emitted < 10:
|
|
210
|
+
if calibrated:
|
|
211
|
+
self._write_line(tap.label, msg, "Tx", due - self.offset)
|
|
212
|
+
elif len(self.pending_tx) < 5000:
|
|
213
|
+
self.pending_tx.append((due, tap.label, msg))
|
|
214
|
+
due += cycle_s
|
|
215
|
+
emitted += 1
|
|
216
|
+
self.next_emit[key] = due
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
# 兼容旧命名:业务项目曾用 CaseCanRecorder
|
|
220
|
+
CaseCanRecorder = AscRecorder
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""统一异常类型。业务项目可捕获 CanLinkError 做统一处理。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CanLinkError(RuntimeError):
|
|
7
|
+
"""canlink 操作失败的基类。"""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class MessageNotFound(CanLinkError):
|
|
11
|
+
"""DBC 中找不到指定报文(按名称或帧 ID)。"""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SignalNotFound(CanLinkError):
|
|
15
|
+
"""指定报文中不存在该信号。"""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class FrameDecodeError(CanLinkError):
|
|
19
|
+
"""报文解码失败(长度不符、DBC 未定义等)。"""
|