stream_receiver.py 24 KB

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