pwm_scope.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. #!/usr/bin/env python3
  2. """6400V2.0 scope test 1.2.0: SET36/GET90 (compat SET35/GET88/86), 20Hz PWM, fan 5s 50%/0% toggle, EPB1/SB1/SB2 + 4000Hz 80% buzzer."""
  3. import argparse
  4. import binascii
  5. import datetime as dt
  6. import json
  7. import math
  8. import os
  9. from pathlib import Path
  10. import re
  11. import signal
  12. import sys
  13. import time
  14. import unicodedata
  15. SCRIPT_VERSION = "1.2.0"
  16. BOX_WIDTH = 90
  17. DEFAULT_PORT = "/dev/serial/by-path/pci-0000:00:14.0-usb-0:3:1.0-port0"
  18. FALLBACK_USB1_PORTS = (
  19. "/dev/serial/by-path/pci-0000:00:14.0-usb-0:3:1.0-port0",
  20. "/dev/serial/by-path/pci-0000:00:14.0-usb-0:2:1.0-port0",
  21. "/dev/serial/by-id/usb-FTDI_USB__-__Serial-if00-port0",
  22. "/dev/ttyUSB1",
  23. )
  24. PTC_DUTIES = bytes(range(1, 25))
  25. SSR_DUTIES = bytes((33, 34, 35))
  26. FAN_DUTY_HIGH = 50
  27. FAN_DUTY_LOW = 0
  28. FAN_HOLD_SECONDS = 5.0
  29. def resolve_port(port):
  30. real = os.path.realpath(port)
  31. if real == "/dev/ttyUSB0" or "BG00WPDX" in str(port):
  32. raise RuntimeError("USB0属于其他项目,拒绝打开")
  33. if os.path.exists(port):
  34. return port
  35. if port in FALLBACK_USB1_PORTS:
  36. by_path_dir = Path("/dev/serial/by-path")
  37. candidates = list(FALLBACK_USB1_PORTS)
  38. if by_path_dir.is_dir():
  39. candidates.extend(str(p) for p in sorted(by_path_dir.iterdir()))
  40. for cand in candidates:
  41. if os.path.exists(cand) and os.path.realpath(cand) == "/dev/ttyUSB1":
  42. return cand
  43. return port
  44. def fan_duty_for_elapsed(elapsed=0.0):
  45. phase = int((max(0.0, float(elapsed)) + 1e-9) // FAN_HOLD_SECONDS) % 2
  46. return FAN_DUTY_HIGH if phase == 0 else FAN_DUTY_LOW
  47. def build_duties(fan_duty=FAN_DUTY_HIGH, buzzer=0):
  48. return PTC_DUTIES + bytes([fan_duty]) * 8 + SSR_DUTIES + bytes([1 if buzzer else 0])
  49. DUTIES = build_duties(FAN_DUTY_HIGH)
  50. DUTIES_FAN_ZERO = build_duties(FAN_DUTY_LOW)
  51. CT_CONNECTORS = ("U6-local", "CON53", "CON55", "CON56", "CON57",
  52. "CON79", "CON80", "CON81", "CON82")
  53. CT_ROLES = ("U6芯片本地", "腔1进风口", "腔1出风口", "腔2进风口", "腔2出风口",
  54. "腔3进风口", "腔3出风口", "腔4进风口", "腔4出风口")
  55. CT_U6_PINS = (None, 6, 5, 4, 3, 2, 1, 16, 15)
  56. CT_RESISTORS = (None, "R569/R568", "R588/R589", "R590/R591", "R592/R593",
  57. "R822/R823", "R824/R825", "R826/R827", "R828/R829")
  58. PTC_BALLS = ("F16 G16 T4 R5 T6 R7 T2 R3 P16 R16 M16 N16 "
  59. "P10 R10 T13 T12 L3 N2 K5 L4 H4 J6 H5 C15").split()
  60. PTC_PINS = ([f"CON147.{p}" for p in (1, 3, 5, 7, 9, 11)] +
  61. [f"CON148.{p}" for p in (1, 3, 5, 7, 9, 11)] +
  62. [f"CON149.{p}" for p in (1, 3, 5, 7, 9, 11)] +
  63. ["CON149.19"] + [f"CON150.{p}" for p in (1, 5, 9, 13, 17)])
  64. FAN_PINS = ("CON154.5", "CON154.11", "CON155.5", "CON155.11",
  65. "CON154.6", "CON154.12", "CON155.6", "CON155.12")
  66. FAN_BALLS = ("C4", "B1", "P12", "D8", "B5", "A14", "A10", "C7")
  67. ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
  68. class Style:
  69. def __init__(self, enabled=True):
  70. self.enabled = bool(enabled)
  71. def _wrap(self, code, text):
  72. return f"\x1b[{code}m{text}\x1b[0m" if self.enabled else str(text)
  73. def bold(self, text):
  74. return self._wrap("1", text)
  75. def dim(self, text):
  76. return self._wrap("2", text)
  77. def cyan(self, text):
  78. return self._wrap("36", text)
  79. def bold_cyan(self, text):
  80. return self._wrap("1;36", text)
  81. def green(self, text):
  82. return self._wrap("32", text)
  83. def bold_green(self, text):
  84. return self._wrap("1;32", text)
  85. def yellow(self, text):
  86. return self._wrap("33", text)
  87. def bold_yellow(self, text):
  88. return self._wrap("1;33", text)
  89. def red(self, text):
  90. return self._wrap("1;31", text)
  91. def magenta(self, text):
  92. return self._wrap("35", text)
  93. def disp_width(text):
  94. clean = ANSI_RE.sub("", str(text))
  95. width = 0
  96. for ch in clean:
  97. if unicodedata.combining(ch):
  98. continue
  99. width += 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
  100. return width
  101. def pad(text, width, align="left"):
  102. s = str(text)
  103. rem = max(0, width - disp_width(s))
  104. if align == "right":
  105. return (" " * rem) + s
  106. if align == "center":
  107. left = rem // 2
  108. return (" " * left) + s + (" " * (rem - left))
  109. return s + (" " * rem)
  110. def progress_bar(ratio, width=16, style=None):
  111. ratio = max(0.0, min(1.0, ratio))
  112. filled = int(round(ratio * width))
  113. bar_fill = "█" * filled
  114. bar_empty = "░" * (width - filled)
  115. if style and style.enabled:
  116. return style.bold_green(bar_fill) + style.dim(bar_empty)
  117. return bar_fill + bar_empty
  118. def format_mmss(seconds):
  119. sec = max(0, int(round(seconds)))
  120. m, s = divmod(sec, 60)
  121. h, m = divmod(m, 60)
  122. return f"{h:d}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}"
  123. def output_rows():
  124. rows = []
  125. for i in range(24):
  126. rows.append((i, f"PTC{i:02d} 腔{i // 6 + 1} 第{i % 6 + 1}路",
  127. PTC_PINS[i], PTC_BALLS[i], 20))
  128. for j in range(8):
  129. role = "进风" if j < 4 else "排风"
  130. rows.append((24 + j, f"腔{j % 4 + 1}{role}",
  131. FAN_PINS[j], FAN_BALLS[j], 20))
  132. for j, (name, pin, ball) in enumerate((
  133. ("SSR1 腔1", "CON165.14", "E14"),
  134. ("SSR2 腔2+3共用", "CON165.13", "E8"),
  135. ("SSR4 腔4", "CON165.11", "D9"))):
  136. rows.append((32 + j, name, pin, ball, 20))
  137. return rows
  138. def _box_helpers(style, w=BOX_WIDTH):
  139. inner = w - 4
  140. def top(title=""):
  141. if not title:
  142. return "┌" + ("─" * (w - 2)) + "┐"
  143. t = f" {title} "
  144. rem = max(0, w - 3 - disp_width(t))
  145. return "┌─" + style.bold_cyan(t) + ("─" * rem) + "┐"
  146. def mid(title=""):
  147. if not title:
  148. return "├" + ("─" * (w - 2)) + "┤"
  149. t = f" {title} "
  150. rem = max(0, w - 3 - disp_width(t))
  151. return "├─" + style.bold_cyan(t) + ("─" * rem) + "┤"
  152. def sep():
  153. return "├" + ("┄" * (w - 2)) + "┤"
  154. def bot(footer=""):
  155. if not footer:
  156. return "└" + ("─" * (w - 2)) + "┘"
  157. f = f" {footer} "
  158. rem = max(0, w - 3 - disp_width(f))
  159. return "└" + ("─" * rem) + style.dim(f) + "─┘"
  160. def row(content):
  161. return "│ " + pad(content, inner) + " │"
  162. def split2(left, right, left_w=41):
  163. right_w = inner - left_w - 3
  164. return "│ " + pad(left, left_w) + " │ " + pad(right, right_w) + " │"
  165. return top, mid, sep, bot, row, split2
  166. def show_map(style=None):
  167. st = style or Style(enabled=sys.stdout.isatty() and not os.environ.get("NO_COLOR"))
  168. top, mid, sep, bot, row, _ = _box_helpers(st)
  169. print(top(f"6400V2.0 示波器与温度测试 (脚本 v{SCRIPT_VERSION} / 适配固件 3.3.0)"))
  170. print(row(
  171. f"{st.bold('协议')}: SET36 / GET90 (921600 8N1) "
  172. f"{st.bold('统一频率')}: 20Hz (周期 50.00ms, 1% = 0.50ms)"
  173. ))
  174. print(row(
  175. f"{st.bold('规则')}: PTC=1~24%,风扇8路=5秒50%/5秒0%交替往复,SSR=33~35%;退出仅停发等30s看门狗"
  176. ))
  177. print(mid("35路 PWM 输出与测量点映射表"))
  178. header = (
  179. f"{pad('SET字节', 7)} │ "
  180. f"{pad('输出通道', 16)} │ "
  181. f"{pad('占空比', 6, 'right')} │ "
  182. f"{pad('导通脉宽', 8, 'right')} │ "
  183. f"{pad('频率', 6, 'right')} │ "
  184. f"{pad('连接器', 9)} │ "
  185. f"{pad('FPGA', 5)} │ "
  186. f"{pad('测量极性', 8)}"
  187. )
  188. print(row(st.bold(header)))
  189. print(sep())
  190. for i, name, pin, ball, hz in output_rows():
  191. if i == 0:
  192. print(row(st.bold_yellow("▶ PTC 加热片 (24路) — 连接器脚为功率正端;示波器读数须结合测量位置与板上驱动极性")))
  193. elif i == 24:
  194. print(sep())
  195. print(row(st.bold_yellow("▶ 风扇 PWM (8路) — 默认5s 50%/5s 0%交替;接口高电平=D,FPGA脚经2N7002反相低电平=D")))
  196. elif i == 32:
  197. print(sep())
  198. print(row(st.bold_yellow("▶ SSR 加热块 (3路) — CON165为3.3V控制端;24V功率端空载测波形建议接330Ω/5W假负载")))
  199. duty = DUTIES[i]
  200. pulse_ms = duty * 0.5
  201. idx_s = pad(f"{i:2d}", 7, "center")
  202. name_s = pad(name, 16)
  203. if 24 <= i < 32:
  204. duty_s = pad("50%/0%", 6, "right")
  205. pulse_s = pad("25.0/0ms", 8, "right")
  206. else:
  207. duty_s = pad(f"{duty:2d}%", 6, "right")
  208. pulse_s = pad(f"{pulse_ms:5.1f}ms", 8, "right")
  209. hz_s = pad(f"{hz:3d}Hz", 6, "right")
  210. pin_s = pad(pin, 9)
  211. ball_s = pad(ball, 5)
  212. if i < 24:
  213. pin_col = st.cyan(pin_s)
  214. note_s = pad("功率正端", 8)
  215. elif i < 32:
  216. pin_col = st.green(pin_s)
  217. note_s = pad("接口高=D", 8)
  218. else:
  219. pin_col = st.magenta(pin_s)
  220. note_s = pad("控制高=D", 8)
  221. line = (
  222. f"{idx_s} │ {name_s} │ {st.bold(duty_s)} │ {pulse_s} │ "
  223. f"{hz_s} │ {pin_col} │ {st.bold(ball_s)} │ {st.dim(note_s)}"
  224. )
  225. print(row(line))
  226. print(mid("CT7428 (U6 @ I2C 0x49) 温度通道映射"))
  227. ct_hdr = (
  228. f"{pad('通道', 5)} │ "
  229. f"{pad('寄存器', 6)} │ "
  230. f"{pad('位置/用途', 10)} │ "
  231. f"{pad('主板接口', 9)} │ "
  232. f"{pad('U6引脚与0Ω电阻路径 (接口1=DP, 2=GND, 3=DN)', 44)}"
  233. )
  234. print(row(st.bold(ct_hdr)))
  235. print(sep())
  236. for idx, (conn, role, u6_pin, res) in enumerate(
  237. zip(CT_CONNECTORS, CT_ROLES, CT_U6_PINS, CT_RESISTORS)):
  238. if u6_pin is None:
  239. mapping = "U6芯片内部本地温度传感器"
  240. else:
  241. r_dp, r_dn = res.split("/")
  242. mapping = f"1脚→{r_dp}→U6.{u6_pin}(DP{idx}) / 3脚→{r_dn}→U6.7(DN)"
  243. row_s = (
  244. f"{pad(f'CT{idx}', 5)} │ "
  245. f"{pad(f'0x{idx:02X}', 6)} │ "
  246. f"{pad(role, 10)} │ "
  247. f"{st.cyan(pad(conn, 9))} │ "
  248. f"{pad(mapping, 44)}"
  249. )
  250. print(row(row_s))
  251. print(sep())
  252. print(row(st.dim("风扇:连接器高电平占空比=D;FPGA引脚低电平占空比=D。PTC表中的连接器脚为功率正端。")))
  253. print(row(st.dim("温度:CT0=U6本地;CT1..8=CON53/55/56/57/79/80/81/82。接口:1=DP,2=GND,3=DN→U6.7。")))
  254. print(row(st.dim("显示 FF 表示无有效值;0C 表示协议读到0(未接探头也可能返回0,不能据此认定真实0℃)。")))
  255. print(bot())
  256. def frame(kind, payload=b""):
  257. body = bytes((kind, len(payload))) + payload
  258. return b"\xA5\x5A" + body + binascii.crc_hqx(body, 0xFFFF).to_bytes(2, "little")
  259. class Link:
  260. def __init__(self, port, log):
  261. import serial
  262. self.serial = serial.Serial(port, 921600, timeout=0.05,
  263. write_timeout=0.5, exclusive=True)
  264. self.buf = bytearray()
  265. self.log = log
  266. self.diag = None
  267. self.diag_slots = {}
  268. self.bad_crc = 0
  269. self.partial_timeouts = 0
  270. self.startup_bytes = 0
  271. self.last_byte_at = None
  272. self.last_ack_at = None
  273. self.frame_gap = 0.1 # 92 bytes take ~1ms; allow USB packet/host latency.
  274. def event(self, kind, **fields):
  275. record = {"time": dt.datetime.now().astimezone().isoformat(),
  276. "event": kind, **fields}
  277. self.log.write(json.dumps(record, ensure_ascii=False) + "\n")
  278. self.log.flush()
  279. def synchronize(self, end):
  280. """Drain only before the first TX; keep raw evidence of queued startup bytes."""
  281. started = last_data = time.monotonic()
  282. limit = min(end, started + 0.3)
  283. while time.monotonic() < limit:
  284. data = self.serial.read(max(1, self.serial.in_waiting))
  285. now = time.monotonic()
  286. if data:
  287. self.startup_bytes += len(data)
  288. self.event("STARTUP_RX", hex=data.hex(" "))
  289. last_data = now
  290. elif now - last_data >= 0.05:
  291. break
  292. self.buf.clear()
  293. self.last_byte_at = None
  294. self.event("SYNC", discarded_bytes=self.startup_bytes,
  295. seconds=round(time.monotonic() - started, 6))
  296. def receive(self):
  297. data = self.serial.read(max(1, self.serial.in_waiting))
  298. now = time.monotonic()
  299. if data:
  300. self.event("RX_BYTES", hex=data.hex(" "))
  301. self.buf.extend(data)
  302. self.last_byte_at = now
  303. return self._parse()
  304. if self.buf and self.last_byte_at is not None and now - self.last_byte_at >= self.frame_gap:
  305. self.partial_timeouts += 1
  306. self.event("RX_PARTIAL_TIMEOUT", hex=bytes(self.buf).hex(" "))
  307. frames = self._parse(stale=True)
  308. self.buf.clear()
  309. return frames
  310. return self._parse()
  311. def _parse(self, stale=False):
  312. frames = []
  313. while True:
  314. pos = self.buf.find(b"\xA5\x5A")
  315. if pos < 0:
  316. self.buf[:] = self.buf[-1:] if self.buf[-1:] == b"\xA5" else b""
  317. break
  318. if pos:
  319. del self.buf[:pos]
  320. if len(self.buf) < 4 or len(self.buf) < self.buf[3] + 6:
  321. if stale:
  322. # An abandoned prefix may contain a complete ACK. Hunt after
  323. # the inter-byte gap, never inside a live fragmented frame.
  324. del self.buf[0]
  325. continue
  326. break
  327. size = self.buf[3] + 6
  328. raw = bytes(self.buf[:size])
  329. if binascii.crc_hqx(raw[2:-2], 0xFFFF) != int.from_bytes(raw[-2:], "little"):
  330. self.bad_crc += 1
  331. self.event("BAD_CRC", hex=raw.hex(" "))
  332. del self.buf[0]
  333. continue
  334. del self.buf[:size]
  335. kind, payload = raw[2], raw[4:-2]
  336. self.event("RX", type=f"{kind:02X}", hex=raw.hex(" "))
  337. if kind == 0x52 and len(payload) == 20:
  338. self.diag = {
  339. "version": ".".join(str(x) for x in payload[2:5]),
  340. "slot": payload[7], "address": payload[8],
  341. "register": payload[9], "error": payload[10],
  342. "raw": int.from_bytes(payload[11:13], "little"),
  343. "decode_mask": int.from_bytes(payload[14:16], "little"),
  344. "bus": payload[5] & 15, "flags": payload[19]}
  345. self.diag_slots[self.diag["register"]] = dict(self.diag)
  346. self.event("DIAG", **self.diag)
  347. frames.append((kind, payload))
  348. return frames
  349. def request(self, kind, end, payload=None):
  350. if time.monotonic() >= end:
  351. raise TimeoutError("运行时间结束")
  352. if payload is None:
  353. payload = DUTIES if kind == 1 else b""
  354. raw = frame(kind, payload)
  355. self.serial.write(raw)
  356. self.event("TX", type=f"{kind:02X}", hex=raw.hex(" "))
  357. limit = min(end, time.monotonic() + 0.7)
  358. get_ack = False
  359. while time.monotonic() < limit:
  360. answer = None
  361. for typ, payload in self.receive():
  362. if typ == 0xC0:
  363. raise RuntimeError(f"NACK: {payload.hex(' ')}")
  364. if kind == 1 and typ == 0x81 and not payload:
  365. self.last_ack_at = time.monotonic()
  366. answer = b""
  367. if kind == 2 and typ == 0x82 and not payload:
  368. self.last_ack_at = time.monotonic()
  369. get_ack = True
  370. elif kind == 2 and typ == 0x42 and get_ack:
  371. if len(payload) not in (86, 88, 90):
  372. raise RuntimeError(f"GET长度={len(payload)},要求86/88/90;需配套3.x固件")
  373. answer = payload
  374. if answer is not None:
  375. return answer
  376. raise TimeoutError(f"{'SET' if kind == 1 else 'GET'}等待应答超时")
  377. def idle_until(self, until):
  378. while time.monotonic() < until:
  379. self.receive()
  380. def temp(value):
  381. return "FF" if value == 255 else f"{value}C"
  382. def styled_temp(value, style, width=3):
  383. t = pad(temp(value), width, "right")
  384. if not style.enabled:
  385. return t
  386. if value == 255:
  387. return style.red(t)
  388. if value == 0:
  389. return style.dim(t)
  390. if value >= 70:
  391. return style.bold_yellow(t)
  392. return style.bold_green(t)
  393. def render_live_panel(style, *, cycles, total_cycles, elapsed, remaining,
  394. read_only, matches, outputs, ct, errors, bad_crc,
  395. diag, diag_slots, last_error, last_ack_age=None,
  396. expected_outputs=None):
  397. top, mid, _, bot, row, split2 = _box_helpers(style)
  398. total_dur = max(0.001, elapsed + remaining)
  399. ratio = min(1.0, elapsed / total_dur)
  400. pbar = progress_bar(ratio, width=16, style=style)
  401. now_str = dt.datetime.now().strftime("%H:%M:%S")
  402. if matches is None:
  403. mode_badge = style.yellow("本轮应答未确认")
  404. elif read_only:
  405. mode_badge = style.cyan("只读 GET90 正常")
  406. elif matches:
  407. mode_badge = style.bold_green("✓ SET35/GET86 35路回读一致")
  408. else:
  409. mode_badge = style.red("✗ 35路回读不符")
  410. if last_ack_age is None:
  411. watchdog = style.yellow("尚未确认")
  412. elif last_ack_age >= 30:
  413. watchdog = style.red("通信已超时")
  414. elif last_ack_age >= 2:
  415. watchdog = style.yellow(f"{last_ack_age:.0f}秒前应答")
  416. else:
  417. watchdog = style.green("应答正常")
  418. err_str = style.red(str(errors)) if errors else style.green("0")
  419. crc_str = style.yellow(str(bad_crc)) if bad_crc else style.green("0")
  420. lines = [
  421. top(f"实时监控面板 [{now_str}]"),
  422. split2(
  423. f"进度: [{pbar}] {ratio * 100:5.1f}%",
  424. f"轮次: {style.bold(f'#{cycles}')}/{total_cycles} │ 已运行: {format_mmss(elapsed)} │ 剩余: {style.bold(format_mmss(remaining))}",
  425. left_w=33,
  426. ),
  427. split2(
  428. f"状态: {mode_badge}",
  429. f"错误: {err_str} │ 丢弃CRC: {crc_str} │ 看门狗: {watchdog}",
  430. left_w=33,
  431. ),
  432. mid("35路 PWM 控制回读核对 (20Hz / 周期 50.00ms)"),
  433. ]
  434. if outputs and len(outputs) in (35, 36):
  435. ptc_ok = list(outputs[:24]) == list(PTC_DUTIES)
  436. fan_vals = list(outputs[24:32])
  437. if expected_outputs is not None and len(expected_outputs) in (35, 36):
  438. fan_ok = fan_vals == list(expected_outputs[24:32])
  439. else:
  440. fan_ok = fan_vals in ([FAN_DUTY_HIGH] * 8, [FAN_DUTY_LOW] * 8)
  441. ssr_vals = list(outputs[32:35])
  442. ssr_ok = ssr_vals == list(SSR_DUTIES)
  443. b1 = style.green("✓") if ptc_ok or read_only else style.red("✗")
  444. b2 = style.green("✓") if fan_ok or read_only else style.red("✗")
  445. b3 = style.green("✓") if ssr_ok or read_only else style.red("✗")
  446. if matches is None:
  447. b1 = b2 = b3 = style.yellow("?")
  448. if len(set(fan_vals)) == 1:
  449. fan_text = f"进/排风8路: {fan_vals[0]:2d}% ({fan_vals[0]*0.5:4.1f}ms, 5s 50/0%) {b2}"
  450. else:
  451. fan_text = f"进/排风8路: {outputs[24]:2d}%~{outputs[31]:2d}% ({outputs[24]*0.5:4.1f}~{outputs[31]*0.5:4.1f}ms) {b2}"
  452. lines.append(split2(
  453. f"PTC00..23 : 1%~24% ( 0.5~12.0ms) {b1}",
  454. fan_text,
  455. left_w=41,
  456. ))
  457. lines.append(row(
  458. f"SSR 1/2/4 : {ssr_vals[0]:2d}% / {ssr_vals[1]:2d}% / {ssr_vals[2]:2d}% "
  459. f"({ssr_vals[0]*0.5:4.1f} / {ssr_vals[1]*0.5:4.1f} / {ssr_vals[2]*0.5:4.1f}ms @ CON165.14/.13/.11) {b3}"
  460. ))
  461. else:
  462. lines.append(row(style.dim("等待首轮 GET90 数据回读...")))
  463. lines.append(mid("CT7428 (U6 @ 0x49) 9路实时温度"))
  464. if ct and len(ct) >= 9:
  465. active_ext = sum(1 for v in ct[1:9] if 0 < v < 255)
  466. lines.append(split2(
  467. f"CT0 U6本地: {styled_temp(ct[0], style)} (U6芯片内部)",
  468. f"外部探头(CT1..8): 非零 {style.bold(f'{active_ext}/8')} 路 (0C可能未接)",
  469. left_w=41,
  470. ))
  471. lines.append(split2(
  472. f"腔1: 进[CT1/CON53]={styled_temp(ct[1], style)} 出[CT2/CON55]={styled_temp(ct[2], style)}",
  473. f"腔2: 进[CT3/CON56]={styled_temp(ct[3], style)} 出[CT4/CON57]={styled_temp(ct[4], style)}",
  474. left_w=41,
  475. ))
  476. lines.append(split2(
  477. f"腔3: 进[CT5/CON79]={styled_temp(ct[5], style)} 出[CT6/CON80]={styled_temp(ct[6], style)}",
  478. f"腔4: 进[CT7/CON81]={styled_temp(ct[7], style)} 出[CT8/CON82]={styled_temp(ct[8], style)}",
  479. left_w=41,
  480. ))
  481. else:
  482. lines.append(row(style.dim("等待温度数据...")))
  483. lines.append(mid("固件自主诊断帧 (0x52)"))
  484. if diag:
  485. d = diag
  486. mask_cnt = bin(d["decode_mask"] & 0x1FF).count("1")
  487. scl = (d["bus"] >> 2) & 1
  488. sda = (d["bus"] >> 1) & 1
  489. err_badge = style.green("err=0") if d["error"] == 0 else style.red(f"err={d['error']}")
  490. lines.append(row(
  491. f"v{d['version']} │ 槽#{d['slot']:02d} reg=0x{d['register']:02X} "
  492. f"raw=0x{d['raw']:04X} {err_badge} │ 掩码:0x{d['decode_mask']:03X}({mask_cnt}/9) │ "
  493. f"bus:0x{d['bus']:X}(SCL={scl},SDA={sda})"
  494. ))
  495. status_parts = []
  496. for reg_id, label in ((0x23, "状态23"), (0x30, "状态30"), (0xC4, "配置C4"),
  497. (0xFE, "厂商FE"), (0xFF, "芯片FF")):
  498. if reg_id in diag_slots:
  499. status_parts.append(f"{label}=0x{diag_slots[reg_id]['raw']:04X}")
  500. if status_parts:
  501. lines.append(row(style.dim("已捕获寄存器: " + " ".join(status_parts))))
  502. else:
  503. lines.append(row(style.dim("等待 0x52 诊断帧...")))
  504. if last_error:
  505. lines.append(row(style.red(f"最近告警: {last_error[:72]}")))
  506. lines.append(bot("Ctrl+C 停发;30s后PTC/SSR=0,风扇20%"))
  507. return lines
  508. def run(args):
  509. port = resolve_port(args.port)
  510. real_port = os.path.realpath(port)
  511. if real_port == "/dev/ttyUSB0":
  512. raise RuntimeError("USB0属于其他项目,拒绝打开")
  513. is_tty = sys.stdout.isatty()
  514. use_color = is_tty and not os.environ.get("NO_COLOR") and not getattr(args, "no_color", False)
  515. live_mode = is_tty and not getattr(args, "scroll", False)
  516. style = Style(enabled=use_color)
  517. log_path = (Path(args.log).expanduser() if args.log else
  518. Path(__file__).resolve().parent / "logs" /
  519. (dt.datetime.now().strftime("%Y%m%d-%H%M%S-%f") + ".jsonl"))
  520. log_path.parent.mkdir(parents=True, exist_ok=True)
  521. show_map(style=style)
  522. print(f"{style.bold('串口')}:{port} -> {style.cyan(real_port)} / 921600 8N1")
  523. print(f"{style.bold('计划')}:运行 {style.bold(f'{args.minutes:g}')} 分钟,每 {style.bold(f'{args.interval:g}')} 秒一轮;日志:{style.dim(log_path)}")
  524. print(f"{style.yellow('提示')}:Ctrl+C停止。结束只关闭串口,不发归零/恢复命令;最后有效命令后约30秒由固件超时。", flush=True)
  525. if live_mode:
  526. print()
  527. cycles = errors = 0
  528. total_cycles = max(1, int(round(args.minutes * 60 / args.interval)))
  529. start = time.monotonic()
  530. end = start + args.minutes * 60
  531. next_due = start
  532. prev_panel_lines = 0
  533. last_outputs = None
  534. last_expected_outputs = DUTIES
  535. last_ct = None
  536. last_matches = None
  537. last_error = None
  538. def clear_live_panel():
  539. nonlocal prev_panel_lines
  540. if live_mode and prev_panel_lines > 0:
  541. sys.stdout.write(f"\x1b[{prev_panel_lines}A\r\x1b[J")
  542. prev_panel_lines = 0
  543. def draw_live_panel():
  544. nonlocal prev_panel_lines
  545. if not live_mode:
  546. return
  547. now_m = time.monotonic()
  548. panel = render_live_panel(
  549. style,
  550. cycles=cycles,
  551. total_cycles=total_cycles,
  552. elapsed=now_m - start,
  553. remaining=max(0.0, end - now_m),
  554. read_only=args.read_only,
  555. matches=last_matches,
  556. outputs=last_outputs,
  557. ct=last_ct,
  558. errors=errors,
  559. bad_crc=link.bad_crc,
  560. diag=link.diag,
  561. diag_slots=link.diag_slots,
  562. last_error=last_error,
  563. last_ack_age=None if link.last_ack_at is None else now_m - link.last_ack_at,
  564. expected_outputs=last_expected_outputs,
  565. )
  566. clear_live_panel()
  567. sys.stdout.write("\n".join(panel) + "\n")
  568. sys.stdout.flush()
  569. prev_panel_lines = len(panel)
  570. with log_path.open("x", encoding="utf-8") as log:
  571. link = Link(port, log)
  572. link.event("START", port=port, minutes=args.minutes,
  573. interval=args.interval, read_only=args.read_only,
  574. set_payload=list(DUTIES),
  575. set_payload_fan0=list(DUTIES_FAN_ZERO),
  576. fan_hold_seconds=FAN_HOLD_SECONDS)
  577. if live_mode:
  578. sys.stdout.write("\x1b[?25l")
  579. sys.stdout.flush()
  580. try:
  581. link.synchronize(end)
  582. print(f"启动同步:清理{link.startup_bytes}字节缓存(原始字节已记录);以下CRC为运行期统计。", flush=True)
  583. loop_start = next_due = time.monotonic()
  584. while time.monotonic() < end:
  585. cycles += 1
  586. last_matches = None
  587. fan_duty = fan_duty_for_elapsed(time.monotonic() - loop_start)
  588. expected_duties = build_duties(fan_duty)
  589. last_expected_outputs = expected_duties
  590. try:
  591. if not args.read_only:
  592. link.request(1, end, expected_duties)
  593. data = link.request(2, end)
  594. outputs = data[:32] + data[83:86]
  595. matches = outputs == expected_duties[:35]
  596. if not args.read_only and not matches:
  597. raise RuntimeError(f"输出回读不符:{list(outputs)} (期望风扇={fan_duty}%)")
  598. ct = list(data[56:65])
  599. last_outputs = outputs
  600. last_ct = ct
  601. last_matches = matches
  602. link.event("CYCLE", cycle=cycles,
  603. elapsed=round(time.monotonic() - start, 3),
  604. fan_duty=fan_duty,
  605. output_match=matches, outputs=list(outputs),
  606. ct=ct, ct_reserved=list(data[65:83]),
  607. bmc=list(data[32:56]))
  608. if live_mode:
  609. draw_live_panel()
  610. else:
  611. values = " ".join(f"CT{i}/{name}={temp(value)}"
  612. for i, (name, value) in enumerate(zip(CT_CONNECTORS, ct)))
  613. mode = "GET OK" if args.read_only else f"SET/GET 35路一致 (风扇={fan_duty}%)"
  614. print(f"[{dt.datetime.now():%H:%M:%S}] #{cycles} {mode}\n {values}", flush=True)
  615. if link.diag:
  616. d = link.diag
  617. print(f" DIAG v{d['version']} reg=0x{d['register']:02X} "
  618. f"raw=0x{d['raw']:04X} err={d['error']} "
  619. f"decode_mask=0x{d['decode_mask']:03X} "
  620. f"bus=0x{d['bus']:X} flags=0x{d['flags']:02X}", flush=True)
  621. except (TimeoutError, RuntimeError) as exc:
  622. if time.monotonic() >= end:
  623. break
  624. errors += 1
  625. last_error = f"[{dt.datetime.now():%H:%M:%S}] {exc}"
  626. link.event("ERROR", message=str(exc))
  627. if live_mode:
  628. clear_live_panel()
  629. print(style.red(last_error), flush=True)
  630. draw_live_panel()
  631. else:
  632. print(f"[{dt.datetime.now():%H:%M:%S}] {exc}", flush=True)
  633. next_due = max(loop_start + cycles * args.interval, time.monotonic())
  634. link.idle_until(min(next_due, end))
  635. except KeyboardInterrupt:
  636. print("\n已停止发送。", flush=True)
  637. finally:
  638. if live_mode:
  639. sys.stdout.write("\x1b[?25h")
  640. sys.stdout.flush()
  641. link.event("END", cycles=cycles, errors=errors,
  642. bad_crc=link.bad_crc, partial_timeouts=link.partial_timeouts,
  643. startup_bytes=link.startup_bytes,
  644. elapsed=round(time.monotonic() - start, 3))
  645. link.serial.close()
  646. print(f"结束:{cycles}轮,{errors}次错误,CRC错误{link.bad_crc};未发送退出控制命令。")
  647. return 1 if errors else 0
  648. def stop_sending(*_):
  649. raise KeyboardInterrupt
  650. def _prepare_windows_console():
  651. if os.name != "nt":
  652. return
  653. for stream in (sys.stdout, sys.stderr):
  654. if hasattr(stream, "reconfigure"):
  655. try:
  656. stream.reconfigure(encoding="utf-8", errors="replace")
  657. except Exception:
  658. pass
  659. try:
  660. import ctypes
  661. kernel32 = ctypes.windll.kernel32
  662. for handle_id in (-11, -12):
  663. handle = kernel32.GetStdHandle(handle_id)
  664. mode = ctypes.c_uint32()
  665. if handle and kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
  666. kernel32.SetConsoleMode(handle, mode.value | 0x0004)
  667. except Exception:
  668. pass
  669. def main(argv=None):
  670. _prepare_windows_console()
  671. parser = argparse.ArgumentParser(description=__doc__)
  672. parser.add_argument("--minutes", type=float, default=15, help="运行分钟数,默认15")
  673. parser.add_argument("--interval", type=float, default=1, help="SET/GET循环间隔秒,默认1")
  674. parser.add_argument("--port", default=DEFAULT_PORT, help="温控串口,Linux默认USB1,Windows请传COMx")
  675. parser.add_argument("--read-only", action="store_true", help="只循环GET;GET也会喂固件看门狗")
  676. parser.add_argument("--dry-run", action="store_true", help="只显示映射与帧,不打开串口")
  677. parser.add_argument("--scroll", action="store_true", help="禁用终端原位刷新面板,改为逐行滚动输出")
  678. parser.add_argument("--no-color", action="store_true", help="禁用ANSI颜色输出")
  679. parser.add_argument("--log", help="JSONL日志路径;默认在脚本旁logs中生成")
  680. args = parser.parse_args(argv)
  681. if any(not math.isfinite(x) or x <= 0 for x in (args.minutes, args.interval)):
  682. parser.error("--minutes和--interval必须为正有限数")
  683. use_color = sys.stdout.isatty() and not os.environ.get("NO_COLOR") and not args.no_color
  684. style = Style(enabled=use_color)
  685. if args.dry_run:
  686. show_map(style=style)
  687. print("SET_ALL (风扇50%):", frame(1, DUTIES).hex(" ").upper())
  688. print("SET_ALL (风扇0%) :", frame(1, DUTIES_FAN_ZERO).hex(" ").upper())
  689. print("GET_ALL :", frame(2).hex(" ").upper())
  690. return 0
  691. signal.signal(signal.SIGTERM, stop_sending)
  692. try:
  693. return run(args)
  694. except (OSError, RuntimeError, ImportError) as exc:
  695. print(f"错误:{exc}", file=sys.stderr)
  696. return 1
  697. if __name__ == "__main__":
  698. sys.exit(main())