schema.py 14 KB

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