| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555 |
- """Robust streaming frame parser, transaction state tracker, and diagnostic logger for Prod2U products.
- """
- from __future__ import annotations
- import datetime
- import hashlib
- import json
- import os
- from pathlib import Path
- import sys
- import threading
- import time
- from typing import Any, Callable
- # Ensure vendored protocol codec is in path
- VENDOR_DIR = Path(__file__).resolve().parent / "_vendor"
- if str(VENDOR_DIR) not in sys.path:
- sys.path.insert(0, str(VENDOR_DIR))
- from hth_protocol import (
- FrameType,
- NackReason,
- DoneReason,
- crc16_ccitt_false,
- PREAMBLE,
- )
- PREAMBLE_BYTES = bytes(PREAMBLE) # b"\xA5\x5A"
- MAX_PAYLOAD = 128
- class StreamReceiver:
- """Byte-stream frame parser with preamble hunting, chunk boundary safety,
- inter-byte timeout handling, and strict CRC/length validation.
- """
- def __init__(
- self,
- product: str,
- event_callback: Callable[[str, Any], None] | None = None,
- timeout_sec: float = 0.5,
- ):
- self.product = product
- self.is_motor = ("mrdimm" in product.lower())
- self.event_callback = event_callback
- self.timeout_sec = timeout_sec
- self._buffer = bytearray()
- self._last_byte_time: float = 0.0
- self._lock = threading.Lock()
- # Contract definition of legal frame lengths per product
- # Dict[FrameType, int | tuple[int, ...]]
- if self.is_motor:
- self._legal_lengths = {
- FrameType.SET_ALL: (68, 69),
- FrameType.GET_ALL: 0,
- FrameType.HEARTBEAT: (0, 4),
- FrameType.SET_ACK: 0,
- FrameType.GET_ACK: 0,
- FrameType.HEARTBEAT_ACK: (0, 4),
- FrameType.BEACON: 0,
- FrameType.DIAGNOSTIC: 8,
- FrameType.GET_DATA: (63, 65),
- FrameType.MOTOR_DONE: 4,
- FrameType.NACK: 2,
- }
- else:
- self._legal_lengths = {
- FrameType.SET_ALL: (35, 36) if self.product == "6400-v2" else 32,
- FrameType.GET_ALL: 0,
- FrameType.HEARTBEAT: (0, 4),
- FrameType.SET_ACK: 0,
- FrameType.GET_ACK: 0,
- FrameType.HEARTBEAT_ACK: (0, 4),
- FrameType.BEACON: 0,
- FrameType.GET_DATA: (86, 88, 90) if self.product == "6400-v2" else 83,
- FrameType.NACK: 2,
- }
- if self.product == "6400-v2":
- self._legal_lengths[FrameType.DIAGNOSTIC] = 20
- def _emit(self, event_type: str, data: Any):
- if self.event_callback:
- self.event_callback(event_type, data)
- def _parse_buffer_locked(self, local_emit: Callable[[str, Any], None]):
- """Internal frame parsing loop with header pre-validation and bounded resynchronization."""
- while True:
- if len(self._buffer) == 0:
- break
- # Search for preamble A5 5A
- idx = self._buffer.find(PREAMBLE_BYTES)
- if idx == -1:
- # Preamble not found in buffer.
- # If buffer ends with 0xA5, keep it! Discard only preceding noise.
- if self._buffer[-1] == 0xA5:
- if len(self._buffer) > 1:
- noise = bytes(self._buffer[:-1])
- local_emit("DISCARDED_NOISE", noise)
- del self._buffer[:-1]
- else:
- noise = bytes(self._buffer)
- local_emit("DISCARDED_NOISE", noise)
- self._buffer.clear()
- break
- # Preamble found at idx
- if idx > 0:
- noise = bytes(self._buffer[:idx])
- local_emit("DISCARDED_NOISE", noise)
- del self._buffer[:idx]
- # Buffer starts with A5 5A. Check if header (4 bytes) is available.
- if len(self._buffer) < 4:
- # Waiting for type and length bytes
- break
- frame_type_val = self._buffer[2]
- declared_len = self._buffer[3]
- # 1. Immediate validation of FrameType against product contract
- try:
- ftype = FrameType(frame_type_val)
- except ValueError:
- ftype = None
- if ftype is None or ftype not in self._legal_lengths:
- reason = f"UNKNOWN_FRAME_TYPE_0x{frame_type_val:02X}" if ftype is None else f"UNSUPPORTED_TYPE_{ftype.name}"
- rejected_hdr = bytes(self._buffer[:4])
- local_emit("FRAME_REJECTED", {
- "reason": reason,
- "data": rejected_hdr,
- })
- # Bounded resynchronization: look for next A5 5A
- next_p = self._buffer.find(PREAMBLE_BYTES, 1)
- if next_p != -1:
- del self._buffer[:next_p]
- else:
- del self._buffer[0]
- continue
- # 2. Immediate validation of declared length against contract
- expected_lens = self._legal_lengths[ftype]
- if isinstance(expected_lens, int):
- expected_lens = (expected_lens,)
- if declared_len not in expected_lens:
- rejected_hdr = bytes(self._buffer[:4])
- local_emit("FRAME_REJECTED", {
- "reason": f"BAD_LENGTH_FOR_{ftype.name} (expected {expected_lens}, got {declared_len})",
- "data": rejected_hdr,
- })
- next_p = self._buffer.find(PREAMBLE_BYTES, 1)
- if next_p != -1:
- del self._buffer[:next_p]
- else:
- del self._buffer[0]
- continue
- expected_total = declared_len + 6 # Preamble(2) + Type(1) + Len(1) + Payload + CRC(2)
- if len(self._buffer) < expected_total:
- # Frame incomplete, waiting for more bytes
- break
- # Complete candidate frame arrived!
- frame_bytes = bytes(self._buffer[:expected_total])
- # Validate CRC-16/CCITT-FALSE
- wire_crc = int.from_bytes(frame_bytes[-2:], "little")
- calc_crc = crc16_ccitt_false(frame_bytes[2:-2])
- if wire_crc != calc_crc:
- local_emit("FRAME_REJECTED", {
- "reason": f"CRC_MISMATCH (calc=0x{calc_crc:04X}, wire=0x{wire_crc:04X})",
- "data": frame_bytes,
- })
- # Bounded resynchronization within candidate slice
- next_p = self._buffer.find(PREAMBLE_BYTES, 1)
- if next_p != -1 and next_p < expected_total:
- del self._buffer[:next_p]
- else:
- del self._buffer[:expected_total]
- continue
- # Frame is completely valid! Consume candidate slice
- del self._buffer[:expected_total]
- local_emit("FRAME_VALID", {
- "frame_bytes": frame_bytes,
- "frame_type": ftype,
- "declared_len": declared_len,
- "payload": frame_bytes[4:-2],
- })
- def feed_bytes(self, chunk: bytes, now: float | None = None) -> list[tuple[str, Any]]:
- """Feed newly received raw bytes from serial line."""
- if not chunk:
- return []
- if now is None:
- now = time.monotonic()
- emitted: list[tuple[str, Any]] = []
- def local_emit(evt: str, d: Any):
- emitted.append((evt, d))
- self._emit(evt, d)
- with self._lock:
- # Check if pending buffer has expired before this new chunk arrived
- if len(self._buffer) > 0 and self._last_byte_time > 0 and (now - self._last_byte_time) >= self.timeout_sec:
- next_p = self._buffer.find(PREAMBLE_BYTES, 1)
- if next_p != -1:
- stalled = bytes(self._buffer[:next_p])
- local_emit("FRAME_REJECTED", {
- "reason": f"INTER_BYTE_TIMEOUT ({len(stalled)} bytes stalled)",
- "data": stalled,
- })
- del self._buffer[:next_p]
- self._parse_buffer_locked(local_emit)
- else:
- stalled = bytes(self._buffer)
- local_emit("FRAME_REJECTED", {
- "reason": f"INTER_BYTE_TIMEOUT ({len(stalled)} bytes stalled)",
- "data": stalled,
- })
- self._buffer.clear()
- local_emit("RX_RAW", chunk)
- self._buffer.extend(chunk)
- self._last_byte_time = now
- self._parse_buffer_locked(local_emit)
- return emitted
- def check_timeout(self, now: float | None = None) -> list[tuple[str, Any]]:
- """Check for half-frame timeout and purge stalled buffer while recovering any trailing frames."""
- if now is None:
- now = time.monotonic()
- emitted: list[tuple[str, Any]] = []
- def local_emit(evt: str, d: Any):
- emitted.append((evt, d))
- self._emit(evt, d)
- with self._lock:
- if len(self._buffer) > 0 and (now - self._last_byte_time) >= self.timeout_sec:
- # Truncated or incomplete frame timed out.
- # Search if there is another preamble in buffer[1:]
- next_p = self._buffer.find(PREAMBLE_BYTES, 1)
- if next_p != -1:
- stalled = bytes(self._buffer[:next_p])
- local_emit("FRAME_REJECTED", {
- "reason": f"INTER_BYTE_TIMEOUT ({len(stalled)} bytes stalled)",
- "data": stalled,
- })
- del self._buffer[:next_p]
- self._last_byte_time = now
- # Parse the remaining buffer immediately!
- self._parse_buffer_locked(local_emit)
- else:
- stalled = bytes(self._buffer)
- local_emit("FRAME_REJECTED", {
- "reason": f"INTER_BYTE_TIMEOUT ({len(stalled)} bytes stalled)",
- "data": stalled,
- })
- self._buffer.clear()
- self._last_byte_time = 0.0
- return emitted
- def clear(self):
- with self._lock:
- self._buffer.clear()
- self._last_byte_time = 0.0
- class TransactionTracker:
- """Stateful transaction coordinator tracking active requests and validating ACK/DATA."""
- def __init__(self, on_state_change: Callable[[str, str], None] | None = None):
- self.pending_request: str | None = None # "GET", "SET", "PING"
- self.pending_ping_nonce: bytes | None = None
- self.tx_state: str = "IDLE" # "IDLE", "WAIT_SET_ACK", "WAIT_GET_ACK", "WAIT_GET_DATA", "WAIT_HEARTBEAT_ACK"
- self.pending_time: float = 0.0
- self.deadline: float = 0.0
- self.state: str = "DISCONNECTED"
- self.hardware_observed: bool = False
- self.last_beacon_time: float = 0.0
- self.rx_valid_frame_count: int = 0
- self.command_applied_count: int = 0
- self.matched_request_reply: bool = False
- self.on_state_change = on_state_change
- self._lock = threading.Lock()
- def _set_state(self, new_state: str, details: str = ""):
- self.state = new_state
- if self.on_state_change:
- self.on_state_change(new_state, details)
- def on_port_opened(self, port_name: str, baud: int):
- with self._lock:
- self.pending_request = None
- self.pending_ping_nonce = None
- self.tx_state = "IDLE"
- self.hardware_observed = False
- self.rx_valid_frame_count = 0
- self.command_applied_count = 0
- self.matched_request_reply = False
- self._set_state("PORT_OPEN", f"串口已打开 {port_name} @ {baud},等待通信")
- def on_port_closed(self):
- with self._lock:
- self.pending_request = None
- self.pending_ping_nonce = None
- self.tx_state = "IDLE"
- self._set_state("DISCONNECTED", "串口已关闭")
- def on_request_queued(self, req_type: str):
- pass
- def on_request_sent(self, req_type: str, now: float | None = None, timeout: float = 1.0, nonce: bytes | None = None):
- with self._lock:
- curr_now = time.monotonic() if now is None else now
- self.pending_request = req_type
- self.pending_ping_nonce = nonce
- self.pending_time = curr_now
- self.deadline = curr_now + timeout
- if req_type == "SET":
- self.tx_state = "WAIT_SET_ACK"
- elif req_type == "GET":
- self.tx_state = "WAIT_GET_ACK"
- elif req_type in ("PING", "HEARTBEAT"):
- self.tx_state = "WAIT_HEARTBEAT_ACK"
- self._set_state("REQUEST_SENT", f"已发送 {req_type} 请求,等待单板应答...")
- def check_request_timeout(self, now: float | None = None) -> dict[str, Any] | None:
- with self._lock:
- curr_now = time.monotonic() if now is None else now
- if self.tx_state != "IDLE" and curr_now >= self.deadline:
- timed_out_req = self.pending_request or "REQUEST"
- self.pending_request = None
- self.pending_ping_nonce = None
- self.tx_state = "IDLE"
- self._set_state("REQUEST_TIMEOUT", f"{timed_out_req} 请求超时 (未收到应答)")
- return {
- "is_timeout": True,
- "request_type": timed_out_req,
- "msg": f"{timed_out_req} 请求超时",
- "status_code": "REQUEST_TIMEOUT",
- }
- return None
- def get_hardware_status(self) -> dict[str, Any]:
- """Return the strict 6-stage communication status hierarchy."""
- with self._lock:
- return {
- "port_open": self.state != "DISCONNECTED",
- "rx_bytes_seen": self.rx_valid_frame_count > 0 or self.hardware_observed,
- "rx_valid_frame": self.rx_valid_frame_count > 0,
- "matched_request_reply": self.matched_request_reply,
- "command_applied": self.command_applied_count > 0,
- "hardware_observed": self.hardware_observed,
- }
- def on_valid_frame(self, frame_type: FrameType, payload: bytes) -> dict[str, Any]:
- """Process incoming valid frame according to transaction rules."""
- with self._lock:
- self.rx_valid_frame_count += 1
- result = {
- "frame_type": frame_type,
- "is_match": False,
- "msg": "",
- "status_code": "INFO",
- }
- if frame_type == FrameType.SET_ACK:
- self.hardware_observed = True
- if self.tx_state == "WAIT_SET_ACK":
- self.tx_state = "IDLE"
- self.pending_request = None
- self.command_applied_count += 1
- self._set_state("SET_APPLIED", "SET 配置已成功应用 (SET_ACK 0x81)!看门狗已重载。")
- result["is_match"] = True
- result["msg"] = "SET 配置已成功应用!看门狗已重载。"
- result["status_code"] = "SUCCESS"
- else:
- result["is_match"] = False
- result["msg"] = "单板回复 SET_ACK,但上位机当前未处于等待 SET 请求状态。"
- result["status_code"] = "UNSOLICITED_ACK"
- elif frame_type == FrameType.GET_ACK:
- self.hardware_observed = True
- if self.tx_state == "WAIT_GET_ACK":
- self.tx_state = "WAIT_GET_DATA"
- self._set_state("GET_ACKED", "单板已受理 GET 查询 (GET_ACK 0x82),等待全量状态数据...")
- result["is_match"] = True
- result["msg"] = "GET 查询已受理,等待数据返回..."
- result["status_code"] = "ACK"
- else:
- result["is_match"] = False
- result["msg"] = "单板回复 GET_ACK (无等待中查询)。"
- result["status_code"] = "UNSOLICITED_ACK"
- elif frame_type == FrameType.HEARTBEAT_ACK:
- if self.tx_state == "WAIT_HEARTBEAT_ACK":
- # If nonce was sent with PING, verify matching nonce
- if self.pending_ping_nonce is not None:
- if payload == self.pending_ping_nonce:
- self.tx_state = "IDLE"
- self.pending_request = None
- self.pending_ping_nonce = None
- self.hardware_observed = True
- self._set_state("HEARTBEAT_OK", "主动 PING 匹配成功 (Nonce 一致,HEARTBEAT_ACK 0x83)!看门狗已重载。")
- result["is_match"] = True
- result["msg"] = "主动 PING 匹配成功!看门狗已重载。"
- result["status_code"] = "SUCCESS"
- else:
- result["is_match"] = False
- result["msg"] = f"心跳应答 Nonce 不匹配 (期望 {self.pending_ping_nonce.hex()}, 收到 {payload[:4].hex()})"
- result["status_code"] = "NONCE_MISMATCH"
- else:
- self.tx_state = "IDLE"
- self.pending_request = None
- self.pending_ping_nonce = None
- self.hardware_observed = True
- self._set_state("HEARTBEAT_OK", "心跳握手成功 (HEARTBEAT_ACK 0x83)!看门狗已重载。")
- result["is_match"] = True
- result["msg"] = "心跳连通正常!看门狗已重载。"
- result["status_code"] = "SUCCESS"
- else:
- result["is_match"] = False
- result["msg"] = "单板回复 HEARTBEAT_ACK (0x83) (无等待中心跳请求)。"
- result["status_code"] = "UNSOLICITED_ACK"
- elif frame_type == FrameType.BEACON:
- self.hardware_observed = True
- self.last_beacon_time = time.monotonic()
- result["is_match"] = False
- result["msg"] = "收到单板自发信标 (BEACON 0x51),板端发送可达;不确认请求应答,不影响当前事务。"
- result["status_code"] = "BEACON"
- elif frame_type == FrameType.DIAGNOSTIC:
- self.hardware_observed = True
- result["msg"] = "收到温度采集诊断 (0x52),不确认请求、不改变当前事务。"
- result["status_code"] = "DIAGNOSTIC"
- elif frame_type == FrameType.GET_DATA:
- self.hardware_observed = True
- if self.tx_state == "WAIT_GET_DATA":
- self.tx_state = "IDLE"
- self.pending_request = None
- self._set_state("DATA_UPDATED", "全量状态数据 (GET_DATA 0x42) 已接收并更新。")
- result["is_match"] = True
- result["msg"] = "全量状态数据已更新。"
- result["status_code"] = "DATA"
- else:
- if self.tx_state == "IDLE":
- self._set_state("TELEMETRY_UPDATED", "收到自动遥测 (GET_DATA 0x42),未关联查询。")
- result["is_match"] = False
- result["msg"] = "收到自动遥测 (GET_DATA 0x42),更新显示;继续等待当前请求应答。" if self.tx_state != "IDLE" else "收到自动遥测 (GET_DATA 0x42),未关联查询。"
- result["status_code"] = "UNSOLICITED_DATA"
- elif frame_type == FrameType.NACK:
- orig = payload[0] if len(payload) > 0 else 0
- reason_code = payload[1] if len(payload) > 1 else 0
- try:
- reason_name = NackReason(reason_code).name
- except ValueError:
- reason_name = f"0x{reason_code:02X}"
- is_orig_match = False
- if orig == 0x01 and self.tx_state == "WAIT_SET_ACK":
- is_orig_match = True
- elif orig == 0x02 and self.tx_state in ("WAIT_GET_ACK", "WAIT_GET_DATA"):
- is_orig_match = True
- elif orig == 0x03 and self.tx_state == "WAIT_HEARTBEAT_ACK":
- is_orig_match = True
- if is_orig_match:
- self.tx_state = "IDLE"
- self.pending_request = None
- self._set_state("REJECTED", f"请求被单板拒绝 (NACK 0xC0): 原请求=0x{orig:02X}, 原因={reason_name}")
- result["is_match"] = True
- result["msg"] = f"请求被单板拒绝: {reason_name}"
- result["status_code"] = "REJECTED"
- else:
- result["is_match"] = False
- result["msg"] = f"单板回复 NACK (原请求=0x{orig:02X}, 原因={reason_name}),非当前等待请求。"
- result["status_code"] = "UNSOLICITED_NACK"
- elif frame_type == FrameType.MOTOR_DONE:
- axis = payload[0] if len(payload) > 0 else 0
- reason_code = payload[1] if len(payload) > 1 else 0
- steps = int.from_bytes(payload[2:4], "little") if len(payload) >= 4 else 0
- try:
- reason_name = DoneReason(reason_code).name
- except ValueError:
- reason_name = f"0x{reason_code:02X}"
- result["is_match"] = True
- result["msg"] = f"电机 Axis{axis} 结束: {reason_name},步数={steps}"
- result["status_code"] = "MOTOR_DONE"
- if result["is_match"] and result["status_code"] != "MOTOR_DONE":
- self.matched_request_reply = True
- return result
- class SessionDiskLogger:
- """Thread-safe disk logger generating session-bound diagnostic logs."""
- def __init__(self, product: str, log_dir: Path | str | None = None):
- self.product = product
- self.session_id = hashlib.sha256(f"{time.time()}:{os.getpid()}".encode()).hexdigest()[:12]
- self.log_dir = Path(log_dir) if log_dir else (Path.cwd() / "logs")
- self.log_dir.mkdir(parents=True, exist_ok=True)
- now_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
- self.log_path = self.log_dir / f"gui_session_{self.product}_{now_str}_{self.session_id}.log"
- self._lock = threading.Lock()
- self._mono_base = time.monotonic()
- self._write_header()
- def _write_header(self):
- exe_path = sys.executable
- try:
- exe_sha = hashlib.sha256(Path(exe_path).read_bytes()).hexdigest()
- except Exception:
- exe_sha = "N/A"
- header = [
- "=" * 80,
- f"Prod2U GUI Diagnostic Session Log",
- f"Session ID : {self.session_id}",
- f"Product : {self.product}",
- f"Start Time : {datetime.datetime.now().astimezone().isoformat()}",
- f"Executable : {exe_path}",
- f"Exe SHA256 : {exe_sha}",
- f"Python Ver : {sys.version}",
- "=" * 80,
- "",
- ]
- with self._lock:
- with open(self.log_path, "w", encoding="utf-8") as f:
- f.write("\n".join(header) + "\n")
- def log_event(self, tag: str, hex_data: str = "", details: str = ""):
- now_dt = datetime.datetime.now().astimezone().isoformat(timespec="milliseconds")
- rel_mono = time.monotonic() - self._mono_base
- line = f"[{now_dt}] [{rel_mono:10.4f}s] [{tag:14s}] {hex_data:30s} {details}"
- with self._lock:
- with open(self.log_path, "a", encoding="utf-8") as f:
- f.write(line + "\n")
|