| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046 |
- #!/usr/bin/env python3
- """Shared interface for the two Prod2U products with full SET/GET command generation,
- detailed field decoding, universal frame inspection, and optional serial communication.
- """
- from __future__ import annotations
- from pathlib import Path
- import datetime, json, os, re, sys, threading, time, zipfile
- from typing import Any
- ROOT = Path(__file__).resolve().parents[1]
- sys.path.insert(0, str(Path(__file__).resolve().parent / "_vendor"))
- from hth_protocol import (
- FrameType,
- NackReason,
- MotorAction,
- DoneReason,
- Type,
- Status,
- encode_frame,
- decode_frame,
- crc16_ccitt_false,
- PREAMBLE,
- )
- from prod2u_status import state_6400, mrdimm_state, decode_temperature
- # Optional pyserial for hardware communication
- try:
- import serial
- import serial.tools.list_ports
- HAVE_SERIAL = True
- except ImportError:
- HAVE_SERIAL = False
- ENDPOINTS = {"nothing": 0, "push_down": 1, "push_up": 2, "stop_clear": 255}
- FRAME_TYPE_NAMES = {
- 0x01: "SET_ALL (下发全量控制)",
- 0x02: "GET_ALL (查询当前状态)",
- 0x81: "SET_ACK (设置确认已应用)",
- 0x82: "GET_ACK (查询确认已受理)",
- 0x42: "GET_DATA (全量状态数据)",
- 0x50: "MOTOR_DONE (电机动作完成事件)",
- 0xC0: "NACK (请求被拒绝)",
- }
- NACK_REASON_NAMES = {
- 0x01: "UNSUPPORTED (不支持的请求类型)",
- 0x02: "BAD_LENGTH (报文长度不匹配)",
- 0x03: "BAD_VALUE (参数值越界或非法)",
- 0x04: "QUEUE_FULL (电机队列已满)",
- 0x05: "BUSY (单板正忙)",
- }
- DONE_REASON_NAMES = {
- 0x00: "STEPS_DONE (脉冲步数正常发射完成)",
- 0x01: "LOWER_LIMIT (运动触发下限位阻断)",
- 0x02: "UPPER_LIMIT (运动触发上限位阻断)",
- 0x03: "BOTH_LIMITS (双向限位同时异常触发)",
- }
- def parse_hex(text: str) -> bytes:
- value = re.sub(r"[\s:_\-]+", "", text)
- if not value or len(value) % 2 or not re.fullmatch(r"[0-9a-fA-F]+", value):
- raise ValueError("HEX 必须是偶数个十六进制字符(支持空格、冒号、连字符分隔)")
- return bytes.fromhex(value)
- def frame_hex(data: bytes) -> str:
- return data.hex(" ").upper()
- def status_rows(state: dict[str, Any], groups: list[tuple[str, int, int]]) -> tuple[list, list]:
- outputs = []
- temperatures = []
- for group, count, _ in groups:
- name = group.lower()
- duties = state.get(name, [])
- for n in range(count):
- val = duties[n] if n < len(duties) else 0
- outputs.append((f"{group}{n}", val))
- for name in ("bmc", "ct"):
- sensor = state.get(name, {})
- temps = sensor.get("temperature_c", [])
- for n, temp in enumerate(temps):
- condition = "无效" if temp is None else "有效"
- temperatures.append((f"{name.upper()}{n}", "未知" if temp is None else f"{temp} °C", condition))
- return outputs, temperatures
- def integer(value: Any, low: int, high: int, name: str) -> int:
- if isinstance(value, bool) or not isinstance(value, (str, int)):
- raise ValueError(f"{name} 必须是整数")
- try:
- n = int(value, 16 if str(value).lower().startswith("0x") else 10) if isinstance(value, str) else value
- except ValueError:
- raise ValueError(f"{name} 必须是整数")
- if not low <= n <= high:
- raise ValueError(f"{name} 必须在 {low}..{high}")
- return n
- class ZipAsset:
- def __init__(self, data: bytes):
- self._data = data
- def read_text(self, encoding: str = "utf-8") -> str:
- return self._data.decode(encoding)
- def read_bytes(self) -> bytes:
- return self._data
- def is_file(self) -> bool:
- return True
- class Model:
- def __init__(self, product: str):
- if product not in ("6400-front-rear", "mrdimm-chamber"):
- raise ValueError("未知产品: " + product)
- self.product = product
- self.motor = (product == "mrdimm-chamber")
- self.folder = "mrdimm" if self.motor else "6400"
- filename = "snapshot-layout.json" if self.motor else "manual-uart-contract.json"
- self.contract = json.loads(self.asset(filename).read_text(encoding="utf-8"))
- self.wire = self.contract["control"]["wire"] if self.motor else self.contract["wire"]
- self.outputs = self.contract["control"]["outputs"] if self.motor else self.contract["outputs"]
- self.board = "FCB V1.2" if self.motor else "FCB V1.1"
- try:
- self.metadata = json.loads(self.asset("gui-build-metadata.json").read_text(encoding="utf-8"))
- except (FileNotFoundError, ValueError):
- self.metadata = {
- "product": product,
- "commit": "source preview",
- "bitstream_sha256": None,
- "contract_sha256": self.contract.get("contract_sha256"),
- }
- def asset(self, name: str) -> Any:
- if hasattr(sys, "_MEIPASS"):
- for root in (Path(sys._MEIPASS), Path(sys._MEIPASS) / "generated" / self.folder):
- if (root / name).is_file():
- return root / name
- for parent in Path(__file__).resolve().parents:
- if parent.is_file() and zipfile.is_zipfile(parent):
- with zipfile.ZipFile(parent) as z:
- for member in z.namelist():
- if member == name or member.endswith("/" + name):
- return ZipAsset(z.read(member))
- roots = [ROOT / "generated" / self.folder, ROOT / "contracts", ROOT / "tools", ROOT]
- for root in roots:
- if (root / name).is_file():
- return root / name
- raise FileNotFoundError(f"GUI asset missing: {name}")
- def groups(self) -> list[tuple[str, int, int]]:
- if self.motor:
- return [("FAN", 4, 20), ("PTC", 4, 0)]
- return [
- ("PTC", self.outputs["ptc_count"], self.outputs["default_ptc_percent"]),
- ("Front", self.outputs["front_fan_count"], self.outputs["default_front_percent"]),
- ("Rear", self.outputs["rear_fan_count"], self.outputs["default_rear_percent"]),
- ]
- def set_all(self, values: list[Any], motor_slots: list[dict[str, Any]] | None = None) -> bytes:
- expected_duties = sum(n for _, n, _ in self.groups())
- if len(values) != expected_duties:
- raise ValueError(f"需要 {expected_duties} 个输出值")
- duty_bytes = bytes(integer(v, 0, 100, "占空比") for v in values)
- if not self.motor:
- return encode_frame(FrameType.SET_ALL, duty_bytes)
- # MRDIMM: 4 FAN + 4 PTC + 12 axis slots (5 bytes each) = 68 bytes
- slots_payload = bytearray(60)
- if motor_slots:
- if len(motor_slots) > 12:
- raise ValueError("最多 12 个电机轴")
- for i, slot in enumerate(motor_slots):
- action = integer(slot.get("action", 0), 0, 255, f"轴{i}动作")
- steps = integer(slot.get("steps", 0), 0, 65535, f"轴{i}步数")
- half = integer(slot.get("half_period_us", 0), 0, 65535, f"轴{i}半周期")
- if action in (1, 2) and (steps == 0 or half == 0):
- raise ValueError(f"轴{i} PUSH 步数与半周期不能为0")
- slots_payload[i * 5] = action
- slots_payload[i * 5 + 1 : i * 5 + 3] = steps.to_bytes(2, "little")
- slots_payload[i * 5 + 3 : i * 5 + 5] = half.to_bytes(2, "little")
- return encode_frame(FrameType.SET_ALL, duty_bytes + bytes(slots_payload))
- def get_all(self) -> bytes:
- """Generate golden GET_ALL request frame (A5 5A 02 00 6D 7B)."""
- return encode_frame(FrameType.GET_ALL)
- def checked_request(self, frame: bytes) -> Any:
- parsed = decode_frame(frame)
- if not parsed.crc_ok:
- raise ValueError("CRC 校验失败")
- allowed = {FrameType.SET_ALL, FrameType.GET_ALL}
- if parsed.frame_type not in allowed:
- raise ValueError("此产品不支持该请求类型;响应请在状态页解析")
- return parsed
- def state(self, payload: bytes) -> dict[str, Any]:
- if self.motor:
- return mrdimm_state(payload, self.contract)
- return state_6400(payload, self.contract)
- def parse(self, data: bytes, raw_status: bool = False) -> list[dict[str, Any]]:
- if raw_status:
- return [{"kind": "status", "state": self.state(data)}]
- result = []
- offset = 0
- while offset < len(data):
- if data[offset : offset + 2] != PREAMBLE:
- raise ValueError("报文头不完整或未找到 A5 5A 同步头")
- if len(data) - offset < 6:
- raise ValueError("报文长度不足最小帧长 (6 字节)")
- frame_type = data[offset + 2]
- declared_len = data[offset + 3]
- frame_len = declared_len + 6
- if offset + frame_len > len(data):
- raise ValueError(f"报文数据不完整: 声明载荷 {declared_len} 字节,总长需 {frame_len} 字节,剩余 {len(data) - offset} 字节")
- frame_bytes = data[offset : offset + frame_len]
- frame = decode_frame(frame_bytes)
- offset += frame_len
- if not frame.crc_ok:
- raise ValueError("CRC 校验失败")
- kind = frame.frame_type
- p = frame.payload
- if kind == FrameType.GET_DATA:
- result.append({"kind": "status", "state": self.state(p)})
- elif kind == FrameType.SET_ACK:
- result.append({"kind": "ack", "type": "SET_ACK"})
- elif kind == FrameType.GET_ACK:
- result.append({"kind": "ack", "type": "GET_ACK"})
- elif kind == FrameType.MOTOR_DONE:
- if len(p) != 4:
- raise ValueError("MOTOR_DONE 长度必须为 4 字节")
- axis = p[0]
- reason = p[1]
- steps = int.from_bytes(p[2:4], "little")
- reason_name = DoneReason(reason).name if reason in DoneReason._value2member_map_ else str(reason)
- result.append({"kind": "done", "axis": axis, "reason": reason_name, "steps_done": steps})
- elif kind == FrameType.NACK:
- if len(p) != 2:
- raise ValueError("NACK 长度必须为 2 字节")
- req = p[0]
- reason = p[1]
- reason_name = NackReason(reason).name if reason in NackReason._value2member_map_ else str(reason)
- result.append({"kind": "nack", "request_type": req, "reason": reason_name})
- else:
- result.append({"kind": "frame", "type": kind, "payload_hex": frame_hex(p)})
- if not result:
- raise ValueError("未提供报文")
- return result
- def explain(self, frame_bytes: bytes) -> dict[str, Any]:
- """Provide detailed, human-readable breakdown of any valid or partial frame."""
- if len(frame_bytes) < 6:
- raise ValueError("报文长度不足 6 字节最小帧长")
- if frame_bytes[:2] != PREAMBLE:
- raise ValueError("帧同步头必须为 A5 5A")
- ftype = frame_bytes[2]
- length = frame_bytes[3]
- if len(frame_bytes) < length + 6:
- raise ValueError(f"帧数据不完整: 声明载荷 {length} 字节,实际仅有 {len(frame_bytes) - 6} 字节")
- payload = frame_bytes[4 : 4 + length]
- crc_actual = int.from_bytes(frame_bytes[4 + length : 6 + length], "little")
- crc_calc = crc16_ccitt_false(frame_bytes[2 : 4 + length])
- crc_ok = (crc_actual == crc_calc)
- type_name = FRAME_TYPE_NAMES.get(ftype, f"未知类型 0x{ftype:02X}")
- explanation: dict[str, Any] = {
- "hex": frame_hex(frame_bytes[: 6 + length]),
- "preamble": "A5 5A (同步头)",
- "type": f"0x{ftype:02X} - {type_name}",
- "length": f"{length} 字节 (0x{length:02X})",
- "crc_hex": f"0x{frame_bytes[4+length]:02X} 0x{frame_bytes[5+length]:02X} (低字节在先)",
- "crc_ok": crc_ok,
- "crc_status": "PASS" if crc_ok else f"FAIL (计算值=0x{crc_calc:04X}, 报文值=0x{crc_actual:04X})",
- }
- # Detailed breakdown per frame type
- fields = []
- if ftype == 0x01: # SET_ALL
- explanation["summary"] = "上位机向单板下发全量输出/电机配置,成功后单板回复 SET_ACK (0x81) 并重载 30s 看门狗"
- if not self.motor:
- # 6400: 32 bytes: 24 PTC + 4 Front + 4 Rear
- if length == 32:
- for i in range(24):
- fields.append(f"PTC{i}: {payload[i]} %")
- for i in range(4):
- fields.append(f"Front{i}: {payload[24+i]} %")
- for i in range(4):
- fields.append(f"Rear{i}: {payload[28+i]} %")
- else:
- fields.append(f"警告: 6400 SET_ALL 载荷长度应为 32 字节,当前为 {length} 字节")
- else:
- # MRDIMM: 68 bytes: 4 FAN + 4 PTC + 12 axis slots
- if length == 68:
- for i in range(4):
- fields.append(f"FAN{i}: {payload[i]} %")
- for i in range(4):
- fields.append(f"PTC{i}: {payload[4+i]} %")
- for i in range(12):
- act = payload[8 + i * 5]
- act_str = {0: "NOTHING", 1: "PUSH_DOWN", 2: "PUSH_UP", 255: "STOP_CLEAR"}.get(act, f"0x{act:02X}")
- st = int.from_bytes(payload[9 + i * 5 : 11 + i * 5], "little")
- hp = int.from_bytes(payload[11 + i * 5 : 13 + i * 5], "little")
- speed = f"{500000 / hp:.1f} Hz" if hp > 0 else "N/A"
- fields.append(f"Axis{i}: 动作={act_str}, 步数={st}, 半周期={hp} us (频率={speed})")
- else:
- fields.append(f"警告: MRDIMM SET_ALL 载荷长度应为 68 字节,当前为 {length} 字节")
- elif ftype == 0x02: # GET_ALL
- explanation["summary"] = "上位机向单板查询当前全量状态与温度;单板先回复 GET_ACK (0x82),紧接着回复 GET_DATA (0x42)"
- fields.append("无载荷 (0 字节)")
- elif ftype == 0x81: # SET_ACK
- explanation["summary"] = "单板确认已应用 SET_ALL 配置;30 秒硬件看门狗已成功重载"
- fields.append("无载荷 (0 字节)")
- elif ftype == 0x82: # GET_ACK
- explanation["summary"] = "单板确认已受理 GET_ALL 查询请求,随后立即发送 GET_DATA"
- fields.append("无载荷 (0 字节)")
- elif ftype == 0x42: # GET_DATA
- explanation["summary"] = "单板返回全量状态、各通道温度与限位信息"
- state = self.state(payload)
- if not self.motor:
- ptc_duties = state.get("ptc", [])
- fields.append(f"PTC 生效占空比 (共 24 路):")
- for chunk_idx in range(0, len(ptc_duties), 8):
- chunk = ptc_duties[chunk_idx : chunk_idx + 8]
- chunk_str = " | ".join(f"PTC{chunk_idx+j:02d}: {val}%" for j, val in enumerate(chunk))
- fields.append(f" {chunk_str}")
- fields.append(f"Front 生效占空比 (4路): {state.get('front', [])}")
- fields.append(f"Rear 生效占空比 (4路): {state.get('rear', [])}")
- else:
- fields.append(f"FAN 生效占空比 (4路): {state.get('fan', [])}")
- fields.append(f"PTC 生效占空比 (4路): {state.get('ptc', [])}")
- fields.append(f"下限位掩码 (Lower Limit): 0x{state.get('lower_limit_mask', 0):04X}")
- fields.append(f"上限位掩码 (Upper Limit): 0x{state.get('upper_limit_mask', 0):04X}")
- bmc_temps = state.get("bmc", {}).get("temperature_c", [])
- ct_temps = state.get("ct", {}).get("temperature_c", [])
- fields.append(f"BMC 24通道温度 (°C): {[f'{t}°C' if t is not None else '无效' for t in bmc_temps]}")
- fields.append(f"CT7428 27通道温度 (°C): {[f'{t}°C' if t is not None else '无效' for t in ct_temps]}")
- elif ftype == 0x50: # MOTOR_DONE
- axis = payload[0] if len(payload) > 0 else 0
- reason = payload[1] if len(payload) > 1 else 0
- steps = int.from_bytes(payload[2:4], "little") if len(payload) >= 4 else 0
- r_name = DONE_REASON_NAMES.get(reason, f"未知 0x{reason:02X}")
- explanation["summary"] = f"MRDIMM 电机 Axis{axis} 运动段结束事件: {r_name},实际输出 {steps} 步"
- fields.append(f"轴号: Axis{axis}")
- fields.append(f"完成原因: 0x{reason:02X} - {r_name}")
- fields.append(f"实际发射脉冲步数: {steps}")
- elif ftype == 0xC0: # NACK
- req = payload[0] if len(payload) > 0 else 0
- reason = payload[1] if len(payload) > 1 else 0
- req_name = FRAME_TYPE_NAMES.get(req, f"0x{req:02X}")
- r_name = NACK_REASON_NAMES.get(reason, f"0x{reason:02X}")
- explanation["summary"] = f"请求被单板拒绝 (NACK)!原请求: {req_name},拒绝原因: {r_name}"
- fields.append(f"原请求类型: 0x{req:02X} ({req_name})")
- fields.append(f"拒绝原因码: 0x{reason:02X} ({r_name})")
- explanation["fields"] = fields
- return explanation
- def self_test(product: str) -> int:
- model = Model(product)
- # 1. Golden GET_ALL frame
- get_frame = encode_frame(FrameType.GET_ALL)
- assert get_frame == bytes.fromhex("A55A02006D7B"), f"GET golden mismatch: {get_frame.hex()}"
- exp_get = model.explain(get_frame)
- assert exp_get["crc_ok"] is True
- assert "GET_ALL" in exp_get["type"]
- # 2. Golden ACKs
- set_ack = bytes.fromhex("A55A8100A635")
- get_ack = bytes.fromhex("A55A8200F560")
- assert decode_frame(set_ack).crc_ok
- assert decode_frame(get_ack).crc_ok
- assert model.parse(set_ack)[0]["kind"] == "ack"
- assert model.parse(get_ack)[0]["kind"] == "ack"
- assert model.explain(set_ack)["crc_ok"] is True
- assert model.explain(get_ack)["crc_ok"] is True
- # 3. Golden NACK
- nack = bytes.fromhex("A55AC0020104B12A")
- assert decode_frame(nack).crc_ok
- parsed_nack = model.parse(nack)[0]
- assert parsed_nack["kind"] == "nack"
- assert parsed_nack["reason"] == "QUEUE_FULL"
- exp_nack = model.explain(nack)
- assert exp_nack["crc_ok"] is True
- assert "QUEUE_FULL" in exp_nack["fields"][1]
- # 4. SET_ALL generation
- values = [val for _, count, val in model.groups() for _ in range(count)]
- frame = model.set_all(values)
- parsed = decode_frame(frame)
- assert parsed.crc_ok
- expected_len = 68 if model.motor else 32
- assert len(parsed.payload) == expected_len
- exp_set = model.explain(frame)
- assert exp_set["crc_ok"] is True
- if model.motor:
- # Golden MOTOR_DONE frames
- done_ul = bytes.fromhex("A55A500404022311B602")
- assert decode_frame(done_ul).crc_ok
- p_done = model.parse(done_ul)[0]
- assert p_done["axis"] == 4 and p_done["reason"] == "UPPER_LIMIT" and p_done["steps_done"] == 4387
- exp_done_ul = model.explain(done_ul)
- assert exp_done_ul["crc_ok"] is True
- assert "4387" in exp_done_ul["fields"][2]
- done_bl = bytes.fromhex("A55A5004040300002364")
- assert decode_frame(done_bl).crc_ok
- p_done_bl = model.parse(done_bl)[0]
- assert p_done_bl["axis"] == 4 and p_done_bl["reason"] == "BOTH_LIMITS" and p_done_bl["steps_done"] == 0
- return 0
- def describe(model: Model, frame: bytes) -> str:
- values = model.parse(frame)
- return json.dumps(
- values[0]["state"] if len(values) == 1 and values[0]["kind"] == "status" else values,
- ensure_ascii=False,
- indent=2,
- )
- # ---------------------------------------------------------------------------
- # Full Tkinter GUI Implementation
- # ---------------------------------------------------------------------------
- def run_gui(product: str) -> int:
- try:
- import tkinter as tk
- from tkinter import ttk, messagebox
- except ImportError:
- if sys.stderr:
- print("Tkinter unavailable in headless environment; run --self-test instead.", file=sys.stderr)
- return 1
- model = Model(product)
- try:
- root = tk.Tk()
- except Exception as exc:
- if sys.stderr:
- print(f"Display unavailable ({exc}); run --self-test instead or use xvfb-run.", file=sys.stderr)
- return 1
- root.title(f"Prod2U {model.board} 调试与监控上位机 — {product}")
- root.geometry("1180x820")
- root.minsize(960, 640)
- # Global serial state
- serial_port_obj: Any = None
- serial_lock = threading.Lock()
- poll_active = False
- # Notebook
- notebook = ttk.Notebook(root)
- notebook.pack(fill="both", expand=True, padx=8, pady=8)
- # -----------------------------------------------------------------------
- # TAB 1: 串口连接与实时控制 (Serial & Realtime Control)
- # -----------------------------------------------------------------------
- tab_serial = ttk.Frame(notebook, padding=10)
- notebook.add(tab_serial, text="📡 串口连接与实时控制")
- # Connection bar
- conn_frame = ttk.LabelFrame(tab_serial, text="串口参数配置 (Host UART: 921600 8N1)", padding=8)
- conn_frame.pack(fill="x", pady=4)
- ttk.Label(conn_frame, text="COM 端口:").pack(side="left", padx=4)
- port_combo = ttk.Combobox(conn_frame, width=14, state="readonly")
- port_combo.pack(side="left", padx=4)
- def refresh_ports():
- if HAVE_SERIAL:
- ports = [p.device for p in serial.tools.list_ports.comports()]
- port_combo["values"] = ports
- if ports and not port_combo.get():
- port_combo.set(ports[0])
- elif not ports:
- port_combo.set("")
- else:
- port_combo["values"] = ["(pyserial 未安装)"]
- port_combo.set("(pyserial 未安装)")
- refresh_ports()
- ttk.Button(conn_frame, text="刷新端口", command=refresh_ports).pack(side="left", padx=4)
- ttk.Label(conn_frame, text="波特率:").pack(side="left", padx=8)
- baud_combo = ttk.Combobox(conn_frame, width=10, values=["921600", "115200", "57600", "9600"], state="readonly")
- baud_combo.set("921600")
- baud_combo.pack(side="left", padx=4)
- btn_connect = ttk.Button(conn_frame, text="打开串口")
- btn_connect.pack(side="left", padx=10)
- lbl_conn_status = ttk.Label(conn_frame, text="未连接", foreground="gray", font=("", 10, "bold"))
- lbl_conn_status.pack(side="left", padx=8)
- # Realtime control bar
- ctrl_bar = ttk.Frame(tab_serial, padding=4)
- ctrl_bar.pack(fill="x", pady=6)
- btn_send_get = ttk.Button(ctrl_bar, text="🔍 发送 GET_ALL 查询", state="disabled")
- btn_send_get.pack(side="left", padx=5)
- btn_send_set = ttk.Button(ctrl_bar, text="⚡ 发送当前 SET 配置", state="disabled")
- btn_send_set.pack(side="left", padx=5)
- poll_var = tk.BooleanVar(value=False)
- chk_poll = ttk.Checkbutton(ctrl_bar, text="自动每秒轮询 GET_ALL (维持看门狗)", variable=poll_var, state="disabled")
- chk_poll.pack(side="left", padx=15)
- # Realtime status summary
- stat_summary_frame = ttk.LabelFrame(tab_serial, text="单板实时状态概要", padding=8)
- stat_summary_frame.pack(fill="x", pady=4)
- lbl_realtime_stat = ttk.Label(stat_summary_frame, text="等待查询或接收单板响应...", font=("", 10))
- lbl_realtime_stat.pack(anchor="w")
- lbl_realtime_ptc = ttk.Label(stat_summary_frame, text="【PTC 生效占空比】: 待查询", font=("Consolas", 9), foreground="#003366")
- lbl_realtime_ptc.pack(anchor="w", pady=2)
- # Serial Log area
- log_frame = ttk.LabelFrame(tab_serial, text="通信原始报文日志 (TX / RX 流)", padding=8)
- log_frame.pack(fill="both", expand=True, pady=6)
- text_log = tk.Text(log_frame, height=14, wrap="char", font=("Consolas", 9))
- text_log.pack(fill="both", expand=True, side="left")
- scroll_log = ttk.Scrollbar(log_frame, command=text_log.yview)
- scroll_log.pack(side="right", fill="y")
- text_log.config(yscrollcommand=scroll_log.set)
- def append_log(direction: str, hex_str: str, note: str = ""):
- now = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3]
- tag = "tx" if direction == "TX" else "rx"
- line = f"[{now}] [{direction}] {hex_str}"
- if note:
- line += f" ({note})"
- line += "\n"
- text_log.insert("end", line, tag)
- text_log.see("end")
- text_log.tag_config("tx", foreground="#0066CC")
- text_log.tag_config("rx", foreground="#008800")
- text_log.tag_config("err", foreground="#CC0000")
- btn_clear_log = ttk.Button(ctrl_bar, text="清空日志", command=lambda: text_log.delete("1.0", "end"))
- btn_clear_log.pack(side="right", padx=5)
- # -----------------------------------------------------------------------
- # TAB 2: SET 命令生成与下发 (SET_ALL Builder & Decoder)
- # -----------------------------------------------------------------------
- tab_set = ttk.Frame(notebook, padding=10)
- notebook.add(tab_set, text="⚙️ SET 命令生成与解析")
- ttk.Label(tab_set, text=f"{model.board} ({product}) — 输出通道百分比设置 (0..100 %)", font=("", 11, "bold")).pack(anchor="w", pady=4)
- set_vars = []
- for grp, cnt, default in model.groups():
- frame_grp = ttk.LabelFrame(tab_set, text=f"{grp} 通道 ({cnt} 路)", padding=6)
- frame_grp.pack(fill="x", pady=4)
- grp_vars = []
- # Batch preset bar for large channel groups (e.g. PTC 24 channels)
- if cnt >= 8:
- preset_bar = ttk.Frame(frame_grp)
- preset_bar.pack(fill="x", pady=2)
- ttk.Label(preset_bar, text=f"快捷预设全部 {grp}:", font=("", 9, "bold")).pack(side="left", padx=4)
- def make_set_all_fn(vs, val):
- def fn():
- for v in vs:
- v.set(str(val))
- return fn
- for p_val in (0, 20, 50, 100):
- ttk.Button(preset_bar, text=f"全设 {p_val}%", width=8,
- command=make_set_all_fn(grp_vars, p_val)).pack(side="left", padx=2)
- # Multi-column grid for channels (8 cols for 24 channels -> 3 rows of 8)
- grid_frame = ttk.Frame(frame_grp)
- grid_frame.pack(fill="x", pady=2)
- cols = 8 if cnt >= 16 else (4 if cnt <= 4 else 6)
- for i in range(cnt):
- row = i // cols
- col = i % cols
- cell = ttk.Frame(grid_frame)
- cell.grid(row=row, column=col, padx=4, pady=2, sticky="w")
- label_text = f"{grp}{i:02d}:" if cnt > 9 else f"{grp}{i}:"
- ttk.Label(cell, text=label_text, width=7, font=("Consolas", 9)).pack(side="left")
- var = tk.StringVar(value=str(default))
- set_vars.append(var)
- grp_vars.append(var)
- ttk.Spinbox(cell, from_=0, to=100, width=4, textvariable=var).pack(side="left")
- ttk.Label(cell, text="%", font=("Consolas", 8), foreground="gray").pack(side="left")
- axis_slots = []
- if model.motor:
- frame_motor = ttk.LabelFrame(tab_set, text="12 轴运动段配置 (每轴 5 字节: action + steps:u16le + half_us:u16le)", padding=6)
- frame_motor.pack(fill="x", pady=4)
- for ax in range(12):
- ax_frame = ttk.Frame(frame_motor)
- ax_frame.pack(anchor="w", pady=2)
- ttk.Label(ax_frame, text=f"Axis{ax}: ").pack(side="left")
- act_var = tk.StringVar(value="NOTHING")
- ttk.Combobox(ax_frame, textvariable=act_var, values=("NOTHING", "PUSH_DOWN", "PUSH_UP", "STOP_CLEAR"), width=11, state="readonly").pack(side="left", padx=2)
- ttk.Label(ax_frame, text="步数:").pack(side="left", padx=2)
- steps_var = tk.StringVar(value="0")
- ttk.Entry(ax_frame, textvariable=steps_var, width=7).pack(side="left", padx=2)
- ttk.Label(ax_frame, text="半周期(us):").pack(side="left", padx=2)
- half_var = tk.StringVar(value="0")
- ttk.Entry(ax_frame, textvariable=half_var, width=7).pack(side="left", padx=2)
- axis_slots.append({"action_var": act_var, "steps_var": steps_var, "half_var": half_var})
- # Generated SET frame display
- frame_set_res = ttk.LabelFrame(tab_set, text="生成的 SET_ALL 命令报文 (HEX 与逐字段拆解)", padding=8)
- frame_set_res.pack(fill="both", expand=True, pady=6)
- set_btn_bar = ttk.Frame(frame_set_res)
- set_btn_bar.pack(fill="x", pady=2)
- text_set_hex = tk.Text(frame_set_res, height=3, wrap="char", font=("Consolas", 10, "bold"), foreground="#003399")
- text_set_hex.pack(fill="x", pady=4)
- text_set_explain = tk.Text(frame_set_res, height=10, wrap="word", font=("Consolas", 9))
- text_set_explain.pack(fill="both", expand=True, pady=4)
- def do_generate_set() -> bytes:
- vals = [int(v.get()) for v in set_vars]
- motor_reqs = None
- if model.motor:
- act_map = {"NOTHING": 0, "PUSH_DOWN": 1, "PUSH_UP": 2, "STOP_CLEAR": 255}
- motor_reqs = [
- {
- "action": act_map[s["action_var"].get()],
- "steps": int(s["steps_var"].get()),
- "half_period_us": int(s["half_var"].get()),
- }
- for s in axis_slots
- ]
- f = model.set_all(vals, motor_reqs)
- text_set_hex.delete("1.0", "end")
- text_set_hex.insert("1.0", frame_hex(f))
- exp = model.explain(f)
- text_set_explain.delete("1.0", "end")
- text_set_explain.insert("end", f"【报文概览】: {exp['summary']}\n")
- text_set_explain.insert("end", f"【帧类型】: {exp['type']} | 【载荷长度】: {exp['length']} | 【CRC-16/CCITT-FALSE】: {exp['crc_hex']} ({exp['crc_status']})\n")
- text_set_explain.insert("end", "【逐通道明细】:\n")
- for fld in exp.get("fields", []):
- text_set_explain.insert("end", f" • {fld}\n")
- return f
- ttk.Button(set_btn_bar, text="🔨 生成 SET_ALL 命令", command=do_generate_set).pack(side="left", padx=4)
- # -----------------------------------------------------------------------
- # TAB 3: GET 命令生成与解析 (GET_ALL & GET_DATA Decoder)
- # -----------------------------------------------------------------------
- tab_get = ttk.Frame(notebook, padding=10)
- notebook.add(tab_get, text="📊 GET 命令生成与解析")
- # Command Generator block
- frame_get_cmd = ttk.LabelFrame(tab_get, text="1. GET_ALL 查询命令生成", padding=8)
- frame_get_cmd.pack(fill="x", pady=4)
- get_cmd_bar = ttk.Frame(frame_get_cmd)
- get_cmd_bar.pack(fill="x")
- ttk.Label(get_cmd_bar, text="标准 GET_ALL 请求报文 (HEX):", font=("", 10, "bold")).pack(side="left", padx=4)
- lbl_get_hex = ttk.Label(get_cmd_bar, text="A5 5A 02 00 6D 7B", font=("Consolas", 11, "bold"), foreground="#0066CC")
- lbl_get_hex.pack(side="left", padx=8)
- lbl_get_desc = ttk.Label(frame_get_cmd, text="解析: 同步头=A5 5A | 帧类型=0x02 (GET_ALL) | 载荷长度=0x00 | CRC16=0x6D 0x7B (低字节在先) | 语义: 请求单板返回实时占空比、BMC 24 通道与 CT7428 27 通道温度", foreground="#555555")
- lbl_get_desc.pack(anchor="w", pady=2)
- # Response Decoder block
- frame_get_resp = ttk.LabelFrame(tab_get, text="2. GET 响应报文解析 (支持粘贴 GET_ACK、GET_DATA 或连续流)", padding=8)
- frame_get_resp.pack(fill="both", expand=True, pady=6)
- ttk.Label(frame_get_resp, text="粘贴单板返回的 HEX 响应:").pack(anchor="w")
- text_get_resp_in = tk.Text(frame_get_resp, height=3, wrap="char", font=("Consolas", 9))
- text_get_resp_in.pack(fill="x", pady=4)
- resp_btn_bar = ttk.Frame(frame_get_resp)
- resp_btn_bar.pack(fill="x", pady=2)
- text_get_resp_out = tk.Text(frame_get_resp, height=15, wrap="word", font=("Consolas", 9))
- text_get_resp_out.pack(fill="both", expand=True, pady=4)
- def do_parse_get_resp(raw_hex_str: str | None = None):
- raw = (raw_hex_str if raw_hex_str is not None else text_get_resp_in.get("1.0", "end")).strip()
- if not raw:
- return
- try:
- data = parse_hex(raw)
- parsed_list = model.parse(data)
- text_get_resp_out.delete("1.0", "end")
- for idx, item in enumerate(parsed_list):
- kind = item.get("kind")
- if kind == "ack":
- text_get_resp_out.insert("end", f"=== [帧 {idx+1}] {item.get('type')} ===\n")
- text_get_resp_out.insert("end", "单板已确认受理查询请求 (GET_ACK 0x82),随后将传输 GET_DATA 状态帧。\n\n")
- elif kind == "status":
- state = item.get("state", {})
- text_get_resp_out.insert("end", f"=== [帧 {idx+1}] GET_DATA (0x42) 详细解码 ===\n")
- # Show duties
- groups = model.groups()
- for grp, cnt, _ in groups:
- duties = state.get(grp.lower(), [])
- if cnt >= 8:
- text_get_resp_out.insert("end", f"【{grp} 实际生效占空比 (共 {len(duties)} 路)】:\n")
- line = ""
- for i, val in enumerate(duties):
- line += f" {grp}{i:02d}: {val:3d} %"
- if (i + 1) % 6 == 0:
- text_get_resp_out.insert("end", line + "\n")
- line = ""
- else:
- line += " | "
- if line:
- text_get_resp_out.insert("end", line.rstrip(" | ") + "\n")
- else:
- ch_strs = [f"{grp}{i}: {v}%" for i, v in enumerate(duties)]
- text_get_resp_out.insert("end", f"【{grp} 实际生效占空比 ({len(duties)} 路)】: {' | '.join(ch_strs)}\n")
- if model.motor:
- lm = state.get("lower_limit_mask", 0)
- um = state.get("upper_limit_mask", 0)
- text_get_resp_out.insert("end", f"【限位状态】: 下限位掩码=0x{lm:04X} (二进制={lm:012b}), 上限位掩码=0x{um:04X} (二进制={um:012b})\n")
- for ax in range(12):
- l_act = "触发阻断" if (lm & (1 << ax)) else "正常"
- u_act = "触发阻断" if (um & (1 << ax)) else "正常"
- if (lm & (1 << ax)) or (um & (1 << ax)):
- text_get_resp_out.insert("end", f" • Axis{ax}: 下限位={l_act}, 上限位={u_act}\n")
- # Temperatures
- bmc = state.get("bmc", {}).get("temperature_c", [])
- ct = state.get("ct", {}).get("temperature_c", [])
- text_get_resp_out.insert("end", "\n【BMC 24 通道温度遥测】:\n")
- for i, t in enumerate(bmc):
- t_str = f"{t:3d} °C" if t is not None else "无效(0xFF)"
- text_get_resp_out.insert("end", f" BMC{i:02d}: {t_str}" + ("\n" if (i + 1) % 6 == 0 else " | "))
- text_get_resp_out.insert("end", "\n【CT7428 27 通道温度遥测】:\n")
- for i, t in enumerate(ct):
- t_str = f"{t:3d} °C" if t is not None else "无效(0xFF)"
- text_get_resp_out.insert("end", f" CT{i:02d}: {t_str}" + ("\n" if (i + 1) % 6 == 0 else " | "))
- text_get_resp_out.insert("end", "\n\n")
- else:
- text_get_resp_out.insert("end", f"=== [帧 {idx+1}] {item} ===\n\n")
- except Exception as exc:
- text_get_resp_out.delete("1.0", "end")
- text_get_resp_out.insert("1.0", f"解析失败: {exc}")
- ttk.Button(resp_btn_bar, text="🔍 解析 GET 响应", command=lambda: do_parse_get_resp()).pack(side="left", padx=4)
- # -----------------------------------------------------------------------
- # TAB 4: 通用报文检查器 (Universal Frame Inspector)
- # -----------------------------------------------------------------------
- tab_inspect = ttk.Frame(notebook, padding=10)
- notebook.add(tab_inspect, text="🔬 通用报文检查器 (Inspector)")
- ttk.Label(tab_inspect, text="输入或粘贴任意 HEX 报文(支持空格、冒号分隔,不区分大小写):", font=("", 10, "bold")).pack(anchor="w")
- text_insp_in = tk.Text(tab_inspect, height=4, wrap="char", font=("Consolas", 10))
- text_insp_in.pack(fill="x", pady=4)
- # Quick golden templates bar
- quick_bar = ttk.LabelFrame(tab_inspect, text="快速载入标准 Golden 帧测试模板", padding=6)
- quick_bar.pack(fill="x", pady=4)
- def load_template(hex_str: str):
- text_insp_in.delete("1.0", "end")
- text_insp_in.insert("1.0", hex_str)
- do_inspect()
- ttk.Button(quick_bar, text="GET_ALL 请求", command=lambda: load_template("A5 5A 02 00 6D 7B")).pack(side="left", padx=3)
- ttk.Button(quick_bar, text="SET_ACK 应答", command=lambda: load_template("A5 5A 81 00 A6 35")).pack(side="left", padx=3)
- ttk.Button(quick_bar, text="GET_ACK 应答", command=lambda: load_template("A5 5A 82 00 F5 60")).pack(side="left", padx=3)
- ttk.Button(quick_bar, text="NACK 队列满", command=lambda: load_template("A5 5A C0 02 01 04 B1 2A")).pack(side="left", padx=3)
- if model.motor:
- ttk.Button(quick_bar, text="MOTOR_DONE(上限位4387步)", command=lambda: load_template("A5 5A 50 04 04 02 23 11 B6 02")).pack(side="left", padx=3)
- ttk.Button(quick_bar, text="MOTOR_DONE(双限位0步)", command=lambda: load_template("A5 5A 50 04 04 03 00 00 23 64")).pack(side="left", padx=3)
- else:
- ttk.Button(quick_bar, text="6400 安全 SET 帧", command=lambda: load_template("A5 5A 01 20 " + "00 " * 24 + "14 " * 8 + "E8 0C")).pack(side="left", padx=3)
- # Inspector output
- insp_out_frame = ttk.LabelFrame(tab_inspect, text="报文逐字节解析与语义拆解", padding=8)
- insp_out_frame.pack(fill="both", expand=True, pady=4)
- text_insp_out = tk.Text(insp_out_frame, wrap="word", font=("Consolas", 10))
- text_insp_out.pack(fill="both", expand=True)
- def do_inspect():
- raw_text = text_insp_in.get("1.0", "end").strip()
- if not raw_text:
- return
- try:
- raw_bytes = parse_hex(raw_text)
- exp = model.explain(raw_bytes)
- text_insp_out.delete("1.0", "end")
- text_insp_out.insert("end", f"【原始 HEX】: {exp['hex']}\n")
- text_insp_out.insert("end", f"【帧类型】: {exp['type']}\n")
- text_insp_out.insert("end", f"【载荷长度】: {exp['length']}\n")
- text_insp_out.insert("end", f"【CRC-16 校验码】: {exp['crc_hex']} -> {exp['crc_status']}\n")
- text_insp_out.insert("end", f"【业务含义总结】: {exp['summary']}\n")
- text_insp_out.insert("end", "-" * 70 + "\n")
- text_insp_out.insert("end", "【字段详细拆解】:\n")
- for f in exp.get("fields", []):
- text_insp_out.insert("end", f" • {f}\n")
- except Exception as exc:
- text_insp_out.delete("1.0", "end")
- text_insp_out.insert("1.0", f"报文解析异常: {exc}")
- ttk.Button(tab_inspect, text="🚀 立即解码报文", command=do_inspect).pack(pady=4)
- # -----------------------------------------------------------------------
- # TAB 5: 构建与工程信息 (Build & Info)
- # -----------------------------------------------------------------------
- tab_info = ttk.Frame(notebook, padding=10)
- notebook.add(tab_info, text="ℹ️ 构建与协议信息")
- text_info = tk.Text(tab_info, height=18, font=("Consolas", 10))
- text_info.pack(fill="both", expand=True)
- info_dict = {
- "product": product,
- "board": model.board,
- "device": "EF2L45BG256B",
- "clock_hz": 25000000,
- "wire_baud": 921600,
- "wire_format": "8N1",
- "wire_framing": "A5 5A | TYPE:u8 | LENGTH:u8 | PAYLOAD | CRC_L:u8 | CRC_H:u8",
- "crc_algorithm": "CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, refin/refout false, xorout 0x0000, LSB first)",
- "watchdog_timeout_sec": 30,
- "temperature_representation": "单字节 uint8 摄氏度 (00..FE = 0..254 °C, FF = 无效)",
- "contract_sha256": model.contract.get("contract_sha256"),
- "metadata": model.metadata,
- }
- text_info.insert("1.0", json.dumps(info_dict, ensure_ascii=False, indent=2))
- # -----------------------------------------------------------------------
- # Serial Port Handler & Background Thread
- # -----------------------------------------------------------------------
- def serial_read_loop():
- nonlocal serial_port_obj
- rx_buf = bytearray()
- while True:
- with serial_lock:
- sp = serial_port_obj
- if sp is None or not sp.is_open:
- break
- try:
- waiting = sp.in_waiting
- if waiting > 0:
- chunk = sp.read(waiting)
- if chunk:
- rx_buf.extend(chunk)
- # Process frames in rx_buf
- while len(rx_buf) >= 6:
- # Search preamble A5 5A
- idx = rx_buf.find(PREAMBLE)
- if idx == -1:
- rx_buf.clear()
- break
- if idx > 0:
- del rx_buf[:idx]
- if len(rx_buf) < 6:
- break
- declared_len = rx_buf[3]
- frame_len = declared_len + 6
- if len(rx_buf) < frame_len:
- break
- frame_data = bytes(rx_buf[:frame_len])
- del rx_buf[:frame_len]
- # Decode frame
- try:
- exp = model.explain(frame_data)
- root.after(0, append_log, "RX", frame_hex(frame_data), exp["type"])
- # If status frame, update display
- if frame_data[2] == 0x42:
- root.after(0, update_realtime_status, frame_data)
- elif frame_data[2] == 0x81:
- root.after(0, lbl_realtime_stat.config, {"text": "SET 配置已成功应用 (SET_ACK 0x81)!看门狗已重载。"})
- elif frame_data[2] == 0xC0:
- root.after(0, lbl_realtime_stat.config, {"text": f"请求被拒绝: {exp['summary']}"})
- except Exception as e:
- root.after(0, append_log, "RX_ERR", frame_hex(frame_data), str(e))
- else:
- time.sleep(0.02)
- except Exception as exc:
- root.after(0, append_log, "ERR", "", f"串口读取异常: {exc}")
- break
- def update_realtime_status(frame_data: bytes):
- try:
- parsed = model.parse(frame_data)
- for item in parsed:
- if item.get("kind") == "status":
- st = item["state"]
- bmc_valid = sum(1 for t in st.get("bmc", {}).get("temperature_c", []) if t is not None)
- ct_valid = sum(1 for t in st.get("ct", {}).get("temperature_c", []) if t is not None)
- summary = f"状态已更新 | BMC 有效温度: {bmc_valid}/24 通道 | CT7428 有效温度: {ct_valid}/27 通道"
- if model.motor:
- lm = st.get("lower_limit_mask", 0)
- um = st.get("upper_limit_mask", 0)
- summary += f" | 下限位=0x{lm:03X} | 上限位=0x{um:03X}"
- fan_d = st.get("fan", [])
- ptc_d = st.get("ptc", [])
- lbl_realtime_ptc.config(text=f"【FAN 4路占空比】: {fan_d} | 【PTC 4路占空比】: {ptc_d}")
- else:
- ptc_d = st.get("ptc", [])
- if ptc_d:
- lines = []
- for c in range(0, len(ptc_d), 8):
- chunk = ptc_d[c : c + 8]
- lines.append(" | ".join(f"PTC{c+j:02d}:{v:3d}%" for j, v in enumerate(chunk)))
- front_d = st.get("front", [])
- rear_d = st.get("rear", [])
- lbl_realtime_ptc.config(text=f"【PTC 生效占空比 (共24路)】:\n " + "\n ".join(lines) + f"\n【风扇占空比】: Front={front_d} | Rear={rear_d}")
- lbl_realtime_stat.config(text=summary)
- # Also update TAB 3 output
- do_parse_get_resp(frame_hex(frame_data))
- except Exception:
- pass
- def poll_loop():
- while poll_active:
- with serial_lock:
- sp = serial_port_obj
- if sp and sp.is_open:
- get_frame = model.get_all()
- try:
- sp.write(get_frame)
- root.after(0, append_log, "TX", frame_hex(get_frame), "自动轮询 GET_ALL")
- except Exception:
- break
- time.sleep(1.0)
- def toggle_connect():
- nonlocal serial_port_obj, poll_active
- if not HAVE_SERIAL:
- messagebox.showerror("缺少库", "未检测到 pyserial 库,无法进行串口通信。\n可在命令行运行: pip install pyserial")
- return
- with serial_lock:
- if serial_port_obj and serial_port_obj.is_open:
- poll_active = False
- serial_port_obj.close()
- serial_port_obj = None
- btn_connect.config(text="打开串口")
- lbl_conn_status.config(text="已断开", foreground="gray")
- btn_send_get.config(state="disabled")
- btn_send_set.config(state="disabled")
- chk_poll.config(state="disabled")
- return
- port = port_combo.get().strip()
- if not port:
- messagebox.showwarning("提示", "请先选择有效的 COM 端口")
- return
- baud = int(baud_combo.get().strip())
- try:
- sp = serial.Serial(port, baudrate=baud, timeout=0.1)
- with serial_lock:
- serial_port_obj = sp
- btn_connect.config(text="关闭串口")
- lbl_conn_status.config(text=f"已连接 {port} @ {baud}", foreground="green")
- btn_send_get.config(state="normal")
- btn_send_set.config(state="normal")
- chk_poll.config(state="normal")
- # Start reading thread
- threading.Thread(target=serial_read_loop, daemon=True).start()
- except Exception as exc:
- messagebox.showerror("连接失败", f"无法打开串口 {port}:\n{exc}")
- def send_get_clicked():
- with serial_lock:
- sp = serial_port_obj
- if not sp or not sp.is_open:
- messagebox.showwarning("提示", "串口未连接")
- return
- get_frame = model.get_all()
- try:
- sp.write(get_frame)
- append_log("TX", frame_hex(get_frame), "GET_ALL 查询")
- except Exception as exc:
- messagebox.showerror("发送失败", str(exc))
- def send_set_clicked():
- with serial_lock:
- sp = serial_port_obj
- if not sp or not sp.is_open:
- messagebox.showwarning("提示", "串口未连接")
- return
- try:
- set_frame = do_generate_set()
- sp.write(set_frame)
- append_log("TX", frame_hex(set_frame), "SET_ALL 配置下发")
- except Exception as exc:
- messagebox.showerror("发送失败", str(exc))
- def on_poll_toggle():
- nonlocal poll_active
- poll_active = poll_var.get()
- if poll_active:
- threading.Thread(target=poll_loop, daemon=True).start()
- btn_connect.config(command=toggle_connect)
- btn_send_get.config(command=send_get_clicked)
- btn_send_set.config(command=send_set_clicked)
- chk_poll.config(command=on_poll_toggle)
- # Initial generation
- do_generate_set()
- root.mainloop()
- return 0
- def main(product: str, argv: list[str] | None = None) -> int:
- args = sys.argv if argv is None else argv
- if "--self-test" in args:
- return self_test(product)
- return run_gui(product)
- if __name__ == "__main__":
- prod = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] in ("6400-front-rear", "mrdimm-chamber") else "6400-front-rear"
- sys.exit(main(prod))
|