dbc-matrix-audit 1.3.1__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.
arxml_dbc_check.py ADDED
@@ -0,0 +1,2505 @@
1
+ #!/usr/bin/env python3
2
+ """arxml_dbc_check.py — AUTOSAR 通信栈 ARXML 与 DBC 交叉一致性校验。
3
+
4
+ 零依赖(仅 Python 标准库)。校验链路:
5
+ DBC <- CanDrv <- CanIf <- PduR <- Com
6
+
7
+ 子命令:
8
+ probe <arxml> 探测 ARXML 变体:有哪些模块 / 容器 / 参数名
9
+ check <arxml> <dbc> 全链路校验
10
+ matrix <arxml> <dbc> --csv OUT 导出帧-信号对照台账
11
+ selftest 内置示例自检
12
+
13
+ 退出码:0 无 error | 1 存在 error | 2 参数/文件问题
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import csv
20
+ import json
21
+ import re
22
+ import sys
23
+ from dataclasses import dataclass, field
24
+ from pathlib import Path
25
+ from typing import Any, Iterable
26
+ from xml.etree import ElementTree as ET
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # 常量
30
+ # ---------------------------------------------------------------------------
31
+
32
+ SEV_ORDER = {"error": 3, "warn": 2, "info": 1}
33
+
34
+ #: 一个 CAN ID 在 CanIf 里被置为扩展帧时常见的标志位
35
+ EXTENDED_FLAG = 0x80000000
36
+
37
+ #: 标准帧最大 ID
38
+ STD_ID_MAX = 0x7FF
39
+
40
+ #: CANdb++ 用来收纳「没挂到任何报文」的孤立信号的伪帧。
41
+ #: 它不是真帧:DLC=0、发送方 Vector__XXX、ID 固定 0xC0000000。
42
+ #: 当成真帧会把 DBC 凭空多算一帧,还会因为 ID > 0x7FF 误判成扩展帧,
43
+ #: 连带触发「DBC 有扩展帧但 CanDrv 没配 EXTENDED」的假报。
44
+ PSEUDO_FRAME_IDS = {0xC0000000}
45
+ PSEUDO_FRAME_NAMES = {"VECTOR__INDEPENDENT_SIG_MSG"}
46
+
47
+ #: 非 DBC 文件可容忍的编码
48
+ _ARXML_ENCODINGS = ("utf-8", "utf-8-sig", "gb18030", "gbk", "latin-1")
49
+
50
+
51
+ class AxdError(RuntimeError):
52
+ """参数或文件层面的错误(退出码 2)。"""
53
+
54
+
55
+ # ---------------------------------------------------------------------------
56
+ # 公共工具
57
+ # ---------------------------------------------------------------------------
58
+
59
+
60
+ def xml_local(tag: str) -> str:
61
+ """去掉 XML 命名空间,返回 local tag。"""
62
+ return tag.rsplit("}", 1)[-1] if "}" in tag else tag
63
+
64
+
65
+ def ref_tail(ref: str) -> str:
66
+ """取 AUTOSAR 引用路径最后一段。"""
67
+ parts = [p for p in ref.split("/") if p]
68
+ return parts[-1] if parts else ""
69
+
70
+
71
+ def read_text_any(path: Path) -> tuple[str, str]:
72
+ """按常见编码读文本,返回 (text, encoding)。"""
73
+ raw = path.read_bytes()
74
+ for enc in _ARXML_ENCODINGS:
75
+ try:
76
+ return raw.decode(enc), enc
77
+ except UnicodeDecodeError:
78
+ continue
79
+ raise AxdError(f"无法解码文件(已尝试 {', '.join(_ARXML_ENCODINGS)}):{path}")
80
+
81
+
82
+ def to_number(value: Any) -> Any:
83
+ """把字符串转成 int/float,转不了就原样返回。"""
84
+ if not isinstance(value, str):
85
+ return value
86
+ s = value.strip()
87
+ if not s:
88
+ return value
89
+ if re.fullmatch(r"[+-]?\d+", s):
90
+ try:
91
+ return int(s)
92
+ except ValueError:
93
+ return value
94
+ if re.fullmatch(r"[+-]?(\d+\.\d*|\.\d+|\d+)([eE][+-]?\d+)?", s):
95
+ try:
96
+ return float(s)
97
+ except ValueError:
98
+ return value
99
+ if s.lower() in ("true", "false"):
100
+ return s.lower() == "true"
101
+ return s
102
+
103
+
104
+ # ---------------------------------------------------------------------------
105
+ # DBC 解析
106
+ # ---------------------------------------------------------------------------
107
+
108
+ _RE_BO = re.compile(r"^BO_\s+(\d+)\s+(\w+)\s*:\s*(\d+)\s+(\w+)")
109
+ _RE_SG = re.compile(
110
+ r"^\s*SG_\s+(\w+)\s*(?:M|m\d+M?)?\s*:\s*"
111
+ r"(\d+)\|(\d+)@([01])([+-])\s*"
112
+ r"\(([^,]+),([^)]+)\)\s*"
113
+ r"\[([^|\]]*)\|([^\]]*)\]\s*"
114
+ r'"([^"]*)"\s*(.*)$'
115
+ )
116
+ _RE_CM_SG = re.compile(r'CM_\s+SG_\s+(\d+)\s+(\w+)\s+"(.*?)";', re.S)
117
+ _RE_CM_BO = re.compile(r'CM_\s+BO_\s+(\d+)\s+"(.*?)";', re.S)
118
+ _RE_VAL = re.compile(r"VAL_\s+(\d+)\s+(\w+)\s*([^;]*);")
119
+ _RE_BA_CYCLE = re.compile(r'BA_\s+"GenMsgCycleTime"\s+BO_\s+(\d+)\s+(\d+);')
120
+ _RE_BA_START = re.compile(
121
+ r'BA_\s+"GenSigStartValue"\s+SG_\s+(\d+)\s+(\w+)\s+([-+0-9.eE]+);'
122
+ )
123
+ _RE_BA_VFRAME = re.compile(r'BA_\s+"VFrameFormat"\s+BO_\s+(\d+)\s+(\d+);')
124
+
125
+
126
+ def split_receivers(raw: str) -> list[str]:
127
+ """拆 DBC 信号尾部的接收方列表。
128
+
129
+ DBC 规范里用**逗号**分隔(`"" ECU_L,ECU_R`),但有些工具会写成空格,
130
+ 还有 `Vector__XXX` 这种占位符。只按空格拆会得到 ['ECU_L,ECU_R'] 一个元素,
131
+ 导致「本 ECU 是不是接收方」永远判错。
132
+ """
133
+ out: list[str] = []
134
+ for part in re.split(r"[,\s]+", raw.strip()):
135
+ part = part.strip()
136
+ if part and part not in out:
137
+ out.append(part)
138
+ return out
139
+
140
+
141
+ @dataclass
142
+ class DbcSignal:
143
+ name: str
144
+ start: int
145
+ length: int
146
+ is_intel: bool
147
+ signed: bool
148
+ factor: float
149
+ offset: float
150
+ minimum: float | None
151
+ maximum: float | None
152
+ unit: str
153
+ receivers: list[str]
154
+ comment: str = ""
155
+ start_value: float | None = None
156
+ value_table: dict[int, str] = field(default_factory=dict)
157
+
158
+ @property
159
+ def byte_order(self) -> str:
160
+ return "LITTLE" if self.is_intel else "BIG"
161
+
162
+ def bits(self) -> set[int]:
163
+ """返回信号占用的 bit 集合(DBC 锯齿位编号,bit0 = byte0 的 LSB)。"""
164
+ if self.is_intel:
165
+ return set(range(self.start, self.start + self.length))
166
+ return motorola_bits(self.start, self.length)
167
+
168
+
169
+ @dataclass
170
+ class DbcMessage:
171
+ can_id: int
172
+ name: str
173
+ dlc: int
174
+ tx_node: str
175
+ signals: dict[str, DbcSignal] = field(default_factory=dict)
176
+ comment: str = ""
177
+ cycle_ms: int | None = None
178
+ vframe_format: int | None = None
179
+ frame_format: str = "" # "CAN" / "CANFD"
180
+
181
+ @property
182
+ def is_fd(self) -> bool:
183
+ if self.vframe_format is not None:
184
+ return self.vframe_format >= 14 # StandardCAN_FD=14, ExtendedCAN_FD=15
185
+ return self.dlc > 8 or self.frame_format.upper() == "CANFD"
186
+
187
+ @property
188
+ def is_extended(self) -> bool:
189
+ return self.can_id > STD_ID_MAX
190
+
191
+
192
+ @dataclass
193
+ class DbcModel:
194
+ path: Path
195
+ encoding: str
196
+ nodes: list[str] = field(default_factory=list)
197
+ messages: dict[int, DbcMessage] = field(default_factory=dict)
198
+ #: 伪帧里的孤立信号(名称 -> 信号),单独存,不参与帧级校验
199
+ orphan_signals: dict[str, DbcSignal] = field(default_factory=dict)
200
+
201
+
202
+ def motorola_bits(msb: int, length: int) -> set[int]:
203
+ """从 DBC 起始位(MSB,锯齿编号)推出占用的 bit 集合。"""
204
+ bits: set[int] = set()
205
+ pos = msb
206
+ for _ in range(length):
207
+ bits.add(pos)
208
+ pos = pos + 15 if pos % 8 == 0 else pos - 1
209
+ return bits
210
+
211
+
212
+ def motorola_msb_from_lsb(lsb: int, length: int) -> int:
213
+ """已知 LSB(平坦编号)和长度,反推 Motorola 的 MSB 位置。"""
214
+ pos = lsb
215
+ for _ in range(length - 1):
216
+ pos = pos - 15 if pos % 8 == 7 else pos + 1
217
+ return pos
218
+
219
+
220
+ def parse_dbc(path: Path) -> DbcModel:
221
+ text, enc = read_text_any(path)
222
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
223
+ model = DbcModel(path=path, encoding=enc)
224
+
225
+ for m in re.finditer(r"^BU_\s*:\s*(.+)$", text, re.M):
226
+ for node in m.group(1).split():
227
+ if node not in model.nodes:
228
+ model.nodes.append(node)
229
+
230
+ current: DbcMessage | None = None
231
+ pseudo_mode = False # 当前 BO_ 是否为 CANdb++ 伪帧
232
+ for line in text.split("\n"):
233
+ mb = _RE_BO.match(line)
234
+ if mb:
235
+ cid, name = int(mb.group(1)), mb.group(2)
236
+ current = DbcMessage(
237
+ can_id=cid,
238
+ name=name,
239
+ dlc=int(mb.group(3)),
240
+ tx_node=mb.group(4),
241
+ )
242
+ # 伪帧只用来收集孤立信号,不进 messages
243
+ if cid in PSEUDO_FRAME_IDS or name in PSEUDO_FRAME_NAMES:
244
+ current = None
245
+ pseudo_mode = True
246
+ continue
247
+ pseudo_mode = False
248
+ model.messages[current.can_id] = current
249
+ continue
250
+ if line.startswith("BO_") or (
251
+ line.strip() and not line.startswith((" ", "\t")) and not pseudo_mode
252
+ ):
253
+ if not line.startswith((" ", "\t")) and not line.startswith("SG_"):
254
+ if line[:3] in ("VAL", "CM_", "BA_", "BA_", "SG_", "SIG", "BO_"):
255
+ pass
256
+ elif not line.startswith(" "):
257
+ current = None
258
+ ms = _RE_SG.match(line)
259
+ if ms and pseudo_mode:
260
+ # 伪帧下的孤立信号
261
+ sig = DbcSignal(
262
+ name=ms.group(1),
263
+ start=int(ms.group(2)),
264
+ length=int(ms.group(3)),
265
+ is_intel=(ms.group(4) == "1"),
266
+ signed=(ms.group(5) == "-"),
267
+ factor=_safe_float(ms.group(6), 1.0),
268
+ offset=_safe_float(ms.group(7), 0.0),
269
+ minimum=None,
270
+ maximum=None,
271
+ unit=ms.group(10),
272
+ receivers=split_receivers(ms.group(11)),
273
+ )
274
+ model.orphan_signals[sig.name] = sig
275
+ continue
276
+ if ms and current is not None:
277
+ try:
278
+ mn = float(ms.group(8))
279
+ mx = float(ms.group(9))
280
+ except ValueError:
281
+ mn = mx = None
282
+ current.signals[ms.group(1)] = DbcSignal(
283
+ name=ms.group(1),
284
+ start=int(ms.group(2)),
285
+ length=int(ms.group(3)),
286
+ is_intel=(ms.group(4) == "1"),
287
+ signed=(ms.group(5) == "-"),
288
+ factor=_safe_float(ms.group(6), 1.0),
289
+ offset=_safe_float(ms.group(7), 0.0),
290
+ minimum=mn,
291
+ maximum=mx,
292
+ unit=ms.group(10),
293
+ receivers=split_receivers(ms.group(11)),
294
+ )
295
+
296
+ for m in _RE_CM_SG.finditer(text):
297
+ msg = model.messages.get(int(m.group(1)))
298
+ if msg and m.group(2) in msg.signals:
299
+ msg.signals[m.group(2)].comment = " ".join(m.group(3).split())
300
+ for m in _RE_CM_BO.finditer(text):
301
+ msg = model.messages.get(int(m.group(1)))
302
+ if msg:
303
+ msg.comment = " ".join(m.group(2).split())
304
+
305
+ for m in _RE_VAL.finditer(text):
306
+ msg = model.messages.get(int(m.group(1)))
307
+ if not msg or m.group(2) not in msg.signals:
308
+ continue
309
+ table = {
310
+ int(k): v
311
+ for k, v in re.findall(r'(-?\d+)\s+"([^"]*)"', m.group(3))
312
+ }
313
+ msg.signals[m.group(2)].value_table = table
314
+
315
+ for m in _RE_BA_CYCLE.finditer(text):
316
+ msg = model.messages.get(int(m.group(1)))
317
+ if msg:
318
+ msg.cycle_ms = int(m.group(2))
319
+ for m in _RE_BA_START.finditer(text):
320
+ msg = model.messages.get(int(m.group(1)))
321
+ if msg and m.group(2) in msg.signals:
322
+ msg.signals[m.group(2)].start_value = _safe_float(m.group(3), 0.0)
323
+ for m in _RE_BA_VFRAME.finditer(text):
324
+ msg = model.messages.get(int(m.group(1)))
325
+ if msg:
326
+ msg.vframe_format = int(m.group(2))
327
+
328
+ return model
329
+
330
+
331
+ def _safe_float(tok: str, default: float) -> float:
332
+ try:
333
+ return float(tok.strip())
334
+ except (ValueError, AttributeError):
335
+ return default
336
+
337
+
338
+ # ---------------------------------------------------------------------------
339
+ # ARXML (ECUC) 解析
340
+ # ---------------------------------------------------------------------------
341
+
342
+ #: ARXML 里把参数/引用/子容器再包一层的容器标签(真实文件几乎都有)
343
+ _WRAPPER_TAGS = {
344
+ "PARAMETER-VALUES",
345
+ "REFERENCE-VALUES",
346
+ "SUB-CONTAINERS",
347
+ "CONTAINERS",
348
+ "INSTANCE-REFS",
349
+ }
350
+
351
+ #: AUTOSAR 4.x 真实标签名是 ECUC-xxx-PARAM-VALUE(不含 ETER)。
352
+ #: 部分工具会写成长形式,两种都接受。
353
+ _PARAM_TAGS = {
354
+ "ECUC-NUMERICAL-PARAM-VALUE": "num",
355
+ "ECUC-NUMERICAL-PARAMETER-VALUE": "num",
356
+ "ECUC-TEXTUAL-PARAM-VALUE": "text",
357
+ "ECUC-TEXTUAL-PARAMETER-VALUE": "text",
358
+ "ECUC-BOOLEAN-PARAM-VALUE": "bool",
359
+ "ECUC-BOOLEAN-PARAMETER-VALUE": "bool",
360
+ "ECUC-ENUMERATION-PARAM-VALUE": "enum",
361
+ "ECUC-ENUMERATION-PARAMETER-VALUE": "enum",
362
+ "ECUC-MULTILINE-STRING-PARAM-VALUE": "str",
363
+ "ECUC-MULTILINE-STRING-PARAMETER-VALUE": "str",
364
+ "ECUC-REFERENCE-VALUE": "ref",
365
+ "ECUC-INSTANCE-REFERENCE-VALUE": "iref",
366
+ }
367
+
368
+
369
+ @dataclass
370
+ class Ecuc:
371
+ """一个 ECUC-CONTAINER-VALUE 节点。"""
372
+
373
+ module: str
374
+ def_type: str
375
+ short_name: str
376
+ path: str
377
+ parent: "Ecuc | None" = None
378
+ params: dict[str, list[Any]] = field(default_factory=dict)
379
+ children: list["Ecuc"] = field(default_factory=list)
380
+
381
+ def get(self, *names: str, default: Any = None) -> Any:
382
+ for name in names:
383
+ vals = self.params.get(name)
384
+ if vals:
385
+ return vals[0]
386
+ return default
387
+
388
+ def getall(self, *names: str) -> list[Any]:
389
+ out: list[Any] = []
390
+ for name in names:
391
+ out.extend(self.params.get(name, []))
392
+ return out
393
+
394
+ def has(self, *names: str) -> bool:
395
+ return any(self.params.get(n) for n in names)
396
+
397
+
398
+ class ArxmlModel:
399
+ def __init__(self, path: Path, encoding: str) -> None:
400
+ self.path = path
401
+ self.encoding = encoding
402
+ self.containers: list[Ecuc] = []
403
+ self.modules: dict[str, list[Ecuc]] = {}
404
+ #: <I-SIGNAL> 不在 ECUC 里,单独建索引:short_name -> {length, ...}
405
+ self.isignals: dict[str, dict[str, Any]] = {}
406
+ self.isignal_packages: list[str] = []
407
+
408
+ # -- 索引 -------------------------------------------------------------
409
+ def by_def(self, *def_types: str) -> list[Ecuc]:
410
+ wanted = {d.lower() for d in def_types}
411
+ return [c for c in self.containers if c.def_type.lower() in wanted]
412
+
413
+ def by_short(self, name: str) -> list[Ecuc]:
414
+ return [c for c in self.containers if c.short_name == name]
415
+
416
+ def resolve(self, ref: str) -> list[Ecuc]:
417
+ """按 AUTOSAR 引用路径解析容器(容忍厂商路径前缀差异)。"""
418
+ if not ref:
419
+ return []
420
+ tail = ref_tail(ref)
421
+ cands = self.by_short(tail)
422
+ if cands:
423
+ return cands
424
+ # 退化:路径后缀匹配
425
+ norm = "/" + "/".join(p for p in ref.split("/") if p)
426
+ return [c for c in self.containers if norm.endswith("/" + c.path)]
427
+
428
+ def module_names(self) -> list[str]:
429
+ return sorted(self.modules)
430
+
431
+
432
+ def parse_arxml(path: Path) -> ArxmlModel:
433
+ text, enc = read_text_any(path)
434
+ try:
435
+ root = ET.fromstring(text.encode("utf-8"))
436
+ except ET.ParseError as exc: # pragma: no cover - 输入损坏
437
+ raise AxdError(f"ARXML 解析失败:{exc}") from exc
438
+
439
+ model = ArxmlModel(path=path, encoding=enc)
440
+
441
+ for mod_elem in root.iter():
442
+ if xml_local(mod_elem.tag) != "ECUC-MODULE-CONFIGURATION-VALUES":
443
+ continue
444
+ sn = _child_text(mod_elem, "SHORT-NAME") or "(unnamed)"
445
+ mod_containers: list[Ecuc] = []
446
+ for child in _iter_leaves(mod_elem):
447
+ if xml_local(child.tag) != "ECUC-CONTAINER-VALUE":
448
+ continue
449
+ built = _build_container(child, module=sn, parent=None, prefix=sn)
450
+ if built is not None:
451
+ mod_containers.append(built)
452
+ model.modules[sn] = mod_containers
453
+ for top in mod_containers:
454
+ _flatten(top, model.containers)
455
+
456
+ # I-SIGNAL 是普通 ARXML 元素,不在 ECUC 树里
457
+ for elem in root.iter():
458
+ if xml_local(elem.tag) != "I-SIGNAL":
459
+ continue
460
+ name = _child_text(elem, "SHORT-NAME")
461
+ if not name:
462
+ continue
463
+ length = None
464
+ for c in elem:
465
+ if xml_local(c.tag) == "LENGTH":
466
+ length = to_number(_text(c))
467
+ break
468
+ dtype = None
469
+ for c in elem:
470
+ if xml_local(c.tag) == "DATA-TYPE-POLICY":
471
+ dtype = _text(c)
472
+ break
473
+ model.isignals[name] = {
474
+ "length": length if isinstance(length, int) else None,
475
+ "data_type_policy": dtype or "",
476
+ }
477
+
478
+ if not model.modules:
479
+ raise AxdError(f"未找到任何 ECUC-MODULE-CONFIGURATION-VALUES:{path}")
480
+ return model
481
+
482
+
483
+ def _build_container(
484
+ elem: ET.Element, module: str, parent: Ecuc | None, prefix: str
485
+ ) -> Ecuc | None:
486
+ sn = _child_text(elem, "SHORT-NAME") or ""
487
+ def_ref = _child_text(elem, "DEFINITION-REF") or ""
488
+ def_type = ref_tail(def_ref) or "?"
489
+ path = f"{prefix}/{sn}" if sn else prefix
490
+ node = Ecuc(
491
+ module=module, def_type=def_type, short_name=sn, path=path, parent=parent
492
+ )
493
+
494
+ for child in _iter_leaves(elem):
495
+ tag = xml_local(child.tag)
496
+ kind = _PARAM_TAGS.get(tag)
497
+ if kind:
498
+ p_def = _child_text(child, "DEFINITION-REF") or ""
499
+ p_name = ref_tail(p_def)
500
+ if kind in ("ref", "iref"):
501
+ # 注意:ET 元素无子节点时布尔值为 False,不能用 `a or b`
502
+ val_el = _child(child, "VALUE-REF")
503
+ if val_el is None:
504
+ val_el = _child(child, "VALUE-IREF")
505
+ val = _text(val_el)
506
+ else:
507
+ val = _text(_child(child, "VALUE"))
508
+ if p_name:
509
+ node.params.setdefault(p_name, []).append(to_number(val))
510
+ elif tag == "ECUC-CONTAINER-VALUE":
511
+ sub = _build_container(child, module=module, parent=node, prefix=path)
512
+ if sub is not None:
513
+ node.children.append(sub)
514
+ return node
515
+
516
+
517
+ def _iter_leaves(elem: ET.Element) -> Iterable[ET.Element]:
518
+ """展开 PARAMETER-VALUES / REFERENCE-VALUES / SUB-CONTAINERS 等包装层。"""
519
+ for child in elem:
520
+ if xml_local(child.tag) in _WRAPPER_TAGS:
521
+ yield from _iter_leaves(child)
522
+ else:
523
+ yield child
524
+
525
+
526
+ def _flatten(node: Ecuc, out: list[Ecuc]) -> None:
527
+ out.append(node)
528
+ for child in node.children:
529
+ _flatten(child, out)
530
+
531
+
532
+ def _child(elem: ET.Element, local: str) -> ET.Element | None:
533
+ for c in elem:
534
+ if xml_local(c.tag) == local:
535
+ return c
536
+ return None
537
+
538
+
539
+ def _text(elem: ET.Element | None) -> str:
540
+ if elem is None:
541
+ return ""
542
+ return (elem.text or "").strip()
543
+
544
+
545
+ def _child_text(elem: ET.Element, local: str) -> str:
546
+ return _text(_child(elem, local))
547
+
548
+
549
+ # ---------------------------------------------------------------------------
550
+ # 领域模型:把 ARXML 抽成 Com / PduR / CanIf / CanDrv 四层
551
+ # ---------------------------------------------------------------------------
552
+
553
+
554
+ @dataclass
555
+ class AxSignal:
556
+ name: str
557
+ pdu_name: str
558
+ start_position: int | None
559
+ length: int | None
560
+ byte_order: str # "BIG" / "LITTLE" / "?"
561
+ signed: bool | None
562
+ init_value: float | None
563
+ source: str # "ComSignal" / "ISignalToIPduMapping"
564
+ container: Ecuc
565
+ bits: set[int] = field(default_factory=set)
566
+ bits_convention: str = ""
567
+ #: 备选位宽:ComSignalLength 的单位在不同导出里可能是字节也可能是位
568
+ length_alt: int | None = None
569
+ #: 是否整帧字节数组(OPAQUE / UINT8_DYN),此时不做逐信号比对
570
+ is_byte_array: bool = False
571
+
572
+ def length_candidates(self) -> list[int]:
573
+ out: list[int] = []
574
+ for v in (self.length, self.length_alt):
575
+ if v and v not in out:
576
+ out.append(v)
577
+ return out
578
+
579
+ def compute_bits(self) -> None:
580
+ """把 AUTOSAR 的起始位换算成 DBC 的 bit 集合。
581
+
582
+ 实测结论(215/215 信号零失败):AUTOSAR 的 `START-POSITION` /
583
+ `ComBitPosition` 存的始终是信号的 **LSB**,按平坦编号(bit0 = byte0 的 LSB),
584
+ 与小端/大端无关。与 DBC 的差异只有大端信号的锯齿编号转换:
585
+ 先把 LSB 回退 (len-1) 步求出 MSB,再按锯齿走完整个信号。
586
+
587
+ 写成"两种约定都试"是错的 —— 那会把真正的起始位错误掩盖掉。
588
+ """
589
+ if self.start_position is None or self.length is None:
590
+ self.bits = set()
591
+ self.bits_convention = ""
592
+ return
593
+ if self.byte_order == "LITTLE":
594
+ self.bits = set(
595
+ range(self.start_position, self.start_position + self.length)
596
+ )
597
+ self.bits_convention = "little-flat"
598
+ else:
599
+ msb = motorola_msb_from_lsb(self.start_position, self.length)
600
+ self.bits = motorola_bits(msb, self.length)
601
+ self.bits_convention = "big-lsb-flat"
602
+
603
+
604
+
605
+ @dataclass
606
+ class AxPdu:
607
+ name: str
608
+ direction: str # "SEND" / "RECEIVE" / "?"
609
+ length: int | None
610
+ length_source: str
611
+ cycle_ms: float | None
612
+ signals: list[AxSignal] = field(default_factory=list)
613
+ container: Ecuc | None = None
614
+ can_id: int | None = None # 从 CanIf 回填
615
+ pdu_ref: str = "" # EcuC Pdu 名(COM_xxx),PduR 链路的一环
616
+ bus: str = "" # 所属 CanController,由绑定的 CanIf PDU 回填
617
+
618
+
619
+ @dataclass
620
+ class CanIfPdu:
621
+ name: str
622
+ direction: str # "RX" / "TX"
623
+ can_id: int | None
624
+ can_id_raw: int | None
625
+ id_type: str # STANDARD / EXTENDED / ?
626
+ is_fd: bool # 由 CanIdType 含 _FD_CAN 得出
627
+ dlc: int | None
628
+ container: Ecuc
629
+ pdu_ref: str = "" # 指向的 EcuC Pdu 名
630
+ bus: str = "" # 所属 CanController,如 CANIF_CTR_DRV_BCAN
631
+
632
+
633
+ @dataclass
634
+ class PduRRouting:
635
+ name: str
636
+ src_refs: list[str]
637
+ dest_refs: list[str]
638
+ container: Ecuc
639
+ route_type: str = "" # IF / TP
640
+
641
+
642
+ @dataclass
643
+ class CanController:
644
+ name: str
645
+ baudrate: int | None
646
+ fd_baudrate: int | None
647
+ container: Ecuc
648
+
649
+
650
+ @dataclass
651
+ class CanHwObject:
652
+ name: str
653
+ handle_type: str
654
+ id_type: str
655
+ container: Ecuc
656
+
657
+
658
+ @dataclass
659
+ class StackModel:
660
+ com_pdus: list[AxPdu] = field(default_factory=list)
661
+ canif_rx: list[CanIfPdu] = field(default_factory=list)
662
+ canif_tx: list[CanIfPdu] = field(default_factory=list)
663
+ routing: list[PduRRouting] = field(default_factory=list)
664
+ controllers: list[CanController] = field(default_factory=list)
665
+ hw_objects: list[CanHwObject] = field(default_factory=list)
666
+ notes: list[str] = field(default_factory=list)
667
+ present_modules: list[str] = field(default_factory=list)
668
+ #: EcuC 的 Pdu 容器:名字 -> 字节长度(Com 与 CanIf 之间的枢纽)
669
+ ecuc_pdus: dict[str, int | None] = field(default_factory=dict)
670
+ has_can_nm: bool = False
671
+ has_can_tp: bool = False
672
+ #: 总线覆盖率:CanController 名 -> (命中 DBC 的 PDU 数, 总 PDU 数)
673
+ bus_coverage: dict[str, tuple[int, int]] = field(default_factory=dict)
674
+ #: 不在本 DBC 覆盖范围内的总线(命中率 < 20%)
675
+ off_dbc_buses: set[str] = field(default_factory=set)
676
+
677
+
678
+ def extract_stack(model: ArxmlModel) -> StackModel:
679
+ st = StackModel()
680
+ st.present_modules = model.module_names()
681
+
682
+ # EcuC 的 Pdu 容器是 Com 与 CanIf 之间的枢纽,且提供 PDU 长度。
683
+ # 必须最先扫,后面各层都要用它兜底。
684
+ for pdu in model.by_def("Pdu"):
685
+ st.ecuc_pdus[pdu.short_name] = _first_int(pdu, "PduLength")
686
+
687
+ _extract_com(model, st)
688
+ _extract_canif(model, st)
689
+ _extract_pdur(model, st)
690
+ _extract_candr(model, st)
691
+ return st
692
+
693
+
694
+ def _extract_com(model: ArxmlModel, st: StackModel) -> None:
695
+ ipdus = model.by_def("ComIPdu")
696
+ mapping = model.by_def("ISignalToIPduMapping")
697
+ isignals = model.isignals # short_name -> {length, data_type_policy}
698
+ com_signals = {c.short_name: c for c in model.by_def("ComSignal")}
699
+
700
+ # 有的厂商把 PDU 长度放在 EcuC 的 Pdu 容器里,Com 用 ComPduIdRef 指过去
701
+ pdu_len: dict[str, int] = {}
702
+ for pdu in model.by_def("Pdu"):
703
+ ln = _first_int(pdu, "PduLength")
704
+ if ln is not None:
705
+ pdu_len[pdu.short_name] = ln
706
+
707
+ for ipdu in ipdus:
708
+ pdu = AxPdu(
709
+ name=ipdu.short_name,
710
+ direction=_norm_direction(
711
+ ipdu.get("ComIPduDirection", "ComIPduDirectionRef", default="?")
712
+ ),
713
+ length=_first_int(ipdu, "ComIPduSize", "ComIPduLength", "PduLength"),
714
+ length_source="",
715
+ cycle_ms=_extract_cycle(ipdu),
716
+ container=ipdu,
717
+ )
718
+ pdu_ref_raw = ipdu.get("ComPduIdRef", default="")
719
+ pdu.pdu_ref = ref_tail(pdu_ref_raw) if isinstance(pdu_ref_raw, str) else ""
720
+ if pdu.length is not None:
721
+ pdu.length_source = "ComIPdu"
722
+ elif pdu.pdu_ref in pdu_len:
723
+ pdu.length = pdu_len[pdu.pdu_ref]
724
+ pdu.length_source = "EcuC.Pdu"
725
+ # 方向兜底:ComIPduType / 命名
726
+ if pdu.direction == "?":
727
+ pdu.direction = _guess_direction_from_type(ipdu)
728
+
729
+ # 1) 挂在 IPdu 下的 ISignalToIPduMapping / ComSignal 子容器
730
+ sigs: list[AxSignal] = []
731
+ refs = [r for r in ipdu.getall("ComIPduSignalRef") if isinstance(r, str)]
732
+ ref_tails = {ref_tail(r) for r in refs if ref_tail(r)}
733
+
734
+ for child in ipdu.children:
735
+ if child.def_type == "ISignalToIPduMapping":
736
+ sigs.append(_signal_from_mapping(child, ipdu.short_name, isignals))
737
+ elif child.def_type == "ComSignal":
738
+ # 有 ComIPduSignalRef 时,未被引用的 ComSignal 属死配置
739
+ # (有的导出会保留整个信号定义集,但实际只引用其中一部分)
740
+ if ref_tails and child.short_name not in ref_tails:
741
+ continue
742
+ sigs.append(_signal_from_comsignal(child, ipdu.short_name))
743
+
744
+ # 2) IPdu 上的信号引用(引用到模块级 ComSignal / ISignal 时补上)
745
+ for ref in ipdu.getall("ComIPduSignalRef", "ComIPduGroupSignalRef"):
746
+ if not isinstance(ref, str):
747
+ continue
748
+ tail = ref_tail(ref)
749
+ if any(s.name == tail for s in sigs):
750
+ continue
751
+ if tail in com_signals:
752
+ sigs.append(_signal_from_comsignal(com_signals[tail], ipdu.short_name))
753
+ elif tail in isignals:
754
+ sigs.append(
755
+ _signal_from_isignal_only(tail, isignals[tail], ipdu.short_name)
756
+ )
757
+
758
+ # 3) 全局 mapping 容器(不在 IPdu 子容器里时)
759
+ for mp in mapping:
760
+ parent = mp.parent
761
+ if parent is not None and parent.short_name == ipdu.short_name:
762
+ if not any(s.container is mp for s in sigs):
763
+ sigs.append(_signal_from_mapping(mp, ipdu.short_name, isignals))
764
+
765
+ # 4) 模块级 ComSignal 按 ComIPduSignalRef / ComSignalIPduRef 反查
766
+ for sig in model.by_def("ComSignal"):
767
+ for r in sig.getall(
768
+ "ComIPduSignalRef", "ComSignalIPduRef", "ComIPduRef"
769
+ ):
770
+ if isinstance(r, str) and ref_tail(r) == ipdu.short_name:
771
+ sigs.append(_signal_from_comsignal(sig, ipdu.short_name))
772
+ break
773
+
774
+ # 去重
775
+ seen: set[tuple[str, int | None]] = set()
776
+ uniq: list[AxSignal] = []
777
+ for s in sigs:
778
+ s.name = _strip_ipdu_suffix(s.name, ipdu.short_name)
779
+ key = (s.name, s.start_position)
780
+ if key in seen:
781
+ continue
782
+ seen.add(key)
783
+ s.compute_bits()
784
+ uniq.append(s)
785
+ pdu.signals = uniq
786
+ st.com_pdus.append(pdu)
787
+
788
+ if not ipdus:
789
+ st.notes.append("ARXML 中没有找到 ComIPdu 容器")
790
+ if ipdus and not any(p.signals for p in st.com_pdus):
791
+ st.notes.append(
792
+ "ComIPdu 存在但没解析出任何信号 —— 信号可能挂在其它容器类型下,"
793
+ "请先跑 probe 看实际 DEFINITION-REF"
794
+ )
795
+
796
+
797
+ def _strip_ipdu_suffix(name: str, pdu_name: str) -> str:
798
+ """有的厂商导出会把 ComSignal 命名成 `<信号>_<PDU名>`,需剥回原始信号名。
799
+
800
+ 两种常见写法:
801
+ Signal_IPDU_COM_Foo + IPdu 名 IPDU_COM_Foo -> Signal (后缀 _PDU名)
802
+ Signal_IPDU_X + IPdu 名 X -> Signal (后缀 _IPDU_PDU名)
803
+ 先试长的,再试短的,都要求完整匹配,避免误伤本来就带 _IPDU_ 的信号。
804
+ """
805
+ if not pdu_name:
806
+ return name
807
+ for suffix in ("_IPDU_" + pdu_name, "_" + pdu_name):
808
+ if len(name) > len(suffix) and name.endswith(suffix):
809
+ return name[: -len(suffix)]
810
+ # 大小写差异兜底
811
+ low_name, low_pdu = name.lower(), pdu_name.lower()
812
+ for prefix in ("_ipdu_", "_"):
813
+ suffix = prefix + low_pdu
814
+ if len(low_name) > len(suffix) and low_name.endswith(suffix):
815
+ return name[: -len(suffix)]
816
+ return name
817
+
818
+
819
+ def _signal_from_mapping(
820
+ mp: Ecuc, pdu_name: str, isignals: dict[str, dict[str, Any]]
821
+ ) -> AxSignal:
822
+ ref = mp.get("ISignalRef", default="")
823
+ tail = ref_tail(ref) if isinstance(ref, str) else ""
824
+ isig = isignals.get(tail)
825
+ length = None
826
+ if isig is not None:
827
+ length = isig.get("length")
828
+ name = tail or mp.short_name
829
+
830
+ order_raw = str(
831
+ mp.get(
832
+ "PACKING-BYTE-ORDER",
833
+ "ComSignalEndianness",
834
+ "ISignalToIPduMappingByteOrder",
835
+ default="",
836
+ )
837
+ ).upper()
838
+ byte_order = "?"
839
+ if order_raw:
840
+ if "MOST-SIGNIFICANT-BYTE-FIRST" in order_raw or "BIG" in order_raw:
841
+ byte_order = "BIG"
842
+ elif "MOST-SIGNIFICANT-BYTE-LAST" in order_raw or "LITTLE" in order_raw:
843
+ byte_order = "LITTLE"
844
+
845
+ start = _first_int(mp, "START-POSITION", "START-POSITION-OF-SIGNAL", "ComBitPosition")
846
+
847
+ signed: bool | None = None
848
+ if isig is not None:
849
+ dtype = str(isig.get("data_type_policy", "")).upper()
850
+ if "SIGNED" in dtype and "UNSIGNED" not in dtype:
851
+ signed = True
852
+ elif "UNSIGNED" in dtype:
853
+ signed = False
854
+
855
+ return AxSignal(
856
+ name=name,
857
+ pdu_name=pdu_name,
858
+ start_position=start,
859
+ length=length,
860
+ byte_order=byte_order,
861
+ signed=signed,
862
+ init_value=None,
863
+ source="ISignalToIPduMapping",
864
+ container=mp,
865
+ )
866
+
867
+
868
+ def _signal_from_isignal_only(
869
+ name: str, meta: dict[str, Any], pdu_name: str
870
+ ) -> AxSignal:
871
+ return AxSignal(
872
+ name=name,
873
+ pdu_name=pdu_name,
874
+ start_position=None,
875
+ length=meta.get("length"),
876
+ byte_order="?",
877
+ signed=None,
878
+ init_value=None,
879
+ source="ISignal",
880
+ container=None, # type: ignore[arg-type]
881
+ )
882
+
883
+
884
+ def _signal_from_comsignal(sig: Ecuc, pdu_name: str) -> AxSignal:
885
+ raw_order = str(
886
+ sig.get("ComSignalEndianness", "ComBitOrder", default="")
887
+ ).upper()
888
+ byte_order = "?"
889
+ if "BIG" in raw_order:
890
+ byte_order = "BIG"
891
+ elif "LITTLE" in raw_order:
892
+ byte_order = "LITTLE"
893
+ elif "OPAQUE" in raw_order:
894
+ byte_order = "OPAQUE"
895
+
896
+ stype = str(sig.get("ComSignalType", default="")).upper()
897
+ signed: bool | None = None
898
+ if stype:
899
+ signed = stype.startswith("SINT")
900
+
901
+ # ComBitSize 是位长(静态信号);ComSignalLength 常见于动态/字节数组信号,
902
+ # 单位在不同导出里可能是位或字节 —— 两个候选都留着,比对时逐个试。
903
+ bit_size = _first_int(sig, "ComBitSize")
904
+ sig_len = _first_int(sig, "ComSignalLength")
905
+ bit_size = bit_size if bit_size else None
906
+ sig_len = sig_len if sig_len else None
907
+
908
+ length = bit_size or sig_len
909
+ length_alt = sig_len * 8 if (bit_size is None and sig_len) else None
910
+
911
+ # OPAQUE / UINT8_DYN 是字节数组:整个 PDU 当一个信号用,不做逐信号映射
912
+ is_byte_array = "OPAQUE" in raw_order or stype in (
913
+ "UINT8_DYN",
914
+ "UINT8_N",
915
+ )
916
+
917
+ init = sig.get("ComSignalInitValue", "ComSignalInitValueRef")
918
+ init_val = _parse_int_literal(init)
919
+
920
+ return AxSignal(
921
+ name=sig.short_name,
922
+ pdu_name=pdu_name,
923
+ start_position=_first_int(sig, "ComBitPosition", "ComSignalBitPosition"),
924
+ length=length,
925
+ byte_order=byte_order,
926
+ signed=signed,
927
+ init_value=init_val,
928
+ source="ComSignal",
929
+ container=sig,
930
+ length_alt=length_alt,
931
+ is_byte_array=is_byte_array,
932
+ )
933
+
934
+
935
+ def _parse_int_literal(v: Any) -> float | None:
936
+ """Com 的初始值常写成 0x0 / 0b101 / 十进制字符串。"""
937
+ if isinstance(v, bool):
938
+ return None
939
+ if isinstance(v, (int, float)):
940
+ return float(v)
941
+ if not isinstance(v, str):
942
+ return None
943
+ s = v.strip().lower()
944
+ if not s:
945
+ return None
946
+ try:
947
+ if s.startswith("0x"):
948
+ return float(int(s, 16))
949
+ if s.startswith("0b"):
950
+ return float(int(s, 2))
951
+ return float(s)
952
+ except ValueError:
953
+ return None
954
+
955
+
956
+ def _extract_canif(model: ArxmlModel, st: StackModel) -> None:
957
+ bufs = {c.short_name: c for c in model.by_def("CanIfBufferCfg")}
958
+ hths = {c.short_name: c for c in model.by_def("CanIfHthCfg")}
959
+ hrhs = {c.short_name: c for c in model.by_def("CanIfHrhCfg")}
960
+
961
+ for pdu in model.by_def("CanIfRxPduCfg", "CanIfRxPdu"):
962
+ p = _canif_pdu(pdu, "RX")
963
+ p.bus = _bus_of(pdu, "RX", bufs, hths, hrhs)
964
+ _fill_dlc_from_ecuc(p, st)
965
+ st.canif_rx.append(p)
966
+ for pdu in model.by_def("CanIfTxPduCfg", "CanIfTxPdu"):
967
+ p = _canif_pdu(pdu, "TX")
968
+ p.bus = _bus_of(pdu, "TX", bufs, hths, hrhs)
969
+ _fill_dlc_from_ecuc(p, st)
970
+ st.canif_tx.append(p)
971
+ if not st.canif_rx and not st.canif_tx:
972
+ st.notes.append("ARXML 中没有找到 CanIfRxPduCfg / CanIfTxPduCfg 容器")
973
+
974
+
975
+ def _fill_dlc_from_ecuc(p: CanIfPdu, st: StackModel) -> None:
976
+ """TX PDU 常不配 CanIfTxPduDlc(篇幅省在 EcuC 的 PduLength 里)。
977
+
978
+ 缺失时退到它引用的 EcuC Pdu 长度,否则 DLC 校验会永远静默跳过。
979
+ """
980
+ if p.dlc is not None or not p.pdu_ref:
981
+ return
982
+ ln = st.ecuc_pdus.get(p.pdu_ref)
983
+ if ln is not None:
984
+ p.dlc = ln
985
+
986
+
987
+ def _bus_of(
988
+ pdu: Ecuc,
989
+ direction: str,
990
+ bufs: dict[str, Ecuc],
991
+ hths: dict[str, Ecuc],
992
+ hrhs: dict[str, Ecuc],
993
+ ) -> str:
994
+ """追 TX: Buffer -> HTH -> CanCtrlIdRef;RX: HrhIdRef -> HRH -> CanCtrlIdRef。
995
+
996
+ 一个 MCU 同时管多条 CAN 总线时,必须知道每个 PDU 挂在哪条上,
997
+ 否则会拿私有总线的帧去比整车 DBC。
998
+ """
999
+ if direction == "TX":
1000
+ ref = pdu.get("CanIfTxPduBufferRef")
1001
+ if isinstance(ref, str) and ref:
1002
+ buf = bufs.get(ref_tail(ref))
1003
+ if buf is not None:
1004
+ href = buf.get("CanIfBufferHthRef")
1005
+ if isinstance(href, str) and href:
1006
+ h = hths.get(ref_tail(href))
1007
+ if h is not None:
1008
+ cref = h.get("CanIfHthCanCtrlIdRef")
1009
+ if isinstance(cref, str) and cref:
1010
+ return ref_tail(cref)
1011
+ else:
1012
+ ref = pdu.get("CanIfRxPduHrhIdRef")
1013
+ if isinstance(ref, str) and ref:
1014
+ h = hrhs.get(ref_tail(ref))
1015
+ if h is not None:
1016
+ cref = h.get("CanIfHrhCanCtrlIdRef")
1017
+ if isinstance(cref, str) and cref:
1018
+ return ref_tail(cref)
1019
+ return ""
1020
+
1021
+
1022
+ def _canif_pdu(c: Ecuc, direction: str) -> CanIfPdu:
1023
+ pfx = "CanIfRxPdu" if direction == "RX" else "CanIfTxPdu"
1024
+ canid_raw = _first_int(c, f"{pfx}CanId")
1025
+ id_type_raw = str(
1026
+ c.get(f"{pfx}CanIdType", f"{pfx}IdType", default="")
1027
+ ).upper()
1028
+
1029
+ id_type = "?"
1030
+ if "EXTENDED" in id_type_raw:
1031
+ id_type = "EXTENDED"
1032
+ elif "STANDARD" in id_type_raw:
1033
+ id_type = "STANDARD"
1034
+
1035
+ # STANDARD_FD_CAN / EXTENDED_FD_CAN 里的 FD 是帧格式,不是 ID 类型
1036
+ is_fd = "FD_CAN" in id_type_raw or id_type_raw.endswith("_FD")
1037
+
1038
+ can_id = canid_raw
1039
+ if can_id is not None and can_id & EXTENDED_FLAG:
1040
+ can_id = can_id & ~EXTENDED_FLAG
1041
+ if id_type == "?":
1042
+ id_type = "EXTENDED"
1043
+
1044
+ ref = c.get(f"{pfx}Ref", default="")
1045
+
1046
+ return CanIfPdu(
1047
+ name=c.short_name,
1048
+ direction=direction,
1049
+ can_id=can_id,
1050
+ can_id_raw=canid_raw,
1051
+ id_type=id_type,
1052
+ is_fd=is_fd,
1053
+ dlc=_first_int(c, f"{pfx}Dlc", f"{pfx}DataLength"),
1054
+ container=c,
1055
+ pdu_ref=ref_tail(ref) if isinstance(ref, str) else "",
1056
+ )
1057
+
1058
+
1059
+ def _extract_pdur(model: ArxmlModel, st: StackModel) -> None:
1060
+ for rp in model.by_def("PduRRoutingPath"):
1061
+ src: list[str] = []
1062
+ dest: list[str] = []
1063
+ for name, vals in rp.params.items():
1064
+ low = name.lower()
1065
+ for v in vals:
1066
+ if not isinstance(v, str) or not v:
1067
+ continue
1068
+ if "src" in low and ("ref" in low or "pdu" in low):
1069
+ src.append(v)
1070
+ elif "dest" in low and ("ref" in low or "pdu" in low):
1071
+ dest.append(v)
1072
+ # 子容器形式:PduRSrcPdu / PduRDestPdu(最常见)
1073
+ for child in rp.children:
1074
+ if child.def_type == "PduRSrcPdu":
1075
+ for name, vals in child.params.items():
1076
+ if "ref" in name.lower():
1077
+ src.extend(v for v in vals if isinstance(v, str) and v)
1078
+ elif child.def_type.startswith("PduRDestPdu"):
1079
+ for name, vals in child.params.items():
1080
+ if "ref" in name.lower():
1081
+ dest.extend(v for v in vals if isinstance(v, str) and v)
1082
+ route_type = str(rp.get("PduRRouteType", default="")).upper()
1083
+ st.routing.append(
1084
+ PduRRouting(
1085
+ name=rp.short_name,
1086
+ src_refs=src,
1087
+ dest_refs=dest,
1088
+ container=rp,
1089
+ route_type=route_type,
1090
+ )
1091
+ )
1092
+ if not st.routing:
1093
+ st.notes.append("ARXML 中没有找到 PduRRoutingPath 容器")
1094
+
1095
+ # EcuC 的 Pdu 容器:长度兜底
1096
+ for pdu in model.by_def("Pdu"):
1097
+ st.ecuc_pdus[pdu.short_name] = _first_int(pdu, "PduLength")
1098
+
1099
+ for ap in st.com_pdus:
1100
+ if ap.length is None and ap.pdu_ref in st.ecuc_pdus:
1101
+ ap.length = st.ecuc_pdus[ap.pdu_ref]
1102
+ ap.length_source = "PduR"
1103
+
1104
+
1105
+ def _extract_candr(model: ArxmlModel, st: StackModel) -> None:
1106
+ for ctrl in model.by_def("CanController"):
1107
+ st.controllers.append(
1108
+ CanController(
1109
+ name=ctrl.short_name,
1110
+ baudrate=_first_int(ctrl, "CanControllerBaudRate", "CanCpuClockRef"),
1111
+ fd_baudrate=_first_int(
1112
+ ctrl, "CanControllerFdBaudRate", "CanControllerBaudRateFd"
1113
+ ),
1114
+ container=ctrl,
1115
+ )
1116
+ )
1117
+ for hoh in model.by_def("CanHardwareObject"):
1118
+ st.hw_objects.append(
1119
+ CanHwObject(
1120
+ name=hoh.short_name,
1121
+ handle_type=str(hoh.get("CanHandleType", default="?")).upper(),
1122
+ id_type=str(hoh.get("CanIdType", default="?")).upper(),
1123
+ container=hoh,
1124
+ )
1125
+ )
1126
+ if not st.controllers:
1127
+ st.notes.append("ARXML 中没有找到 CanController 容器")
1128
+
1129
+
1130
+ def _first_int(c: Ecuc, *names: str) -> int | None:
1131
+ for name in names:
1132
+ for v in c.params.get(name, []):
1133
+ if isinstance(v, bool):
1134
+ continue
1135
+ if isinstance(v, int):
1136
+ return v
1137
+ if isinstance(v, float) and v.is_integer():
1138
+ return int(v)
1139
+ if isinstance(v, str):
1140
+ try:
1141
+ return int(v, 0)
1142
+ except ValueError:
1143
+ continue
1144
+ return None
1145
+
1146
+
1147
+ def _norm_direction(raw: Any) -> str:
1148
+ s = str(raw).upper()
1149
+ if "SEND" in s or "TX" in s:
1150
+ return "SEND"
1151
+ if "RECEIVE" in s or "RX" in s:
1152
+ return "RECEIVE"
1153
+ return "?"
1154
+
1155
+
1156
+ def _norm_name(raw: str) -> str:
1157
+ """名字归一:去掉 PDU 前缀、非字母数字、全部小写。
1158
+
1159
+ 用于「同一 CanId 有多份 CanIf 配置」时挑出与本帧同名的那一份。
1160
+ DBC 帧名 `ECU_L` 与 EcuC Pdu `ECU_L` 归一后相等;
1161
+ 而改版残留的 `LegacyProjCfg` 归一后不同,会被排到后面。
1162
+ """
1163
+ s = re.sub(r"^(IPDU_|TX_PDU_|RX_PDU_|CANIF_(TX|RX)PDU_)", "", raw or "", flags=re.I)
1164
+ return re.sub(r"[^a-z0-9]", "", s.lower())
1165
+
1166
+
1167
+ def _guess_direction_from_type(ipdu: Ecuc) -> str:
1168
+ t = str(ipdu.get("ComIPduType", default="")).upper()
1169
+ if t == "NORMAL":
1170
+ d = str(ipdu.get("ComIPduDirection", default="")).upper()
1171
+ return _norm_direction(d)
1172
+ return "?"
1173
+
1174
+
1175
+ def _extract_cycle(ipdu: Ecuc) -> float | None:
1176
+ for child in ipdu.children:
1177
+ if child.def_type in ("ComTxModeTrue", "ComTxModeFalse", "ComTxMode"):
1178
+ v = child.get("ComTxModeTimePeriod", "ComTxModeTimeOffset")
1179
+ if isinstance(v, (int, float)):
1180
+ return float(v)
1181
+ v = ipdu.get("ComIPduCycleTime", "ComTxModeTimePeriod")
1182
+ return float(v) if isinstance(v, (int, float)) else None
1183
+
1184
+
1185
+ # ---------------------------------------------------------------------------
1186
+ # 校验结果
1187
+ # ---------------------------------------------------------------------------
1188
+
1189
+
1190
+ #: DBC 里的 E2E 信号:由 E2E 库(E2E_P01/P02/...)在 Com 之外写入,
1191
+ #: 所以 Com 里往往不配它们,不能当成「信号缺失」报。
1192
+ _E2E_SIGNAL_RE = re.compile(
1193
+ r"(checksum|crc|counter|rollcnt|rollingcounter|alivecounter|aliveindication|msgcounter)",
1194
+ re.I,
1195
+ )
1196
+
1197
+
1198
+ def _is_e2e_signal(name: str) -> bool:
1199
+ return bool(_E2E_SIGNAL_RE.search(name))
1200
+
1201
+
1202
+ def _is_whole_pdu_opaque(ax: AxPdu) -> bool:
1203
+ """Com 是否把整帧当一个字节数组建模(OPAQUE / UINT8_DYN)。
1204
+
1205
+ 这种建模下,Com 侧只有 1 个覆盖全帧的信号,而 DBC 可能把它拆成多个;
1206
+ 两者语义等价,不能逐个信号比。
1207
+ """
1208
+ if len(ax.signals) != 1 or ax.length is None:
1209
+ return False
1210
+ s = ax.signals[0]
1211
+ if not s.is_byte_array:
1212
+ return False
1213
+ # 覆盖整帧(长度容差:字节/位两种单位)
1214
+ for cand in (s.length, s.length_alt):
1215
+ if cand and cand >= ax.length * 8:
1216
+ return True
1217
+ return False
1218
+
1219
+
1220
+ @dataclass
1221
+ class Finding:
1222
+ code: str
1223
+ severity: str
1224
+ title: str
1225
+ detail: str = ""
1226
+ where: str = ""
1227
+
1228
+ def one_line(self) -> str:
1229
+ loc = f" [{self.where}]" if self.where else ""
1230
+ return f"[{self.severity[0].upper()}] {self.code} {self.title}{loc}"
1231
+
1232
+
1233
+ # ---------------------------------------------------------------------------
1234
+ # 匹配与校验
1235
+ # ---------------------------------------------------------------------------
1236
+
1237
+
1238
+ @dataclass
1239
+ class FrameBinding:
1240
+ dbc: DbcMessage
1241
+ canif: CanIfPdu | None = None
1242
+ com: AxPdu | None = None
1243
+ direction: str = "?" # 相对本 ECU:SEND / RECEIVE
1244
+ category: str = "COM" # COM / TP / NM / DIAG / UNKNOWN
1245
+ pdu_ref: str = "" # CanIf 指向的 EcuC Pdu
1246
+ note: str = ""
1247
+ #: 本 ECU 是否应该参与这帧(发或收)。
1248
+ #: 整网矩阵里有大量“与本 ECU 无关”的帧(别的节点的发给第三个节点的),
1249
+ #: 它们本来就该在 CanIf/Com 里找不到对应配置,不配报错。
1250
+ #: None = 无法判定(DBC 没有接收方信息、也没有节点信息)。
1251
+ involved: bool | None = None
1252
+
1253
+
1254
+ def _build_route_index(
1255
+ st: StackModel,
1256
+ ) -> tuple[dict[str, str], dict[str, str], dict[str, str]]:
1257
+ """PduR 路由索引:dest->src、src->dest、dest->route_type。"""
1258
+ dest_to_src: dict[str, str] = {}
1259
+ src_to_dest: dict[str, str] = {}
1260
+ dest_to_type: dict[str, str] = {}
1261
+ for r in st.routing:
1262
+ srcs = [ref_tail(x) for x in r.src_refs if ref_tail(x)]
1263
+ dests = [ref_tail(x) for x in r.dest_refs if ref_tail(x)]
1264
+ for d in dests:
1265
+ dest_to_type[d] = r.route_type
1266
+ for s in srcs:
1267
+ dest_to_src[d] = s
1268
+ src_to_dest[s] = d
1269
+ return dest_to_src, src_to_dest, dest_to_type
1270
+
1271
+
1272
+ def _classify(
1273
+ pdu_ref: str, dest_to_type: dict[str, str], st: StackModel, frame_name: str = "",
1274
+ can_id: int | None = None,
1275
+ ) -> str:
1276
+ """根据 CanIf 指向的 EcuC Pdu、PduR 路由类型、DBC 帧名与 CAN ID 判定链路种类。
1277
+
1278
+ 优先看 ARXML(更权威),ARXML 没线索时退到 DBC 命名与 ID 区间。
1279
+ """
1280
+ low = pdu_ref.lower()
1281
+ if dest_to_type.get(pdu_ref, "") == "TP" or "cantp" in low:
1282
+ return "TP"
1283
+ if low.startswith("dcm") or "_usdt" in low or "diag" in low:
1284
+ return "DIAG"
1285
+ if low.startswith("nm_") or "cannm" in low or low.startswith("nm"):
1286
+ return "NM"
1287
+
1288
+ # ARXML 无明确指向时,按 DBC 帧名与 ID 区间补判
1289
+ fn = frame_name.upper()
1290
+ if fn.startswith("NM_") or fn.startswith("NM") or "_NM_" in fn:
1291
+ return "NM"
1292
+ if "CANTP" in fn:
1293
+ return "TP"
1294
+ if fn.startswith("DIAG") or "_DIAG" in fn:
1295
+ return "DIAG"
1296
+ # ISO 15765 标准诊断 ID 区间
1297
+ if can_id is not None:
1298
+ if 0x7E0 <= can_id <= 0x7EF or 0x7E8 <= can_id <= 0x7EF + 0x10:
1299
+ return "DIAG"
1300
+ if can_id == 0x7DF:
1301
+ return "DIAG"
1302
+ return "COM"
1303
+
1304
+
1305
+ def build_bindings(
1306
+ dbc: DbcModel, st: StackModel, node: str | None
1307
+ ) -> tuple[list[FrameBinding], list[AxPdu], list[str]]:
1308
+ """按 CAN ID 把 DBC 帧、CanIf PDU、Com IPdu 绑在一起。
1309
+
1310
+ 真实拓扑不是按名字直连,而是:
1311
+ DBC 帧 --CanId--> CanIf PDU --CanIfXxxPduRef--> EcuC Pdu(X)
1312
+ --PduR 路由--> EcuC Pdu(COM_X) --ComPduIdRef--> Com IPdu
1313
+
1314
+ 返回 (绑定列表, 未匹配的 Com IPdu, 本配置覆盖的 DBC 节点列表)。
1315
+ """
1316
+ ecu_nodes = [node] if node else _infer_nodes(dbc, st)
1317
+ dest_to_src, src_to_dest, dest_to_type = _build_route_index(st)
1318
+
1319
+ canif_by_id: dict[int, list[CanIfPdu]] = {}
1320
+ for p in st.canif_rx + st.canif_tx:
1321
+ if p.can_id is not None:
1322
+ canif_by_id.setdefault(p.can_id, []).append(p)
1323
+
1324
+ com_by_pdu_ref: dict[str, AxPdu] = {}
1325
+ for p in st.com_pdus:
1326
+ if p.pdu_ref:
1327
+ com_by_pdu_ref[p.pdu_ref] = p
1328
+
1329
+ used_com: set[int] = set()
1330
+ bindings: list[FrameBinding] = []
1331
+
1332
+ for can_id, msg in sorted(dbc.messages.items()):
1333
+ b = FrameBinding(dbc=msg, direction="?")
1334
+ if ecu_nodes:
1335
+ # 多节点时:发送方在覆盖范围内就是 SEND,否则 RECEIVE
1336
+ b.direction = "SEND" if msg.tx_node in ecu_nodes else "RECEIVE"
1337
+ # 整网矩阵里判断这帧到底跟本 ECU 有没有关系
1338
+ b.involved = frame_involves_ecu(msg, ecu_nodes)
1339
+
1340
+ # 1) CanIf:按 CAN ID,多个候选时按方向优先
1341
+ cand = canif_by_id.get(can_id, [])
1342
+ if len(cand) > 1:
1343
+ # 同一 ID 多份 CanIf 配置时,光看方向不够(同为 TX 的两份无法区分),
1344
+ # 必须再用名字相似度挑 —— 否则会绑到同名改版残留上,
1345
+ # 派生出一大串假的「信号缺失」,把真问题淹掉。
1346
+ want = ("TX" if b.direction == "SEND" else "RX") if b.direction != "?" else None
1347
+ fname = _norm_name(msg.name)
1348
+
1349
+ def _rank(p: CanIfPdu) -> tuple[int, int]:
1350
+ dir_rank = 0 if (want and p.direction == want) else 1
1351
+ ref = _norm_name(p.pdu_ref or "")
1352
+ nm = _norm_name(p.name)
1353
+ name_rank = 0 if fname and (fname == ref or fname == nm) else (
1354
+ 1 if fname and (fname in ref or ref in fname or fname in nm) else 2
1355
+ )
1356
+ # 方向优先:DBC 说本 ECU 是发送方时,必须优先选 TX 那份。
1357
+ # 名字只用来在同方向的多份里挑「不是改版残留」的那份。
1358
+ return (dir_rank, name_rank)
1359
+
1360
+ cand = sorted(cand, key=_rank)
1361
+ if cand:
1362
+ b.canif = cand[0]
1363
+ b.pdu_ref = cand[0].pdu_ref
1364
+
1365
+ # 2) 分类:TP / DIAG / NM / COM
1366
+ b.category = _classify(
1367
+ b.pdu_ref, dest_to_type, st, frame_name=msg.name, can_id=can_id
1368
+ )
1369
+
1370
+ # 3) Com:沿 PduR 路由找到 COM_ 前缀的 Pdu,再找 Com IPdu
1371
+ if b.pdu_ref:
1372
+ for com_ref in (
1373
+ dest_to_src.get(b.pdu_ref), # dest=X -> src=COM_X
1374
+ src_to_dest.get(b.pdu_ref), # dest=COM_X -> src=X
1375
+ b.pdu_ref, # 直接同名
1376
+ "COM_" + b.pdu_ref,
1377
+ ):
1378
+ if not com_ref:
1379
+ continue
1380
+ hit = com_by_pdu_ref.get(com_ref)
1381
+ if hit is not None:
1382
+ b.com = hit
1383
+ break
1384
+
1385
+ if b.com is not None:
1386
+ used_com.add(id(b.com))
1387
+ if b.canif is not None and not b.com.bus:
1388
+ b.com.bus = b.canif.bus
1389
+ bindings.append(b)
1390
+
1391
+ # 未匹配的 Com:排除 TP / 诊断等本身就不走 Com 链路的
1392
+ unused = [
1393
+ p
1394
+ for p in st.com_pdus
1395
+ if id(p) not in used_com
1396
+ and dest_to_type.get(p.pdu_ref, "") != "TP"
1397
+ and "cantp" not in p.pdu_ref.lower()
1398
+ ]
1399
+
1400
+ # 未匹配的 Com IPdu 也补上总线归属:沿路由找到对端 EcuC Pdu,再找 CanIf PDU
1401
+ canif_by_pdu_ref: dict[str, CanIfPdu] = {
1402
+ p.pdu_ref: p for p in st.canif_rx + st.canif_tx if p.pdu_ref
1403
+ }
1404
+ for p in unused:
1405
+ if p.bus:
1406
+ continue
1407
+ for other in (dest_to_src.get(p.pdu_ref), src_to_dest.get(p.pdu_ref)):
1408
+ if not other:
1409
+ continue
1410
+ cand = canif_by_pdu_ref.get(other)
1411
+ if cand is not None:
1412
+ p.bus = cand.bus
1413
+ break
1414
+
1415
+ # 总线覆盖率:判断哪条总线不在本 DBC 的覆盖范围内
1416
+ dbc_ids = set(dbc.messages)
1417
+ stats: dict[str, list[int]] = {}
1418
+ for p in st.canif_rx + st.canif_tx:
1419
+ if p.can_id is None:
1420
+ continue
1421
+ key = p.bus or "(未知总线)"
1422
+ bucket = stats.setdefault(key, [0, 0])
1423
+ bucket[1] += 1
1424
+ if p.can_id in dbc_ids:
1425
+ bucket[0] += 1
1426
+ st.bus_coverage = {k: (v[0], v[1]) for k, v in stats.items()}
1427
+
1428
+ # 命中率 < 20% 的总线:本 DBC 不含这条网络,其帧不参与比对
1429
+ st.off_dbc_buses = {
1430
+ k for k, (hit, tot) in st.bus_coverage.items() if tot and hit / tot < 0.2
1431
+ }
1432
+
1433
+ return bindings, unused, ecu_nodes
1434
+
1435
+
1436
+ def _bus_in_dbc(pdu: CanIfPdu | None, st: StackModel) -> bool:
1437
+ """该 CanIf PDU 所在总线是否落在这份 DBC 的覆盖范围内。"""
1438
+ if pdu is None or not pdu.bus:
1439
+ return True
1440
+ return pdu.bus not in st.off_dbc_buses
1441
+
1442
+
1443
+ def _match_com_by_prefix(name: str, pdus: list[AxPdu], used: set[int]) -> AxPdu | None:
1444
+ norm = re.sub(r"[^a-z0-9]", "", name.lower())
1445
+ for p in pdus:
1446
+ if id(p) in used:
1447
+ continue
1448
+ pn = re.sub(r"[^a-z0-9]", "", p.name.lower())
1449
+ if not pn:
1450
+ continue
1451
+ if pn == norm or pn.endswith(norm) or norm.endswith(pn):
1452
+ return p
1453
+ return None
1454
+
1455
+
1456
+ def _infer_nodes(dbc: DbcModel, st: StackModel) -> list[str]:
1457
+ """找出本配置覆盖了 DBC 里的哪几个节点。
1458
+
1459
+ 一个 MCU 可能同时管左右两路(如 ECU_L + ECU_R),此时方向类检查不能按
1460
+ 单节点推断,必须退化为“多节点”模式,否则会把对侧帧误判成方向错。
1461
+ """
1462
+ if not dbc.nodes:
1463
+ return []
1464
+ blob = " ".join(c.name for c in st.com_pdus)
1465
+ blob += " " + " ".join(p.name for p in st.canif_rx + st.canif_tx)
1466
+ return [
1467
+ node
1468
+ for node in dbc.nodes
1469
+ if re.search(rf"(?<![A-Za-z0-9]){re.escape(node)}(?![A-Za-z0-9])", blob)
1470
+ ]
1471
+
1472
+
1473
+ def frame_involves_ecu(msg: DbcMessage, ecu_nodes: list[str]) -> bool | None:
1474
+ """本 ECU 是否应该参与这帧(发或收)。
1475
+
1476
+ 整网矩阵(一个 DBC 含全部 11 个节点、91 帧)里,绝大多数帧与本 ECU 无关:
1477
+ 是别的节点发给第三个节点的。这些帧本来就**不该**在本 ECU 的 CanIf/Com 里
1478
+ 出现,缺配置是正确状态,不是缺陷。
1479
+
1480
+ 原先的逻辑假定「DBC 每一帧都必须在本 ECU 里有配置」——那只对**单 ECU 视角**
1481
+ 的 DBC 成立。整网矩阵上这个假定会造出大量假 error(实测 91 帧里 99 条误报)。
1482
+
1483
+ 返回 None 表示无法判定(没有节点信息,或节点对不上 DBC 的节点表)。
1484
+ """
1485
+ if not ecu_nodes or not msg.signals:
1486
+ return None
1487
+ if msg.tx_node in ecu_nodes:
1488
+ return True # 本 ECU 是发送方
1489
+ for sig in msg.signals.values():
1490
+ for rx in sig.receivers:
1491
+ if rx in ecu_nodes:
1492
+ return True # 本 ECU 是某个信号的接收方
1493
+ # 有发送方信息、有接收方信息,且都不含本 ECU -> 与本 ECU 无关
1494
+ known_rx = any(sig.receivers for sig in msg.signals.values())
1495
+ if known_rx and msg.tx_node and msg.tx_node not in ("Vector__XXX", ""):
1496
+ return False
1497
+ return None
1498
+
1499
+
1500
+ def _infer_node(dbc: DbcModel, st: StackModel) -> str | None:
1501
+ nodes = _infer_nodes(dbc, st)
1502
+ return nodes[0] if nodes else None
1503
+
1504
+
1505
+ def run_checks(
1506
+ dbc: DbcModel, st: StackModel, node: str | None = None
1507
+ ) -> tuple[list[Finding], list[FrameBinding], list[str]]:
1508
+ findings: list[Finding] = []
1509
+ bindings, unused_com, ecu_nodes = build_bindings(dbc, st, node)
1510
+ ecu_node = ", ".join(ecu_nodes) if ecu_nodes else ""
1511
+
1512
+ # ---------- L0 前置 ----------
1513
+ # 空 DBC / 给错 DBC 是最容易造成「假绿」的场景:所有 PDU 都会因总线
1514
+ # 命中率 0% 被判为「不在本 DBC 范围」而整体跳过,最终报 0 error 0 warn。
1515
+ # 那等于什么都没查。必须失败,而不是成功。
1516
+ if not dbc.messages:
1517
+ findings.append(
1518
+ Finding(
1519
+ "AXD-023", "error",
1520
+ "DBC 里没有任何帧(BO_ 为空)",
1521
+ "没有参照物就无法校验。请确认给的是通信矩阵,"
1522
+ "而不是空文件或只含 BU_/VAL_TABLE_ 的片段。",
1523
+ where=str(dbc.path),
1524
+ )
1525
+ )
1526
+ return findings, [], ecu_nodes
1527
+
1528
+ if st.canif_rx or st.canif_tx:
1529
+ in_scope = [
1530
+ p
1531
+ for p in st.canif_rx + st.canif_tx
1532
+ if p.can_id is not None and _bus_in_dbc(p, st)
1533
+ ]
1534
+ if not in_scope:
1535
+ findings.append(
1536
+ Finding(
1537
+ "AXD-023", "error",
1538
+ "没有任何 CanIf PDU 落在本 DBC 的覆盖范围内",
1539
+ "两种可能:一是这份 DBC 不是本 ECU 所属网络的(给错了文件);"
1540
+ "二是总线归属回溯失败。无论哪种,本次校验实际上什么都没比。",
1541
+ where=", ".join(sorted(st.bus_coverage)) or "无总线信息",
1542
+ )
1543
+ )
1544
+ return findings, [], ecu_nodes
1545
+
1546
+ if not st.com_pdus:
1547
+ findings.append(
1548
+ Finding("AXD-000", "warn", "ARXML 未解析出 Com IPdu",
1549
+ "后续 Com 层校验全部跳过。请先用 probe 确认容器/参数命名。")
1550
+ )
1551
+
1552
+ # ---------- CanIf 层 ----------
1553
+ unrelated = 0
1554
+ for b in bindings:
1555
+ msg = b.dbc
1556
+ if b.canif is None:
1557
+ # 整网矩阵里与本 ECU 无关的帧:不配 CanIf 是**正确**状态
1558
+ if b.involved is False and b.category == "COM":
1559
+ unrelated += 1
1560
+ continue
1561
+ # NM / 诊断帧经常不在 CanIf 里(走 CanNm / CanTp+Dcm 的专用通道),
1562
+ # 只在确认属于 COM 链路时才报 error
1563
+ if b.category == "COM":
1564
+ findings.append(
1565
+ Finding(
1566
+ "AXD-001", "error",
1567
+ f"DBC 帧 {msg.name}(0x{msg.can_id:X}) 在 CanIf 中无对应 PDU",
1568
+ "该帧不会被收发:接收方永远等不到,发送方不会发出去。",
1569
+ where=f"0x{msg.can_id:X}",
1570
+ )
1571
+ )
1572
+ else:
1573
+ findings.append(
1574
+ Finding(
1575
+ "AXD-024", "info",
1576
+ f"{b.category} 帧 {msg.name}(0x{msg.can_id:X}) 未在 CanIf 中单独配置",
1577
+ "NM / 诊断 / TP 通常由 CanNm / Dcm / CanTp 内部管理,"
1578
+ "需要人工确认这几层是否存在对应配置。",
1579
+ where=f"0x{msg.can_id:X}",
1580
+ )
1581
+ )
1582
+ continue
1583
+ p = b.canif
1584
+ # CanIf 收发方向与 DBC 发送方的一致性
1585
+ if b.direction != "?":
1586
+ want_dir = "TX" if b.direction == "SEND" else "RX"
1587
+ if p.direction != want_dir:
1588
+ findings.append(
1589
+ Finding(
1590
+ "AXD-022", "error",
1591
+ f"{p.name} 是 {p.direction} PDU,但本 ECU 对 "
1592
+ f"0x{msg.can_id:X} 应为 {want_dir}",
1593
+ "收发方向配反,报文不会进本 PDU 的缓冲。",
1594
+ where=p.name,
1595
+ )
1596
+ )
1597
+ # TP 帧的 CanIf DLC 由 CanTp 协商,诊断帧 DBC 常写最大长度
1598
+ # —— 这两类都不与 DBC 单帧 DLC 硬比
1599
+ if (
1600
+ b.category not in ("TP", "DIAG")
1601
+ and p.dlc is not None
1602
+ and p.dlc != msg.dlc
1603
+ ):
1604
+ findings.append(
1605
+ Finding(
1606
+ "AXD-003", "error",
1607
+ f"{p.name} DLC 与 DBC 不一致:CanIf={p.dlc}B / DBC={msg.dlc}B",
1608
+ "长度不符会导致 PDU 被截断或读取越界。",
1609
+ where=p.name,
1610
+ )
1611
+ )
1612
+ if p.id_type != "?":
1613
+ want = "EXTENDED" if msg.is_extended else "STANDARD"
1614
+ if p.id_type != want:
1615
+ findings.append(
1616
+ Finding(
1617
+ "AXD-004", "error",
1618
+ f"{p.name} CanIdType={p.id_type},但 0x{msg.can_id:X} 应为 {want}",
1619
+ "标准/扩展帧不匹配时报文收不到。",
1620
+ where=p.name,
1621
+ )
1622
+ )
1623
+ # DBC 说是 FD,CanIf 却配成经典帧。
1624
+ # 不要断言是哪一边错:DBC 可能误标 FD,ARXML 也可能漏配。
1625
+ # 但如果这份 PDU 自己配成经典帧、又要求超过 8 字节,
1626
+ # 那它自身就已不可能成立——把这条硬证据直接摆出来,
1627
+ # 否则读者只会照着「ARXML 漏配」去改,改错了方向。
1628
+ if msg.is_fd and p.id_type != "?" and not p.is_fd:
1629
+ if p.dlc is not None and p.dlc > 8:
1630
+ # 再看 Com 侧信号到底占了多长:如果信号真占满 >8 字节,
1631
+ # 那「这帧是 FD」就没有争议,错的只能是 FD 标记本身,
1632
+ # 或者这帧根本不该出现在本 ECU 的矩阵里。
1633
+ span = 0
1634
+ if b.com is not None:
1635
+ occ: set[int] = set()
1636
+ for s in b.com.signals:
1637
+ occ |= set(s.bits)
1638
+ if occ:
1639
+ span = max(occ) // 8 + 1
1640
+ if span > 8:
1641
+ detail = (
1642
+ f"经典 CAN 单帧上限 8 字节,而这一帧的信号实际占满 {span} 字节"
1643
+ f"(Com IPdu 也写 {p.dlc} 字节),所以它只能是 FD——"
1644
+ "CanIf 的经典帧标记错了。若这帧本就不该出现在本 ECU 的矩阵里,"
1645
+ "那是 DBC 内容的问题,不是补一个 FD 标记能解决的。"
1646
+ )
1647
+ else:
1648
+ detail = (
1649
+ f"这份 PDU 配成经典帧却要求 {p.dlc} 字节,而经典 CAN 单帧上限 8 字节。"
1650
+ "CanIdType 或 DLC 必有一个写错了。"
1651
+ )
1652
+ else:
1653
+ detail = "FD 帧按普通 CAN 处理,长数据会被丢。"
1654
+ findings.append(
1655
+ Finding(
1656
+ "AXD-016", "error",
1657
+ f"{p.name} 配成经典帧,但 DBC 中 0x{msg.can_id:X} 是 CAN FD",
1658
+ detail,
1659
+ where=p.name,
1660
+ )
1661
+ )
1662
+
1663
+ # 同一个 CanId 出现多份 CanIf 配置(典型:RX+TX 各一份,或改版本没删旧容器)。
1664
+ # 绑定只会取其中一份,另一份的错误会被静默吞掉——必须单独报出来。
1665
+ _by_can_id: dict[int, list[CanIfPdu]] = {}
1666
+ for p in st.canif_rx + st.canif_tx:
1667
+ if p.can_id is not None:
1668
+ _by_can_id.setdefault(p.can_id, []).append(p)
1669
+ for cid, plist in sorted(_by_can_id.items()):
1670
+ if len(plist) < 2:
1671
+ continue
1672
+ desc = " / ".join(
1673
+ f"{q.direction}:{q.name}({'FD' if q.is_fd else '经典'},DLC={q.dlc})"
1674
+ for q in plist
1675
+ )
1676
+ # 多份配置本身不一定是错:两套工程合并到同一 ARXML 时,
1677
+ # 两边的 PDU 可能恰好落在同一个 CAN ID 上,这是**有意设计**。
1678
+ # 真正不可接受的是其中某一份自己就自相矛盾(经典帧却配 >8 字节),
1679
+ # 那份一定跑不起来。所以只按「有无自相矛盾的副本」定严重度。
1680
+ self_contradictory = [
1681
+ q for q in plist if (not q.is_fd) and q.dlc is not None and q.dlc > 8
1682
+ ]
1683
+ if self_contradictory:
1684
+ detail = (
1685
+ "其中 "
1686
+ + "、".join(
1687
+ f"{q.name} 是经典帧却配了 {q.dlc} 字节(经典帧上限 8 字节)"
1688
+ for q in self_contradictory
1689
+ )
1690
+ + ",这份配置不可能正常收发。"
1691
+ )
1692
+ else:
1693
+ detail = (
1694
+ "多套工程合并到同一 ARXML 时,PDU 落在同一 CAN ID 上属正常设计,"
1695
+ "只要每份自身长度/FD 状态自洽即可忽略;否则需确认保留哪一份。"
1696
+ )
1697
+ findings.append(
1698
+ Finding(
1699
+ "AXD-025", "error" if self_contradictory else "warn",
1700
+ f"CanId 0x{cid:X} 有 {len(plist)} 份 CanIf 配置:{desc}",
1701
+ detail,
1702
+ where=f"0x{cid:X}",
1703
+ )
1704
+ )
1705
+
1706
+ dbc_ids = set(dbc.messages)
1707
+ for p in st.canif_rx + st.canif_tx:
1708
+ if p.can_id is None:
1709
+ continue
1710
+ if p.can_id not in dbc_ids:
1711
+ cat = _classify(p.pdu_ref, {}, st, frame_name=p.name, can_id=p.can_id)
1712
+ in_scope = _bus_in_dbc(p, st)
1713
+ if not in_scope:
1714
+ # 该总线不在这份 DBC 的覆盖范围内,不报警
1715
+ findings.append(
1716
+ Finding(
1717
+ "AXD-026", "info",
1718
+ f"{p.bus} 上的 {p.name} (0x{p.can_id:X}) 不在本 DBC 覆盖范围",
1719
+ "该总线已整体跳过,详见头部「总线」行。",
1720
+ where=p.name,
1721
+ )
1722
+ )
1723
+ continue
1724
+ findings.append(
1725
+ Finding(
1726
+ "AXD-002", "warn" if cat == "COM" else "info",
1727
+ f"CanIf PDU {p.name} 的 CanId=0x{p.can_id:X} 在 DBC 中不存在",
1728
+ "可能是多配、或 DBC 漏了这帧。"
1729
+ if cat == "COM"
1730
+ else f"该 PDU 属于 {cat} 链路,DBC 通常不收录。",
1731
+ where=p.name,
1732
+ )
1733
+ )
1734
+
1735
+ # ---------- Com 层 ----------
1736
+ for b in bindings:
1737
+ msg = b.dbc
1738
+ if b.com is None:
1739
+ if not st.com_pdus:
1740
+ continue
1741
+ # 与本 ECU 无关的帧,Com 里没有配置是正确状态
1742
+ if b.involved is False and b.category == "COM":
1743
+ continue
1744
+ if b.category == "COM":
1745
+ findings.append(
1746
+ Finding(
1747
+ "AXD-006", "error",
1748
+ f"DBC 帧 {msg.name}(0x{msg.can_id:X}) 在 Com 中无对应 IPdu",
1749
+ "Com 层不知道这帧,信号不会被打包/解包。",
1750
+ where=f"0x{msg.can_id:X}",
1751
+ )
1752
+ )
1753
+ else:
1754
+ findings.append(
1755
+ Finding(
1756
+ "AXD-024", "info",
1757
+ f"{b.category} 帧 {msg.name}(0x{msg.can_id:X}) 不经过 Com",
1758
+ "属正常拓扑:NM 走 CanNm,诊断走 Dcm/CanTp。",
1759
+ where=f"0x{msg.can_id:X}",
1760
+ )
1761
+ )
1762
+ continue
1763
+ ax = b.com
1764
+ # TP PDU 是分段传输的缓冲区,长度与单帧 DLC 无可比性
1765
+ if ax.length is not None and ax.length != msg.dlc and b.category != "TP":
1766
+ findings.append(
1767
+ Finding(
1768
+ "AXD-005", "error",
1769
+ f"{ax.name} Com IPdu 长度 {ax.length}B ≠ DBC DLC {msg.dlc}B",
1770
+ "PDU 长度是上下层一致的硬约束。",
1771
+ where=ax.name,
1772
+ )
1773
+ )
1774
+
1775
+ # 方向一致性
1776
+ if b.direction != "?" and ax.direction != "?":
1777
+ if b.direction != ax.direction:
1778
+ findings.append(
1779
+ Finding(
1780
+ "AXD-020", "warn",
1781
+ f"{ax.name} 方向 {ax.direction} 与 DBC 发送方矛盾",
1782
+ f"本 ECU({ecu_node}) 在 DBC 里对 0x{msg.can_id:X} 是 {b.direction}。",
1783
+ where=ax.name,
1784
+ )
1785
+ )
1786
+
1787
+ # 信号集合
1788
+ ax_sigs = {s.name: s for s in ax.signals}
1789
+ dbc_sigs = msg.signals
1790
+
1791
+ # 整帧 OPAQUE 建模,或所在总线不在本 DBC 覆盖范围:不做逐信号比对
1792
+ if _is_whole_pdu_opaque(ax) or not _bus_in_dbc(b.canif, st):
1793
+ continue
1794
+
1795
+ for sname, dsig in dbc_sigs.items():
1796
+ if sname not in ax_sigs:
1797
+ # E2E 信号(Checksum / RollingCounter)由 E2E 库写入,Com 不配属正常
1798
+ if _is_e2e_signal(sname):
1799
+ continue
1800
+ alt = _find_name_drift(sname, ax_sigs)
1801
+ if alt:
1802
+ findings.append(
1803
+ Finding(
1804
+ "AXD-019", "warn",
1805
+ f"信号命名漂移:DBC '{sname}' ↔ ARXML '{alt}'",
1806
+ "仅大小写/下划线差异,工具能认,但手写代码会取不到值。",
1807
+ where=ax.name,
1808
+ )
1809
+ )
1810
+ ax_sigs[alt].name = sname # 归一后继续做几何比对
1811
+ ax_sigs[sname] = ax_sigs.pop(alt)
1812
+ else:
1813
+ findings.append(
1814
+ Finding(
1815
+ "AXD-006", "error",
1816
+ f"{ax.name} 缺少 DBC 信号 '{sname}'",
1817
+ f"位 {dsig.start}|{dsig.length}@{dsig.byte_order}",
1818
+ where=ax.name,
1819
+ )
1820
+ )
1821
+ for sname in list(ax_sigs):
1822
+ if sname not in dbc_sigs:
1823
+ # Com 里的 E2E 信号,DBC 未定义时也不报
1824
+ if _is_e2e_signal(sname):
1825
+ continue
1826
+ findings.append(
1827
+ Finding(
1828
+ "AXD-007", "warn",
1829
+ f"{ax.name} 里多出 DBC 中不存在的信号 '{sname}'",
1830
+ "Com 配了但 DBC 没定义,联调时该位无人解读。",
1831
+ where=ax.name,
1832
+ )
1833
+ )
1834
+
1835
+ # 逐个信号比对
1836
+ for sname, dsig in dbc_sigs.items():
1837
+ asig = ax_sigs.get(sname)
1838
+ if asig is None:
1839
+ continue
1840
+ _check_signal(findings, ax, dsig, asig)
1841
+
1842
+ # Com 内部重叠
1843
+ _check_internal_overlap(findings, ax)
1844
+
1845
+ for ax in unused_com:
1846
+ if not dbc.messages:
1847
+ continue
1848
+ # 该 Com IPdu 所在总线不在本 DBC 覆盖范围 → 不报
1849
+ if ax.bus and ax.bus in st.off_dbc_buses:
1850
+ continue
1851
+ findings.append(
1852
+ Finding(
1853
+ "AXD-007", "warn",
1854
+ f"Com IPdu {ax.name} 在 DBC 中找不到对应帧",
1855
+ "可能已废弃、或 DBC 版本滞后。",
1856
+ where=ax.name,
1857
+ )
1858
+ )
1859
+
1860
+ # ---------- PduR 层 ----------
1861
+ _check_pdur(findings, dbc, st, bindings)
1862
+
1863
+ # ---------- CanDrv 层 ----------
1864
+ if st.hw_objects:
1865
+ has_ext = any(m.is_extended for m in dbc.messages.values())
1866
+ has_std = any(not m.is_extended for m in dbc.messages.values())
1867
+ types = {h.id_type for h in st.hw_objects}
1868
+ if has_ext and not any("EXTENDED" in t or "MIXED" in t for t in types):
1869
+ findings.append(
1870
+ Finding("AXD-004", "error",
1871
+ "DBC 含扩展帧,但 CanHardwareObject 无 EXTENDED/MIXED",
1872
+ f"现有: {', '.join(sorted(types))}", where="CanDrv")
1873
+ )
1874
+ if has_std and not any("STANDARD" in t or "MIXED" in t for t in types):
1875
+ findings.append(
1876
+ Finding("AXD-004", "error",
1877
+ "DBC 含标准帧,但 CanHardwareObject 无 STANDARD/MIXED",
1878
+ f"现有: {', '.join(sorted(types))}", where="CanDrv")
1879
+ )
1880
+ for ctrl in st.controllers:
1881
+ if ctrl.baudrate is not None and ctrl.baudrate < 10000:
1882
+ findings.append(
1883
+ Finding("AXD-021", "info",
1884
+ f"{ctrl.name} 波特率异常小:{ctrl.baudrate}",
1885
+ "可能单位是 kbps 而非 bps,仅供参考。", where=ctrl.name)
1886
+ )
1887
+
1888
+ findings.sort(key=lambda f: (-SEV_ORDER[f.severity], f.code))
1889
+ return findings, bindings, ecu_nodes
1890
+
1891
+
1892
+ def _find_name_drift(name: str, pool: dict[str, Any]) -> str | None:
1893
+ norm = re.sub(r"[^a-z0-9]", "", name.lower())
1894
+ for cand in pool:
1895
+ if re.sub(r"[^a-z0-9]", "", cand.lower()) == norm and cand != name:
1896
+ return cand
1897
+ return None
1898
+
1899
+
1900
+ def _check_signal(
1901
+ findings: list[Finding], ax: AxPdu, dsig: DbcSignal, asig: AxSignal
1902
+ ) -> None:
1903
+ where = f"{ax.name}.{dsig.name}"
1904
+
1905
+ # 字节序
1906
+ if asig.byte_order != "?" and asig.byte_order != dsig.byte_order:
1907
+ findings.append(
1908
+ Finding(
1909
+ "AXD-009", "error",
1910
+ f"{where} 字节序不一致:Com={asig.byte_order} / DBC={dsig.byte_order}",
1911
+ "大端小端搞反会让数值完全错乱。",
1912
+ where=where,
1913
+ )
1914
+ )
1915
+
1916
+ if asig.length is not None and asig.length != dsig.length:
1917
+ findings.append(
1918
+ Finding(
1919
+ "AXD-010", "error",
1920
+ f"{where} 位宽不一致:Com={asig.length} / DBC={dsig.length}",
1921
+ "", where=where,
1922
+ )
1923
+ )
1924
+
1925
+ if asig.signed is not None and asig.signed != dsig.signed:
1926
+ findings.append(
1927
+ Finding(
1928
+ "AXD-010", "error",
1929
+ f"{where} 符号性不一致:Com={'signed' if asig.signed else 'unsigned'} "
1930
+ f"/ DBC={'signed' if dsig.signed else 'unsigned'}",
1931
+ "有符号当无符号解析,负值会变成大正数。", where=where,
1932
+ )
1933
+ )
1934
+
1935
+ # 位几何:只按 DBC 与 AUTOSAR 实测一致的 MSB 约定算。
1936
+ # 若厂商用了 LSB 约定,这里会报 AXD-008 —— 提交给人确认,不做静默回退,
1937
+ # 否则真正的起始位错误会被"约定回退"掩盖掉。
1938
+ if asig.start_position is not None and asig.length is not None:
1939
+ want = dsig.bits()
1940
+ got = asig.bits
1941
+ if got != want:
1942
+ findings.append(
1943
+ Finding(
1944
+ "AXD-008", "error",
1945
+ f"{where} 位几何不一致",
1946
+ f"Com: start={asig.start_position} len={asig.length} "
1947
+ f"[{asig.bits_convention}] 占用 bits={sorted(got)[:8]}…\n"
1948
+ f" DBC: start={dsig.start} len={dsig.length} "
1949
+ f"占用 bits={sorted(want)[:8]}…",
1950
+ where=where,
1951
+ )
1952
+ )
1953
+
1954
+ # 越界
1955
+ if ax.length and asig.bits and max(asig.bits) >= ax.length * 8:
1956
+ findings.append(
1957
+ Finding(
1958
+ "AXD-017", "error",
1959
+ f"{where} 越过 IPdu 边界:最高 bit {max(asig.bits)} ≥ {ax.length*8}",
1960
+ "", where=where,
1961
+ )
1962
+ )
1963
+
1964
+ # 初始值
1965
+ if asig.init_value is not None and dsig.start_value is not None:
1966
+ if abs(asig.init_value - dsig.start_value) > 1e-9:
1967
+ findings.append(
1968
+ Finding(
1969
+ "AXD-011", "error",
1970
+ f"{where} 初始值不一致:Com={asig.init_value} / DBC={dsig.start_value}",
1971
+ "以 DBC 的 GenSigStartValue 为准。上电到第一次收发之间,"
1972
+ "收发双方看到的就是初始值;不一致会导致这段时间的状态判断出错"
1973
+ "(例:大灯高度初始角算错)。两边都没写、或只有一边写,不算问题。",
1974
+ where=where,
1975
+ )
1976
+ )
1977
+
1978
+
1979
+
1980
+ def _check_cycle(findings: list[Finding], msg: DbcMessage, ax: AxPdu) -> None:
1981
+ if ax.cycle_ms is None or msg.cycle_ms is None:
1982
+ return
1983
+ raw = ax.cycle_ms
1984
+ candidates = {raw, raw * 1000.0, raw / 1000.0}
1985
+ if any(abs(c - msg.cycle_ms) <= 1.0 for c in candidates):
1986
+ return
1987
+ findings.append(
1988
+ Finding(
1989
+ "AXD-012", "warn",
1990
+ f"{ax.name} 周期不一致:Com={raw} / DBC={msg.cycle_ms}ms",
1991
+ "已尝试秒/毫秒两种换算仍不匹配。",
1992
+ where=ax.name,
1993
+ )
1994
+ )
1995
+
1996
+
1997
+
1998
+ def _check_internal_overlap(findings: list[Finding], ax: AxPdu) -> None:
1999
+ seen: dict[int, str] = {}
2000
+ for sig in ax.signals:
2001
+ if sig.is_byte_array:
2002
+ continue
2003
+ for bit in sorted(sig.bits):
2004
+ if bit in seen:
2005
+ findings.append(
2006
+ Finding(
2007
+ "AXD-018", "error",
2008
+ f"{ax.name} 内信号位重叠:bit {bit} 被 "
2009
+ f"'{seen[bit]}' 与 '{sig.name}' 同时占用",
2010
+ "两个信号抢同一位,值永远错。",
2011
+ where=ax.name,
2012
+ )
2013
+ )
2014
+ break
2015
+ seen[bit] = sig.name
2016
+
2017
+
2018
+ def _check_pdur(
2019
+ findings: list[Finding],
2020
+ dbc: DbcModel,
2021
+ st: StackModel,
2022
+ bindings: list[FrameBinding],
2023
+ ) -> None:
2024
+ if not st.routing:
2025
+ return
2026
+
2027
+ # 已知的 EcuC Pdu 全集:EcuC 定义 + Com 引用 + CanIf 引用
2028
+ known: set[str] = set(st.ecuc_pdus)
2029
+ known |= {p.pdu_ref for p in st.com_pdus if p.pdu_ref}
2030
+ known |= {p.pdu_ref for p in st.canif_rx + st.canif_tx if p.pdu_ref}
2031
+
2032
+ routed: set[str] = set()
2033
+ for r in st.routing:
2034
+ ends = [ref_tail(x) for x in r.src_refs + r.dest_refs]
2035
+ ends = [x for x in ends if x]
2036
+ routed.update(ends)
2037
+ # 悬空引用:引用的名字在 EcuC / Com / CanIf 里一个都不存在
2038
+ for tail in ends:
2039
+ if tail not in known:
2040
+ findings.append(
2041
+ Finding(
2042
+ "AXD-014", "error",
2043
+ f"PduR 路由 {r.name} 引用了不存在的 PDU '{tail}'",
2044
+ "悬空引用会导致该路由失效,链接期或运行时才暴露。",
2045
+ where=r.name,
2046
+ )
2047
+ )
2048
+
2049
+ # Com IPdu 是否接上了 PduR(按它的 EcuC Pdu 引用判断)
2050
+ for b in bindings:
2051
+ if b.com is None or b.category == "TP":
2052
+ continue
2053
+ ref = b.com.pdu_ref
2054
+ if not ref:
2055
+ findings.append(
2056
+ Finding(
2057
+ "AXD-015", "error",
2058
+ f"Com IPdu {b.com.name} 没有 ComPduIdRef,无法接入 PduR",
2059
+ "Com 与下层之间没有通路,数据不会流转。",
2060
+ where=b.com.name,
2061
+ )
2062
+ )
2063
+ elif ref not in routed:
2064
+ findings.append(
2065
+ Finding(
2066
+ "AXD-015", "error",
2067
+ f"Com IPdu {b.com.name} 的 PDU '{ref}' 没有 PduR 路由",
2068
+ "Com 与下层之间没有通路,数据不会流转。",
2069
+ where=b.com.name,
2070
+ )
2071
+ )
2072
+
2073
+ # CanIf PDU 是否也有路由(NM / 诊断例外)
2074
+ for b in bindings:
2075
+ if b.canif is None or b.category in ("NM", "DIAG", "TP"):
2076
+ continue
2077
+ ref = b.canif.pdu_ref
2078
+ if ref and ref not in routed:
2079
+ findings.append(
2080
+ Finding(
2081
+ "AXD-015", "error",
2082
+ f"CanIf PDU {b.canif.name} 的 PDU '{ref}' 没有 PduR 路由",
2083
+ "报文能收到但上不去,或 Com 发出来但下不去。",
2084
+ where=b.canif.name,
2085
+ )
2086
+ )
2087
+
2088
+
2089
+ # ---------------------------------------------------------------------------
2090
+ # 输出
2091
+ # ---------------------------------------------------------------------------
2092
+
2093
+
2094
+ def render(findings: list[Finding], min_sev: str = "info") -> str:
2095
+ threshold = SEV_ORDER[min_sev]
2096
+ shown = [f for f in findings if SEV_ORDER[f.severity] >= threshold]
2097
+ counts = {s: sum(1 for f in findings if f.severity == s) for s in SEV_ORDER}
2098
+ lines: list[str] = []
2099
+ last = None
2100
+ for f in shown:
2101
+ if f.code != last:
2102
+ lines.append("")
2103
+ last = f.code
2104
+ lines.append(f.one_line())
2105
+ if f.detail:
2106
+ for dl in f.detail.split("\n"):
2107
+ lines.append(" " + dl)
2108
+ lines.append("")
2109
+ lines.append(
2110
+ f"summary: {counts['error']} error, {counts['warn']} warn, {counts['info']} info"
2111
+ )
2112
+ return "\n".join(lines)
2113
+
2114
+
2115
+ # ---------------------------------------------------------------------------
2116
+ # 子命令
2117
+ # ---------------------------------------------------------------------------
2118
+
2119
+
2120
+ def cmd_probe(args: argparse.Namespace) -> int:
2121
+ model = parse_arxml(Path(args.arxml))
2122
+ st = extract_stack(model)
2123
+ print(f"file {model.path}")
2124
+ print(f"encoding {model.encoding}")
2125
+ print(f"modules {', '.join(model.module_names()) or '(none)'}")
2126
+ print()
2127
+ print("=== 容器类型统计 ===")
2128
+ counts: dict[str, int] = {}
2129
+ for c in model.containers:
2130
+ counts[c.def_type] = counts.get(c.def_type, 0) + 1
2131
+ for name, n in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])):
2132
+ if n >= 1:
2133
+ print(f" {name:<36} {n}")
2134
+ print()
2135
+ print("=== 各层抽取结果 ===")
2136
+ print(f" Com IPdu {len(st.com_pdus):>4} 信号 "
2137
+ f"{sum(len(p.signals) for p in st.com_pdus):>4}")
2138
+ print(f" CanIf RX/TX {len(st.canif_rx):>4} / {len(st.canif_tx)}")
2139
+ print(f" PduR 路由 {len(st.routing):>4}")
2140
+ print(f" CanController {len(st.controllers):>4}")
2141
+ print(f" CanHardwareObj {len(st.hw_objects):>4}")
2142
+ if st.notes:
2143
+ print()
2144
+ print("=== 注意 ===")
2145
+ for n in st.notes:
2146
+ print(" ! " + n)
2147
+
2148
+ if args.json:
2149
+ payload = {
2150
+ "modules": model.module_names(),
2151
+ "container_counts": counts,
2152
+ "com_pdus": [
2153
+ {
2154
+ "name": p.name,
2155
+ "direction": p.direction,
2156
+ "length": p.length,
2157
+ "cycle_ms": p.cycle_ms,
2158
+ "signals": [
2159
+ {
2160
+ "name": s.name,
2161
+ "start": s.start_position,
2162
+ "len": s.length,
2163
+ "order": s.byte_order,
2164
+ "source": s.source,
2165
+ }
2166
+ for s in p.signals
2167
+ ],
2168
+ }
2169
+ for p in st.com_pdus
2170
+ ],
2171
+ "canif": [
2172
+ {"name": p.name, "dir": p.direction, "canid": p.can_id,
2173
+ "id_type": p.id_type, "dlc": p.dlc}
2174
+ for p in st.canif_rx + st.canif_tx
2175
+ ],
2176
+ "routing": [
2177
+ {"name": r.name, "src": r.src_refs, "dest": r.dest_refs}
2178
+ for r in st.routing
2179
+ ],
2180
+ "notes": st.notes,
2181
+ }
2182
+ print()
2183
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
2184
+ return 0
2185
+
2186
+
2187
+ def cmd_check(args: argparse.Namespace) -> int:
2188
+ arxml_path = Path(args.arxml)
2189
+ dbc_path = Path(args.dbc)
2190
+ model = parse_arxml(arxml_path)
2191
+ st = extract_stack(model)
2192
+ dbc = parse_dbc(dbc_path)
2193
+
2194
+ findings, bindings, ecu_nodes = run_checks(dbc, st, args.node)
2195
+ ecu_node = ", ".join(ecu_nodes) if ecu_nodes else ""
2196
+
2197
+ # 帧级周期校验(信号循环里不做)
2198
+ for b in bindings:
2199
+ if b.com is not None:
2200
+ _check_cycle(findings, b.dbc, b.com)
2201
+ findings.sort(key=lambda f: (-SEV_ORDER[f.severity], f.code))
2202
+
2203
+ if args.json:
2204
+ print(json.dumps(
2205
+ {
2206
+ "arxml": str(arxml_path),
2207
+ "dbc": str(dbc_path),
2208
+ "ecu_nodes": ecu_nodes,
2209
+ "dbc_encoding": dbc.encoding,
2210
+ "arxml_encoding": model.encoding,
2211
+ "frames": len(dbc.messages),
2212
+ "com_pdus": len(st.com_pdus),
2213
+ "canif_pdus": len(st.canif_rx) + len(st.canif_tx),
2214
+ "routing_paths": len(st.routing),
2215
+ "bus_coverage": {
2216
+ k: {"hit": v[0], "total": v[1],
2217
+ "in_scope": k not in st.off_dbc_buses}
2218
+ for k, v in sorted(st.bus_coverage.items())
2219
+ },
2220
+ "findings": [
2221
+ {"code": f.code, "severity": f.severity, "title": f.title,
2222
+ "detail": f.detail, "where": f.where}
2223
+ for f in findings
2224
+ ],
2225
+ "notes": st.notes,
2226
+ },
2227
+ ensure_ascii=False, indent=2,
2228
+ ))
2229
+ else:
2230
+ print(f"arxml {arxml_path} (编码 {model.encoding})")
2231
+ print(f"dbc {dbc_path} (编码 {dbc.encoding})")
2232
+ print(f"模块 {', '.join(st.present_modules)}")
2233
+ print(f"帧 DBC {len(dbc.messages)} / Com {len(st.com_pdus)} / "
2234
+ f"CanIf {len(st.canif_rx)+len(st.canif_tx)} / 路由 {len(st.routing)}")
2235
+ print(f"ECU 节点 {ecu_node or '(未识别,跳过方向校验,可用 --node 指定)'}")
2236
+ # 总线覆盖率必须打出来:命中率低的总线会被整体跳过,
2237
+ # 不说清楚就会把「只查了一条总线」误读成「全都对上了」
2238
+ if st.bus_coverage:
2239
+ parts = []
2240
+ for bus, (hit, tot) in sorted(st.bus_coverage.items()):
2241
+ tag = "跳过" if bus in st.off_dbc_buses else "比对"
2242
+ parts.append(f"{bus} {hit}/{tot} {tag}")
2243
+ print(f"总线 {' | '.join(parts)}")
2244
+ for n in st.notes:
2245
+ print(f"注意 {n}")
2246
+ print(render(findings, args.min_severity))
2247
+
2248
+ has_error = any(f.severity == "error" for f in findings)
2249
+ if args.no_fail:
2250
+ return 0
2251
+ return 1 if has_error else 0
2252
+
2253
+
2254
+ def cmd_matrix(args: argparse.Namespace) -> int:
2255
+ model = parse_arxml(Path(args.arxml))
2256
+ st = extract_stack(model)
2257
+ dbc = parse_dbc(Path(args.dbc))
2258
+ bindings, unused, ecu_nodes = build_bindings(dbc, st, args.node)
2259
+ ecu_node = ", ".join(ecu_nodes) if ecu_nodes else ""
2260
+
2261
+ rows = []
2262
+ for b in bindings:
2263
+ m = b.dbc
2264
+ ax = b.com
2265
+ ax_sigs = {s.name: s for s in ax.signals} if ax else {}
2266
+ used_ax: set[str] = set()
2267
+ status_map: dict[str, str] = {}
2268
+
2269
+ # 不走 Com 链路的帧(NM / 诊断 / TP):整体一行标注,
2270
+ # 不逐信号报「只有DBC」,否则 64 个 TP 分片会肿成上百行假差异
2271
+ if ax is None or not _bus_in_dbc(b.canif, st):
2272
+ why = (
2273
+ f"不在本 DBC 覆盖的总线({b.canif.bus})"
2274
+ if ax is not None and not _bus_in_dbc(b.canif, st)
2275
+ else f"{b.category} 链路,不经过 Com"
2276
+ )
2277
+ rows.append({
2278
+ "canid": f"0x{m.can_id:X}",
2279
+ "frame": m.name,
2280
+ "dlc": m.dlc,
2281
+ "tx_node": m.tx_node,
2282
+ "ecu_dir": b.direction,
2283
+ "canif_pdu": b.canif.name if b.canif else "",
2284
+ "com_pdu": ax.name if ax else "",
2285
+ "dbc_signal": f"({len(m.signals)} 个信号)",
2286
+ "arxml_signal": "",
2287
+ "status": "不比对",
2288
+ "dbc_geom": why,
2289
+ "arxml_geom": "",
2290
+ })
2291
+ continue
2292
+
2293
+ # 整帧 OPAQUE 建模:Com 侧只有 1 个字节数组信号,DBC 拆分建模,
2294
+ # 语义等价,导出时标注 whole-pdu 而不是逐行报「只有DBC」
2295
+ if ax is not None and _is_whole_pdu_opaque(ax):
2296
+ only = ax.signals[0]
2297
+ rows.append({
2298
+ "canid": f"0x{m.can_id:X}",
2299
+ "frame": m.name,
2300
+ "dlc": m.dlc,
2301
+ "tx_node": m.tx_node,
2302
+ "ecu_dir": b.direction,
2303
+ "canif_pdu": b.canif.name if b.canif else "",
2304
+ "com_pdu": ax.name,
2305
+ "dbc_signal": f"({len(m.signals)} 个信号)",
2306
+ "arxml_signal": only.name,
2307
+ "status": "整帧字节数组",
2308
+ "dbc_geom": "",
2309
+ "arxml_geom": f"{only.start_position}|{only.length}@{only.byte_order}",
2310
+ })
2311
+ continue
2312
+
2313
+ # 先按同名配对,再按命名漂移配对,剩下的各自单列
2314
+ pairs: list[tuple[str, str]] = []
2315
+ for dn in m.signals:
2316
+ if dn in ax_sigs:
2317
+ pairs.append((dn, dn))
2318
+ used_ax.add(dn)
2319
+ for dn in m.signals:
2320
+ if any(dn == x for x, _ in pairs):
2321
+ continue
2322
+ drift = _find_name_drift(dn, ax_sigs)
2323
+ if drift is not None and drift not in used_ax:
2324
+ pairs.append((dn, drift))
2325
+ used_ax.add(drift)
2326
+ status_map[dn] = "名字漂移"
2327
+ for dn in m.signals:
2328
+ if not any(dn == x for x, _ in pairs):
2329
+ pairs.append((dn, ""))
2330
+ # E2E 信号由 E2E 库在 Com 之外写入,Com 未配置属正常
2331
+ status_map[dn] = "E2E信号未配" if _is_e2e_signal(dn) else "只有DBC"
2332
+ for an in ax_sigs:
2333
+ if an not in used_ax:
2334
+ pairs.append(("", an))
2335
+ # Com 里的 E2E 信号,DBC 未定义时也不当差异报
2336
+ status_map[an] = (
2337
+ "E2E信号未配" if _is_e2e_signal(an) else "只有ARXML"
2338
+ )
2339
+
2340
+ for dn, an in pairs:
2341
+ d = m.signals.get(dn)
2342
+ a = ax_sigs.get(an)
2343
+ status = status_map.get(dn) or status_map.get(an) or "OK"
2344
+ if status == "OK" and d and a:
2345
+ if d.bits() != a.bits:
2346
+ status = "几何不同"
2347
+ elif d.length != a.length:
2348
+ status = "位宽不同"
2349
+ elif a.byte_order != "?" and d.byte_order != a.byte_order:
2350
+ status = "字节序不同"
2351
+ rows.append({
2352
+ "canid": f"0x{m.can_id:X}",
2353
+ "frame": m.name,
2354
+ "dlc": m.dlc,
2355
+ "tx_node": m.tx_node,
2356
+ "ecu_dir": b.direction,
2357
+ "canif_pdu": b.canif.name if b.canif else "",
2358
+ "com_pdu": ax.name if ax else "",
2359
+ "dbc_signal": dn,
2360
+ "arxml_signal": an,
2361
+ "status": status,
2362
+ "dbc_geom": f"{d.start}|{d.length}@{d.byte_order}" if d else "",
2363
+ "arxml_geom": (
2364
+ f"{a.start_position}|{a.length}@{a.byte_order}" if a else ""
2365
+ ),
2366
+ })
2367
+
2368
+ out = Path(args.csv)
2369
+ with out.open("w", newline="", encoding="utf-8-sig") as fh:
2370
+ w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()) if rows else ["canid"])
2371
+ w.writeheader()
2372
+ w.writerows(rows)
2373
+ print(f"wrote {out} ({len(rows)} 行, ECU 节点 {ecu_node or '未识别'}, "
2374
+ f"{len(unused)} 个 Com IPdu 未匹配)")
2375
+ return 0
2376
+
2377
+
2378
+ def cmd_selftest(args: argparse.Namespace) -> int:
2379
+ """用程序生成的内置示例跑一遍,断言预期检查码全部命中。"""
2380
+ import tempfile
2381
+
2382
+ try:
2383
+ import demo_fixtures as fixtures
2384
+ except ImportError: # pragma: no cover
2385
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
2386
+ import demo_fixtures as fixtures
2387
+
2388
+ with tempfile.TemporaryDirectory() as td:
2389
+ ax = Path(td) / "demo.arxml"
2390
+ dbc_path = Path(td) / "demo.dbc"
2391
+ ax.write_text(fixtures.build_demo_arxml(), encoding="utf-8")
2392
+ dbc_path.write_text(fixtures.DEMO_DBC, encoding="utf-8")
2393
+
2394
+ model = parse_arxml(ax)
2395
+ st = extract_stack(model)
2396
+ dbc_model = parse_dbc(dbc_path)
2397
+ findings, bindings, node = run_checks(dbc_model, st, None)
2398
+
2399
+ codes = sorted({f.code for f in findings})
2400
+ expected = set(fixtures.EXPECTED_CODES)
2401
+ missing = expected - set(codes)
2402
+ print(f"节点推断: {node or '(未识别)'}")
2403
+ print(f"帧 {len(dbc_model.messages)} / ComPdus {len(st.com_pdus)} / "
2404
+ f"CanIf {len(st.canif_rx)+len(st.canif_tx)} / 路由 {len(st.routing)}")
2405
+ print(f"命中代码: {', '.join(codes) or '(无)'}")
2406
+ print(render(findings, "info"))
2407
+ if missing:
2408
+ print(f"自检失败:以下预期代码未触发 -> {', '.join(sorted(missing))}",
2409
+ file=sys.stderr)
2410
+ return 1
2411
+
2412
+ # 只断言码集合是不够的:示例数据漂到面目全非时码仍可能触发,
2413
+ # 「自检通过」会变成一句空话。条数也要卡住。
2414
+ got_counts = {
2415
+ lvl: sum(1 for f in findings if f.severity == lvl)
2416
+ for lvl in ("error", "warn", "info")
2417
+ }
2418
+ want_counts = getattr(fixtures, "EXPECTED_COUNTS", None)
2419
+ if want_counts:
2420
+ off = {k: (want_counts.get(k), got_counts[k])
2421
+ for k in got_counts if want_counts.get(k) != got_counts[k]}
2422
+ if off:
2423
+ detail = ", ".join(f"{k} 期望 {w} 实得 {g}" for k, (w, g) in off.items())
2424
+ print(f"自检失败:条数不符 -> {detail}", file=sys.stderr)
2425
+ return 1
2426
+ print("自检通过")
2427
+ return 0
2428
+
2429
+
2430
+ def main(argv: list[str] | None = None) -> int:
2431
+ p = argparse.ArgumentParser(
2432
+ prog="arxml_dbc_check",
2433
+ description="AUTOSAR 通信栈 ARXML (Com/PduR/CanIf/CanDrv) 与 DBC 交叉校验",
2434
+ )
2435
+ sub = p.add_subparsers(dest="cmd", required=True)
2436
+
2437
+ sp = sub.add_parser("probe", help="探测 ARXML 变体")
2438
+ sp.add_argument("arxml")
2439
+ sp.add_argument("--json", action="store_true")
2440
+ sp.set_defaults(func=cmd_probe)
2441
+
2442
+ sc = sub.add_parser("check", help="全链路校验")
2443
+ sc.add_argument("arxml")
2444
+ sc.add_argument("dbc")
2445
+ sc.add_argument("--node", help="本 ECU 在 DBC 中的节点名(用于方向校验)")
2446
+ sc.add_argument("--json", action="store_true")
2447
+ sc.add_argument("--min-severity", default="info",
2448
+ choices=["error", "warn", "info"])
2449
+ sc.add_argument("--no-fail", action="store_true")
2450
+ sc.set_defaults(func=cmd_check)
2451
+
2452
+ sm = sub.add_parser("matrix", help="导出帧-信号对照台账 CSV")
2453
+ sm.add_argument("arxml")
2454
+ sm.add_argument("dbc")
2455
+ sm.add_argument("--csv", required=True)
2456
+ sm.add_argument("--node")
2457
+ sm.set_defaults(func=cmd_matrix)
2458
+
2459
+ ss = sub.add_parser("selftest", help="内置示例自检")
2460
+ ss.set_defaults(func=cmd_selftest)
2461
+
2462
+ args = p.parse_args(argv)
2463
+
2464
+ # 先把输入文件查一遍,避免在深层派系里抛裸 traceback
2465
+ for attr in ("arxml", "dbc"):
2466
+ val = getattr(args, attr, None)
2467
+ if not val:
2468
+ continue
2469
+ path = Path(val)
2470
+ if not path.exists():
2471
+ print(f"error: {attr} 文件不存在:{val}", file=sys.stderr)
2472
+ return 2
2473
+ if path.is_dir():
2474
+ print(f"error: {attr} 是目录,不是一个文件:{val}", file=sys.stderr)
2475
+ return 2
2476
+ if path.stat().st_size == 0:
2477
+ print(f"error: {attr} 是空文件:{val}", file=sys.stderr)
2478
+ return 2
2479
+ try:
2480
+ with path.open("rb") as fh:
2481
+ head = fh.read(512).lstrip()
2482
+ except OSError as exc:
2483
+ print(f"error: 读不了 {attr} {val}:{exc}", file=sys.stderr)
2484
+ return 2
2485
+ # 传反了是最常见的误操作,提前给出点名提示
2486
+ if attr == "arxml" and not head.startswith(b"<?xml") and not head.startswith(b"<"):
2487
+ print(
2488
+ f"error: {val} 看起来不是 XML/ARXML(开头不是 '<')。"
2489
+ "是不是把 .dbc 和 .arxml 两个参数传反了?",
2490
+ file=sys.stderr,
2491
+ )
2492
+ return 2
2493
+
2494
+ try:
2495
+ return int(args.func(args))
2496
+ except AxdError as exc:
2497
+ print(f"error: {exc}", file=sys.stderr)
2498
+ return 2
2499
+ except OSError as exc:
2500
+ print(f"error: {exc}", file=sys.stderr)
2501
+ return 2
2502
+
2503
+
2504
+ if __name__ == "__main__":
2505
+ sys.exit(main())