stream_receiver.py 24 KB

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