stream_receiver.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. """Robust streaming frame parser, transaction state tracker, and diagnostic logger for Prod2U products.
  2. """
  3. from __future__ import annotations
  4. import datetime
  5. import hashlib
  6. import json
  7. import os
  8. from pathlib import Path
  9. import sys
  10. import threading
  11. import time
  12. from typing import Any, Callable
  13. # Ensure vendored protocol codec is in path
  14. VENDOR_DIR = Path(__file__).resolve().parent / "_vendor"
  15. if str(VENDOR_DIR) not in sys.path:
  16. sys.path.insert(0, str(VENDOR_DIR))
  17. from hth_protocol import (
  18. FrameType,
  19. NackReason,
  20. DoneReason,
  21. crc16_ccitt_false,
  22. PREAMBLE,
  23. )
  24. PREAMBLE_BYTES = bytes(PREAMBLE) # b"\xA5\x5A"
  25. MAX_PAYLOAD = 128
  26. class StreamReceiver:
  27. """Byte-stream frame parser with preamble hunting, chunk boundary safety,
  28. inter-byte timeout handling, and strict CRC/length validation.
  29. """
  30. def __init__(
  31. self,
  32. product: str,
  33. event_callback: Callable[[str, Any], None] | None = None,
  34. timeout_sec: float = 0.5,
  35. ):
  36. self.product = product
  37. self.is_motor = ("mrdimm" in product.lower())
  38. self.event_callback = event_callback
  39. self.timeout_sec = timeout_sec
  40. self._buffer = bytearray()
  41. self._last_byte_time: float = 0.0
  42. self._lock = threading.Lock()
  43. # Contract definition of legal frame lengths per product
  44. # Dict[FrameType, int | tuple[int, ...]]
  45. if self.is_motor:
  46. self._legal_lengths = {
  47. FrameType.SET_ALL: 68,
  48. FrameType.GET_ALL: 0,
  49. FrameType.HEARTBEAT: (0, 4),
  50. FrameType.SET_ACK: 0,
  51. FrameType.GET_ACK: 0,
  52. FrameType.HEARTBEAT_ACK: (0, 4),
  53. FrameType.BEACON: 0,
  54. FrameType.GET_DATA: 63,
  55. FrameType.MOTOR_DONE: 4,
  56. FrameType.NACK: 2,
  57. }
  58. else:
  59. self._legal_lengths = {
  60. FrameType.SET_ALL: 32,
  61. FrameType.GET_ALL: 0,
  62. FrameType.HEARTBEAT: (0, 4),
  63. FrameType.SET_ACK: 0,
  64. FrameType.GET_ACK: 0,
  65. FrameType.HEARTBEAT_ACK: (0, 4),
  66. FrameType.BEACON: 0,
  67. FrameType.GET_DATA: 83,
  68. FrameType.NACK: 2,
  69. }
  70. def _emit(self, event_type: str, data: Any):
  71. if self.event_callback:
  72. self.event_callback(event_type, data)
  73. def _parse_buffer_locked(self, local_emit: Callable[[str, Any], None]):
  74. """Internal frame parsing loop with header pre-validation and bounded resynchronization."""
  75. while True:
  76. if len(self._buffer) == 0:
  77. break
  78. # Search for preamble A5 5A
  79. idx = self._buffer.find(PREAMBLE_BYTES)
  80. if idx == -1:
  81. # Preamble not found in buffer.
  82. # If buffer ends with 0xA5, keep it! Discard only preceding noise.
  83. if self._buffer[-1] == 0xA5:
  84. if len(self._buffer) > 1:
  85. noise = bytes(self._buffer[:-1])
  86. local_emit("DISCARDED_NOISE", noise)
  87. del self._buffer[:-1]
  88. else:
  89. noise = bytes(self._buffer)
  90. local_emit("DISCARDED_NOISE", noise)
  91. self._buffer.clear()
  92. break
  93. # Preamble found at idx
  94. if idx > 0:
  95. noise = bytes(self._buffer[:idx])
  96. local_emit("DISCARDED_NOISE", noise)
  97. del self._buffer[:idx]
  98. # Buffer starts with A5 5A. Check if header (4 bytes) is available.
  99. if len(self._buffer) < 4:
  100. # Waiting for type and length bytes
  101. break
  102. frame_type_val = self._buffer[2]
  103. declared_len = self._buffer[3]
  104. # 1. Immediate validation of FrameType against product contract
  105. try:
  106. ftype = FrameType(frame_type_val)
  107. except ValueError:
  108. ftype = None
  109. if ftype is None or ftype not in self._legal_lengths:
  110. reason = f"UNKNOWN_FRAME_TYPE_0x{frame_type_val:02X}" if ftype is None else f"UNSUPPORTED_TYPE_{ftype.name}"
  111. rejected_hdr = bytes(self._buffer[:4])
  112. local_emit("FRAME_REJECTED", {
  113. "reason": reason,
  114. "data": rejected_hdr,
  115. })
  116. # Bounded resynchronization: look for next A5 5A
  117. next_p = self._buffer.find(PREAMBLE_BYTES, 1)
  118. if next_p != -1:
  119. del self._buffer[:next_p]
  120. else:
  121. del self._buffer[0]
  122. continue
  123. # 2. Immediate validation of declared length against contract
  124. expected_lens = self._legal_lengths[ftype]
  125. if isinstance(expected_lens, int):
  126. expected_lens = (expected_lens,)
  127. if declared_len not in expected_lens:
  128. rejected_hdr = bytes(self._buffer[:4])
  129. local_emit("FRAME_REJECTED", {
  130. "reason": f"BAD_LENGTH_FOR_{ftype.name} (expected {expected_lens}, got {declared_len})",
  131. "data": rejected_hdr,
  132. })
  133. next_p = self._buffer.find(PREAMBLE_BYTES, 1)
  134. if next_p != -1:
  135. del self._buffer[:next_p]
  136. else:
  137. del self._buffer[0]
  138. continue
  139. expected_total = declared_len + 6 # Preamble(2) + Type(1) + Len(1) + Payload + CRC(2)
  140. if len(self._buffer) < expected_total:
  141. # Frame incomplete, waiting for more bytes
  142. break
  143. # Complete candidate frame arrived!
  144. frame_bytes = bytes(self._buffer[:expected_total])
  145. # Validate CRC-16/CCITT-FALSE
  146. wire_crc = int.from_bytes(frame_bytes[-2:], "little")
  147. calc_crc = crc16_ccitt_false(frame_bytes[2:-2])
  148. if wire_crc != calc_crc:
  149. local_emit("FRAME_REJECTED", {
  150. "reason": f"CRC_MISMATCH (calc=0x{calc_crc:04X}, wire=0x{wire_crc:04X})",
  151. "data": frame_bytes,
  152. })
  153. # Bounded resynchronization within candidate slice
  154. next_p = self._buffer.find(PREAMBLE_BYTES, 1)
  155. if next_p != -1 and next_p < expected_total:
  156. del self._buffer[:next_p]
  157. else:
  158. del self._buffer[:expected_total]
  159. continue
  160. # Frame is completely valid! Consume candidate slice
  161. del self._buffer[:expected_total]
  162. local_emit("FRAME_VALID", {
  163. "frame_bytes": frame_bytes,
  164. "frame_type": ftype,
  165. "declared_len": declared_len,
  166. "payload": frame_bytes[4:-2],
  167. })
  168. def feed_bytes(self, chunk: bytes, now: float | None = None) -> list[tuple[str, Any]]:
  169. """Feed newly received raw bytes from serial line."""
  170. if not chunk:
  171. return []
  172. if now is None:
  173. now = time.monotonic()
  174. emitted: list[tuple[str, Any]] = []
  175. def local_emit(evt: str, d: Any):
  176. emitted.append((evt, d))
  177. self._emit(evt, d)
  178. with self._lock:
  179. # Check if pending buffer has expired before this new chunk arrived
  180. if len(self._buffer) > 0 and self._last_byte_time > 0 and (now - self._last_byte_time) >= self.timeout_sec:
  181. next_p = self._buffer.find(PREAMBLE_BYTES, 1)
  182. if next_p != -1:
  183. stalled = bytes(self._buffer[:next_p])
  184. local_emit("FRAME_REJECTED", {
  185. "reason": f"INTER_BYTE_TIMEOUT ({len(stalled)} bytes stalled)",
  186. "data": stalled,
  187. })
  188. del self._buffer[:next_p]
  189. self._parse_buffer_locked(local_emit)
  190. else:
  191. stalled = bytes(self._buffer)
  192. local_emit("FRAME_REJECTED", {
  193. "reason": f"INTER_BYTE_TIMEOUT ({len(stalled)} bytes stalled)",
  194. "data": stalled,
  195. })
  196. self._buffer.clear()
  197. local_emit("RX_RAW", chunk)
  198. self._buffer.extend(chunk)
  199. self._last_byte_time = now
  200. self._parse_buffer_locked(local_emit)
  201. return emitted
  202. def check_timeout(self, now: float | None = None) -> list[tuple[str, Any]]:
  203. """Check for half-frame timeout and purge stalled buffer while recovering any trailing frames."""
  204. if now is None:
  205. now = time.monotonic()
  206. emitted: list[tuple[str, Any]] = []
  207. def local_emit(evt: str, d: Any):
  208. emitted.append((evt, d))
  209. self._emit(evt, d)
  210. with self._lock:
  211. if len(self._buffer) > 0 and (now - self._last_byte_time) >= self.timeout_sec:
  212. # Truncated or incomplete frame timed out.
  213. # Search if there is another preamble in buffer[1:]
  214. next_p = self._buffer.find(PREAMBLE_BYTES, 1)
  215. if next_p != -1:
  216. stalled = bytes(self._buffer[:next_p])
  217. local_emit("FRAME_REJECTED", {
  218. "reason": f"INTER_BYTE_TIMEOUT ({len(stalled)} bytes stalled)",
  219. "data": stalled,
  220. })
  221. del self._buffer[:next_p]
  222. self._last_byte_time = now
  223. # Parse the remaining buffer immediately!
  224. self._parse_buffer_locked(local_emit)
  225. else:
  226. stalled = bytes(self._buffer)
  227. local_emit("FRAME_REJECTED", {
  228. "reason": f"INTER_BYTE_TIMEOUT ({len(stalled)} bytes stalled)",
  229. "data": stalled,
  230. })
  231. self._buffer.clear()
  232. self._last_byte_time = 0.0
  233. return emitted
  234. def clear(self):
  235. with self._lock:
  236. self._buffer.clear()
  237. self._last_byte_time = 0.0
  238. class TransactionTracker:
  239. """Stateful transaction coordinator tracking active requests and validating ACK/DATA."""
  240. def __init__(self, on_state_change: Callable[[str, str], None] | None = None):
  241. self.pending_request: str | None = None # "GET", "SET", "PING"
  242. self.pending_ping_nonce: bytes | None = None
  243. self.tx_state: str = "IDLE" # "IDLE", "WAIT_SET_ACK", "WAIT_GET_ACK", "WAIT_GET_DATA", "WAIT_HEARTBEAT_ACK"
  244. self.pending_time: float = 0.0
  245. self.deadline: float = 0.0
  246. self.state: str = "DISCONNECTED"
  247. self.hardware_observed: bool = False
  248. self.last_beacon_time: float = 0.0
  249. self.rx_valid_frame_count: int = 0
  250. self.command_applied_count: int = 0
  251. self.on_state_change = on_state_change
  252. self._lock = threading.Lock()
  253. def _set_state(self, new_state: str, details: str = ""):
  254. self.state = new_state
  255. if self.on_state_change:
  256. self.on_state_change(new_state, details)
  257. def on_port_opened(self, port_name: str, baud: int):
  258. with self._lock:
  259. self.pending_request = None
  260. self.pending_ping_nonce = None
  261. self.tx_state = "IDLE"
  262. self.hardware_observed = False
  263. self.rx_valid_frame_count = 0
  264. self.command_applied_count = 0
  265. self._set_state("PORT_OPEN", f"串口已打开 {port_name} @ {baud},等待通信")
  266. def on_port_closed(self):
  267. with self._lock:
  268. self.pending_request = None
  269. self.pending_ping_nonce = None
  270. self.tx_state = "IDLE"
  271. self._set_state("DISCONNECTED", "串口已关闭")
  272. def on_request_queued(self, req_type: str):
  273. pass
  274. def on_request_sent(self, req_type: str, now: float | None = None, timeout: float = 1.0, nonce: bytes | None = None):
  275. with self._lock:
  276. curr_now = time.monotonic() if now is None else now
  277. self.pending_request = req_type
  278. self.pending_ping_nonce = nonce
  279. self.pending_time = curr_now
  280. self.deadline = curr_now + timeout
  281. if req_type == "SET":
  282. self.tx_state = "WAIT_SET_ACK"
  283. elif req_type == "GET":
  284. self.tx_state = "WAIT_GET_ACK"
  285. elif req_type in ("PING", "HEARTBEAT"):
  286. self.tx_state = "WAIT_HEARTBEAT_ACK"
  287. self._set_state("REQUEST_SENT", f"已发送 {req_type} 请求,等待单板应答...")
  288. def check_request_timeout(self, now: float | None = None) -> dict[str, Any] | None:
  289. with self._lock:
  290. curr_now = time.monotonic() if now is None else now
  291. if self.tx_state != "IDLE" and curr_now >= self.deadline:
  292. timed_out_req = self.pending_request or "REQUEST"
  293. self.pending_request = None
  294. self.pending_ping_nonce = None
  295. self.tx_state = "IDLE"
  296. self._set_state("REQUEST_TIMEOUT", f"{timed_out_req} 请求超时 (未收到应答)")
  297. return {
  298. "is_timeout": True,
  299. "request_type": timed_out_req,
  300. "msg": f"{timed_out_req} 请求超时",
  301. "status_code": "REQUEST_TIMEOUT",
  302. }
  303. return None
  304. def get_hardware_status(self) -> dict[str, Any]:
  305. """Return the strict 6-stage communication status hierarchy."""
  306. with self._lock:
  307. return {
  308. "port_open": self.state != "DISCONNECTED",
  309. "rx_bytes_seen": self.rx_valid_frame_count > 0 or self.hardware_observed,
  310. "rx_valid_frame": self.rx_valid_frame_count > 0,
  311. "matched_request_reply": (self.command_applied_count > 0 or self.state in ("SET_APPLIED", "GET_ACKED", "DATA_UPDATED", "HEARTBEAT_OK")),
  312. "command_applied": self.command_applied_count > 0,
  313. "hardware_observed": self.hardware_observed,
  314. }
  315. def on_valid_frame(self, frame_type: FrameType, payload: bytes) -> dict[str, Any]:
  316. """Process incoming valid frame according to transaction rules."""
  317. with self._lock:
  318. self.rx_valid_frame_count += 1
  319. result = {
  320. "frame_type": frame_type,
  321. "is_match": False,
  322. "msg": "",
  323. "status_code": "INFO",
  324. }
  325. if frame_type == FrameType.SET_ACK:
  326. self.hardware_observed = True
  327. if self.tx_state == "WAIT_SET_ACK":
  328. self.tx_state = "IDLE"
  329. self.pending_request = None
  330. self.command_applied_count += 1
  331. self._set_state("SET_APPLIED", "SET 配置已成功应用 (SET_ACK 0x81)!看门狗已重载。")
  332. result["is_match"] = True
  333. result["msg"] = "SET 配置已成功应用!看门狗已重载。"
  334. result["status_code"] = "SUCCESS"
  335. else:
  336. result["is_match"] = False
  337. result["msg"] = "单板回复 SET_ACK,但上位机当前未处于等待 SET 请求状态。"
  338. result["status_code"] = "UNSOLICITED_ACK"
  339. elif frame_type == FrameType.GET_ACK:
  340. self.hardware_observed = True
  341. if self.tx_state == "WAIT_GET_ACK":
  342. self.tx_state = "WAIT_GET_DATA"
  343. self._set_state("GET_ACKED", "单板已受理 GET 查询 (GET_ACK 0x82),等待全量状态数据...")
  344. result["is_match"] = True
  345. result["msg"] = "GET 查询已受理,等待数据返回..."
  346. result["status_code"] = "ACK"
  347. else:
  348. result["is_match"] = False
  349. result["msg"] = "单板回复 GET_ACK (无等待中查询)。"
  350. result["status_code"] = "UNSOLICITED_ACK"
  351. elif frame_type == FrameType.HEARTBEAT_ACK:
  352. if self.tx_state == "WAIT_HEARTBEAT_ACK":
  353. # If nonce was sent with PING, verify matching nonce
  354. if self.pending_ping_nonce is not None and len(payload) >= 4:
  355. if payload[:4] == self.pending_ping_nonce:
  356. self.tx_state = "IDLE"
  357. self.pending_request = None
  358. self.pending_ping_nonce = None
  359. self.hardware_observed = True
  360. self._set_state("HEARTBEAT_OK", "主动 PING 匹配成功 (Nonce 一致,HEARTBEAT_ACK 0x83)!看门狗已重载。")
  361. result["is_match"] = True
  362. result["msg"] = "主动 PING 匹配成功!看门狗已重载。"
  363. result["status_code"] = "SUCCESS"
  364. else:
  365. result["is_match"] = False
  366. result["msg"] = f"心跳应答 Nonce 不匹配 (期望 {self.pending_ping_nonce.hex()}, 收到 {payload[:4].hex()})"
  367. result["status_code"] = "NONCE_MISMATCH"
  368. else:
  369. self.tx_state = "IDLE"
  370. self.pending_request = None
  371. self.pending_ping_nonce = None
  372. self.hardware_observed = True
  373. self._set_state("HEARTBEAT_OK", "心跳握手成功 (HEARTBEAT_ACK 0x83)!看门狗已重载。")
  374. result["is_match"] = True
  375. result["msg"] = "心跳连通正常!看门狗已重载。"
  376. result["status_code"] = "SUCCESS"
  377. else:
  378. result["is_match"] = False
  379. result["msg"] = "单板回复 HEARTBEAT_ACK (0x83) (无等待中心跳请求)。"
  380. result["status_code"] = "UNSOLICITED_ACK"
  381. elif frame_type == FrameType.BEACON:
  382. self.hardware_observed = True
  383. self.last_beacon_time = time.monotonic()
  384. result["is_match"] = False
  385. result["msg"] = "收到单板定时自发信标 (BEACON 0x51),物理链路与芯片运行正常 (不影响当前事务)。"
  386. result["status_code"] = "BEACON"
  387. elif frame_type == FrameType.GET_DATA:
  388. if self.tx_state == "WAIT_GET_DATA":
  389. self.tx_state = "IDLE"
  390. self.pending_request = None
  391. self._set_state("DATA_UPDATED", "全量状态数据 (GET_DATA 0x42) 已接收并更新。")
  392. result["is_match"] = True
  393. result["msg"] = "全量状态数据已更新。"
  394. result["status_code"] = "DATA"
  395. else:
  396. self._set_state("DATA_UPDATED", "收到未关联遥测数据 (GET_DATA 0x42),已更新显示。")
  397. result["is_match"] = False
  398. result["msg"] = "收到未关联遥测数据 (GET_DATA 0x42)。"
  399. result["status_code"] = "UNSOLICITED_DATA"
  400. elif frame_type == FrameType.NACK:
  401. orig = payload[0] if len(payload) > 0 else 0
  402. reason_code = payload[1] if len(payload) > 1 else 0
  403. try:
  404. reason_name = NackReason(reason_code).name
  405. except ValueError:
  406. reason_name = f"0x{reason_code:02X}"
  407. is_orig_match = False
  408. if orig == 0x01 and self.tx_state == "WAIT_SET_ACK":
  409. is_orig_match = True
  410. elif orig == 0x02 and self.tx_state in ("WAIT_GET_ACK", "WAIT_GET_DATA"):
  411. is_orig_match = True
  412. elif orig == 0x03 and self.tx_state == "WAIT_HEARTBEAT_ACK":
  413. is_orig_match = True
  414. if is_orig_match:
  415. self.tx_state = "IDLE"
  416. self.pending_request = None
  417. self._set_state("REJECTED", f"请求被单板拒绝 (NACK 0xC0): 原请求=0x{orig:02X}, 原因={reason_name}")
  418. result["is_match"] = True
  419. result["msg"] = f"请求被单板拒绝: {reason_name}"
  420. result["status_code"] = "REJECTED"
  421. else:
  422. result["is_match"] = False
  423. result["msg"] = f"单板回复 NACK (原请求=0x{orig:02X}, 原因={reason_name}),非当前等待请求。"
  424. result["status_code"] = "UNSOLICITED_NACK"
  425. elif frame_type == FrameType.MOTOR_DONE:
  426. axis = payload[0] if len(payload) > 0 else 0
  427. reason_code = payload[1] if len(payload) > 1 else 0
  428. steps = int.from_bytes(payload[2:4], "little") if len(payload) >= 4 else 0
  429. try:
  430. reason_name = DoneReason(reason_code).name
  431. except ValueError:
  432. reason_name = f"0x{reason_code:02X}"
  433. result["is_match"] = True
  434. result["msg"] = f"电机 Axis{axis} 结束: {reason_name},步数={steps}"
  435. result["status_code"] = "MOTOR_DONE"
  436. return result
  437. class SessionDiskLogger:
  438. """Thread-safe disk logger generating session-bound diagnostic logs."""
  439. def __init__(self, product: str, log_dir: Path | str | None = None):
  440. self.product = product
  441. self.session_id = hashlib.sha256(f"{time.time()}:{os.getpid()}".encode()).hexdigest()[:12]
  442. self.log_dir = Path(log_dir) if log_dir else (Path.cwd() / "logs")
  443. self.log_dir.mkdir(parents=True, exist_ok=True)
  444. now_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  445. self.log_path = self.log_dir / f"gui_session_{self.product}_{now_str}_{self.session_id}.log"
  446. self._lock = threading.Lock()
  447. self._mono_base = time.monotonic()
  448. self._write_header()
  449. def _write_header(self):
  450. exe_path = sys.executable
  451. try:
  452. exe_sha = hashlib.sha256(Path(exe_path).read_bytes()).hexdigest()
  453. except Exception:
  454. exe_sha = "N/A"
  455. header = [
  456. "=" * 80,
  457. f"Prod2U GUI Diagnostic Session Log",
  458. f"Session ID : {self.session_id}",
  459. f"Product : {self.product}",
  460. f"Start Time : {datetime.datetime.now().astimezone().isoformat()}",
  461. f"Executable : {exe_path}",
  462. f"Exe SHA256 : {exe_sha}",
  463. f"Python Ver : {sys.version}",
  464. "=" * 80,
  465. "",
  466. ]
  467. with self._lock:
  468. with open(self.log_path, "w", encoding="utf-8") as f:
  469. f.write("\n".join(header) + "\n")
  470. def log_event(self, tag: str, hex_data: str = "", details: str = ""):
  471. now_dt = datetime.datetime.now().astimezone().isoformat(timespec="milliseconds")
  472. rel_mono = time.monotonic() - self._mono_base
  473. line = f"[{now_dt}] [{rel_mono:10.4f}s] [{tag:14s}] {hex_data:30s} {details}"
  474. with self._lock:
  475. with open(self.log_path, "a", encoding="utf-8") as f:
  476. f.write(line + "\n")