python-cantools 0.2.0__py3-none-any.whl
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.
- canlink/__init__.py +34 -0
- canlink/asc.py +220 -0
- canlink/errors.py +19 -0
- canlink/mirror.py +361 -0
- canlink/tapped.py +144 -0
- python_cantools-0.2.0.dist-info/METADATA +183 -0
- python_cantools-0.2.0.dist-info/RECORD +10 -0
- python_cantools-0.2.0.dist-info/WHEEL +5 -0
- python_cantools-0.2.0.dist-info/licenses/LICENSE +10 -0
- python_cantools-0.2.0.dist-info/top_level.txt +1 -0
canlink/__init__.py
ADDED
|
@@ -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
|
+
]
|
canlink/asc.py
ADDED
|
@@ -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
|
canlink/errors.py
ADDED
|
@@ -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 未定义等)。"""
|
canlink/mirror.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"""DBC 信号镜像:周期发送 + 信号更新 + 后台解码缓存。
|
|
2
|
+
|
|
3
|
+
抽取自 tester_as33_frame / tester_pdcm_frame 的 `src/drv/drv_can.py::VehicleCanBus`,
|
|
4
|
+
保留其中与项目无关的通用机制,业务约定全部由调用方注入:
|
|
5
|
+
|
|
6
|
+
auto_start_predicate(msg) 哪些报文在 start() 时自动周期发送
|
|
7
|
+
skip_name_prefixes 不参与周期广播的报文名前缀(如 ("Diag_", "Tester_"))
|
|
8
|
+
ignore_frame_ids 解码缓存要忽略的帧(通常是本端自发帧)
|
|
9
|
+
default_cycle_s DBC 未定义 GenMsgCycleTime 时的兜底周期
|
|
10
|
+
|
|
11
|
+
与 drv_can.py 的行为对齐点(都是台架踩过的坑,不要"优化"掉):
|
|
12
|
+
|
|
13
|
+
1. **无周期报文也要发**:`start()` 对 DBC 里没有 cycle_time 的报文按
|
|
14
|
+
`default_cycle_s`(默认 0.1s)发送。整车 DBC 常把 EnRun/唤醒类报文写成无周期,
|
|
15
|
+
而它们是控制器工作的前置条件,缺发会导致控制器根本不响应。
|
|
16
|
+
2. **编码用 strict=False**:OEM DBC 初始值常超出信号物理范围(如座椅位置 127=SNA),
|
|
17
|
+
关掉范围断言后仍按 DBC 缩放/位打包,与真节点行为一致。
|
|
18
|
+
3. **信号值先归一**:CSV/配置里传进来的是字符串("3"、"1.75"),直接编码枚举信号
|
|
19
|
+
会 KeyError,所以 update 前统一 coerce 成 int/float。
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import logging
|
|
25
|
+
import threading
|
|
26
|
+
import time
|
|
27
|
+
from typing import Any, Callable, Dict, Iterable, Optional
|
|
28
|
+
|
|
29
|
+
import can
|
|
30
|
+
import cantools
|
|
31
|
+
|
|
32
|
+
from .errors import MessageNotFound, SignalNotFound
|
|
33
|
+
|
|
34
|
+
log = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class DbcSignalMirror:
|
|
38
|
+
"""DBC 信号镜像 + 周期发送 + 后台接收解码缓存。"""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
dbc_file: str,
|
|
43
|
+
bus: Any,
|
|
44
|
+
*,
|
|
45
|
+
auto_start_predicate: Optional[Callable[[Any], bool]] = None,
|
|
46
|
+
skip_name_prefixes: Iterable[str] = (),
|
|
47
|
+
ignore_frame_ids: Optional[Iterable[int]] = None,
|
|
48
|
+
decode_choices: bool = False,
|
|
49
|
+
strict_encode: bool = False,
|
|
50
|
+
default_cycle_s: float = 0.1,
|
|
51
|
+
max_dlc: int = 8,
|
|
52
|
+
stop_drain_s: float = 0.2,
|
|
53
|
+
):
|
|
54
|
+
self.db = cantools.database.load_file(dbc_file)
|
|
55
|
+
self.bus = bus
|
|
56
|
+
self.auto_start_predicate = auto_start_predicate
|
|
57
|
+
self.skip_name_prefixes = tuple(skip_name_prefixes or ())
|
|
58
|
+
self.ignore_frame_ids = set(ignore_frame_ids or ())
|
|
59
|
+
self.decode_choices = decode_choices
|
|
60
|
+
self.strict_encode = strict_encode
|
|
61
|
+
self.default_cycle_s = default_cycle_s
|
|
62
|
+
self.max_dlc = max_dlc
|
|
63
|
+
self.stop_drain_s = stop_drain_s
|
|
64
|
+
|
|
65
|
+
self.tasks: Dict[str, Any] = {}
|
|
66
|
+
self.task_cycles: Dict[str, float] = {}
|
|
67
|
+
self.signal_values: Dict[str, Dict[str, Any]] = {}
|
|
68
|
+
self.lock = threading.RLock()
|
|
69
|
+
self.stop_event = threading.Event()
|
|
70
|
+
self.rx_thread: Optional[threading.Thread] = None
|
|
71
|
+
self._latest: Dict[str, Dict[str, Any]] = {}
|
|
72
|
+
self._frame_times: Dict[str, float] = {}
|
|
73
|
+
self._rx_lock = threading.Lock()
|
|
74
|
+
|
|
75
|
+
# ---- 基础 ----------------------------------------------------------- #
|
|
76
|
+
def message(self, message_name: str):
|
|
77
|
+
try:
|
|
78
|
+
return self.db.get_message_by_name(message_name)
|
|
79
|
+
except (KeyError, ValueError) as exc:
|
|
80
|
+
raise MessageNotFound(f"DBC 中找不到报文 {message_name!r}") from exc
|
|
81
|
+
|
|
82
|
+
get_message = message
|
|
83
|
+
|
|
84
|
+
def init_message_signals(self, msg) -> Dict[str, Any]:
|
|
85
|
+
"""按 DBC initial 值初始化;枚举名字符串无法写入,退化为 0。"""
|
|
86
|
+
return {
|
|
87
|
+
sig.name: (sig.initial if not isinstance(sig.initial, str) else 0) or 0
|
|
88
|
+
for sig in msg.signals
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
def register_message(self, message_name: str) -> None:
|
|
92
|
+
if message_name in self.signal_values:
|
|
93
|
+
return
|
|
94
|
+
self.signal_values[message_name] = self.init_message_signals(
|
|
95
|
+
self.message(message_name)
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
def resolve_cycle_s(self, message_name: str, cycle_s: Optional[float] = None) -> float:
|
|
99
|
+
"""显式周期 > DBC GenMsgCycleTime > default_cycle_s。"""
|
|
100
|
+
if cycle_s is not None:
|
|
101
|
+
return float(cycle_s)
|
|
102
|
+
msg = self.message(message_name)
|
|
103
|
+
if msg.cycle_time and msg.cycle_time > 0:
|
|
104
|
+
return msg.cycle_time / 1000.0
|
|
105
|
+
return self.default_cycle_s
|
|
106
|
+
|
|
107
|
+
# ---- 编码 ----------------------------------------------------------- #
|
|
108
|
+
@staticmethod
|
|
109
|
+
def _coerce_value(value: Any) -> Any:
|
|
110
|
+
"""数值字符串 → int/float(CSV 前置列等来源是字符串)。"""
|
|
111
|
+
if isinstance(value, str):
|
|
112
|
+
s = value.strip()
|
|
113
|
+
try:
|
|
114
|
+
return int(s)
|
|
115
|
+
except ValueError:
|
|
116
|
+
pass
|
|
117
|
+
try:
|
|
118
|
+
return float(s)
|
|
119
|
+
except ValueError:
|
|
120
|
+
pass
|
|
121
|
+
return value
|
|
122
|
+
|
|
123
|
+
def build_message(self, message_name: str) -> can.Message:
|
|
124
|
+
msg = self.message(message_name)
|
|
125
|
+
with self.lock:
|
|
126
|
+
if message_name not in self.signal_values:
|
|
127
|
+
self.register_message(message_name)
|
|
128
|
+
signals = self.signal_values[message_name].copy()
|
|
129
|
+
try:
|
|
130
|
+
data = self.db.encode_message(
|
|
131
|
+
message_name, signals, strict=self.strict_encode
|
|
132
|
+
)
|
|
133
|
+
except Exception as exc:
|
|
134
|
+
raise MessageNotFound(f"报文 {message_name} 编码失败: {exc}") from exc
|
|
135
|
+
return can.Message(
|
|
136
|
+
arbitration_id=msg.frame_id,
|
|
137
|
+
data=data,
|
|
138
|
+
is_extended_id=msg.is_extended_frame,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
# 业务旧命名
|
|
142
|
+
build_can_message = build_message
|
|
143
|
+
|
|
144
|
+
# ---- 信号更新 ------------------------------------------------------- #
|
|
145
|
+
def update_signal(self, message_name: str, signal_name: str, value: Any) -> None:
|
|
146
|
+
self.update_signals(message_name, {signal_name: value})
|
|
147
|
+
|
|
148
|
+
def update_signals(self, message_name: str, signal_dict: Dict[str, Any]) -> None:
|
|
149
|
+
with self.lock:
|
|
150
|
+
if message_name not in self.signal_values:
|
|
151
|
+
self.register_message(message_name)
|
|
152
|
+
bucket = self.signal_values[message_name]
|
|
153
|
+
for name in signal_dict:
|
|
154
|
+
if name not in bucket:
|
|
155
|
+
raise SignalNotFound(f"报文 {message_name} 中不存在信号: {name}")
|
|
156
|
+
for name, value in signal_dict.items():
|
|
157
|
+
bucket[name] = self._coerce_value(value)
|
|
158
|
+
self.refresh_message(message_name)
|
|
159
|
+
|
|
160
|
+
def refresh_message(self, message_name: str) -> None:
|
|
161
|
+
task = self.tasks.get(message_name)
|
|
162
|
+
if task is not None:
|
|
163
|
+
task.modify_data(self.build_message(message_name))
|
|
164
|
+
|
|
165
|
+
# ---- 周期任务 ------------------------------------------------------- #
|
|
166
|
+
def start_periodic(
|
|
167
|
+
self,
|
|
168
|
+
message_name: str,
|
|
169
|
+
signals: Optional[Dict[str, Any]] = None,
|
|
170
|
+
cycle_s: Optional[float] = None,
|
|
171
|
+
):
|
|
172
|
+
"""启动(或复用)某报文的周期发送。"""
|
|
173
|
+
if signals:
|
|
174
|
+
self.update_signals(message_name, signals)
|
|
175
|
+
can_msg = self.build_message(message_name)
|
|
176
|
+
resolved = self.resolve_cycle_s(message_name, cycle_s)
|
|
177
|
+
|
|
178
|
+
old_task = self.tasks.get(message_name)
|
|
179
|
+
if old_task is not None and self.task_cycles.get(message_name) == resolved:
|
|
180
|
+
old_task.modify_data(can_msg)
|
|
181
|
+
return old_task
|
|
182
|
+
if old_task is not None:
|
|
183
|
+
old_task.stop()
|
|
184
|
+
task = self.bus.send_periodic(can_msg, resolved)
|
|
185
|
+
self.tasks[message_name] = task
|
|
186
|
+
self.task_cycles[message_name] = resolved
|
|
187
|
+
return task
|
|
188
|
+
|
|
189
|
+
# 业务旧命名
|
|
190
|
+
start_manual_periodic = start_periodic
|
|
191
|
+
|
|
192
|
+
def stop_periodic(self, message_name: Optional[str] = None) -> None:
|
|
193
|
+
if message_name is None:
|
|
194
|
+
for name, task in list(self.tasks.items()):
|
|
195
|
+
if task is not None:
|
|
196
|
+
task.stop()
|
|
197
|
+
self.tasks.clear()
|
|
198
|
+
return
|
|
199
|
+
task = self.tasks.pop(message_name, None)
|
|
200
|
+
if task is not None:
|
|
201
|
+
task.stop()
|
|
202
|
+
|
|
203
|
+
stop_periodic_message = stop_periodic
|
|
204
|
+
|
|
205
|
+
def resume_periodic(self, message_name: str, cycle_s: Optional[float] = None) -> None:
|
|
206
|
+
old_task = self.tasks.get(message_name)
|
|
207
|
+
if old_task is not None:
|
|
208
|
+
old_task.stop()
|
|
209
|
+
resolved = self.resolve_cycle_s(
|
|
210
|
+
message_name, cycle_s or self.task_cycles.get(message_name)
|
|
211
|
+
)
|
|
212
|
+
self.tasks[message_name] = self.bus.send_periodic(
|
|
213
|
+
self.build_message(message_name), resolved
|
|
214
|
+
)
|
|
215
|
+
self.task_cycles[message_name] = resolved
|
|
216
|
+
|
|
217
|
+
resume_periodic_message = resume_periodic
|
|
218
|
+
|
|
219
|
+
def _should_auto_start(self, msg) -> bool:
|
|
220
|
+
if self.skip_name_prefixes and msg.name.startswith(self.skip_name_prefixes):
|
|
221
|
+
return False
|
|
222
|
+
if self.auto_start_predicate is not None:
|
|
223
|
+
return bool(self.auto_start_predicate(msg))
|
|
224
|
+
return True
|
|
225
|
+
|
|
226
|
+
def start(self) -> None:
|
|
227
|
+
"""按 predicate 启动周期报文(无 DBC 周期的也按默认周期发),并开解码线程。"""
|
|
228
|
+
for msg in self.db.messages:
|
|
229
|
+
if not self._should_auto_start(msg):
|
|
230
|
+
continue
|
|
231
|
+
cycle_s = (
|
|
232
|
+
msg.cycle_time / 1000.0
|
|
233
|
+
if (msg.cycle_time and msg.cycle_time > 0)
|
|
234
|
+
else self.default_cycle_s
|
|
235
|
+
)
|
|
236
|
+
self.register_message(msg.name)
|
|
237
|
+
self.start_periodic(msg.name, cycle_s=cycle_s)
|
|
238
|
+
self.start_rx_thread()
|
|
239
|
+
|
|
240
|
+
def restore_defaults(self, predicate: Optional[Callable[[Any], bool]] = None) -> None:
|
|
241
|
+
"""把所有周期报文信号恢复为 DBC initial 值并重启发送。
|
|
242
|
+
|
|
243
|
+
predicate 不传时沿用 auto_start_predicate;skip_name_prefixes 始终生效。
|
|
244
|
+
"""
|
|
245
|
+
pred = predicate or self.auto_start_predicate
|
|
246
|
+
for msg in self.db.messages:
|
|
247
|
+
if self.skip_name_prefixes and msg.name.startswith(self.skip_name_prefixes):
|
|
248
|
+
continue
|
|
249
|
+
if pred is not None and not pred(msg):
|
|
250
|
+
continue
|
|
251
|
+
with self.lock:
|
|
252
|
+
self.signal_values[msg.name] = self.init_message_signals(msg)
|
|
253
|
+
cycle_s = (
|
|
254
|
+
msg.cycle_time / 1000.0
|
|
255
|
+
if (msg.cycle_time and msg.cycle_time > 0)
|
|
256
|
+
else self.default_cycle_s
|
|
257
|
+
)
|
|
258
|
+
self.start_periodic(msg.name, cycle_s=cycle_s)
|
|
259
|
+
|
|
260
|
+
# ---- 裸帧收发 ------------------------------------------------------- #
|
|
261
|
+
def send_raw(self, message_name: str, data) -> can.Message:
|
|
262
|
+
dbc_msg = self.message(message_name)
|
|
263
|
+
raw = bytearray(data)
|
|
264
|
+
if len(raw) > self.max_dlc:
|
|
265
|
+
raise ValueError(f"{message_name} data 长度不能超过 {self.max_dlc} 字节: {len(raw)}")
|
|
266
|
+
can_msg = can.Message(
|
|
267
|
+
arbitration_id=dbc_msg.frame_id,
|
|
268
|
+
data=raw,
|
|
269
|
+
is_extended_id=dbc_msg.is_extended_frame,
|
|
270
|
+
)
|
|
271
|
+
self.bus.send(can_msg)
|
|
272
|
+
return can_msg
|
|
273
|
+
|
|
274
|
+
send_raw_message = send_raw
|
|
275
|
+
|
|
276
|
+
def recv_frame_by_id(self, frame_id: int, timeout: float = 1.0) -> Optional[can.Message]:
|
|
277
|
+
deadline = time.monotonic() + timeout
|
|
278
|
+
while True:
|
|
279
|
+
remaining = deadline - time.monotonic()
|
|
280
|
+
if remaining <= 0:
|
|
281
|
+
return None
|
|
282
|
+
msg = self.bus.recv(timeout=remaining)
|
|
283
|
+
if msg is None:
|
|
284
|
+
return None
|
|
285
|
+
if msg.arbitration_id == frame_id:
|
|
286
|
+
return msg
|
|
287
|
+
|
|
288
|
+
recv_frame = recv_frame_by_id
|
|
289
|
+
|
|
290
|
+
# ---- 后台接收:解码缓存 + 帧时间戳 ---------------------------------- #
|
|
291
|
+
def start_rx_thread(self) -> None:
|
|
292
|
+
if self.rx_thread and self.rx_thread.is_alive():
|
|
293
|
+
return
|
|
294
|
+
self.stop_event.clear()
|
|
295
|
+
self.rx_thread = threading.Thread(
|
|
296
|
+
target=self._rx_loop, name="canlink-rx", daemon=True
|
|
297
|
+
)
|
|
298
|
+
self.rx_thread.start()
|
|
299
|
+
|
|
300
|
+
def _rx_loop(self) -> None:
|
|
301
|
+
while not self.stop_event.is_set():
|
|
302
|
+
try:
|
|
303
|
+
msg = self.bus.recv(timeout=0.2)
|
|
304
|
+
except Exception as exc:
|
|
305
|
+
log.debug("rx loop error ignored: %s", exc)
|
|
306
|
+
time.sleep(0.05)
|
|
307
|
+
continue
|
|
308
|
+
if msg is None:
|
|
309
|
+
continue
|
|
310
|
+
if msg.arbitration_id in self.ignore_frame_ids:
|
|
311
|
+
continue
|
|
312
|
+
try:
|
|
313
|
+
dbc_msg = self.db.get_message_by_frame_id(msg.arbitration_id)
|
|
314
|
+
signals = dbc_msg.decode(msg.data, decode_choices=self.decode_choices)
|
|
315
|
+
except Exception:
|
|
316
|
+
continue
|
|
317
|
+
with self._rx_lock:
|
|
318
|
+
self._latest[dbc_msg.name] = signals
|
|
319
|
+
self._frame_times[dbc_msg.name] = time.monotonic()
|
|
320
|
+
|
|
321
|
+
def latest_signals(self, message_name: str) -> Dict[str, Any]:
|
|
322
|
+
with self._rx_lock:
|
|
323
|
+
return (self._latest.get(message_name) or {}).copy()
|
|
324
|
+
|
|
325
|
+
def last_frame_age(self, message_name: str) -> Optional[float]:
|
|
326
|
+
"""距该报文最后一帧的秒数;从未收到返回 None。"""
|
|
327
|
+
with self._rx_lock:
|
|
328
|
+
t = self._frame_times.get(message_name)
|
|
329
|
+
return None if t is None else time.monotonic() - t
|
|
330
|
+
|
|
331
|
+
def frame_count(self, message_name: str) -> int:
|
|
332
|
+
return 1 if self.last_frame_age(message_name) is not None else 0
|
|
333
|
+
|
|
334
|
+
def read_signal(self, message_name: str, signal_name: str) -> Any:
|
|
335
|
+
return self.latest_signals(message_name).get(signal_name)
|
|
336
|
+
|
|
337
|
+
# ---- 生命周期 ------------------------------------------------------- #
|
|
338
|
+
def stop(self) -> None:
|
|
339
|
+
self.stop_event.set()
|
|
340
|
+
if self.rx_thread and self.rx_thread.is_alive():
|
|
341
|
+
self.rx_thread.join(timeout=2.0)
|
|
342
|
+
for name, task in list(self.tasks.items()):
|
|
343
|
+
try:
|
|
344
|
+
task.stop()
|
|
345
|
+
except Exception as exc:
|
|
346
|
+
log.warning("stop periodic %s failed: %s", name, exc)
|
|
347
|
+
try:
|
|
348
|
+
self.bus.stop_all_periodic_tasks()
|
|
349
|
+
except Exception:
|
|
350
|
+
pass
|
|
351
|
+
self.tasks.clear()
|
|
352
|
+
if self.stop_drain_s:
|
|
353
|
+
# 给驱动一点时间把最后一次 stop 落地,避免紧接着重开总线失败
|
|
354
|
+
time.sleep(self.stop_drain_s)
|
|
355
|
+
|
|
356
|
+
def shutdown(self) -> None:
|
|
357
|
+
self.stop()
|
|
358
|
+
try:
|
|
359
|
+
self.bus.shutdown()
|
|
360
|
+
except Exception:
|
|
361
|
+
pass
|
canlink/tapped.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""总线搭线层:在单条物理总线上广播收/发报文,并维护周期任务快照。
|
|
2
|
+
|
|
3
|
+
背景:PCAN 等驱动在同一进程内只允许打开一条 bus,且自发帧不回显。
|
|
4
|
+
因此录音/旁路监听不能"另开一条通道",只能在 bus 外包一层 TappedBus,
|
|
5
|
+
把 recv/send/send_periodic 的报文复制给监听者;周期自发帧则由监听者
|
|
6
|
+
依据 periodic_snapshot() 按周期重放。
|
|
7
|
+
|
|
8
|
+
本模块不含任何项目专有约定。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from typing import Any, Callable, List, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
import can
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
Listener = Callable[[str, can.Message, str], None]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TappedPeriodicTask:
|
|
26
|
+
"""包装 send_periodic 任务:拦截 modify_data,同步更新搭线器的重放表。"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, task: Any, tap: "TappedBus", arbitration_id: Optional[int] = None):
|
|
29
|
+
self._task = task
|
|
30
|
+
self._tap = tap
|
|
31
|
+
self._arbitration_id = arbitration_id
|
|
32
|
+
|
|
33
|
+
def modify_data(self, msg: can.Message) -> None:
|
|
34
|
+
self._tap.update_periodic_message(msg)
|
|
35
|
+
self._task.modify_data(msg)
|
|
36
|
+
|
|
37
|
+
def stop(self) -> None:
|
|
38
|
+
self._task.stop()
|
|
39
|
+
if self._arbitration_id is not None:
|
|
40
|
+
self._tap.drop_periodic(self._arbitration_id, self)
|
|
41
|
+
|
|
42
|
+
def __getattr__(self, name: str):
|
|
43
|
+
return getattr(self._task, name)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class TappedBus:
|
|
47
|
+
"""包装 python-can Bus,把收发报文广播给监听者。
|
|
48
|
+
|
|
49
|
+
listener(label, msg, direction):direction 为 "Rx" 或 "Tx"。
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(self, bus: Any, label: str = "1", overrun_warn_s: float = 5.0):
|
|
53
|
+
self.bus = bus
|
|
54
|
+
self.label = label
|
|
55
|
+
self.overrun_warn_s = overrun_warn_s
|
|
56
|
+
self._listeners: List[Listener] = []
|
|
57
|
+
self._periodic: dict = {}
|
|
58
|
+
self._lock = threading.RLock()
|
|
59
|
+
self._last_overrun_warn = 0.0
|
|
60
|
+
|
|
61
|
+
# ---- 监听者 ----
|
|
62
|
+
def add_listener(self, listener: Listener) -> None:
|
|
63
|
+
with self._lock:
|
|
64
|
+
if listener not in self._listeners:
|
|
65
|
+
self._listeners.append(listener)
|
|
66
|
+
|
|
67
|
+
def remove_listener(self, listener: Listener) -> None:
|
|
68
|
+
with self._lock:
|
|
69
|
+
if listener in self._listeners:
|
|
70
|
+
self._listeners.remove(listener)
|
|
71
|
+
|
|
72
|
+
# ---- 周期任务快照(供 ASC 重放) ----
|
|
73
|
+
def periodic_snapshot(self) -> List[Tuple[int, float, can.Message]]:
|
|
74
|
+
with self._lock:
|
|
75
|
+
return [
|
|
76
|
+
(arbitration_id, entry["cycle_s"], entry["msg"])
|
|
77
|
+
for arbitration_id, entry in self._periodic.items()
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
def update_periodic_message(self, msg: can.Message) -> None:
|
|
81
|
+
with self._lock:
|
|
82
|
+
entry = self._periodic.get(msg.arbitration_id)
|
|
83
|
+
if entry is not None:
|
|
84
|
+
entry["msg"] = msg
|
|
85
|
+
|
|
86
|
+
def drop_periodic(self, arbitration_id: int, task: Any) -> None:
|
|
87
|
+
with self._lock:
|
|
88
|
+
entry = self._periodic.get(arbitration_id)
|
|
89
|
+
if entry is not None and entry.get("task") is task:
|
|
90
|
+
self._periodic.pop(arbitration_id, None)
|
|
91
|
+
|
|
92
|
+
# ---- 收发 ----
|
|
93
|
+
def _emit(self, msg: can.Message, direction: str) -> None:
|
|
94
|
+
with self._lock:
|
|
95
|
+
listeners = list(self._listeners)
|
|
96
|
+
for listener in listeners:
|
|
97
|
+
try:
|
|
98
|
+
listener(self.label, msg, direction)
|
|
99
|
+
except Exception as exc: # 监听者异常不得影响总线
|
|
100
|
+
log.warning("tap listener failed: %s", exc)
|
|
101
|
+
|
|
102
|
+
def recv(self, timeout: Optional[float] = None) -> Optional[can.Message]:
|
|
103
|
+
try:
|
|
104
|
+
msg = self.bus.recv(timeout=timeout)
|
|
105
|
+
except can.CanError as exc:
|
|
106
|
+
# 部分驱动在接收队列溢出时抛 "too late",属可恢复错误
|
|
107
|
+
if "too late" not in str(exc).lower():
|
|
108
|
+
raise
|
|
109
|
+
now = time.monotonic()
|
|
110
|
+
if now - self._last_overrun_warn > self.overrun_warn_s:
|
|
111
|
+
self._last_overrun_warn = now
|
|
112
|
+
log.warning("bus %s rx queue overrun, some frames lost", self.label)
|
|
113
|
+
return None
|
|
114
|
+
if msg is not None:
|
|
115
|
+
self._emit(msg, "Rx")
|
|
116
|
+
return msg
|
|
117
|
+
|
|
118
|
+
def send(self, msg: can.Message, timeout: Optional[float] = None):
|
|
119
|
+
result = self.bus.send(msg, timeout=timeout)
|
|
120
|
+
self._emit(msg, "Tx")
|
|
121
|
+
return result
|
|
122
|
+
|
|
123
|
+
def send_periodic(self, msg: can.Message, period: float = None, *args, **kwargs):
|
|
124
|
+
task = self.bus.send_periodic(msg, period, *args, **kwargs)
|
|
125
|
+
wrapper = TappedPeriodicTask(task, self, msg.arbitration_id)
|
|
126
|
+
with self._lock:
|
|
127
|
+
self._periodic[msg.arbitration_id] = {
|
|
128
|
+
"cycle_s": float(period),
|
|
129
|
+
"msg": msg,
|
|
130
|
+
"task": wrapper,
|
|
131
|
+
}
|
|
132
|
+
self._emit(msg, "Tx")
|
|
133
|
+
return wrapper
|
|
134
|
+
|
|
135
|
+
def stop_all_periodic_tasks(self):
|
|
136
|
+
with self._lock:
|
|
137
|
+
self._periodic.clear()
|
|
138
|
+
return self.bus.stop_all_periodic_tasks()
|
|
139
|
+
|
|
140
|
+
def shutdown(self):
|
|
141
|
+
return self.bus.shutdown()
|
|
142
|
+
|
|
143
|
+
def __getattr__(self, name: str):
|
|
144
|
+
return getattr(self.bus, name)
|
|
@@ -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,10 @@
|
|
|
1
|
+
canlink/__init__.py,sha256=ApyvxjyXhlAsPdeD-Y3CDtR6IiQjEJuz8jX6xxkjfpA,1216
|
|
2
|
+
canlink/asc.py,sha256=lJXBLYiO5BW4a7hTKZNDo_MJg_oR0X2F8G-AVe-WgL8,8517
|
|
3
|
+
canlink/errors.py,sha256=O6opoNLY85P1hgebNgIc8-eu5W4u8PUXu8ZY2Zyu39Q,495
|
|
4
|
+
canlink/mirror.py,sha256=vubU7UZvoQTiUdEbrqfoSXGfvzGLhesB_5eyOj3umsU,14283
|
|
5
|
+
canlink/tapped.py,sha256=ay-oUa48kJ-B1qlV5xmxohO5K7Hguo4kZQume2kY_QQ,5101
|
|
6
|
+
python_cantools-0.2.0.dist-info/licenses/LICENSE,sha256=jM6jb9EX4u5pXr3FuFgmZMBle0uOtT_-o_9uqf_n8Rc,398
|
|
7
|
+
python_cantools-0.2.0.dist-info/METADATA,sha256=GcicEHDKdAq4IaKIlfjnFJsNyMD0fuEKibVmIKreZdg,7692
|
|
8
|
+
python_cantools-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
python_cantools-0.2.0.dist-info/top_level.txt,sha256=KqVKsSnhasYhjsAFT8xhEvNulyAZb0g4GVylI2kOULc,8
|
|
10
|
+
python_cantools-0.2.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
canlink
|