schema.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. """公共数据结构:检测框、单帧观测、时序判决、PLC 快照。
  2. 约定
  3. ----
  4. * 检测框一律使用 **像素坐标**,原点在图像左上角,``y`` 向下增大。
  5. * :class:`SceneState` 的枚举值就是最终反馈给西门子 PLC 的编码,改动前先确认 PLC 侧。
  6. * :class:`VisionSnapshot` 是"视觉 → PLC"的唯一数据载体,Modbus/TCP 服务端与 S7 推送端
  7. 都必须通过它来编码,保证两条链路语义一致。
  8. """
  9. from __future__ import annotations
  10. from dataclasses import dataclass, field
  11. from enum import Enum, IntEnum
  12. from typing import TYPE_CHECKING, Dict, List, Sequence, Tuple
  13. if TYPE_CHECKING: # pragma: no cover - 仅类型检查,避免 schema ↔ recognition 循环导入
  14. from .recognition import RecognitionResult
  15. __all__ = [
  16. "Box",
  17. "CommitPhase",
  18. "Decision",
  19. "Observation",
  20. "PlcCommand",
  21. "SceneState",
  22. "STATE_LABELS",
  23. "STATE_NAME_TO_CODE",
  24. "StatusBits",
  25. "ViewMode",
  26. "VisionSnapshot",
  27. "crc16_modbus",
  28. "recognition_results",
  29. ]
  30. class SceneState(IntEnum):
  31. """反馈给 PLC 的场景编码。
  32. ``3``(空车)是 v2 P0-Q9 新增的**独立车型结论**,不是 ``0`` 的子类:
  33. ``0`` = 不是目标车(地面/堆场/卡车/其他车型),``3`` = 确认是敞车、但车斗
  34. 里没有箱(可以装车)。二者对 PLC 的动作含义完全不同,不能合并。
  35. """
  36. NOT_ON_TRAIN = 0 # 集装箱不在车上 / 不是目标车
  37. BED = 1 # 车斗(敞车,车上有箱)
  38. FLATBED = 2 # 平板车(平车,车上有箱)
  39. EMPTY = 3 # 空车(敞车,车斗内无箱)
  40. UNKNOWN = 255 # 视觉未就绪 / 结果不可信
  41. @property
  42. def label(self) -> str:
  43. return STATE_LABELS.get(int(self), "unknown")
  44. STATE_LABELS: Dict[int, str] = {
  45. 0: "not_on_train",
  46. 1: "bed",
  47. 2: "flatbed",
  48. 3: "empty",
  49. 255: "unknown",
  50. }
  51. STATE_NAME_TO_CODE: Dict[str, int] = {v: k for k, v in STATE_LABELS.items()}
  52. class ViewMode(str, Enum):
  53. """P1 双视角模式(``docs/route_v2.md`` §3)。"""
  54. FRONT = "front"
  55. HIGH = "high"
  56. UNKNOWN = "unknown"
  57. @classmethod
  58. def parse(cls, value: object) -> "ViewMode":
  59. text = str(value or "").strip().lower()
  60. for item in cls:
  61. if item.value == text:
  62. return item
  63. return cls.UNKNOWN
  64. class CommitPhase(str, Enum):
  65. """落位相位:T1 可判窗口、T2 已落位、T3 吊装中。"""
  66. T1 = "T1"
  67. T2 = "T2"
  68. T3 = "T3"
  69. class StatusBits(IntEnum):
  70. """``VisionSnapshot.flags`` 的位定义(同时写入 Modbus 寄存器与 S7 DB)。"""
  71. READY = 1 << 0 # 模型已加载且完成预热
  72. FRAME_OK = 1 << 1 # 最近一帧是新的(未超过 stale 时限)
  73. STABLE = 1 << 2 # 状态稳定,可用于联锁/自动落箱
  74. LOW_FPS = 1 << 3 # 帧率低于下限
  75. FRAME_TIMEOUT = 1 << 4 # 长时间拿不到帧(相机/网络异常)
  76. ON_DEMAND = 1 << 5 # 当前处于 PLC 请求触发的按需识别
  77. RESULT_VALID = 1 << 6 # 置信度达到阈值,结果有效
  78. PUBLISH_OK = 1 << 7 # 最近一次向 PLC 发布成功(服务端模式恒为 1)
  79. # P0-2:GB/T 45163.5 5.1.3/5.1.4 的感知健康位(bit8~12)。
  80. # 约束:PERCEPTION_UNCERTAIN=1 时 RESULT_VALID 必须为 0。
  81. PERCEPTION_UNCERTAIN = 1 << 8 # 感知不确定(低置信度/证据不足/模糊等)
  82. MRC_REQUEST = 1 << 9 # 请求 PLC 进入最小风险状态(MRC)
  83. SENSOR_DEGRADED = 1 << 10 # 图像质量/传感器退化(模糊、过曝、遮挡)
  84. CALIB_STALE = 1 << 11 # 标定过期或漂移
  85. DATA_LOSS = 1 << 12 # 数据链中断(取帧超时/丢流)
  86. def crc16_modbus(data: bytes) -> int:
  87. """CRC-16/MODBUS,用于快照校验,便于 PLC 侧判断数据是否完整/刷新。"""
  88. crc = 0xFFFF
  89. for byte in data:
  90. crc ^= byte
  91. for _ in range(8):
  92. if crc & 0x0001:
  93. crc = (crc >> 1) ^ 0xA001
  94. else:
  95. crc >>= 1
  96. return crc & 0xFFFF
  97. @dataclass
  98. class Box:
  99. """一个检测框。``class_id`` 为模型输出索引,``class_name`` 为标签名。"""
  100. x1: float
  101. y1: float
  102. x2: float
  103. y2: float
  104. score: float = 0.0
  105. class_id: int = -1
  106. class_name: str = ""
  107. def __post_init__(self) -> None:
  108. if self.x2 < self.x1:
  109. self.x1, self.x2 = self.x2, self.x1
  110. if self.y2 < self.y1:
  111. self.y1, self.y2 = self.y2, self.y1
  112. # -- 几何属性 ---------------------------------------------------------
  113. @property
  114. def width(self) -> float:
  115. return max(0.0, self.x2 - self.x1)
  116. @property
  117. def height(self) -> float:
  118. return max(0.0, self.y2 - self.y1)
  119. @property
  120. def area(self) -> float:
  121. return self.width * self.height
  122. @property
  123. def cx(self) -> float:
  124. return (self.x1 + self.x2) / 2.0
  125. @property
  126. def cy(self) -> float:
  127. return (self.y1 + self.y2) / 2.0
  128. @property
  129. def top(self) -> float:
  130. return min(self.y1, self.y2)
  131. @property
  132. def bottom(self) -> float:
  133. return max(self.y1, self.y2)
  134. def as_xyxy(self) -> Tuple[float, float, float, float]:
  135. return (self.x1, self.y1, self.x2, self.y2)
  136. def as_list(self) -> List[float]:
  137. return [float(self.x1), float(self.y1), float(self.x2), float(self.y2)]
  138. def to_dict(self) -> Dict[str, object]:
  139. return {
  140. "box": [round(v, 1) for v in self.as_list()],
  141. "score": round(float(self.score), 4),
  142. "class_id": int(self.class_id),
  143. "class_name": self.class_name,
  144. }
  145. # -- 构造 / 变换 ------------------------------------------------------
  146. @classmethod
  147. def from_xywh(
  148. cls,
  149. cx: float,
  150. cy: float,
  151. w: float,
  152. h: float,
  153. score: float = 0.0,
  154. class_id: int = -1,
  155. class_name: str = "",
  156. ) -> "Box":
  157. return cls(
  158. cx - w / 2.0,
  159. cy - h / 2.0,
  160. cx + w / 2.0,
  161. cy + h / 2.0,
  162. score=score,
  163. class_id=class_id,
  164. class_name=class_name,
  165. )
  166. def clip(self, width: float, height: float) -> "Box":
  167. """裁剪到图像范围内。"""
  168. return Box(
  169. min(max(self.x1, 0.0), width),
  170. min(max(self.y1, 0.0), height),
  171. min(max(self.x2, 0.0), width),
  172. min(max(self.y2, 0.0), height),
  173. score=self.score,
  174. class_id=self.class_id,
  175. class_name=self.class_name,
  176. )
  177. # -- 关系运算 ---------------------------------------------------------
  178. def intersection(self, other: "Box") -> float:
  179. ix1 = max(self.x1, other.x1)
  180. iy1 = max(self.y1, other.y1)
  181. ix2 = min(self.x2, other.x2)
  182. iy2 = min(self.y2, other.y2)
  183. if ix2 <= ix1 or iy2 <= iy1:
  184. return 0.0
  185. return float((ix2 - ix1) * (iy2 - iy1))
  186. def iou(self, other: "Box") -> float:
  187. inter = self.intersection(other)
  188. if inter <= 0.0:
  189. return 0.0
  190. union = self.area + other.area - inter
  191. return float(inter / union) if union > 0 else 0.0
  192. def overlap_ratio(self, other: "Box") -> float:
  193. """交叠面积占两者**较小**面积的比例(小框被大框包含时为 1)。"""
  194. inter = self.intersection(other)
  195. if inter <= 0.0:
  196. return 0.0
  197. denom = min(self.area, other.area)
  198. return float(inter / denom) if denom > 0 else 0.0
  199. def contains_point(self, x: float, y: float) -> bool:
  200. return self.x1 <= x <= self.x2 and self.y1 <= y <= self.y2
  201. @dataclass
  202. class Observation:
  203. """单帧的场景判定结果(未经时序滤波)。"""
  204. ts: float = 0.0
  205. state: int = int(SceneState.UNKNOWN)
  206. confidence: float = 0.0
  207. detections: List[Box] = field(default_factory=list)
  208. reason: str = ""
  209. frame_id: int = 0
  210. @property
  211. def is_valid(self) -> bool:
  212. return int(self.state) != int(SceneState.UNKNOWN)
  213. @dataclass
  214. class Decision:
  215. """时序滤波后的判决,可直接发布给 PLC。"""
  216. state: int = int(SceneState.UNKNOWN)
  217. confidence: float = 0.0
  218. stable: bool = False
  219. seq: int = 0 # 状态每提交一次变化 +1,PLC 用它判断"有新结果"
  220. since_ts: float = 0.0 # 当前状态起始时间(秒,time.time())
  221. reason: str = "init"
  222. changed: bool = False # 本次 update 是否发生了状态变化
  223. @property
  224. def label(self) -> str:
  225. return STATE_LABELS.get(int(self.state), "unknown")
  226. def to_dict(self) -> Dict[str, object]:
  227. return {
  228. "state": int(self.state),
  229. "label": self.label,
  230. "confidence": round(float(self.confidence), 4),
  231. "stable": bool(self.stable),
  232. "seq": int(self.seq),
  233. "reason": self.reason,
  234. }
  235. @dataclass
  236. class VisionSnapshot:
  237. """视觉侧写入 PLC 的一张"结果快照"。
  238. Modbus/TCP 服务端把它铺到输入寄存器(FC4 只读),S7 推送端把它打成 DB 字节数组。
  239. 字段宽度之和 = 11 个 16bit 字,第 12 个字是 CRC-16/MODBUS。
  240. """
  241. state: int = int(SceneState.UNKNOWN)
  242. confidence: int = 0 # 千分比 0..1000
  243. flags: int = 0
  244. seq: int = 0 # 32bit,状态变化计数
  245. ts_s: int = 0 # unix 秒(32bit)
  246. heartbeat: int = 0 # 0..65535,每个心跳周期 +1
  247. fps_x10: int = 0 # 帧率 x10
  248. latency_ms: int = 0 # 单帧端到端耗时
  249. reserved: int = 0
  250. #: 寄存器布局:字段 → 16bit 字宽度
  251. REGISTER_LAYOUT: Tuple[Tuple[str, int], ...] = (
  252. ("state", 1),
  253. ("confidence", 1),
  254. ("flags", 1),
  255. ("seq", 2),
  256. ("ts_s", 2),
  257. ("heartbeat", 1),
  258. ("fps_x10", 1),
  259. ("latency_ms", 1),
  260. ("reserved", 1),
  261. )
  262. @staticmethod
  263. def register_count() -> int:
  264. return int(sum(width for _, width in VisionSnapshot.REGISTER_LAYOUT)) + 1 # +1 = CRC
  265. def to_registers(self) -> List[int]:
  266. """铺成 16bit 寄存器数组(大端),最后一个字为 CRC-16/MODBUS 校验。"""
  267. words = [
  268. int(self.state) & 0xFFFF,
  269. int(self.confidence) & 0xFFFF,
  270. int(self.flags) & 0xFFFF,
  271. (int(self.seq) >> 16) & 0xFFFF,
  272. int(self.seq) & 0xFFFF,
  273. (int(self.ts_s) >> 16) & 0xFFFF,
  274. int(self.ts_s) & 0xFFFF,
  275. int(self.heartbeat) & 0xFFFF,
  276. int(self.fps_x10) & 0xFFFF,
  277. int(self.latency_ms) & 0xFFFF,
  278. int(self.reserved) & 0xFFFF,
  279. ]
  280. payload = b"".join(int(w).to_bytes(2, "big") for w in words)
  281. words.append(crc16_modbus(payload))
  282. return words
  283. @classmethod
  284. def from_registers(cls, words: Sequence[int], verify: bool = False) -> "VisionSnapshot":
  285. values = [int(w) & 0xFFFF for w in words]
  286. if len(values) < cls.register_count():
  287. raise ValueError(
  288. "寄存器数量不足: 需要 %d,实际 %d" % (cls.register_count(), len(values))
  289. )
  290. if verify:
  291. payload = b"".join(int(w).to_bytes(2, "big") for w in values[:-1])
  292. if crc16_modbus(payload) != values[-1]:
  293. raise ValueError("CRC 校验失败,数据可能不完整")
  294. return cls(
  295. state=values[0],
  296. confidence=values[1],
  297. flags=values[2],
  298. seq=(values[3] << 16) | values[4],
  299. ts_s=(values[5] << 16) | values[6],
  300. heartbeat=values[7],
  301. fps_x10=values[8],
  302. latency_ms=values[9],
  303. reserved=values[10],
  304. )
  305. def to_db_bytes(self) -> bytes:
  306. """S7 DB 字节块(每字大端),布局与 :meth:`to_registers` 一致。"""
  307. return b"".join(int(w).to_bytes(2, "big") for w in self.to_registers())
  308. def has_flag(self, bit: StatusBits) -> bool:
  309. return bool(int(self.flags) & int(bit))
  310. def to_dict(self) -> Dict[str, object]:
  311. return {
  312. "state": int(self.state),
  313. "state_label": STATE_LABELS.get(int(self.state), "unknown"),
  314. "confidence": int(self.confidence),
  315. "flags": int(self.flags),
  316. "seq": int(self.seq),
  317. "ts_s": int(self.ts_s),
  318. "heartbeat": int(self.heartbeat),
  319. "fps_x10": int(self.fps_x10),
  320. "latency_ms": int(self.latency_ms),
  321. }
  322. @dataclass
  323. class PlcCommand:
  324. """PLC → 视觉的指令块(保持寄存器 FC3/FC6/FC16)。"""
  325. cmd: int = 0 # 0=空闲, 1=请求识别(按需), 2=复位, 3=清统计
  326. preset: int = 0 # ROI / 相机预设编号
  327. min_conf: int = 0 # 覆盖最小置信度(千分比,0=用配置值)
  328. reserved: int = 0
  329. #: 保持寄存器布局:字段 → 16bit 字宽度
  330. REGISTER_LAYOUT: Tuple[Tuple[str, int], ...] = (
  331. ("cmd", 1),
  332. ("preset", 1),
  333. ("min_conf", 1),
  334. ("reserved", 1),
  335. )
  336. @staticmethod
  337. def register_count() -> int:
  338. return int(sum(width for _, width in PlcCommand.REGISTER_LAYOUT))
  339. def to_registers(self) -> List[int]:
  340. return [
  341. int(self.cmd) & 0xFFFF,
  342. int(self.preset) & 0xFFFF,
  343. int(self.min_conf) & 0xFFFF,
  344. int(self.reserved) & 0xFFFF,
  345. ]
  346. @classmethod
  347. def from_registers(cls, words: Sequence[int]) -> "PlcCommand":
  348. values = [int(w) & 0xFFFF for w in words]
  349. while len(values) < cls.register_count():
  350. values.append(0)
  351. return cls(cmd=values[0], preset=values[1], min_conf=values[2], reserved=values[3])
  352. def is_request(self) -> bool:
  353. return int(self.cmd) == 1
  354. def is_reset(self) -> bool:
  355. return int(self.cmd) == 2
  356. def recognition_results(
  357. observation: Observation,
  358. *,
  359. sensor_id: str = "",
  360. odd_id: str = "",
  361. include_environment: bool = False,
  362. ) -> List["RecognitionResult"]:
  363. """兼容入口:旧 ``Observation`` → 标准识别对象结果(P0-1)。
  364. 实现放在 :mod:`portcv.recognition`;这里只做延迟导入,保持
  365. ``Observation`` / ``Decision`` 字段与旧行为完全不变。
  366. """
  367. from .recognition import results_from_observation
  368. return results_from_observation(
  369. observation,
  370. sensor_id=sensor_id,
  371. odd_id=odd_id,
  372. include_environment=include_environment,
  373. )