| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785 |
- #!/usr/bin/env python3
- """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."""
- import argparse
- import binascii
- import datetime as dt
- import json
- import math
- import os
- from pathlib import Path
- import re
- import signal
- import sys
- import time
- import unicodedata
- SCRIPT_VERSION = "1.2.0"
- BOX_WIDTH = 90
- DEFAULT_PORT = "/dev/serial/by-path/pci-0000:00:14.0-usb-0:3:1.0-port0"
- FALLBACK_USB1_PORTS = (
- "/dev/serial/by-path/pci-0000:00:14.0-usb-0:3:1.0-port0",
- "/dev/serial/by-path/pci-0000:00:14.0-usb-0:2:1.0-port0",
- "/dev/serial/by-id/usb-FTDI_USB__-__Serial-if00-port0",
- "/dev/ttyUSB1",
- )
- PTC_DUTIES = bytes(range(1, 25))
- SSR_DUTIES = bytes((33, 34, 35))
- FAN_DUTY_HIGH = 50
- FAN_DUTY_LOW = 0
- FAN_HOLD_SECONDS = 5.0
- def resolve_port(port):
- real = os.path.realpath(port)
- if real == "/dev/ttyUSB0" or "BG00WPDX" in str(port):
- raise RuntimeError("USB0属于其他项目,拒绝打开")
- if os.path.exists(port):
- return port
- if port in FALLBACK_USB1_PORTS:
- by_path_dir = Path("/dev/serial/by-path")
- candidates = list(FALLBACK_USB1_PORTS)
- if by_path_dir.is_dir():
- candidates.extend(str(p) for p in sorted(by_path_dir.iterdir()))
- for cand in candidates:
- if os.path.exists(cand) and os.path.realpath(cand) == "/dev/ttyUSB1":
- return cand
- return port
- def fan_duty_for_elapsed(elapsed=0.0):
- phase = int((max(0.0, float(elapsed)) + 1e-9) // FAN_HOLD_SECONDS) % 2
- return FAN_DUTY_HIGH if phase == 0 else FAN_DUTY_LOW
- def build_duties(fan_duty=FAN_DUTY_HIGH, buzzer=0):
- return PTC_DUTIES + bytes([fan_duty]) * 8 + SSR_DUTIES + bytes([1 if buzzer else 0])
- DUTIES = build_duties(FAN_DUTY_HIGH)
- DUTIES_FAN_ZERO = build_duties(FAN_DUTY_LOW)
- CT_CONNECTORS = ("U6-local", "CON53", "CON55", "CON56", "CON57",
- "CON79", "CON80", "CON81", "CON82")
- CT_ROLES = ("U6芯片本地", "腔1进风口", "腔1出风口", "腔2进风口", "腔2出风口",
- "腔3进风口", "腔3出风口", "腔4进风口", "腔4出风口")
- CT_U6_PINS = (None, 6, 5, 4, 3, 2, 1, 16, 15)
- CT_RESISTORS = (None, "R569/R568", "R588/R589", "R590/R591", "R592/R593",
- "R822/R823", "R824/R825", "R826/R827", "R828/R829")
- PTC_BALLS = ("F16 G16 T4 R5 T6 R7 T2 R3 P16 R16 M16 N16 "
- "P10 R10 T13 T12 L3 N2 K5 L4 H4 J6 H5 C15").split()
- PTC_PINS = ([f"CON147.{p}" for p in (1, 3, 5, 7, 9, 11)] +
- [f"CON148.{p}" for p in (1, 3, 5, 7, 9, 11)] +
- [f"CON149.{p}" for p in (1, 3, 5, 7, 9, 11)] +
- ["CON149.19"] + [f"CON150.{p}" for p in (1, 5, 9, 13, 17)])
- FAN_PINS = ("CON154.5", "CON154.11", "CON155.5", "CON155.11",
- "CON154.6", "CON154.12", "CON155.6", "CON155.12")
- FAN_BALLS = ("C4", "B1", "P12", "D8", "B5", "A14", "A10", "C7")
- ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
- class Style:
- def __init__(self, enabled=True):
- self.enabled = bool(enabled)
- def _wrap(self, code, text):
- return f"\x1b[{code}m{text}\x1b[0m" if self.enabled else str(text)
- def bold(self, text):
- return self._wrap("1", text)
- def dim(self, text):
- return self._wrap("2", text)
- def cyan(self, text):
- return self._wrap("36", text)
- def bold_cyan(self, text):
- return self._wrap("1;36", text)
- def green(self, text):
- return self._wrap("32", text)
- def bold_green(self, text):
- return self._wrap("1;32", text)
- def yellow(self, text):
- return self._wrap("33", text)
- def bold_yellow(self, text):
- return self._wrap("1;33", text)
- def red(self, text):
- return self._wrap("1;31", text)
- def magenta(self, text):
- return self._wrap("35", text)
- def disp_width(text):
- clean = ANSI_RE.sub("", str(text))
- width = 0
- for ch in clean:
- if unicodedata.combining(ch):
- continue
- width += 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
- return width
- def pad(text, width, align="left"):
- s = str(text)
- rem = max(0, width - disp_width(s))
- if align == "right":
- return (" " * rem) + s
- if align == "center":
- left = rem // 2
- return (" " * left) + s + (" " * (rem - left))
- return s + (" " * rem)
- def progress_bar(ratio, width=16, style=None):
- ratio = max(0.0, min(1.0, ratio))
- filled = int(round(ratio * width))
- bar_fill = "█" * filled
- bar_empty = "░" * (width - filled)
- if style and style.enabled:
- return style.bold_green(bar_fill) + style.dim(bar_empty)
- return bar_fill + bar_empty
- def format_mmss(seconds):
- sec = max(0, int(round(seconds)))
- m, s = divmod(sec, 60)
- h, m = divmod(m, 60)
- return f"{h:d}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}"
- def output_rows():
- rows = []
- for i in range(24):
- rows.append((i, f"PTC{i:02d} 腔{i // 6 + 1} 第{i % 6 + 1}路",
- PTC_PINS[i], PTC_BALLS[i], 20))
- for j in range(8):
- role = "进风" if j < 4 else "排风"
- rows.append((24 + j, f"腔{j % 4 + 1}{role}",
- FAN_PINS[j], FAN_BALLS[j], 20))
- for j, (name, pin, ball) in enumerate((
- ("SSR1 腔1", "CON165.14", "E14"),
- ("SSR2 腔2+3共用", "CON165.13", "E8"),
- ("SSR4 腔4", "CON165.11", "D9"))):
- rows.append((32 + j, name, pin, ball, 20))
- return rows
- def _box_helpers(style, w=BOX_WIDTH):
- inner = w - 4
- def top(title=""):
- if not title:
- return "┌" + ("─" * (w - 2)) + "┐"
- t = f" {title} "
- rem = max(0, w - 3 - disp_width(t))
- return "┌─" + style.bold_cyan(t) + ("─" * rem) + "┐"
- def mid(title=""):
- if not title:
- return "├" + ("─" * (w - 2)) + "┤"
- t = f" {title} "
- rem = max(0, w - 3 - disp_width(t))
- return "├─" + style.bold_cyan(t) + ("─" * rem) + "┤"
- def sep():
- return "├" + ("┄" * (w - 2)) + "┤"
- def bot(footer=""):
- if not footer:
- return "└" + ("─" * (w - 2)) + "┘"
- f = f" {footer} "
- rem = max(0, w - 3 - disp_width(f))
- return "└" + ("─" * rem) + style.dim(f) + "─┘"
- def row(content):
- return "│ " + pad(content, inner) + " │"
- def split2(left, right, left_w=41):
- right_w = inner - left_w - 3
- return "│ " + pad(left, left_w) + " │ " + pad(right, right_w) + " │"
- return top, mid, sep, bot, row, split2
- def show_map(style=None):
- st = style or Style(enabled=sys.stdout.isatty() and not os.environ.get("NO_COLOR"))
- top, mid, sep, bot, row, _ = _box_helpers(st)
- print(top(f"6400V2.0 示波器与温度测试 (脚本 v{SCRIPT_VERSION} / 适配固件 3.3.0)"))
- print(row(
- f"{st.bold('协议')}: SET36 / GET90 (921600 8N1) "
- f"{st.bold('统一频率')}: 20Hz (周期 50.00ms, 1% = 0.50ms)"
- ))
- print(row(
- f"{st.bold('规则')}: PTC=1~24%,风扇8路=5秒50%/5秒0%交替往复,SSR=33~35%;退出仅停发等30s看门狗"
- ))
- print(mid("35路 PWM 输出与测量点映射表"))
- header = (
- f"{pad('SET字节', 7)} │ "
- f"{pad('输出通道', 16)} │ "
- f"{pad('占空比', 6, 'right')} │ "
- f"{pad('导通脉宽', 8, 'right')} │ "
- f"{pad('频率', 6, 'right')} │ "
- f"{pad('连接器', 9)} │ "
- f"{pad('FPGA', 5)} │ "
- f"{pad('测量极性', 8)}"
- )
- print(row(st.bold(header)))
- print(sep())
- for i, name, pin, ball, hz in output_rows():
- if i == 0:
- print(row(st.bold_yellow("▶ PTC 加热片 (24路) — 连接器脚为功率正端;示波器读数须结合测量位置与板上驱动极性")))
- elif i == 24:
- print(sep())
- print(row(st.bold_yellow("▶ 风扇 PWM (8路) — 默认5s 50%/5s 0%交替;接口高电平=D,FPGA脚经2N7002反相低电平=D")))
- elif i == 32:
- print(sep())
- print(row(st.bold_yellow("▶ SSR 加热块 (3路) — CON165为3.3V控制端;24V功率端空载测波形建议接330Ω/5W假负载")))
- duty = DUTIES[i]
- pulse_ms = duty * 0.5
- idx_s = pad(f"{i:2d}", 7, "center")
- name_s = pad(name, 16)
- if 24 <= i < 32:
- duty_s = pad("50%/0%", 6, "right")
- pulse_s = pad("25.0/0ms", 8, "right")
- else:
- duty_s = pad(f"{duty:2d}%", 6, "right")
- pulse_s = pad(f"{pulse_ms:5.1f}ms", 8, "right")
- hz_s = pad(f"{hz:3d}Hz", 6, "right")
- pin_s = pad(pin, 9)
- ball_s = pad(ball, 5)
- if i < 24:
- pin_col = st.cyan(pin_s)
- note_s = pad("功率正端", 8)
- elif i < 32:
- pin_col = st.green(pin_s)
- note_s = pad("接口高=D", 8)
- else:
- pin_col = st.magenta(pin_s)
- note_s = pad("控制高=D", 8)
- line = (
- f"{idx_s} │ {name_s} │ {st.bold(duty_s)} │ {pulse_s} │ "
- f"{hz_s} │ {pin_col} │ {st.bold(ball_s)} │ {st.dim(note_s)}"
- )
- print(row(line))
- print(mid("CT7428 (U6 @ I2C 0x49) 温度通道映射"))
- ct_hdr = (
- f"{pad('通道', 5)} │ "
- f"{pad('寄存器', 6)} │ "
- f"{pad('位置/用途', 10)} │ "
- f"{pad('主板接口', 9)} │ "
- f"{pad('U6引脚与0Ω电阻路径 (接口1=DP, 2=GND, 3=DN)', 44)}"
- )
- print(row(st.bold(ct_hdr)))
- print(sep())
- for idx, (conn, role, u6_pin, res) in enumerate(
- zip(CT_CONNECTORS, CT_ROLES, CT_U6_PINS, CT_RESISTORS)):
- if u6_pin is None:
- mapping = "U6芯片内部本地温度传感器"
- else:
- r_dp, r_dn = res.split("/")
- mapping = f"1脚→{r_dp}→U6.{u6_pin}(DP{idx}) / 3脚→{r_dn}→U6.7(DN)"
- row_s = (
- f"{pad(f'CT{idx}', 5)} │ "
- f"{pad(f'0x{idx:02X}', 6)} │ "
- f"{pad(role, 10)} │ "
- f"{st.cyan(pad(conn, 9))} │ "
- f"{pad(mapping, 44)}"
- )
- print(row(row_s))
- print(sep())
- print(row(st.dim("风扇:连接器高电平占空比=D;FPGA引脚低电平占空比=D。PTC表中的连接器脚为功率正端。")))
- print(row(st.dim("温度:CT0=U6本地;CT1..8=CON53/55/56/57/79/80/81/82。接口:1=DP,2=GND,3=DN→U6.7。")))
- print(row(st.dim("显示 FF 表示无有效值;0C 表示协议读到0(未接探头也可能返回0,不能据此认定真实0℃)。")))
- print(bot())
- def frame(kind, payload=b""):
- body = bytes((kind, len(payload))) + payload
- return b"\xA5\x5A" + body + binascii.crc_hqx(body, 0xFFFF).to_bytes(2, "little")
- class Link:
- def __init__(self, port, log):
- import serial
- self.serial = serial.Serial(port, 921600, timeout=0.05,
- write_timeout=0.5, exclusive=True)
- self.buf = bytearray()
- self.log = log
- self.diag = None
- self.diag_slots = {}
- self.bad_crc = 0
- self.partial_timeouts = 0
- self.startup_bytes = 0
- self.last_byte_at = None
- self.last_ack_at = None
- self.frame_gap = 0.1 # 92 bytes take ~1ms; allow USB packet/host latency.
- def event(self, kind, **fields):
- record = {"time": dt.datetime.now().astimezone().isoformat(),
- "event": kind, **fields}
- self.log.write(json.dumps(record, ensure_ascii=False) + "\n")
- self.log.flush()
- def synchronize(self, end):
- """Drain only before the first TX; keep raw evidence of queued startup bytes."""
- started = last_data = time.monotonic()
- limit = min(end, started + 0.3)
- while time.monotonic() < limit:
- data = self.serial.read(max(1, self.serial.in_waiting))
- now = time.monotonic()
- if data:
- self.startup_bytes += len(data)
- self.event("STARTUP_RX", hex=data.hex(" "))
- last_data = now
- elif now - last_data >= 0.05:
- break
- self.buf.clear()
- self.last_byte_at = None
- self.event("SYNC", discarded_bytes=self.startup_bytes,
- seconds=round(time.monotonic() - started, 6))
- def receive(self):
- data = self.serial.read(max(1, self.serial.in_waiting))
- now = time.monotonic()
- if data:
- self.event("RX_BYTES", hex=data.hex(" "))
- self.buf.extend(data)
- self.last_byte_at = now
- return self._parse()
- if self.buf and self.last_byte_at is not None and now - self.last_byte_at >= self.frame_gap:
- self.partial_timeouts += 1
- self.event("RX_PARTIAL_TIMEOUT", hex=bytes(self.buf).hex(" "))
- frames = self._parse(stale=True)
- self.buf.clear()
- return frames
- return self._parse()
- def _parse(self, stale=False):
- frames = []
- while True:
- pos = self.buf.find(b"\xA5\x5A")
- if pos < 0:
- self.buf[:] = self.buf[-1:] if self.buf[-1:] == b"\xA5" else b""
- break
- if pos:
- del self.buf[:pos]
- if len(self.buf) < 4 or len(self.buf) < self.buf[3] + 6:
- if stale:
- # An abandoned prefix may contain a complete ACK. Hunt after
- # the inter-byte gap, never inside a live fragmented frame.
- del self.buf[0]
- continue
- break
- size = self.buf[3] + 6
- raw = bytes(self.buf[:size])
- if binascii.crc_hqx(raw[2:-2], 0xFFFF) != int.from_bytes(raw[-2:], "little"):
- self.bad_crc += 1
- self.event("BAD_CRC", hex=raw.hex(" "))
- del self.buf[0]
- continue
- del self.buf[:size]
- kind, payload = raw[2], raw[4:-2]
- self.event("RX", type=f"{kind:02X}", hex=raw.hex(" "))
- if kind == 0x52 and len(payload) == 20:
- self.diag = {
- "version": ".".join(str(x) for x in payload[2:5]),
- "slot": payload[7], "address": payload[8],
- "register": payload[9], "error": payload[10],
- "raw": int.from_bytes(payload[11:13], "little"),
- "decode_mask": int.from_bytes(payload[14:16], "little"),
- "bus": payload[5] & 15, "flags": payload[19]}
- self.diag_slots[self.diag["register"]] = dict(self.diag)
- self.event("DIAG", **self.diag)
- frames.append((kind, payload))
- return frames
- def request(self, kind, end, payload=None):
- if time.monotonic() >= end:
- raise TimeoutError("运行时间结束")
- if payload is None:
- payload = DUTIES if kind == 1 else b""
- raw = frame(kind, payload)
- self.serial.write(raw)
- self.event("TX", type=f"{kind:02X}", hex=raw.hex(" "))
- limit = min(end, time.monotonic() + 0.7)
- get_ack = False
- while time.monotonic() < limit:
- answer = None
- for typ, payload in self.receive():
- if typ == 0xC0:
- raise RuntimeError(f"NACK: {payload.hex(' ')}")
- if kind == 1 and typ == 0x81 and not payload:
- self.last_ack_at = time.monotonic()
- answer = b""
- if kind == 2 and typ == 0x82 and not payload:
- self.last_ack_at = time.monotonic()
- get_ack = True
- elif kind == 2 and typ == 0x42 and get_ack:
- if len(payload) not in (86, 88, 90):
- raise RuntimeError(f"GET长度={len(payload)},要求86/88/90;需配套3.x固件")
- answer = payload
- if answer is not None:
- return answer
- raise TimeoutError(f"{'SET' if kind == 1 else 'GET'}等待应答超时")
- def idle_until(self, until):
- while time.monotonic() < until:
- self.receive()
- def temp(value):
- return "FF" if value == 255 else f"{value}C"
- def styled_temp(value, style, width=3):
- t = pad(temp(value), width, "right")
- if not style.enabled:
- return t
- if value == 255:
- return style.red(t)
- if value == 0:
- return style.dim(t)
- if value >= 70:
- return style.bold_yellow(t)
- return style.bold_green(t)
- def render_live_panel(style, *, cycles, total_cycles, elapsed, remaining,
- read_only, matches, outputs, ct, errors, bad_crc,
- diag, diag_slots, last_error, last_ack_age=None,
- expected_outputs=None):
- top, mid, _, bot, row, split2 = _box_helpers(style)
- total_dur = max(0.001, elapsed + remaining)
- ratio = min(1.0, elapsed / total_dur)
- pbar = progress_bar(ratio, width=16, style=style)
- now_str = dt.datetime.now().strftime("%H:%M:%S")
- if matches is None:
- mode_badge = style.yellow("本轮应答未确认")
- elif read_only:
- mode_badge = style.cyan("只读 GET90 正常")
- elif matches:
- mode_badge = style.bold_green("✓ SET35/GET86 35路回读一致")
- else:
- mode_badge = style.red("✗ 35路回读不符")
- if last_ack_age is None:
- watchdog = style.yellow("尚未确认")
- elif last_ack_age >= 30:
- watchdog = style.red("通信已超时")
- elif last_ack_age >= 2:
- watchdog = style.yellow(f"{last_ack_age:.0f}秒前应答")
- else:
- watchdog = style.green("应答正常")
- err_str = style.red(str(errors)) if errors else style.green("0")
- crc_str = style.yellow(str(bad_crc)) if bad_crc else style.green("0")
- lines = [
- top(f"实时监控面板 [{now_str}]"),
- split2(
- f"进度: [{pbar}] {ratio * 100:5.1f}%",
- f"轮次: {style.bold(f'#{cycles}')}/{total_cycles} │ 已运行: {format_mmss(elapsed)} │ 剩余: {style.bold(format_mmss(remaining))}",
- left_w=33,
- ),
- split2(
- f"状态: {mode_badge}",
- f"错误: {err_str} │ 丢弃CRC: {crc_str} │ 看门狗: {watchdog}",
- left_w=33,
- ),
- mid("35路 PWM 控制回读核对 (20Hz / 周期 50.00ms)"),
- ]
- if outputs and len(outputs) in (35, 36):
- ptc_ok = list(outputs[:24]) == list(PTC_DUTIES)
- fan_vals = list(outputs[24:32])
- if expected_outputs is not None and len(expected_outputs) in (35, 36):
- fan_ok = fan_vals == list(expected_outputs[24:32])
- else:
- fan_ok = fan_vals in ([FAN_DUTY_HIGH] * 8, [FAN_DUTY_LOW] * 8)
- ssr_vals = list(outputs[32:35])
- ssr_ok = ssr_vals == list(SSR_DUTIES)
- b1 = style.green("✓") if ptc_ok or read_only else style.red("✗")
- b2 = style.green("✓") if fan_ok or read_only else style.red("✗")
- b3 = style.green("✓") if ssr_ok or read_only else style.red("✗")
- if matches is None:
- b1 = b2 = b3 = style.yellow("?")
- if len(set(fan_vals)) == 1:
- fan_text = f"进/排风8路: {fan_vals[0]:2d}% ({fan_vals[0]*0.5:4.1f}ms, 5s 50/0%) {b2}"
- else:
- fan_text = f"进/排风8路: {outputs[24]:2d}%~{outputs[31]:2d}% ({outputs[24]*0.5:4.1f}~{outputs[31]*0.5:4.1f}ms) {b2}"
- lines.append(split2(
- f"PTC00..23 : 1%~24% ( 0.5~12.0ms) {b1}",
- fan_text,
- left_w=41,
- ))
- lines.append(row(
- f"SSR 1/2/4 : {ssr_vals[0]:2d}% / {ssr_vals[1]:2d}% / {ssr_vals[2]:2d}% "
- 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}"
- ))
- else:
- lines.append(row(style.dim("等待首轮 GET90 数据回读...")))
- lines.append(mid("CT7428 (U6 @ 0x49) 9路实时温度"))
- if ct and len(ct) >= 9:
- active_ext = sum(1 for v in ct[1:9] if 0 < v < 255)
- lines.append(split2(
- f"CT0 U6本地: {styled_temp(ct[0], style)} (U6芯片内部)",
- f"外部探头(CT1..8): 非零 {style.bold(f'{active_ext}/8')} 路 (0C可能未接)",
- left_w=41,
- ))
- lines.append(split2(
- f"腔1: 进[CT1/CON53]={styled_temp(ct[1], style)} 出[CT2/CON55]={styled_temp(ct[2], style)}",
- f"腔2: 进[CT3/CON56]={styled_temp(ct[3], style)} 出[CT4/CON57]={styled_temp(ct[4], style)}",
- left_w=41,
- ))
- lines.append(split2(
- f"腔3: 进[CT5/CON79]={styled_temp(ct[5], style)} 出[CT6/CON80]={styled_temp(ct[6], style)}",
- f"腔4: 进[CT7/CON81]={styled_temp(ct[7], style)} 出[CT8/CON82]={styled_temp(ct[8], style)}",
- left_w=41,
- ))
- else:
- lines.append(row(style.dim("等待温度数据...")))
- lines.append(mid("固件自主诊断帧 (0x52)"))
- if diag:
- d = diag
- mask_cnt = bin(d["decode_mask"] & 0x1FF).count("1")
- scl = (d["bus"] >> 2) & 1
- sda = (d["bus"] >> 1) & 1
- err_badge = style.green("err=0") if d["error"] == 0 else style.red(f"err={d['error']}")
- lines.append(row(
- f"v{d['version']} │ 槽#{d['slot']:02d} reg=0x{d['register']:02X} "
- f"raw=0x{d['raw']:04X} {err_badge} │ 掩码:0x{d['decode_mask']:03X}({mask_cnt}/9) │ "
- f"bus:0x{d['bus']:X}(SCL={scl},SDA={sda})"
- ))
- status_parts = []
- for reg_id, label in ((0x23, "状态23"), (0x30, "状态30"), (0xC4, "配置C4"),
- (0xFE, "厂商FE"), (0xFF, "芯片FF")):
- if reg_id in diag_slots:
- status_parts.append(f"{label}=0x{diag_slots[reg_id]['raw']:04X}")
- if status_parts:
- lines.append(row(style.dim("已捕获寄存器: " + " ".join(status_parts))))
- else:
- lines.append(row(style.dim("等待 0x52 诊断帧...")))
- if last_error:
- lines.append(row(style.red(f"最近告警: {last_error[:72]}")))
- lines.append(bot("Ctrl+C 停发;30s后PTC/SSR=0,风扇20%"))
- return lines
- def run(args):
- port = resolve_port(args.port)
- real_port = os.path.realpath(port)
- if real_port == "/dev/ttyUSB0":
- raise RuntimeError("USB0属于其他项目,拒绝打开")
- is_tty = sys.stdout.isatty()
- use_color = is_tty and not os.environ.get("NO_COLOR") and not getattr(args, "no_color", False)
- live_mode = is_tty and not getattr(args, "scroll", False)
- style = Style(enabled=use_color)
- log_path = (Path(args.log).expanduser() if args.log else
- Path(__file__).resolve().parent / "logs" /
- (dt.datetime.now().strftime("%Y%m%d-%H%M%S-%f") + ".jsonl"))
- log_path.parent.mkdir(parents=True, exist_ok=True)
- show_map(style=style)
- print(f"{style.bold('串口')}:{port} -> {style.cyan(real_port)} / 921600 8N1")
- print(f"{style.bold('计划')}:运行 {style.bold(f'{args.minutes:g}')} 分钟,每 {style.bold(f'{args.interval:g}')} 秒一轮;日志:{style.dim(log_path)}")
- print(f"{style.yellow('提示')}:Ctrl+C停止。结束只关闭串口,不发归零/恢复命令;最后有效命令后约30秒由固件超时。", flush=True)
- if live_mode:
- print()
- cycles = errors = 0
- total_cycles = max(1, int(round(args.minutes * 60 / args.interval)))
- start = time.monotonic()
- end = start + args.minutes * 60
- next_due = start
- prev_panel_lines = 0
- last_outputs = None
- last_expected_outputs = DUTIES
- last_ct = None
- last_matches = None
- last_error = None
- def clear_live_panel():
- nonlocal prev_panel_lines
- if live_mode and prev_panel_lines > 0:
- sys.stdout.write(f"\x1b[{prev_panel_lines}A\r\x1b[J")
- prev_panel_lines = 0
- def draw_live_panel():
- nonlocal prev_panel_lines
- if not live_mode:
- return
- now_m = time.monotonic()
- panel = render_live_panel(
- style,
- cycles=cycles,
- total_cycles=total_cycles,
- elapsed=now_m - start,
- remaining=max(0.0, end - now_m),
- read_only=args.read_only,
- matches=last_matches,
- outputs=last_outputs,
- ct=last_ct,
- errors=errors,
- bad_crc=link.bad_crc,
- diag=link.diag,
- diag_slots=link.diag_slots,
- last_error=last_error,
- last_ack_age=None if link.last_ack_at is None else now_m - link.last_ack_at,
- expected_outputs=last_expected_outputs,
- )
- clear_live_panel()
- sys.stdout.write("\n".join(panel) + "\n")
- sys.stdout.flush()
- prev_panel_lines = len(panel)
- with log_path.open("x", encoding="utf-8") as log:
- link = Link(port, log)
- link.event("START", port=port, minutes=args.minutes,
- interval=args.interval, read_only=args.read_only,
- set_payload=list(DUTIES),
- set_payload_fan0=list(DUTIES_FAN_ZERO),
- fan_hold_seconds=FAN_HOLD_SECONDS)
- if live_mode:
- sys.stdout.write("\x1b[?25l")
- sys.stdout.flush()
- try:
- link.synchronize(end)
- print(f"启动同步:清理{link.startup_bytes}字节缓存(原始字节已记录);以下CRC为运行期统计。", flush=True)
- loop_start = next_due = time.monotonic()
- while time.monotonic() < end:
- cycles += 1
- last_matches = None
- fan_duty = fan_duty_for_elapsed(time.monotonic() - loop_start)
- expected_duties = build_duties(fan_duty)
- last_expected_outputs = expected_duties
- try:
- if not args.read_only:
- link.request(1, end, expected_duties)
- data = link.request(2, end)
- outputs = data[:32] + data[83:86]
- matches = outputs == expected_duties[:35]
- if not args.read_only and not matches:
- raise RuntimeError(f"输出回读不符:{list(outputs)} (期望风扇={fan_duty}%)")
- ct = list(data[56:65])
- last_outputs = outputs
- last_ct = ct
- last_matches = matches
- link.event("CYCLE", cycle=cycles,
- elapsed=round(time.monotonic() - start, 3),
- fan_duty=fan_duty,
- output_match=matches, outputs=list(outputs),
- ct=ct, ct_reserved=list(data[65:83]),
- bmc=list(data[32:56]))
- if live_mode:
- draw_live_panel()
- else:
- values = " ".join(f"CT{i}/{name}={temp(value)}"
- for i, (name, value) in enumerate(zip(CT_CONNECTORS, ct)))
- mode = "GET OK" if args.read_only else f"SET/GET 35路一致 (风扇={fan_duty}%)"
- print(f"[{dt.datetime.now():%H:%M:%S}] #{cycles} {mode}\n {values}", flush=True)
- if link.diag:
- d = link.diag
- print(f" DIAG v{d['version']} reg=0x{d['register']:02X} "
- f"raw=0x{d['raw']:04X} err={d['error']} "
- f"decode_mask=0x{d['decode_mask']:03X} "
- f"bus=0x{d['bus']:X} flags=0x{d['flags']:02X}", flush=True)
- except (TimeoutError, RuntimeError) as exc:
- if time.monotonic() >= end:
- break
- errors += 1
- last_error = f"[{dt.datetime.now():%H:%M:%S}] {exc}"
- link.event("ERROR", message=str(exc))
- if live_mode:
- clear_live_panel()
- print(style.red(last_error), flush=True)
- draw_live_panel()
- else:
- print(f"[{dt.datetime.now():%H:%M:%S}] {exc}", flush=True)
- next_due = max(loop_start + cycles * args.interval, time.monotonic())
- link.idle_until(min(next_due, end))
- except KeyboardInterrupt:
- print("\n已停止发送。", flush=True)
- finally:
- if live_mode:
- sys.stdout.write("\x1b[?25h")
- sys.stdout.flush()
- link.event("END", cycles=cycles, errors=errors,
- bad_crc=link.bad_crc, partial_timeouts=link.partial_timeouts,
- startup_bytes=link.startup_bytes,
- elapsed=round(time.monotonic() - start, 3))
- link.serial.close()
- print(f"结束:{cycles}轮,{errors}次错误,CRC错误{link.bad_crc};未发送退出控制命令。")
- return 1 if errors else 0
- def stop_sending(*_):
- raise KeyboardInterrupt
- def _prepare_windows_console():
- if os.name != "nt":
- return
- for stream in (sys.stdout, sys.stderr):
- if hasattr(stream, "reconfigure"):
- try:
- stream.reconfigure(encoding="utf-8", errors="replace")
- except Exception:
- pass
- try:
- import ctypes
- kernel32 = ctypes.windll.kernel32
- for handle_id in (-11, -12):
- handle = kernel32.GetStdHandle(handle_id)
- mode = ctypes.c_uint32()
- if handle and kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
- kernel32.SetConsoleMode(handle, mode.value | 0x0004)
- except Exception:
- pass
- def main(argv=None):
- _prepare_windows_console()
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--minutes", type=float, default=15, help="运行分钟数,默认15")
- parser.add_argument("--interval", type=float, default=1, help="SET/GET循环间隔秒,默认1")
- parser.add_argument("--port", default=DEFAULT_PORT, help="温控串口,Linux默认USB1,Windows请传COMx")
- parser.add_argument("--read-only", action="store_true", help="只循环GET;GET也会喂固件看门狗")
- parser.add_argument("--dry-run", action="store_true", help="只显示映射与帧,不打开串口")
- parser.add_argument("--scroll", action="store_true", help="禁用终端原位刷新面板,改为逐行滚动输出")
- parser.add_argument("--no-color", action="store_true", help="禁用ANSI颜色输出")
- parser.add_argument("--log", help="JSONL日志路径;默认在脚本旁logs中生成")
- args = parser.parse_args(argv)
- if any(not math.isfinite(x) or x <= 0 for x in (args.minutes, args.interval)):
- parser.error("--minutes和--interval必须为正有限数")
- use_color = sys.stdout.isatty() and not os.environ.get("NO_COLOR") and not args.no_color
- style = Style(enabled=use_color)
- if args.dry_run:
- show_map(style=style)
- print("SET_ALL (风扇50%):", frame(1, DUTIES).hex(" ").upper())
- print("SET_ALL (风扇0%) :", frame(1, DUTIES_FAN_ZERO).hex(" ").upper())
- print("GET_ALL :", frame(2).hex(" ").upper())
- return 0
- signal.signal(signal.SIGTERM, stop_sending)
- try:
- return run(args)
- except (OSError, RuntimeError, ImportError) as exc:
- print(f"错误:{exc}", file=sys.stderr)
- return 1
- if __name__ == "__main__":
- sys.exit(main())
|