stream_receiver.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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.matched_request_reply: bool = False
  252. self.on_state_change = on_state_change
  253. self._lock = threading.Lock()
  254. def _set_state(self, new_state: str, details: str = ""):
  255. self.state = new_state
  256. if self.on_state_change:
  257. self.on_state_change(new_state, details)
  258. def on_port_opened(self, port_name: str, baud: int):
  259. with self._lock:
  260. self.pending_request = None
  261. self.pending_ping_nonce = None
  262. self.tx_state = "IDLE"
  263. self.hardware_observed = False
  264. self.rx_valid_frame_count = 0
  265. self.command_applied_count = 0
  266. self.matched_request_reply = False
  267. self._set_state("PORT_OPEN", f"串口已打开 {port_name} @ {baud},等待通信")
  268. def on_port_closed(self):
  269. with self._lock:
  270. self.pending_request = None
  271. self.pending_ping_nonce = None
  272. self.tx_state = "IDLE"
  273. self._set_state("DISCONNECTED", "串口已关闭")
  274. def on_request_queued(self, req_type: str):
  275. pass
  276. def on_request_sent(self, req_type: str, now: float | None = None, timeout: float = 1.0, nonce: bytes | None = None):
  277. with self._lock:
  278. curr_now = time.monotonic() if now is None else now
  279. self.pending_request = req_type
  280. self.pending_ping_nonce = nonce
  281. self.pending_time = curr_now
  282. self.deadline = curr_now + timeout
  283. if req_type == "SET":
  284. self.tx_state = "WAIT_SET_ACK"
  285. elif req_type == "GET":
  286. self.tx_state = "WAIT_GET_ACK"
  287. elif req_type in ("PING", "HEARTBEAT"):
  288. self.tx_state = "WAIT_HEARTBEAT_ACK"
  289. self._set_state("REQUEST_SENT", f"已发送 {req_type} 请求,等待单板应答...")
  290. def check_request_timeout(self, now: float | None = None) -> dict[str, Any] | None:
  291. with self._lock:
  292. curr_now = time.monotonic() if now is None else now
  293. if self.tx_state != "IDLE" and curr_now >= self.deadline:
  294. timed_out_req = self.pending_request or "REQUEST"
  295. self.pending_request = None
  296. self.pending_ping_nonce = None
  297. self.tx_state = "IDLE"
  298. self._set_state("REQUEST_TIMEOUT", f"{timed_out_req} 请求超时 (未收到应答)")
  299. return {
  300. "is_timeout": True,
  301. "request_type": timed_out_req,
  302. "msg": f"{timed_out_req} 请求超时",
  303. "status_code": "REQUEST_TIMEOUT",
  304. }
  305. return None
  306. def get_hardware_status(self) -> dict[str, Any]:
  307. """Return the strict 6-stage communication status hierarchy."""
  308. with self._lock:
  309. return {
  310. "port_open": self.state != "DISCONNECTED",
  311. "rx_bytes_seen": self.rx_valid_frame_count > 0 or self.hardware_observed,
  312. "rx_valid_frame": self.rx_valid_frame_count > 0,
  313. "matched_request_reply": self.matched_request_reply,
  314. "command_applied": self.command_applied_count > 0,
  315. "hardware_observed": self.hardware_observed,
  316. }
  317. def on_valid_frame(self, frame_type: FrameType, payload: bytes) -> dict[str, Any]:
  318. """Process incoming valid frame according to transaction rules."""
  319. with self._lock:
  320. self.rx_valid_frame_count += 1
  321. result = {
  322. "frame_type": frame_type,
  323. "is_match": False,
  324. "msg": "",
  325. "status_code": "INFO",
  326. }
  327. if frame_type == FrameType.SET_ACK:
  328. self.hardware_observed = True
  329. if self.tx_state == "WAIT_SET_ACK":
  330. self.tx_state = "IDLE"
  331. self.pending_request = None
  332. self.command_applied_count += 1
  333. self._set_state("SET_APPLIED", "SET 配置已成功应用 (SET_ACK 0x81)!看门狗已重载。")
  334. result["is_match"] = True
  335. result["msg"] = "SET 配置已成功应用!看门狗已重载。"
  336. result["status_code"] = "SUCCESS"
  337. else:
  338. result["is_match"] = False
  339. result["msg"] = "单板回复 SET_ACK,但上位机当前未处于等待 SET 请求状态。"
  340. result["status_code"] = "UNSOLICITED_ACK"
  341. elif frame_type == FrameType.GET_ACK:
  342. self.hardware_observed = True
  343. if self.tx_state == "WAIT_GET_ACK":
  344. self.tx_state = "WAIT_GET_DATA"
  345. self._set_state("GET_ACKED", "单板已受理 GET 查询 (GET_ACK 0x82),等待全量状态数据...")
  346. result["is_match"] = True
  347. result["msg"] = "GET 查询已受理,等待数据返回..."
  348. result["status_code"] = "ACK"
  349. else:
  350. result["is_match"] = False
  351. result["msg"] = "单板回复 GET_ACK (无等待中查询)。"
  352. result["status_code"] = "UNSOLICITED_ACK"
  353. elif frame_type == FrameType.HEARTBEAT_ACK:
  354. if self.tx_state == "WAIT_HEARTBEAT_ACK":
  355. # If nonce was sent with PING, verify matching nonce
  356. if self.pending_ping_nonce is not None:
  357. if payload == self.pending_ping_nonce:
  358. self.tx_state = "IDLE"
  359. self.pending_request = None
  360. self.pending_ping_nonce = None
  361. self.hardware_observed = True
  362. self._set_state("HEARTBEAT_OK", "主动 PING 匹配成功 (Nonce 一致,HEARTBEAT_ACK 0x83)!看门狗已重载。")
  363. result["is_match"] = True
  364. result["msg"] = "主动 PING 匹配成功!看门狗已重载。"
  365. result["status_code"] = "SUCCESS"
  366. else:
  367. result["is_match"] = False
  368. result["msg"] = f"心跳应答 Nonce 不匹配 (期望 {self.pending_ping_nonce.hex()}, 收到 {payload[:4].hex()})"
  369. result["status_code"] = "NONCE_MISMATCH"
  370. else:
  371. self.tx_state = "IDLE"
  372. self.pending_request = None
  373. self.pending_ping_nonce = None
  374. self.hardware_observed = True
  375. self._set_state("HEARTBEAT_OK", "心跳握手成功 (HEARTBEAT_ACK 0x83)!看门狗已重载。")
  376. result["is_match"] = True
  377. result["msg"] = "心跳连通正常!看门狗已重载。"
  378. result["status_code"] = "SUCCESS"
  379. else:
  380. result["is_match"] = False
  381. result["msg"] = "单板回复 HEARTBEAT_ACK (0x83) (无等待中心跳请求)。"
  382. result["status_code"] = "UNSOLICITED_ACK"
  383. elif frame_type == FrameType.BEACON:
  384. self.hardware_observed = True
  385. self.last_beacon_time = time.monotonic()
  386. result["is_match"] = False
  387. result["msg"] = "收到单板自发信标 (BEACON 0x51),板端发送可达;不确认请求应答,不影响当前事务。"
  388. result["status_code"] = "BEACON"
  389. elif frame_type == FrameType.GET_DATA:
  390. self.hardware_observed = True
  391. if self.tx_state == "WAIT_GET_DATA":
  392. self.tx_state = "IDLE"
  393. self.pending_request = None
  394. self._set_state("DATA_UPDATED", "全量状态数据 (GET_DATA 0x42) 已接收并更新。")
  395. result["is_match"] = True
  396. result["msg"] = "全量状态数据已更新。"
  397. result["status_code"] = "DATA"
  398. else:
  399. if self.tx_state == "IDLE":
  400. self._set_state("TELEMETRY_UPDATED", "收到自动遥测 (GET_DATA 0x42),未关联查询。")
  401. result["is_match"] = False
  402. result["msg"] = "收到自动遥测 (GET_DATA 0x42),更新显示;继续等待当前请求应答。" if self.tx_state != "IDLE" else "收到自动遥测 (GET_DATA 0x42),未关联查询。"
  403. result["status_code"] = "UNSOLICITED_DATA"
  404. elif frame_type == FrameType.NACK:
  405. orig = payload[0] if len(payload) > 0 else 0
  406. reason_code = payload[1] if len(payload) > 1 else 0
  407. try:
  408. reason_name = NackReason(reason_code).name
  409. except ValueError:
  410. reason_name = f"0x{reason_code:02X}"
  411. is_orig_match = False
  412. if orig == 0x01 and self.tx_state == "WAIT_SET_ACK":
  413. is_orig_match = True
  414. elif orig == 0x02 and self.tx_state in ("WAIT_GET_ACK", "WAIT_GET_DATA"):
  415. is_orig_match = True
  416. elif orig == 0x03 and self.tx_state == "WAIT_HEARTBEAT_ACK":
  417. is_orig_match = True
  418. if is_orig_match:
  419. self.tx_state = "IDLE"
  420. self.pending_request = None
  421. self._set_state("REJECTED", f"请求被单板拒绝 (NACK 0xC0): 原请求=0x{orig:02X}, 原因={reason_name}")
  422. result["is_match"] = True
  423. result["msg"] = f"请求被单板拒绝: {reason_name}"
  424. result["status_code"] = "REJECTED"
  425. else:
  426. result["is_match"] = False
  427. result["msg"] = f"单板回复 NACK (原请求=0x{orig:02X}, 原因={reason_name}),非当前等待请求。"
  428. result["status_code"] = "UNSOLICITED_NACK"
  429. elif frame_type == FrameType.MOTOR_DONE:
  430. axis = payload[0] if len(payload) > 0 else 0
  431. reason_code = payload[1] if len(payload) > 1 else 0
  432. steps = int.from_bytes(payload[2:4], "little") if len(payload) >= 4 else 0
  433. try:
  434. reason_name = DoneReason(reason_code).name
  435. except ValueError:
  436. reason_name = f"0x{reason_code:02X}"
  437. result["is_match"] = True
  438. result["msg"] = f"电机 Axis{axis} 结束: {reason_name},步数={steps}"
  439. result["status_code"] = "MOTOR_DONE"
  440. if result["is_match"] and result["status_code"] != "MOTOR_DONE":
  441. self.matched_request_reply = True
  442. return result
  443. class SessionDiskLogger:
  444. """Thread-safe disk logger generating session-bound diagnostic logs."""
  445. def __init__(self, product: str, log_dir: Path | str | None = None):
  446. self.product = product
  447. self.session_id = hashlib.sha256(f"{time.time()}:{os.getpid()}".encode()).hexdigest()[:12]
  448. self.log_dir = Path(log_dir) if log_dir else (Path.cwd() / "logs")
  449. self.log_dir.mkdir(parents=True, exist_ok=True)
  450. now_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  451. self.log_path = self.log_dir / f"gui_session_{self.product}_{now_str}_{self.session_id}.log"
  452. self._lock = threading.Lock()
  453. self._mono_base = time.monotonic()
  454. self._write_header()
  455. def _write_header(self):
  456. exe_path = sys.executable
  457. try:
  458. exe_sha = hashlib.sha256(Path(exe_path).read_bytes()).hexdigest()
  459. except Exception:
  460. exe_sha = "N/A"
  461. header = [
  462. "=" * 80,
  463. f"Prod2U GUI Diagnostic Session Log",
  464. f"Session ID : {self.session_id}",
  465. f"Product : {self.product}",
  466. f"Start Time : {datetime.datetime.now().astimezone().isoformat()}",
  467. f"Executable : {exe_path}",
  468. f"Exe SHA256 : {exe_sha}",
  469. f"Python Ver : {sys.version}",
  470. "=" * 80,
  471. "",
  472. ]
  473. with self._lock:
  474. with open(self.log_path, "w", encoding="utf-8") as f:
  475. f.write("\n".join(header) + "\n")
  476. def log_event(self, tag: str, hex_data: str = "", details: str = ""):
  477. now_dt = datetime.datetime.now().astimezone().isoformat(timespec="milliseconds")
  478. rel_mono = time.monotonic() - self._mono_base
  479. line = f"[{now_dt}] [{rel_mono:10.4f}s] [{tag:14s}] {hex_data:30s} {details}"
  480. with self._lock:
  481. with open(self.log_path, "a", encoding="utf-8") as f:
  482. f.write(line + "\n")