thermal_test_server.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. #!/usr/bin/env python3
  2. """Prod2U 6400V2.0 / MRDIMM High-Temperature Hood Thermal Test Backend & Web Frontend.
  3. Deployed inside the privileged container on 192.168.2.25 to execute remote or simulated
  4. 4-chamber heating tests, track per-chamber Sensor (CT) and Memory (BMC) time-to-target
  5. (default 70°C), continue recording all chambers after any chamber reaches target first,
  6. and analyze the relationship between fan speed, fan intervention timing/reference
  7. temperature, and heating time to target temperature.
  8. """
  9. from __future__ import annotations
  10. import argparse
  11. import datetime
  12. import json
  13. import math
  14. import os
  15. import sys
  16. import threading
  17. import time
  18. import urllib.parse
  19. from http import HTTPStatus
  20. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  21. from pathlib import Path
  22. from typing import Any
  23. ROOT = Path(__file__).resolve().parents[1]
  24. if str(ROOT) not in sys.path:
  25. sys.path.insert(0, str(ROOT))
  26. from tools import prod2u_gui as gui
  27. def detect_container_privileges() -> dict[str, Any]:
  28. """Inspect current container privilege and device/kernel capabilities."""
  29. dev_nodes = []
  30. for candidate in ("/dev/mem", "/dev/kmsg", "/dev/net/tun", "/dev/bus/usb", "/dev/ttyS0"):
  31. if os.path.exists(candidate):
  32. dev_nodes.append(candidate)
  33. cap_eff = ""
  34. try:
  35. status_txt = Path("/proc/self/status").read_text(encoding="utf-8", errors="replace")
  36. for line in status_txt.splitlines():
  37. if line.startswith("CapEff:"):
  38. cap_eff = line.split(":", 1)[1].strip()
  39. break
  40. except Exception:
  41. pass
  42. is_privileged = cap_eff.endswith("fffffffff") or ("/dev/mem" in dev_nodes and os.geteuid() == 0)
  43. return {
  44. "host": os.environ.get("PROD2U_BACKEND_HOST_IP", "192.168.2.25"),
  45. "container_hostname": os.uname().nodename if hasattr(os, "uname") else "linux-container",
  46. "kernel": os.uname().release if hasattr(os, "uname") else "linux",
  47. "uid": os.geteuid() if hasattr(os, "geteuid") else 0,
  48. "cap_eff": cap_eff,
  49. "privileged": is_privileged,
  50. "device_nodes": dev_nodes,
  51. "pwm_unified_hz": 20,
  52. "software_version": getattr(gui, "SOFTWARE_VERSION", "3.3.0"),
  53. "protocol": {"6400-v2": "SET36/GET90 (EPB1+SB1+SB2+4kHz80% buzzer)", "mrdimm": "SET69/GET65+DIAG8 (4kHz80% buzzer)"},
  54. }
  55. def simulate_thermal_run(
  56. *,
  57. session_id: str,
  58. test_name: str,
  59. product: str = "6400-v2",
  60. overall_pass_min_temp_c: float = 70.0,
  61. chamber_target_temp_c: dict[int, float] | None = None,
  62. ptc_duty_percent: int = 100,
  63. ssr_duty_percent: int = 100,
  64. initial_fan_duty_percent: int = 0,
  65. active_fan_duty_percent: int = 50,
  66. fan_intervention_mode: str = "time_s",
  67. fan_intervention_time_s: float = 120.0,
  68. fan_intervention_ref_temp_c: float = 55.0,
  69. fan_intervention_ref_source: str = "ct",
  70. duration_s: int = 360,
  71. step_s: int = 5,
  72. base_timestamp: float = 1761800000.0,
  73. mapping: gui.ChamberMappingConfig | None = None,
  74. ) -> dict[str, Any]:
  75. """Generate a physically representative 4-chamber heating curve run to study fan vs. reach time.
  76. Models:
  77. - PTC + SSR heating power driving air/sensor temperature and memory temperature
  78. - Intake/exhaust fan convective heat transfer coupling:
  79. * Too high fan speed from t=0 increases exhaust heat loss, slowing initial ramp;
  80. * Zero fan speed heats the local heater/sensor fast but delays memory uniform heating;
  81. * Optimal fan intervention (e.g. 30%~50% fan intervening at ~50-55°C or ~90-120s)
  82. accelerates convective transfer from PTC to DIMM memory while minimizing exhaust loss.
  83. - Continues recording all 4 chambers for the full `duration_s` even after the fastest
  84. chamber reaches 70°C first.
  85. """
  86. cmap = mapping or gui.ChamberMappingConfig.default(product)
  87. store = gui.TemperatureCurveStore(max_capacity=max(7200, duration_s // max(1, step_s) + 10))
  88. session = gui.ThermalTestSession(
  89. product=product,
  90. test_name=test_name,
  91. overall_pass_min_temp_c=overall_pass_min_temp_c,
  92. chamber_target_temp_c=chamber_target_temp_c or {1: 70.0, 2: 70.0, 3: 70.0, 4: 70.0},
  93. ptc_duty_percent=ptc_duty_percent,
  94. ssr_duty_percent=ssr_duty_percent,
  95. initial_fan_duty_percent=initial_fan_duty_percent,
  96. active_fan_duty_percent=active_fan_duty_percent,
  97. fan_intervention_mode=fan_intervention_mode,
  98. fan_intervention_time_s=fan_intervention_time_s,
  99. fan_intervention_ref_temp_c=fan_intervention_ref_temp_c,
  100. fan_intervention_ref_source=fan_intervention_ref_source,
  101. )
  102. session.start(start_timestamp=base_timestamp)
  103. session.session_id = session_id
  104. # Per-chamber initial state (slight natural asymmetry across Chambers 1..4: Chamber 2 & 3 share SSR2)
  105. chamber_factors = {1: 1.03, 2: 1.06, 3: 1.00, 4: 0.96}
  106. ct_temp = {1: 26.0, 2: 26.5, 3: 26.0, 4: 25.5}
  107. bmc_temp = {1: 28.0, 2: 28.5, 3: 28.0, 4: 27.5}
  108. heat_drive = (0.65 * (ptc_duty_percent / 100.0) + 0.35 * (ssr_duty_percent / 100.0))
  109. for elapsed in range(0, duration_s + 1, max(1, step_s)):
  110. ts = base_timestamp + float(elapsed)
  111. t_lbl = datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S")
  112. fan_pct = session.current_fan_duty_percent
  113. fan_norm = fan_pct / 100.0
  114. bmc_arr = [255] * 24
  115. ct_arr = [255] * 27
  116. ct_arr[0] = int(round(27.0 + min(12.0, elapsed * 0.02))) # U6 local
  117. for cid in gui.CHAMBER_IDS:
  118. cf = chamber_factors[cid]
  119. if elapsed > 0:
  120. dt = float(step_s)
  121. # Air/Sensor heating rate: heater power minus exhaust cooling from fan
  122. air_target_asymp = 26.0 + (68.0 * heat_drive * cf) * (1.0 - 0.18 * fan_norm)
  123. air_tau = 95.0 / (0.85 + 0.45 * fan_norm)
  124. ct_temp[cid] += (air_target_asymp - ct_temp[cid]) * (1.0 - math.exp(-dt / air_tau))
  125. # Memory (BMC) heating rate: depends on convective coupling from air + direct radiation
  126. # Convective coupling improves significantly when fan is 25%..60%
  127. conv_coupling = 0.38 + 0.85 * math.sin(min(1.0, fan_norm) * math.pi * 0.65)
  128. mem_target_asymp = ct_temp[cid] + 3.5 * heat_drive
  129. mem_tau = 115.0 / conv_coupling
  130. bmc_temp[cid] += (mem_target_asymp - bmc_temp[cid]) * (1.0 - math.exp(-dt / mem_tau))
  131. c_int = max(0, min(254, int(round(ct_temp[cid]))))
  132. b_int = max(0, min(254, int(round(bmc_temp[cid]))))
  133. for idx_pos, ch_ct in enumerate(cmap.chambers[cid]["ct"]):
  134. if 0 <= ch_ct < 27:
  135. ct_arr[ch_ct] = max(0, min(254, c_int + (idx_pos % 2)))
  136. for idx_pos, ch_bmc in enumerate(cmap.chambers[cid]["bmc"]):
  137. if 0 <= ch_bmc < 24:
  138. bmc_arr[ch_bmc] = max(0, min(254, b_int + (idx_pos % 3) - 1))
  139. sample = store.record_raw_arrays(bmc_arr, ct_arr, timestamp=ts, time_label=t_lbl, source="THERMAL_TEST")
  140. session.process_sample(sample, cmap)
  141. session.stop(stop_timestamp=base_timestamp + float(duration_s))
  142. return {
  143. "session_id": session.session_id,
  144. "report": session.summary(),
  145. "mapping": cmap.to_dict(),
  146. "samples": store.snapshot(),
  147. }
  148. class ThermalTestBackendState:
  149. """Thread-safe state manager for the 192.168.2.25 thermal test backend."""
  150. def __init__(self, storage_dir: Path | None = None):
  151. self.storage_dir = storage_dir or (ROOT / "logs" / "thermal_test_runs")
  152. self.storage_dir.mkdir(parents=True, exist_ok=True)
  153. self.lock = threading.Lock()
  154. self.runs: dict[str, dict[str, Any]] = {}
  155. self.active_session_id: str | None = None
  156. self._bg_stop = threading.Event()
  157. self._bg_thread: threading.Thread | None = None
  158. self._load_persisted_runs()
  159. if not self.runs:
  160. self._seed_baseline_experiments()
  161. def _load_persisted_runs(self) -> None:
  162. for path in sorted(self.storage_dir.glob("*.json")):
  163. try:
  164. data = json.loads(path.read_text(encoding="utf-8"))
  165. sid = data.get("session_id") or data.get("report", {}).get("session_id")
  166. if sid:
  167. self.runs[sid] = data
  168. except Exception:
  169. pass
  170. def _persist_run(self, sid: str, data: dict[str, Any]) -> None:
  171. try:
  172. target = self.storage_dir / f"{sid}.json"
  173. target.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
  174. except Exception:
  175. pass
  176. def _seed_baseline_experiments(self) -> None:
  177. """Seed 4 baseline experiment runs demonstrating fan speed & intervention timing vs. 70°C reach time."""
  178. presets = [
  179. {
  180. "session_id": "EXP-01-FAN0-TO-40-AT-55C",
  181. "test_name": "实验1: 初始风扇0% → 参考温度55°C介入40%风扇 (最优均衡)",
  182. "initial_fan_duty_percent": 0,
  183. "active_fan_duty_percent": 40,
  184. "fan_intervention_mode": "ref_temp_c",
  185. "fan_intervention_ref_temp_c": 55.0,
  186. "fan_intervention_time_s": 90.0,
  187. },
  188. {
  189. "session_id": "EXP-02-FAN0-TO-50-AT-120S",
  190. "test_name": "实验2: 初始风扇0% → 加热120s定时介入50%风扇",
  191. "initial_fan_duty_percent": 0,
  192. "active_fan_duty_percent": 50,
  193. "fan_intervention_mode": "time_s",
  194. "fan_intervention_time_s": 120.0,
  195. "fan_intervention_ref_temp_c": 55.0,
  196. },
  197. {
  198. "session_id": "EXP-03-FAN20-IMMEDIATE",
  199. "test_name": "实验3: 全程20%风扇立即介入 (0s起转)",
  200. "initial_fan_duty_percent": 20,
  201. "active_fan_duty_percent": 20,
  202. "fan_intervention_mode": "immediate",
  203. "fan_intervention_time_s": 0.0,
  204. "fan_intervention_ref_temp_c": 40.0,
  205. },
  206. {
  207. "session_id": "EXP-04-FAN80-IMMEDIATE",
  208. "test_name": "实验4: 全程80%高风速立即介入 (排风热损偏大对照)",
  209. "initial_fan_duty_percent": 80,
  210. "active_fan_duty_percent": 80,
  211. "fan_intervention_mode": "immediate",
  212. "fan_intervention_time_s": 0.0,
  213. "fan_intervention_ref_temp_c": 40.0,
  214. },
  215. ]
  216. for idx, p in enumerate(presets):
  217. run_data = simulate_thermal_run(
  218. session_id=p["session_id"],
  219. test_name=p["test_name"],
  220. overall_pass_min_temp_c=70.0,
  221. chamber_target_temp_c={1: 70.0, 2: 70.0, 3: 70.0, 4: 70.0},
  222. ptc_duty_percent=100,
  223. ssr_duty_percent=100,
  224. initial_fan_duty_percent=p["initial_fan_duty_percent"],
  225. active_fan_duty_percent=p["active_fan_duty_percent"],
  226. fan_intervention_mode=p["fan_intervention_mode"],
  227. fan_intervention_time_s=p["fan_intervention_time_s"],
  228. fan_intervention_ref_temp_c=p["fan_intervention_ref_temp_c"],
  229. duration_s=360,
  230. step_s=5,
  231. base_timestamp=1761800000.0 + idx * 1000.0,
  232. )
  233. self.runs[p["session_id"]] = run_data
  234. self._persist_run(p["session_id"], run_data)
  235. def save_run(self, payload: dict[str, Any]) -> dict[str, Any]:
  236. report = payload.get("report") or {}
  237. mapping_dict = payload.get("mapping") or gui.ChamberMappingConfig.default("6400-v2").to_dict()
  238. samples = payload.get("samples") or []
  239. sid = payload.get("session_id") or report.get("session_id") or datetime.datetime.now().strftime("TT-%Y%m%d-%H%M%S")
  240. # If report was not pre-computed or samples were uploaded raw, compute report through ThermalTestSession
  241. if not report or "chambers" not in report:
  242. cmap = gui.ChamberMappingConfig.from_dict(mapping_dict)
  243. store = gui.TemperatureCurveStore()
  244. for s in samples:
  245. store.record_raw_arrays(
  246. s.get("bmc", []),
  247. s.get("ct", []),
  248. timestamp=s.get("timestamp"),
  249. time_label=s.get("time_label"),
  250. )
  251. tt = gui.ThermalTestSession(
  252. product=mapping_dict.get("product", "6400-v2"),
  253. test_name=payload.get("test_name", f"上传测试 {sid}"),
  254. overall_pass_min_temp_c=float(payload.get("overall_pass_min_temp_c", 70.0)),
  255. )
  256. tt.session_id = sid
  257. report = tt.evaluate_from_store(store, cmap)
  258. record = {
  259. "session_id": sid,
  260. "report": report,
  261. "mapping": mapping_dict,
  262. "samples": samples,
  263. }
  264. with self.lock:
  265. self.runs[sid] = record
  266. self._persist_run(sid, record)
  267. total = len(self.runs)
  268. return {"status": "ok", "session_id": sid, "total_runs": total, "report": report}
  269. def recalculate_run(self, sid: str, params: dict[str, Any]) -> dict[str, Any]:
  270. with self.lock:
  271. if sid not in self.runs:
  272. raise KeyError(f"未找到测试会话: {sid}")
  273. rec = self.runs[sid]
  274. mapping_data = params.get("mapping") or rec.get("mapping") or gui.ChamberMappingConfig.default("6400-v2").to_dict()
  275. cmap = gui.ChamberMappingConfig.from_dict(mapping_data)
  276. old_rep = rec.get("report", {})
  277. old_exp = old_rep.get("experiment_params", {})
  278. pass_min = float(params.get("overall_pass_min_temp_c", old_rep.get("overall_pass_min_temp_c", 70.0)))
  279. raw_c_targets = params.get("chamber_target_temp_c") or old_rep.get("chamber_target_temp_c") or {}
  280. c_targets = {cid: float(raw_c_targets.get(cid, raw_c_targets.get(str(cid), pass_min))) for cid in gui.CHAMBER_IDS}
  281. tt = gui.ThermalTestSession(
  282. product=old_rep.get("product", "6400-v2"),
  283. test_name=str(params.get("test_name", old_rep.get("test_name", sid))),
  284. overall_pass_min_temp_c=pass_min,
  285. chamber_target_temp_c=c_targets,
  286. bmc_eval_mode=str(params.get("bmc_eval_mode", old_rep.get("bmc_eval_mode", "avg"))),
  287. ct_eval_mode=str(params.get("ct_eval_mode", old_rep.get("ct_eval_mode", "avg"))),
  288. ptc_duty_percent=int(params.get("ptc_duty_percent", old_exp.get("ptc_duty_percent", 100))),
  289. ssr_duty_percent=int(params.get("ssr_duty_percent", old_exp.get("ssr_duty_percent", 100))),
  290. initial_fan_duty_percent=int(params.get("initial_fan_duty_percent", old_exp.get("initial_fan_duty_percent", 0))),
  291. active_fan_duty_percent=int(params.get("active_fan_duty_percent", old_exp.get("active_fan_duty_percent", 50))),
  292. fan_intervention_mode=str(params.get("fan_intervention_mode", old_exp.get("fan_intervention_mode", "time_s"))),
  293. fan_intervention_time_s=float(params.get("fan_intervention_time_s", old_exp.get("fan_intervention_time_s", 120.0))),
  294. fan_intervention_ref_temp_c=float(params.get("fan_intervention_ref_temp_c", old_exp.get("fan_intervention_ref_temp_c", 55.0))),
  295. )
  296. tt.session_id = sid
  297. store = gui.TemperatureCurveStore()
  298. for s in rec.get("samples", []):
  299. store.record_raw_arrays(
  300. s.get("bmc", []),
  301. s.get("ct", []),
  302. timestamp=s.get("timestamp"),
  303. time_label=s.get("time_label"),
  304. )
  305. new_report = tt.evaluate_from_store(store, cmap, ignore_zero_ct=bool(params.get("ignore_zero_ct", False)))
  306. updated = {
  307. "session_id": sid,
  308. "report": new_report,
  309. "mapping": cmap.to_dict(),
  310. "samples": rec.get("samples", []),
  311. }
  312. with self.lock:
  313. self.runs[sid] = updated
  314. self._persist_run(sid, updated)
  315. return updated
  316. def start_new_test(self, params: dict[str, Any]) -> dict[str, Any]:
  317. sid = params.get("session_id") or datetime.datetime.now().strftime("TT-%Y%m%d-%H%M%S")
  318. test_name = str(params.get("test_name") or f"远程升温测试 {sid}")
  319. pass_min = float(params.get("overall_pass_min_temp_c", 70.0))
  320. raw_ct = params.get("chamber_target_temp_c") or {}
  321. c_targets = {cid: float(raw_ct.get(cid, raw_ct.get(str(cid), pass_min))) for cid in gui.CHAMBER_IDS}
  322. mapping_dict = params.get("mapping")
  323. cmap = (
  324. gui.ChamberMappingConfig.from_dict(mapping_dict)
  325. if isinstance(mapping_dict, dict)
  326. else gui.ChamberMappingConfig.default("6400-v2")
  327. )
  328. duration_s = max(30, min(3600, int(params.get("duration_s", 360))))
  329. step_s = max(1, min(60, int(params.get("step_s", 5))))
  330. run_data = simulate_thermal_run(
  331. session_id=sid,
  332. test_name=test_name,
  333. product=str(params.get("product", "6400-v2")),
  334. overall_pass_min_temp_c=pass_min,
  335. chamber_target_temp_c=c_targets,
  336. ptc_duty_percent=int(params.get("ptc_duty_percent", 100)),
  337. ssr_duty_percent=int(params.get("ssr_duty_percent", 100)),
  338. initial_fan_duty_percent=int(params.get("initial_fan_duty_percent", 0)),
  339. active_fan_duty_percent=int(params.get("active_fan_duty_percent", 50)),
  340. fan_intervention_mode=str(params.get("fan_intervention_mode", "time_s")),
  341. fan_intervention_time_s=float(params.get("fan_intervention_time_s", 120.0)),
  342. fan_intervention_ref_temp_c=float(params.get("fan_intervention_ref_temp_c", 55.0)),
  343. fan_intervention_ref_source=str(params.get("fan_intervention_ref_source", "ct")),
  344. duration_s=duration_s,
  345. step_s=step_s,
  346. base_timestamp=time.time(),
  347. mapping=cmap,
  348. )
  349. with self.lock:
  350. self.runs[sid] = run_data
  351. self.active_session_id = sid
  352. self._persist_run(sid, run_data)
  353. return run_data
  354. def export_multi_run_comparison_csv(self) -> str:
  355. headers = [
  356. "session_id",
  357. "test_name",
  358. "overall_pass_min_c",
  359. "ptc_duty_pct",
  360. "ssr_duty_pct",
  361. "initial_fan_pct",
  362. "active_fan_pct",
  363. "fan_intervention_mode",
  364. "fan_intervened_elapsed_s",
  365. "fan_intervened_temp_c",
  366. "C1_sensor_reach_s",
  367. "C1_memory_reach_s",
  368. "C2_sensor_reach_s",
  369. "C2_memory_reach_s",
  370. "C3_sensor_reach_s",
  371. "C3_memory_reach_s",
  372. "C4_sensor_reach_s",
  373. "C4_memory_reach_s",
  374. "hood_sensor_reach_s",
  375. "hood_memory_reach_s",
  376. "first_reached_chamber",
  377. "first_reached_elapsed_s",
  378. "total_post_target_samples",
  379. ]
  380. rows = [",".join(headers)]
  381. with self.lock:
  382. items = list(self.runs.values())
  383. for item in items:
  384. rep = item.get("report", {})
  385. exp = rep.get("experiment_params", {})
  386. hs = rep.get("hood_summary", {})
  387. fr = rep.get("first_reached", {})
  388. chs = rep.get("chambers", {})
  389. def _fmt(v: Any) -> str:
  390. return "" if v is None else f"{float(v):.1f}"
  391. row = [
  392. str(rep.get("session_id", "")),
  393. str(rep.get("test_name", "")).replace(",", ";"),
  394. _fmt(rep.get("overall_pass_min_temp_c", 70.0)),
  395. str(exp.get("ptc_duty_percent", 100)),
  396. str(exp.get("ssr_duty_percent", 100)),
  397. str(exp.get("initial_fan_duty_percent", 0)),
  398. str(exp.get("active_fan_duty_percent", 50)),
  399. str(exp.get("fan_intervention_mode", "")),
  400. _fmt(exp.get("fan_intervened_elapsed_s")),
  401. _fmt(exp.get("fan_intervened_temp_c")),
  402. ]
  403. for cid in ("1", "2", "3", "4"):
  404. c_st = chs.get(cid, {})
  405. row.append(_fmt(c_st.get("sensor_time_to_target_s")))
  406. row.append(_fmt(c_st.get("memory_time_to_target_s")))
  407. row.extend([
  408. _fmt(hs.get("hood_sensor_reach_time_s")),
  409. _fmt(hs.get("hood_memory_reach_time_s")),
  410. "" if fr.get("chamber_id") is None else f"腔体{fr.get('chamber_id')}",
  411. _fmt(fr.get("elapsed_s")),
  412. str(fr.get("total_post_target_samples", 0)),
  413. ])
  414. rows.append(",".join(row))
  415. return "\n".join(rows) + "\n"
  416. def build_session_and_store(self, sid: str) -> tuple[gui.ThermalTestSession, gui.TemperatureCurveStore, gui.ChamberMappingConfig]:
  417. with self.lock:
  418. if sid not in self.runs:
  419. raise KeyError(f"未找到测试会话: {sid}")
  420. rec = self.runs[sid]
  421. rep = rec.get("report", {})
  422. exp = rep.get("experiment_params", {})
  423. cmap = gui.ChamberMappingConfig.from_dict(rec.get("mapping") or gui.ChamberMappingConfig.default("6400-v2").to_dict())
  424. store = gui.TemperatureCurveStore()
  425. for s in rec.get("samples", []):
  426. store.record_raw_arrays(
  427. s.get("bmc", []),
  428. s.get("ct", []),
  429. timestamp=s.get("timestamp"),
  430. time_label=s.get("time_label"),
  431. )
  432. raw_ct = rep.get("chamber_target_temp_c") or {}
  433. c_targets = {cid: float(raw_ct.get(cid, raw_ct.get(str(cid), 70.0))) for cid in gui.CHAMBER_IDS}
  434. tt = gui.ThermalTestSession(
  435. product=rep.get("product", "6400-v2"),
  436. test_name=rep.get("test_name", sid),
  437. overall_pass_min_temp_c=float(rep.get("overall_pass_min_temp_c", 70.0)),
  438. chamber_target_temp_c=c_targets,
  439. bmc_eval_mode=rep.get("bmc_eval_mode", "avg"),
  440. ct_eval_mode=rep.get("ct_eval_mode", "avg"),
  441. ptc_duty_percent=int(exp.get("ptc_duty_percent", 100)),
  442. ssr_duty_percent=int(exp.get("ssr_duty_percent", 100)),
  443. initial_fan_duty_percent=int(exp.get("initial_fan_duty_percent", 0)),
  444. active_fan_duty_percent=int(exp.get("active_fan_duty_percent", 50)),
  445. fan_intervention_mode=exp.get("fan_intervention_mode", "time_s"),
  446. fan_intervention_time_s=float(exp.get("fan_intervention_time_s", 120.0)),
  447. fan_intervention_ref_temp_c=float(exp.get("fan_intervention_ref_temp_c", 55.0)),
  448. )
  449. tt.session_id = sid
  450. tt.evaluate_from_store(store, cmap)
  451. return tt, store, cmap
  452. WEB_HTML = r"""<!DOCTYPE html>
  453. <html lang="zh-CN">
  454. <head>
  455. <meta charset="utf-8" />
  456. <meta name="viewport" content="width=device-width, initial-scale=1" />
  457. <title>6400V2.0 高温罩四腔温度测试与风扇介入分析系统 (192.168.2.25)</title>
  458. <style>
  459. :root {
  460. --bg: #f1f5f9;
  461. --card: #ffffff;
  462. --navy: #0f2747;
  463. --blue: #1d4ed8;
  464. --teal: #0d9488;
  465. --amber: #d97706;
  466. --red: #dc2626;
  467. --green: #15803d;
  468. --border: #cbd5e1;
  469. --text: #1e293b;
  470. --muted: #64748b;
  471. }
  472. * { box-sizing: border-box; }
  473. body {
  474. margin: 0;
  475. font-family: "Microsoft YaHei", "PingFang SC", "Noto Sans CJK SC", system-ui, sans-serif;
  476. background: var(--bg);
  477. color: var(--text);
  478. font-size: 13px;
  479. }
  480. header {
  481. background: linear-gradient(90deg, #0f2747 0%, #1e3a8a 100%);
  482. color: #fff;
  483. padding: 12px 20px;
  484. display: flex;
  485. justify-content: space-between;
  486. align-items: center;
  487. flex-wrap: wrap;
  488. gap: 10px;
  489. }
  490. header h1 { margin: 0; font-size: 18px; letter-spacing: 0.3px; }
  491. header .sub { font-size: 12px; color: #bfdbfe; margin-top: 3px; }
  492. .badge {
  493. display: inline-block;
  494. padding: 4px 10px;
  495. border-radius: 999px;
  496. font-size: 12px;
  497. font-weight: 600;
  498. background: rgba(255,255,255,0.15);
  499. color: #fff;
  500. }
  501. .badge.ok { background: #15803d; color: #fff; }
  502. .badge.warn { background: #d97706; color: #fff; }
  503. main { max-width: 1640px; margin: 12px auto; padding: 0 14px 28px; }
  504. .card {
  505. background: var(--card);
  506. border: 1px solid var(--border);
  507. border-radius: 8px;
  508. padding: 12px 14px;
  509. margin-bottom: 12px;
  510. box-shadow: 0 1px 2px rgba(15, 39, 71, 0.04);
  511. }
  512. .card h2 {
  513. margin: 0 0 10px 0;
  514. font-size: 14px;
  515. color: var(--navy);
  516. border-bottom: 1px solid #e2e8f0;
  517. padding-bottom: 6px;
  518. display: flex;
  519. justify-content: space-between;
  520. align-items: center;
  521. }
  522. .form-row {
  523. display: flex;
  524. flex-wrap: wrap;
  525. gap: 10px 14px;
  526. align-items: center;
  527. margin-bottom: 8px;
  528. }
  529. label { font-weight: 600; color: #334155; }
  530. input[type="text"], input[type="number"], select {
  531. padding: 5px 8px;
  532. border: 1px solid #94a3b8;
  533. border-radius: 4px;
  534. font-size: 13px;
  535. font-family: Consolas, monospace;
  536. }
  537. input[type="number"] { width: 72px; }
  538. button, .btn {
  539. padding: 6px 12px;
  540. border-radius: 5px;
  541. border: 1px solid transparent;
  542. font-size: 12px;
  543. font-weight: 600;
  544. cursor: pointer;
  545. text-decoration: none;
  546. display: inline-flex;
  547. align-items: center;
  548. gap: 4px;
  549. }
  550. .btn-primary { background: var(--blue); color: #fff; }
  551. .btn-primary:hover { background: #1e40af; }
  552. .btn-teal { background: var(--teal); color: #fff; }
  553. .btn-amber { background: var(--amber); color: #fff; }
  554. .btn-outline { background: #f8fafc; border-color: #94a3b8; color: #1e293b; }
  555. .btn-outline:hover { background: #e2e8f0; }
  556. table {
  557. width: 100%;
  558. border-collapse: collapse;
  559. font-size: 12px;
  560. }
  561. th, td {
  562. border: 1px solid #cbd5e1;
  563. padding: 7px 8px;
  564. text-align: center;
  565. }
  566. th { background: #f1f5f9; color: var(--navy); font-weight: 700; }
  567. tr:nth-child(even) { background: #f8fafc; }
  568. tr.highlight { background: #fef3c7; font-weight: 700; }
  569. .status-pass { color: var(--green); font-weight: 700; }
  570. .status-wait { color: var(--amber); font-weight: 700; }
  571. .grid-2 { display: grid; grid-template-columns: 1.15fr 0.85fr; gap: 12px; }
  572. @media (max-width: 1100px) { .grid-2 { grid-template-columns: 1fr; } }
  573. .svg-box {
  574. width: 100%;
  575. overflow-x: auto;
  576. background: #f8fafc;
  577. border: 1px solid #cbd5e1;
  578. border-radius: 6px;
  579. padding: 6px;
  580. text-align: center;
  581. }
  582. .svg-box svg { max-width: 100%; height: auto; }
  583. </style>
  584. </head>
  585. <body>
  586. <header>
  587. <div>
  588. <h1>🔥 6400V2.0 高温罩四腔体温度测试与风扇介入关系分析系统</h1>
  589. <div class="sub" id="hdr-sub">后端容器: 192.168.2.25 (全设备/内核栈权限) | 全板 PWM 统一 20Hz (50ms周期) | 先达标腔体锁定耗时后持续记录全腔数据</div>
  590. </div>
  591. <div>
  592. <span class="badge ok" id="priv-badge">内核/设备权限: 已就绪</span>
  593. <span class="badge" id="runs-badge">已存实验组: 0</span>
  594. </div>
  595. </header>
  596. <main>
  597. <!-- 1. Test Configuration & Mapping -->
  598. <div class="card">
  599. <h2>
  600. <span>⚙️ 1. 高温罩目标温度、腔体通道映射与风扇介入实验配置</span>
  601. <span>
  602. <button class="btn-outline" onclick="syncTargets()">🎯 将最低通过温度同步至四腔目标</button>
  603. <button class="btn-outline" onclick="swapCtPairs()">🔀 1/2与3/4腔Sensor对调</button>
  604. </span>
  605. </h2>
  606. <div class="form-row">
  607. <label>测试名称:</label>
  608. <input type="text" id="cfg-name" value="6400V2.0 风扇介入与升温耗时测试" style="width:230px;" />
  609. <label style="color:#b45309;">高温罩四腔通过最低温度(°C):</label>
  610. <input type="number" id="cfg-pass-min" value="70" min="20" max="200" step="1" />
  611. <label>腔1目标(°C):</label><input type="number" id="cfg-t1" value="70" />
  612. <label>腔2目标(°C):</label><input type="number" id="cfg-t2" value="70" />
  613. <label>腔3目标(°C):</label><input type="number" id="cfg-t3" value="70" />
  614. <label>腔4目标(°C):</label><input type="number" id="cfg-t4" value="70" />
  615. </div>
  616. <div class="form-row">
  617. <label>PTC加热(%):</label><input type="number" id="cfg-ptc" value="100" min="0" max="100" />
  618. <label>SSR加热(%):</label><input type="number" id="cfg-ssr" value="100" min="0" max="100" />
  619. <label>初始风扇转速(%):</label><input type="number" id="cfg-fan-init" value="0" min="0" max="100" />
  620. <label style="color:#1d4ed8;">介入后风扇转速(%):</label><input type="number" id="cfg-fan-active" value="45" min="0" max="100" />
  621. <label>风扇介入方式:</label>
  622. <select id="cfg-fan-mode">
  623. <option value="ref_temp_c">按参考温度触发介入 (°C)</option>
  624. <option value="time_s">按加热时间触发介入 (s)</option>
  625. <option value="immediate">立即介入 (0s)</option>
  626. <option value="manual">仅手动/纯观测</option>
  627. </select>
  628. <label>介入时间(s):</label><input type="number" id="cfg-fan-time" value="120" min="0" max="3600" />
  629. <label>介入参考温度(°C):</label><input type="number" id="cfg-fan-temp" value="55" min="20" max="200" />
  630. <label>测试总时长(s):</label><input type="number" id="cfg-duration" value="360" min="60" max="3600" />
  631. </div>
  632. <div class="form-row">
  633. <label>腔1映射(BMC / CT):</label>
  634. <input type="text" id="map-b1" value="0-5" style="width:68px;" /><input type="text" id="map-c1" value="1,2" style="width:58px;" />
  635. <label>腔2映射:</label>
  636. <input type="text" id="map-b2" value="6-11" style="width:68px;" /><input type="text" id="map-c2" value="3,4" style="width:58px;" />
  637. <label>腔3映射:</label>
  638. <input type="text" id="map-b3" value="12-17" style="width:68px;" /><input type="text" id="map-c3" value="5,6" style="width:58px;" />
  639. <label>腔4映射:</label>
  640. <input type="text" id="map-b4" value="18-23" style="width:68px;" /><input type="text" id="map-c4" value="7,8" style="width:58px;" />
  641. </div>
  642. <div class="form-row" style="margin-top:10px;">
  643. <button class="btn-primary" onclick="runNewExperiment()">▶️ 在后端执行升温测试 (先达标腔体持续记录)</button>
  644. <button class="btn-teal" onclick="recalcCurrentRun()">🔄 对当前选中实验重新应用目标温度/映射统计</button>
  645. <label style="margin-left:14px;">切换查看已存实验:</label>
  646. <select id="run-select" onchange="selectRun(this.value)" style="min-width:340px;"></select>
  647. </div>
  648. </div>
  649. <!-- 2. Current Run Reach-Time Table -->
  650. <div class="card">
  651. <h2>
  652. <span id="cur-run-title">⏱️ 2. 当前实验各腔体 Sensor 温度与内存(BMC)温度达到目标温度所需时间统计</span>
  653. <span id="export-links"></span>
  654. </h2>
  655. <div id="continuous-banner" style="margin-bottom:8px; padding:6px 10px; background:#ecfdf5; border:1px solid #86efac; border-radius:5px; color:#065f46; font-weight:600;">
  656. 加载中...
  657. </div>
  658. <table>
  659. <thead>
  660. <tr>
  661. <th>腔体 / 区域</th>
  662. <th>预期目标 / 最低通过标准</th>
  663. <th>Sensor(CT) 初始 / 结束 / 峰值</th>
  664. <th>Sensor(CT) 达到目标耗时</th>
  665. <th>内存(BMC) 初始 / 结束 / 峰值</th>
  666. <th>内存(BMC) 达到目标耗时</th>
  667. <th>达标状态与持续记录数据验证</th>
  668. </tr>
  669. </thead>
  670. <tbody id="chamber-tbody"></tbody>
  671. </table>
  672. </div>
  673. <!-- 3. Curves & Multi-Run Fan Relationship Study -->
  674. <div class="grid-2">
  675. <div class="card">
  676. <h2>
  677. <span>📈 3. 四腔体内存温度(BMC)与Sensor温度(CT)曲线图 (含目标温度阈值线)</span>
  678. <span id="img-links"></span>
  679. </h2>
  680. <div class="svg-box" id="curve-svg-container">正在渲染四腔体温度曲线...</div>
  681. </div>
  682. <div class="card">
  683. <h2>
  684. <span>🔬 4. 风扇转速 / 介入时机 vs 升温达标耗时关系探究对比</span>
  685. <a class="btn btn-outline" href="/api/compare/csv" download="fan_heating_comparison.csv">📥 导出多轮对比 CSV</a>
  686. </h2>
  687. <div class="svg-box" id="relation-chart-box" style="margin-bottom:10px;"></div>
  688. <table>
  689. <thead>
  690. <tr>
  691. <th>实验名称</th>
  692. <th>风扇转速 (初→介入)</th>
  693. <th>介入条件 / 实测触发</th>
  694. <th>最快达标腔体</th>
  695. <th>四腔Sensor全达标</th>
  696. <th>四腔内存全达标</th>
  697. <th>达标后追记点</th>
  698. </tr>
  699. </thead>
  700. <tbody id="compare-tbody"></tbody>
  701. </table>
  702. </div>
  703. </div>
  704. </main>
  705. <script>
  706. let allRuns = [];
  707. let currentSessionId = null;
  708. function fmtMMSS(sec) {
  709. if (sec === null || sec === undefined || sec === "") return "--";
  710. const s = Number(sec);
  711. const m = Math.floor(s / 60);
  712. const r = Math.round(s - m * 60);
  713. return `${s.toFixed(1)}s (${String(m).padStart(2,'0')}:${String(r).padStart(2,'0')})`;
  714. }
  715. function syncTargets() {
  716. const v = document.getElementById("cfg-pass-min").value || "70";
  717. for (let i = 1; i <= 4; i++) document.getElementById(`cfg-t${i}`).value = v;
  718. }
  719. function swapCtPairs() {
  720. const c1 = document.getElementById("map-c1").value;
  721. const c2 = document.getElementById("map-c2").value;
  722. const c3 = document.getElementById("map-c3").value;
  723. const c4 = document.getElementById("map-c4").value;
  724. document.getElementById("map-c1").value = c3;
  725. document.getElementById("map-c3").value = c1;
  726. document.getElementById("map-c2").value = c4;
  727. document.getElementById("map-c4").value = c2;
  728. }
  729. function collectConfig() {
  730. return {
  731. test_name: document.getElementById("cfg-name").value,
  732. overall_pass_min_temp_c: Number(document.getElementById("cfg-pass-min").value || 70),
  733. chamber_target_temp_c: {
  734. "1": Number(document.getElementById("cfg-t1").value || 70),
  735. "2": Number(document.getElementById("cfg-t2").value || 70),
  736. "3": Number(document.getElementById("cfg-t3").value || 70),
  737. "4": Number(document.getElementById("cfg-t4").value || 70),
  738. },
  739. ptc_duty_percent: Number(document.getElementById("cfg-ptc").value || 100),
  740. ssr_duty_percent: Number(document.getElementById("cfg-ssr").value || 100),
  741. initial_fan_duty_percent: Number(document.getElementById("cfg-fan-init").value || 0),
  742. active_fan_duty_percent: Number(document.getElementById("cfg-fan-active").value || 45),
  743. fan_intervention_mode: document.getElementById("cfg-fan-mode").value,
  744. fan_intervention_time_s: Number(document.getElementById("cfg-fan-time").value || 120),
  745. fan_intervention_ref_temp_c: Number(document.getElementById("cfg-fan-temp").value || 55),
  746. duration_s: Number(document.getElementById("cfg-duration").value || 360),
  747. mapping: {
  748. product: "6400-v2",
  749. chambers: {
  750. "1": { name: "腔体 1", bmc: document.getElementById("map-b1").value, ct: document.getElementById("map-c1").value },
  751. "2": { name: "腔体 2", bmc: document.getElementById("map-b2").value, ct: document.getElementById("map-c2").value },
  752. "3": { name: "腔体 3", bmc: document.getElementById("map-b3").value, ct: document.getElementById("map-c3").value },
  753. "4": { name: "腔体 4", bmc: document.getElementById("map-b4").value, ct: document.getElementById("map-c4").value }
  754. }
  755. }
  756. };
  757. }
  758. async function loadStatusAndRuns(preferId) {
  759. const stResp = await fetch("/api/status");
  760. const st = await stResp.json();
  761. document.getElementById("priv-badge").textContent =
  762. `容器权限: ${st.privileges.privileged ? "Privileged 全设备/内核栈就绪" : "标准容器"} | 固件 v${st.privileges.software_version} (${st.privileges.pwm_unified_hz}Hz)`;
  763. const runsResp = await fetch("/api/runs");
  764. const runsData = await runsResp.json();
  765. allRuns = runsData.runs || [];
  766. document.getElementById("runs-badge").textContent = `已存实验组: ${allRuns.length}`;
  767. const sel = document.getElementById("run-select");
  768. sel.innerHTML = "";
  769. allRuns.forEach(r => {
  770. const opt = document.createElement("option");
  771. opt.value = r.session_id;
  772. opt.textContent = `${r.session_id} — ${r.test_name}`;
  773. sel.appendChild(opt);
  774. });
  775. renderComparisonTable();
  776. renderRelationChart();
  777. const targetId = preferId || currentSessionId || (allRuns[0] && allRuns[0].session_id);
  778. if (targetId) {
  779. sel.value = targetId;
  780. await selectRun(targetId);
  781. }
  782. }
  783. async function selectRun(sid) {
  784. if (!sid) return;
  785. currentSessionId = sid;
  786. const resp = await fetch(`/api/runs/${encodeURIComponent(sid)}`);
  787. const data = await resp.json();
  788. const rep = data.report;
  789. const exp = rep.experiment_params;
  790. const hs = rep.hood_summary;
  791. const fr = rep.first_reached;
  792. document.getElementById("cur-run-title").textContent =
  793. `⏱️ 2. [${rep.session_id}] ${rep.test_name} — 四腔 Sensor 与内存达标耗时统计`;
  794. document.getElementById("export-links").innerHTML = `
  795. <a class="btn btn-outline" href="/api/runs/${encodeURIComponent(sid)}/export/csv" download="${sid}_summary.csv">📥 达标统计 CSV</a>
  796. <a class="btn btn-outline" href="/api/runs/${encodeURIComponent(sid)}/export/csv?kind=curves" download="${sid}_curves.csv">📥 全量曲线 CSV</a>
  797. <a class="btn btn-outline" href="/api/runs/${encodeURIComponent(sid)}/export/json" download="${sid}_report.json">📥 JSON 报告</a>
  798. `;
  799. document.getElementById("img-links").innerHTML = `
  800. <a class="btn btn-teal" href="/api/runs/${encodeURIComponent(sid)}/export/png" target="_blank" download="${sid}_curves.png">🖼 下载高清 PNG 图</a>
  801. <a class="btn btn-outline" href="/api/runs/${encodeURIComponent(sid)}/export/svg" target="_blank" download="${sid}_curves.svg">📐 下载矢量 SVG 图</a>
  802. `;
  803. const fanTxt = exp.fan_intervened
  804. ? `风扇已由 ${exp.initial_fan_duty_percent}% 切换至 ${exp.active_fan_duty_percent}% (${exp.fan_intervened_reason})`
  805. : `风扇保持 ${exp.current_fan_duty_percent}% (未触发介入)`;
  806. const firstTxt = fr.chamber_id
  807. ? `腔体 ${fr.chamber_id} 于 ${fr.elapsed_s.toFixed(1)}s 率先达到目标温度,系统未停止采集,已持续追加记录 ${fr.total_post_target_samples} 个腔体周期样本点!`
  808. : `当前尚未有腔体达到目标温度。`;
  809. document.getElementById("continuous-banner").textContent =
  810. `📌 实验工况: PTC=${exp.ptc_duty_percent}% | SSR=${exp.ssr_duty_percent}% | ${fanTxt} | ⏱️ ${firstTxt}`;
  811. const tbody = document.getElementById("chamber-tbody");
  812. tbody.innerHTML = "";
  813. for (let cid = 1; cid <= 4; cid++) {
  814. const st = rep.chambers[String(cid)];
  815. const tr = document.createElement("tr");
  816. const sOk = st.sensor_reached;
  817. const mOk = st.memory_reached;
  818. tr.innerHTML = `
  819. <td><b>腔体 ${cid}</b></td>
  820. <td>目标 ${st.target_temp_c.toFixed(0)}°C / 最低 ≥${st.pass_min_temp_c.toFixed(0)}°C</td>
  821. <td>${st.sensor_initial_c ?? '--'}°C → ${st.sensor_current_c ?? '--'}°C (峰值 ${st.sensor_peak_c ?? '--'}°C)</td>
  822. <td class="${sOk ? 'status-pass' : 'status-wait'}">${sOk ? '✅ ' + fmtMMSS(st.sensor_time_to_target_s) : '⏳ 未达标'}</td>
  823. <td>${st.memory_initial_c ?? '--'}°C → ${st.memory_current_c ?? '--'}°C (峰值 ${st.memory_peak_c ?? '--'}°C)</td>
  824. <td class="${mOk ? 'status-pass' : 'status-wait'}">${mOk ? '✅ ' + fmtMMSS(st.memory_time_to_target_s) : '⏳ 未达标'}</td>
  825. <td>${st.both_reached ? '✅ 双项达标' : '⏳ 部分/未达标'} (达标后持续记录 <b>+${st.post_target_samples}</b> 点)</td>
  826. `;
  827. tbody.appendChild(tr);
  828. }
  829. const sumTr = document.createElement("tr");
  830. sumTr.className = "highlight";
  831. sumTr.innerHTML = `
  832. <td>🏆 高温罩四腔整体</td>
  833. <td>四腔通过温度最低值 ≥${rep.overall_pass_min_temp_c.toFixed(0)}°C</td>
  834. <td>Sensor 已达标: ${hs.sensor_reached_count}/4 腔</td>
  835. <td class="${hs.sensor_all_4_reached ? 'status-pass' : 'status-wait'}">${hs.sensor_all_4_reached ? '🌟 ' + fmtMMSS(hs.hood_sensor_reach_time_s) : hs.sensor_reached_count + '/4 腔达标'}</td>
  836. <td>内存 已达标: ${hs.memory_reached_count}/4 腔</td>
  837. <td class="${hs.memory_all_4_reached ? 'status-pass' : 'status-wait'}">${hs.memory_all_4_reached ? '🌟 ' + fmtMMSS(hs.hood_memory_reach_time_s) : hs.memory_reached_count + '/4 腔达标'}</td>
  838. <td>总采样 ${rep.sample_count} 点 (总耗时 ${rep.elapsed_total_s.toFixed(0)}s)</td>
  839. `;
  840. tbody.appendChild(sumTr);
  841. const svgResp = await fetch(`/api/runs/${encodeURIComponent(sid)}/export/svg`);
  842. document.getElementById("curve-svg-container").innerHTML = await svgResp.text();
  843. }
  844. function renderComparisonTable() {
  845. const tbody = document.getElementById("compare-tbody");
  846. tbody.innerHTML = "";
  847. allRuns.forEach(r => {
  848. const exp = r.experiment_params || {};
  849. const hs = r.hood_summary || {};
  850. const fr = r.first_reached || {};
  851. const tr = document.createElement("tr");
  852. tr.style.cursor = "pointer";
  853. tr.onclick = () => {
  854. document.getElementById("run-select").value = r.session_id;
  855. selectRun(r.session_id);
  856. };
  857. const intv = exp.fan_intervened
  858. ? `${exp.fan_intervened_elapsed_s?.toFixed(0) ?? 0}s / ${exp.fan_intervened_temp_c ?? '--'}°C`
  859. : exp.fan_intervention_mode;
  860. tr.innerHTML = `
  861. <td style="text-align:left;"><b>${r.test_name}</b></td>
  862. <td>${exp.initial_fan_duty_percent}% → <b>${exp.active_fan_duty_percent}%</b></td>
  863. <td>${intv}</td>
  864. <td>${fr.chamber_id ? '腔' + fr.chamber_id + ' (' + fr.elapsed_s.toFixed(0) + 's)' : '--'}</td>
  865. <td class="${hs.sensor_all_4_reached ? 'status-pass' : 'status-wait'}">${fmtMMSS(hs.hood_sensor_reach_time_s)}</td>
  866. <td class="${hs.memory_all_4_reached ? 'status-pass' : 'status-wait'}">${fmtMMSS(hs.hood_memory_reach_time_s)}</td>
  867. <td>+${fr.total_post_target_samples ?? 0}</td>
  868. `;
  869. tbody.appendChild(tr);
  870. });
  871. }
  872. function renderRelationChart() {
  873. const box = document.getElementById("relation-chart-box");
  874. if (!allRuns.length) {
  875. box.textContent = "暂无实验数据";
  876. return;
  877. }
  878. const w = 680, h = 230, px0 = 55, py0 = 28, px1 = 650, py1 = 185;
  879. const pw = px1 - px0, ph = py1 - py0;
  880. const maxTime = Math.max(240, ...allRuns.map(r => Math.max(
  881. r.hood_summary?.hood_sensor_reach_time_s || 0,
  882. r.hood_summary?.hood_memory_reach_time_s || 0
  883. ))) * 1.15;
  884. let svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">`;
  885. svg += `<rect width="${w}" height="${h}" fill="#ffffff"/>`;
  886. svg += `<text x="${w/2}" y="17" text-anchor="middle" font-size="12" font-weight="bold" fill="#0f2747">各实验组【四腔Sensor全达标耗时】与【四腔内存全达标耗时】对比 (越短越快)</text>`;
  887. svg += `<rect x="${px0}" y="${py0}" width="${pw}" height="${ph}" fill="#f8fafc" stroke="#cbd5e1"/>`;
  888. for (let i = 0; i <= 4; i++) {
  889. const val = Math.round((maxTime * i) / 4);
  890. const y = py1 - (i / 4) * ph;
  891. svg += `<line x1="${px0}" y1="${y}" x2="${px1}" y2="${y}" stroke="#e2e8f0" stroke-dasharray="3,3"/>`;
  892. svg += `<text x="${px0-6}" y="${y+4}" text-anchor="end" font-size="10" fill="#64748b">${val}s</text>`;
  893. }
  894. const slotW = pw / allRuns.length;
  895. allRuns.forEach((r, idx) => {
  896. const cx = px0 + (idx + 0.5) * slotW;
  897. const sTime = r.hood_summary?.hood_sensor_reach_time_s;
  898. const mTime = r.hood_summary?.hood_memory_reach_time_s;
  899. const bw = Math.min(28, slotW * 0.32);
  900. if (sTime) {
  901. const bh = (sTime / maxTime) * ph;
  902. const by = py1 - bh;
  903. svg += `<rect x="${cx - bw - 2}" y="${by}" width="${bw}" height="${bh}" fill="#dc2626" rx="2"/>`;
  904. svg += `<text x="${cx - bw/2 - 2}" y="${by - 4}" text-anchor="middle" font-size="10" fill="#dc2626" font-weight="bold">${sTime.toFixed(0)}s</text>`;
  905. }
  906. if (mTime) {
  907. const bh = (mTime / maxTime) * ph;
  908. const by = py1 - bh;
  909. svg += `<rect x="${cx + 2}" y="${by}" width="${bw}" height="${bh}" fill="#1d4ed8" rx="2"/>`;
  910. svg += `<text x="${cx + bw/2 + 2}" y="${by - 4}" text-anchor="middle" font-size="10" fill="#1d4ed8" font-weight="bold">${mTime.toFixed(0)}s</text>`;
  911. }
  912. const exp = r.experiment_params || {};
  913. const lbl = `风扇${exp.initial_fan_duty_percent}→${exp.active_fan_duty_percent}%`;
  914. svg += `<text x="${cx}" y="${py1 + 15}" text-anchor="middle" font-size="10" fill="#1e293b" font-weight="bold">${lbl}</text>`;
  915. const sub = exp.fan_intervened ? `@${exp.fan_intervened_elapsed_s?.toFixed(0)}s/${exp.fan_intervened_temp_c ?? ''}°C` : exp.fan_intervention_mode;
  916. svg += `<text x="${cx}" y="${py1 + 29}" text-anchor="middle" font-size="9" fill="#64748b">${sub}</text>`;
  917. });
  918. svg += `<rect x="${px1-190}" y="${py0+6}" width="10" height="10" fill="#dc2626"/><text x="${px1-175}" y="${py0+15}" font-size="10" fill="#1e293b">Sensor达标耗时</text>`;
  919. svg += `<rect x="${px1-95}" y="${py0+6}" width="10" height="10" fill="#1d4ed8"/><text x="${px1-80}" y="${py0+15}" font-size="10" fill="#1e293b">内存达标耗时</text>`;
  920. svg += `</svg>`;
  921. box.innerHTML = svg;
  922. }
  923. async function runNewExperiment() {
  924. const cfg = collectConfig();
  925. const resp = await fetch("/api/test/start", {
  926. method: "POST",
  927. headers: { "Content-Type": "application/json" },
  928. body: JSON.stringify(cfg),
  929. });
  930. const res = await resp.json();
  931. await loadStatusAndRuns(res.session_id);
  932. }
  933. async function recalcCurrentRun() {
  934. if (!currentSessionId) return;
  935. const cfg = collectConfig();
  936. await fetch(`/api/runs/${encodeURIComponent(currentSessionId)}/recalculate`, {
  937. method: "POST",
  938. headers: { "Content-Type": "application/json" },
  939. body: JSON.stringify(cfg),
  940. });
  941. await loadStatusAndRuns(currentSessionId);
  942. }
  943. loadStatusAndRuns();
  944. </script>
  945. </body>
  946. </html>
  947. """
  948. def create_thermal_test_server(
  949. host: str = "0.0.0.0",
  950. port: int = 8766,
  951. storage_dir: Path | None = None,
  952. ) -> tuple[ThreadingHTTPServer, ThermalTestBackendState]:
  953. state = ThermalTestBackendState(storage_dir=storage_dir)
  954. priv_info = detect_container_privileges()
  955. class ThermalHandler(BaseHTTPRequestHandler):
  956. def _send_json(self, payload: Any, status: int = HTTPStatus.OK) -> None:
  957. body = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
  958. self.send_response(status)
  959. self.send_header("Content-Type", "application/json; charset=utf-8")
  960. self.send_header("Content-Length", str(len(body)))
  961. self.send_header("Access-Control-Allow-Origin", "*")
  962. self.end_headers()
  963. self.wfile.write(body)
  964. def _send_bytes(self, body: bytes, content_type: str, filename: str | None = None) -> None:
  965. self.send_response(HTTPStatus.OK)
  966. self.send_header("Content-Type", content_type)
  967. self.send_header("Content-Length", str(len(body)))
  968. self.send_header("Access-Control-Allow-Origin", "*")
  969. if filename:
  970. self.send_header("Content-Disposition", f'attachment; filename="{filename}"')
  971. self.end_headers()
  972. self.wfile.write(body)
  973. def _read_json(self) -> dict[str, Any]:
  974. length = int(self.headers.get("Content-Length", "0"))
  975. raw = self.rfile.read(length) if length > 0 else b"{}"
  976. return json.loads(raw.decode("utf-8")) if raw else {}
  977. def do_OPTIONS(self) -> None: # noqa: N802
  978. self.send_response(HTTPStatus.NO_CONTENT)
  979. self.send_header("Access-Control-Allow-Origin", "*")
  980. self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
  981. self.send_header("Access-Control-Allow-Headers", "Content-Type")
  982. self.end_headers()
  983. def do_GET(self) -> None: # noqa: N802
  984. parsed = urllib.parse.urlparse(self.path)
  985. path = parsed.path
  986. query = urllib.parse.parse_qs(parsed.query)
  987. if path in ("/", "/index.html"):
  988. self._send_bytes(WEB_HTML.encode("utf-8"), "text/html; charset=utf-8")
  989. return
  990. if path == "/api/status":
  991. with state.lock:
  992. total = len(state.runs)
  993. active_id = state.active_session_id
  994. self._send_json({
  995. "status": "pass",
  996. "service": "prod2u-thermal-test-backend",
  997. "privileges": priv_info,
  998. "total_runs": total,
  999. "active_session_id": active_id,
  1000. })
  1001. return
  1002. if path == "/api/runs":
  1003. with state.lock:
  1004. summaries = [
  1005. {
  1006. "session_id": sid,
  1007. "test_name": r["report"].get("test_name", sid),
  1008. "sample_count": r["report"].get("sample_count", 0),
  1009. "elapsed_total_s": r["report"].get("elapsed_total_s", 0.0),
  1010. "overall_pass_min_temp_c": r["report"].get("overall_pass_min_temp_c", 70.0),
  1011. "experiment_params": r["report"].get("experiment_params", {}),
  1012. "hood_summary": r["report"].get("hood_summary", {}),
  1013. "first_reached": r["report"].get("first_reached", {}),
  1014. }
  1015. for sid, r in state.runs.items()
  1016. ]
  1017. self._send_json({"status": "ok", "runs": summaries})
  1018. return
  1019. if path == "/api/compare/csv":
  1020. csv_text = state.export_multi_run_comparison_csv()
  1021. self._send_bytes(
  1022. csv_text.encode("utf-8-sig"),
  1023. "text/csv; charset=utf-8",
  1024. filename="fan_heating_comparison.csv",
  1025. )
  1026. return
  1027. if path.startswith("/api/runs/"):
  1028. parts = [urllib.parse.unquote(p) for p in path.split("/")[3:] if p]
  1029. if not parts:
  1030. self._send_json({"error": "missing session_id"}, status=HTTPStatus.BAD_REQUEST)
  1031. return
  1032. sid = parts[0]
  1033. try:
  1034. if len(parts) == 1:
  1035. with state.lock:
  1036. if sid not in state.runs:
  1037. raise KeyError(sid)
  1038. rec = state.runs[sid]
  1039. self._send_json(rec)
  1040. return
  1041. if len(parts) == 3 and parts[1] == "export":
  1042. fmt = parts[2].lower()
  1043. tt, store, cmap = state.build_session_and_store(sid)
  1044. if fmt == "csv":
  1045. kind = (query.get("kind") or ["summary"])[0]
  1046. if kind == "curves":
  1047. csv_str = gui.export_chamber_curves_csv(store, cmap)
  1048. self._send_bytes(csv_str.encode("utf-8-sig"), "text/csv; charset=utf-8", f"{sid}_curves.csv")
  1049. else:
  1050. csv_str = tt.export_summary_csv()
  1051. self._send_bytes(csv_str.encode("utf-8-sig"), "text/csv; charset=utf-8", f"{sid}_summary.csv")
  1052. return
  1053. if fmt == "json":
  1054. with state.lock:
  1055. rec = state.runs[sid]
  1056. self._send_bytes(
  1057. (json.dumps(rec, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
  1058. "application/json; charset=utf-8",
  1059. f"{sid}_report.json",
  1060. )
  1061. return
  1062. if fmt == "png":
  1063. png = gui.render_chamber_curves_png(
  1064. store, cmap, product=tt.product, board="6400V2.0", thermal_session=tt
  1065. )
  1066. self._send_bytes(png, "image/png", f"{sid}_curves.png")
  1067. return
  1068. if fmt == "svg":
  1069. svg = gui.render_chamber_curves_svg(
  1070. store, cmap, product=tt.product, board="6400V2.0", thermal_session=tt
  1071. )
  1072. self._send_bytes(svg.encode("utf-8"), "image/svg+xml; charset=utf-8", f"{sid}_curves.svg")
  1073. return
  1074. except KeyError:
  1075. self._send_json({"error": f"run not found: {sid}"}, status=HTTPStatus.NOT_FOUND)
  1076. return
  1077. self._send_json({"error": f"not found: {path}"}, status=HTTPStatus.NOT_FOUND)
  1078. def do_POST(self) -> None: # noqa: N802
  1079. parsed = urllib.parse.urlparse(self.path)
  1080. path = parsed.path
  1081. try:
  1082. payload = self._read_json()
  1083. if path == "/api/runs":
  1084. res = state.save_run(payload)
  1085. self._send_json(res)
  1086. return
  1087. if path == "/api/test/start":
  1088. run_data = state.start_new_test(payload)
  1089. self._send_json({
  1090. "status": "ok",
  1091. "session_id": run_data["session_id"],
  1092. "report": run_data["report"],
  1093. })
  1094. return
  1095. if path.startswith("/api/runs/") and path.endswith("/recalculate"):
  1096. sid = urllib.parse.unquote(path.split("/")[3])
  1097. updated = state.recalculate_run(sid, payload)
  1098. self._send_json({"status": "ok", "session_id": sid, "report": updated["report"]})
  1099. return
  1100. self._send_json({"error": f"unsupported POST path: {path}"}, status=HTTPStatus.NOT_FOUND)
  1101. except Exception as exc:
  1102. self._send_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST)
  1103. def log_message(self, format: str, *args: object) -> None: # noqa: A002
  1104. return
  1105. server = ThreadingHTTPServer((host, port), ThermalHandler)
  1106. return server, state
  1107. def main(argv: list[str] | None = None) -> int:
  1108. parser = argparse.ArgumentParser(description=__doc__)
  1109. parser.add_argument("--host", default="0.0.0.0", help="Bind address (default 0.0.0.0)")
  1110. parser.add_argument("--port", type=int, default=8766, help="Listen port (default 8766)")
  1111. parser.add_argument("--storage-dir", type=Path, default=None, help="Directory to persist thermal test runs")
  1112. parser.add_argument("--self-test", action="store_true", help="Run self-test of backend & frontend endpoints")
  1113. args = parser.parse_args(argv)
  1114. if args.self_test:
  1115. import tempfile
  1116. import urllib.request
  1117. with tempfile.TemporaryDirectory() as tmp:
  1118. srv, st = create_thermal_test_server("127.0.0.1", 0, storage_dir=Path(tmp))
  1119. port = srv.server_address[1]
  1120. t = threading.Thread(target=srv.serve_forever, daemon=True)
  1121. t.start()
  1122. try:
  1123. base = f"http://127.0.0.1:{port}"
  1124. status_data = json.loads(urllib.request.urlopen(f"{base}/api/status", timeout=5).read().decode("utf-8"))
  1125. assert status_data["status"] == "pass"
  1126. assert status_data["privileges"]["pwm_unified_hz"] == 20
  1127. assert status_data["total_runs"] >= 4
  1128. html_text = urllib.request.urlopen(f"{base}/", timeout=5).read().decode("utf-8")
  1129. assert "高温罩四腔体温度测试与风扇介入关系分析系统" in html_text
  1130. comp_csv = urllib.request.urlopen(f"{base}/api/compare/csv", timeout=5).read().decode("utf-8-sig")
  1131. assert "EXP-01-FAN0-TO-40-AT-55C" in comp_csv
  1132. finally:
  1133. srv.shutdown()
  1134. srv.server_close()
  1135. print("THERMAL_TEST_SERVER_SELF_TEST_PASS")
  1136. return 0
  1137. server, _ = create_thermal_test_server(args.host, args.port, storage_dir=args.storage_dir)
  1138. print(f"Thermal Test Backend & Web Frontend listening on http://{args.host}:{args.port}", flush=True)
  1139. try:
  1140. server.serve_forever()
  1141. except KeyboardInterrupt:
  1142. pass
  1143. finally:
  1144. server.server_close()
  1145. return 0
  1146. if __name__ == "__main__":
  1147. raise SystemExit(main())