|
|
@@ -1,5 +1,5 @@
|
|
|
#!/usr/bin/env python3
|
|
|
-"""6400V2.0 scope test 1.0.1: SET35 / GET86, no shutdown command."""
|
|
|
+"""6400V2.0 scope test 1.0.2: SET35 / GET86, 500Hz PWM, no shutdown command."""
|
|
|
import argparse
|
|
|
import binascii
|
|
|
import datetime as dt
|
|
|
@@ -7,15 +7,23 @@ import json
|
|
|
import math
|
|
|
import os
|
|
|
from pathlib import Path
|
|
|
+import re
|
|
|
import signal
|
|
|
import sys
|
|
|
import time
|
|
|
+import unicodedata
|
|
|
|
|
|
+SCRIPT_VERSION = "1.0.2"
|
|
|
+BOX_WIDTH = 90
|
|
|
DEFAULT_PORT = "/dev/serial/by-path/pci-0000:00:14.0-usb-0:2:1.0-port0"
|
|
|
DUTIES = bytes(range(1, 36))
|
|
|
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)] +
|
|
|
@@ -26,6 +34,84 @@ 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 = []
|
|
|
@@ -44,15 +130,133 @@ def output_rows():
|
|
|
return rows
|
|
|
|
|
|
|
|
|
-def show_map():
|
|
|
- print("6400V2.0 / 脚本1.0.1:SET字节从0编号,35路占空比 = 字节编号 + 1 (%)")
|
|
|
- print("SET字节 输出 占空比 频率 连接器 FPGA")
|
|
|
+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.0.2)"))
|
|
|
+ print(row(
|
|
|
+ f"{st.bold('协议')}: SET35 / GET86 (921600 8N1) "
|
|
|
+ f"{st.bold('统一频率')}: 500Hz (周期 2.00ms, 1% = 20µs)"
|
|
|
+ ))
|
|
|
+ print(row(
|
|
|
+ f"{st.bold('规则')}: SET字节从0编号,35路占空比 = 字节编号 + 1 (%);退出仅停发等待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():
|
|
|
- print(f"{i:2d} {name:<19} {DUTIES[i]:2d}% {hz:3d}Hz {pin:<12} {ball}")
|
|
|
- print("风扇:连接器高电平占空比=D;FPGA引脚低电平占空比=D。")
|
|
|
- print("PTC表中的连接器脚为功率正端;示波器读数须结合测量位置与板上驱动极性。")
|
|
|
- print("温度:CT0=U6本地;CT1..8=CON53/55/56/57/79/80/81/82。")
|
|
|
- print("CT探头接口:1=DP,2=GND,3=DN;DN经0Ω汇入U6.7。")
|
|
|
+ if i == 0:
|
|
|
+ print(row(st.bold_yellow("▶ PTC 加热片 (24路) — 连接器脚为功率正端;示波器读数须结合测量位置与板上驱动极性")))
|
|
|
+ elif i == 24:
|
|
|
+ print(sep())
|
|
|
+ print(row(st.bold_yellow("▶ 风扇 PWM (8路) — 连接器高电平占空比=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_us = duty * 20
|
|
|
+ idx_s = pad(f"{i:2d}", 7, "center")
|
|
|
+ name_s = pad(name, 16)
|
|
|
+ duty_s = pad(f"{duty:2d}%", 6, "right")
|
|
|
+ pulse_s = pad(f"{pulse_us:3d}µs", 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""):
|
|
|
@@ -68,6 +272,7 @@ class Link:
|
|
|
self.buf = bytearray()
|
|
|
self.log = log
|
|
|
self.diag = None
|
|
|
+ self.diag_slots = {}
|
|
|
self.bad_crc = 0
|
|
|
|
|
|
def event(self, kind, **fields):
|
|
|
@@ -106,6 +311,7 @@ class Link:
|
|
|
"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
|
|
|
@@ -144,26 +350,194 @@ 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):
|
|
|
+ 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 read_only:
|
|
|
+ mode_badge = style.cyan("只读 GET86 正常")
|
|
|
+ elif matches:
|
|
|
+ mode_badge = style.bold_green("✓ SET35/GET86 35路回读一致")
|
|
|
+ else:
|
|
|
+ mode_badge = style.red("✗ 35路回读不符")
|
|
|
+
|
|
|
+ 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} │ 看门狗: {style.green('喂狗正常')}",
|
|
|
+ left_w=33,
|
|
|
+ ),
|
|
|
+ mid("35路 PWM 控制回读核对 (500Hz / 周期 2.00ms)"),
|
|
|
+ ]
|
|
|
+
|
|
|
+ if outputs and len(outputs) == 35:
|
|
|
+ ptc_ok = list(outputs[:24]) == list(DUTIES[:24])
|
|
|
+ fan_ok = list(outputs[24:32]) == list(DUTIES[24:32])
|
|
|
+ ssr_vals = list(outputs[32:35])
|
|
|
+ ssr_ok = ssr_vals == list(DUTIES[32:35])
|
|
|
+ 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("✗")
|
|
|
+ lines.append(split2(
|
|
|
+ f"PTC00..23 : 1%~24% ( 20~480µs) {b1}",
|
|
|
+ f"进/排风8路: {outputs[24]:2d}%~{outputs[31]:2d}% ({outputs[24]*20:3d}~{outputs[31]*20:3d}µs) {b2}",
|
|
|
+ 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]*20:3d} / {ssr_vals[1]*20:3d} / {ssr_vals[2]*20:3d}µs @ CON165.1/.2/.4) {b3}"
|
|
|
+ ))
|
|
|
+ else:
|
|
|
+ lines.append(row(style.dim("等待首轮 GET86 数据回读...")))
|
|
|
+
|
|
|
+ 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后看门狗归零)"))
|
|
|
+ return lines
|
|
|
+
|
|
|
+
|
|
|
def run(args):
|
|
|
if os.path.realpath(args.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()
|
|
|
- print(f"串口:{args.port} -> {os.path.realpath(args.port)} / 921600 8N1")
|
|
|
- print(f"运行{args.minutes:g}分钟,每{args.interval:g}秒一轮;日志:{log_path}")
|
|
|
- print("Ctrl+C停止。结束只关闭串口,不发归零/恢复命令;最后有效命令后约30秒由固件超时。", flush=True)
|
|
|
+ show_map(style=style)
|
|
|
+ real_port = os.path.realpath(args.port)
|
|
|
+ print(f"{style.bold('串口')}:{args.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_ct = None
|
|
|
+ last_matches = False
|
|
|
+ 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,
|
|
|
+ )
|
|
|
+ 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(args.port, log)
|
|
|
link.event("START", port=args.port, minutes=args.minutes,
|
|
|
interval=args.interval, read_only=args.read_only,
|
|
|
set_payload=list(DUTIES))
|
|
|
+ if live_mode:
|
|
|
+ sys.stdout.write("\x1b[?25l")
|
|
|
+ sys.stdout.flush()
|
|
|
try:
|
|
|
while time.monotonic() < end:
|
|
|
cycles += 1
|
|
|
@@ -176,32 +550,47 @@ def run(args):
|
|
|
if not args.read_only and not matches:
|
|
|
raise RuntimeError(f"输出回读不符:{list(outputs)}")
|
|
|
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),
|
|
|
output_match=matches, outputs=list(outputs),
|
|
|
ct=ct, ct_reserved=list(data[65:83]),
|
|
|
bmc=list(data[32:56]))
|
|
|
- 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 "SET/GET 35路一致"
|
|
|
- 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)
|
|
|
+ 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 "SET/GET 35路一致"
|
|
|
+ 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))
|
|
|
- print(f"[{dt.datetime.now():%H:%M:%S}] {exc}", flush=True)
|
|
|
+ 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(next_due + 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,
|
|
|
elapsed=round(time.monotonic() - start, 3))
|
|
|
@@ -214,19 +603,23 @@ def stop_sending(*_):
|
|
|
raise KeyboardInterrupt
|
|
|
|
|
|
|
|
|
-def main():
|
|
|
+def main(argv=None):
|
|
|
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="温控串口,默认固定USB1物理路径")
|
|
|
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()
|
|
|
+ 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()
|
|
|
+ show_map(style=style)
|
|
|
print("SET_ALL:", frame(1, DUTIES).hex(" ").upper())
|
|
|
print("GET_ALL:", frame(2).hex(" ").upper())
|
|
|
return 0
|