#!/usr/bin/env python3
"""Prod2U 6400V2.0 / MRDIMM High-Temperature Hood Thermal Test Backend & Web Frontend.
Deployed inside the privileged container on 192.168.2.25 to execute remote or simulated
4-chamber heating tests, track per-chamber Sensor (CT) and Memory (BMC) time-to-target
(default 70°C), continue recording all chambers after any chamber reaches target first,
and analyze the relationship between fan speed, fan intervention timing/reference
temperature, and heating time to target temperature.
"""
from __future__ import annotations
import argparse
import datetime
import json
import math
import os
import sys
import threading
import time
import urllib.parse
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from tools import prod2u_gui as gui
def detect_container_privileges() -> dict[str, Any]:
"""Inspect current container privilege and device/kernel capabilities."""
dev_nodes = []
for candidate in ("/dev/mem", "/dev/kmsg", "/dev/net/tun", "/dev/bus/usb", "/dev/ttyS0"):
if os.path.exists(candidate):
dev_nodes.append(candidate)
cap_eff = ""
try:
status_txt = Path("/proc/self/status").read_text(encoding="utf-8", errors="replace")
for line in status_txt.splitlines():
if line.startswith("CapEff:"):
cap_eff = line.split(":", 1)[1].strip()
break
except Exception:
pass
is_privileged = cap_eff.endswith("fffffffff") or ("/dev/mem" in dev_nodes and os.geteuid() == 0)
return {
"host": os.environ.get("PROD2U_BACKEND_HOST_IP", "192.168.2.25"),
"container_hostname": os.uname().nodename if hasattr(os, "uname") else "linux-container",
"kernel": os.uname().release if hasattr(os, "uname") else "linux",
"uid": os.geteuid() if hasattr(os, "geteuid") else 0,
"cap_eff": cap_eff,
"privileged": is_privileged,
"device_nodes": dev_nodes,
"pwm_unified_hz": 20,
"software_version": getattr(gui, "SOFTWARE_VERSION", "3.3.0"),
"protocol": {"6400-v2": "SET36/GET90 (EPB1+SB1+SB2+4kHz80% buzzer)", "mrdimm": "SET69/GET65+DIAG8 (4kHz80% buzzer)"},
}
def simulate_thermal_run(
*,
session_id: str,
test_name: str,
product: str = "6400-v2",
overall_pass_min_temp_c: float = 70.0,
chamber_target_temp_c: dict[int, float] | None = None,
ptc_duty_percent: int = 100,
ssr_duty_percent: int = 100,
initial_fan_duty_percent: int = 0,
active_fan_duty_percent: int = 50,
fan_intervention_mode: str = "time_s",
fan_intervention_time_s: float = 120.0,
fan_intervention_ref_temp_c: float = 55.0,
fan_intervention_ref_source: str = "ct",
duration_s: int = 360,
step_s: int = 5,
base_timestamp: float = 1761800000.0,
mapping: gui.ChamberMappingConfig | None = None,
) -> dict[str, Any]:
"""Generate a physically representative 4-chamber heating curve run to study fan vs. reach time.
Models:
- PTC + SSR heating power driving air/sensor temperature and memory temperature
- Intake/exhaust fan convective heat transfer coupling:
* Too high fan speed from t=0 increases exhaust heat loss, slowing initial ramp;
* Zero fan speed heats the local heater/sensor fast but delays memory uniform heating;
* Optimal fan intervention (e.g. 30%~50% fan intervening at ~50-55°C or ~90-120s)
accelerates convective transfer from PTC to DIMM memory while minimizing exhaust loss.
- Continues recording all 4 chambers for the full `duration_s` even after the fastest
chamber reaches 70°C first.
"""
cmap = mapping or gui.ChamberMappingConfig.default(product)
store = gui.TemperatureCurveStore(max_capacity=max(7200, duration_s // max(1, step_s) + 10))
session = gui.ThermalTestSession(
product=product,
test_name=test_name,
overall_pass_min_temp_c=overall_pass_min_temp_c,
chamber_target_temp_c=chamber_target_temp_c or {1: 70.0, 2: 70.0, 3: 70.0, 4: 70.0},
ptc_duty_percent=ptc_duty_percent,
ssr_duty_percent=ssr_duty_percent,
initial_fan_duty_percent=initial_fan_duty_percent,
active_fan_duty_percent=active_fan_duty_percent,
fan_intervention_mode=fan_intervention_mode,
fan_intervention_time_s=fan_intervention_time_s,
fan_intervention_ref_temp_c=fan_intervention_ref_temp_c,
fan_intervention_ref_source=fan_intervention_ref_source,
)
session.start(start_timestamp=base_timestamp)
session.session_id = session_id
# Per-chamber initial state (slight natural asymmetry across Chambers 1..4: Chamber 2 & 3 share SSR2)
chamber_factors = {1: 1.03, 2: 1.06, 3: 1.00, 4: 0.96}
ct_temp = {1: 26.0, 2: 26.5, 3: 26.0, 4: 25.5}
bmc_temp = {1: 28.0, 2: 28.5, 3: 28.0, 4: 27.5}
heat_drive = (0.65 * (ptc_duty_percent / 100.0) + 0.35 * (ssr_duty_percent / 100.0))
for elapsed in range(0, duration_s + 1, max(1, step_s)):
ts = base_timestamp + float(elapsed)
t_lbl = datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S")
fan_pct = session.current_fan_duty_percent
fan_norm = fan_pct / 100.0
bmc_arr = [255] * 24
ct_arr = [255] * 27
ct_arr[0] = int(round(27.0 + min(12.0, elapsed * 0.02))) # U6 local
for cid in gui.CHAMBER_IDS:
cf = chamber_factors[cid]
if elapsed > 0:
dt = float(step_s)
# Air/Sensor heating rate: heater power minus exhaust cooling from fan
air_target_asymp = 26.0 + (68.0 * heat_drive * cf) * (1.0 - 0.18 * fan_norm)
air_tau = 95.0 / (0.85 + 0.45 * fan_norm)
ct_temp[cid] += (air_target_asymp - ct_temp[cid]) * (1.0 - math.exp(-dt / air_tau))
# Memory (BMC) heating rate: depends on convective coupling from air + direct radiation
# Convective coupling improves significantly when fan is 25%..60%
conv_coupling = 0.38 + 0.85 * math.sin(min(1.0, fan_norm) * math.pi * 0.65)
mem_target_asymp = ct_temp[cid] + 3.5 * heat_drive
mem_tau = 115.0 / conv_coupling
bmc_temp[cid] += (mem_target_asymp - bmc_temp[cid]) * (1.0 - math.exp(-dt / mem_tau))
c_int = max(0, min(254, int(round(ct_temp[cid]))))
b_int = max(0, min(254, int(round(bmc_temp[cid]))))
for idx_pos, ch_ct in enumerate(cmap.chambers[cid]["ct"]):
if 0 <= ch_ct < 27:
ct_arr[ch_ct] = max(0, min(254, c_int + (idx_pos % 2)))
for idx_pos, ch_bmc in enumerate(cmap.chambers[cid]["bmc"]):
if 0 <= ch_bmc < 24:
bmc_arr[ch_bmc] = max(0, min(254, b_int + (idx_pos % 3) - 1))
sample = store.record_raw_arrays(bmc_arr, ct_arr, timestamp=ts, time_label=t_lbl, source="THERMAL_TEST")
session.process_sample(sample, cmap)
session.stop(stop_timestamp=base_timestamp + float(duration_s))
return {
"session_id": session.session_id,
"report": session.summary(),
"mapping": cmap.to_dict(),
"samples": store.snapshot(),
}
class ThermalTestBackendState:
"""Thread-safe state manager for the 192.168.2.25 thermal test backend."""
def __init__(self, storage_dir: Path | None = None):
self.storage_dir = storage_dir or (ROOT / "logs" / "thermal_test_runs")
self.storage_dir.mkdir(parents=True, exist_ok=True)
self.lock = threading.Lock()
self.runs: dict[str, dict[str, Any]] = {}
self.active_session_id: str | None = None
self._bg_stop = threading.Event()
self._bg_thread: threading.Thread | None = None
self._load_persisted_runs()
if not self.runs:
self._seed_baseline_experiments()
def _load_persisted_runs(self) -> None:
for path in sorted(self.storage_dir.glob("*.json")):
try:
data = json.loads(path.read_text(encoding="utf-8"))
sid = data.get("session_id") or data.get("report", {}).get("session_id")
if sid:
self.runs[sid] = data
except Exception:
pass
def _persist_run(self, sid: str, data: dict[str, Any]) -> None:
try:
target = self.storage_dir / f"{sid}.json"
target.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
except Exception:
pass
def _seed_baseline_experiments(self) -> None:
"""Seed 4 baseline experiment runs demonstrating fan speed & intervention timing vs. 70°C reach time."""
presets = [
{
"session_id": "EXP-01-FAN0-TO-40-AT-55C",
"test_name": "实验1: 初始风扇0% → 参考温度55°C介入40%风扇 (最优均衡)",
"initial_fan_duty_percent": 0,
"active_fan_duty_percent": 40,
"fan_intervention_mode": "ref_temp_c",
"fan_intervention_ref_temp_c": 55.0,
"fan_intervention_time_s": 90.0,
},
{
"session_id": "EXP-02-FAN0-TO-50-AT-120S",
"test_name": "实验2: 初始风扇0% → 加热120s定时介入50%风扇",
"initial_fan_duty_percent": 0,
"active_fan_duty_percent": 50,
"fan_intervention_mode": "time_s",
"fan_intervention_time_s": 120.0,
"fan_intervention_ref_temp_c": 55.0,
},
{
"session_id": "EXP-03-FAN20-IMMEDIATE",
"test_name": "实验3: 全程20%风扇立即介入 (0s起转)",
"initial_fan_duty_percent": 20,
"active_fan_duty_percent": 20,
"fan_intervention_mode": "immediate",
"fan_intervention_time_s": 0.0,
"fan_intervention_ref_temp_c": 40.0,
},
{
"session_id": "EXP-04-FAN80-IMMEDIATE",
"test_name": "实验4: 全程80%高风速立即介入 (排风热损偏大对照)",
"initial_fan_duty_percent": 80,
"active_fan_duty_percent": 80,
"fan_intervention_mode": "immediate",
"fan_intervention_time_s": 0.0,
"fan_intervention_ref_temp_c": 40.0,
},
]
for idx, p in enumerate(presets):
run_data = simulate_thermal_run(
session_id=p["session_id"],
test_name=p["test_name"],
overall_pass_min_temp_c=70.0,
chamber_target_temp_c={1: 70.0, 2: 70.0, 3: 70.0, 4: 70.0},
ptc_duty_percent=100,
ssr_duty_percent=100,
initial_fan_duty_percent=p["initial_fan_duty_percent"],
active_fan_duty_percent=p["active_fan_duty_percent"],
fan_intervention_mode=p["fan_intervention_mode"],
fan_intervention_time_s=p["fan_intervention_time_s"],
fan_intervention_ref_temp_c=p["fan_intervention_ref_temp_c"],
duration_s=360,
step_s=5,
base_timestamp=1761800000.0 + idx * 1000.0,
)
self.runs[p["session_id"]] = run_data
self._persist_run(p["session_id"], run_data)
def save_run(self, payload: dict[str, Any]) -> dict[str, Any]:
report = payload.get("report") or {}
mapping_dict = payload.get("mapping") or gui.ChamberMappingConfig.default("6400-v2").to_dict()
samples = payload.get("samples") or []
sid = payload.get("session_id") or report.get("session_id") or datetime.datetime.now().strftime("TT-%Y%m%d-%H%M%S")
# If report was not pre-computed or samples were uploaded raw, compute report through ThermalTestSession
if not report or "chambers" not in report:
cmap = gui.ChamberMappingConfig.from_dict(mapping_dict)
store = gui.TemperatureCurveStore()
for s in samples:
store.record_raw_arrays(
s.get("bmc", []),
s.get("ct", []),
timestamp=s.get("timestamp"),
time_label=s.get("time_label"),
)
tt = gui.ThermalTestSession(
product=mapping_dict.get("product", "6400-v2"),
test_name=payload.get("test_name", f"上传测试 {sid}"),
overall_pass_min_temp_c=float(payload.get("overall_pass_min_temp_c", 70.0)),
)
tt.session_id = sid
report = tt.evaluate_from_store(store, cmap)
record = {
"session_id": sid,
"report": report,
"mapping": mapping_dict,
"samples": samples,
}
with self.lock:
self.runs[sid] = record
self._persist_run(sid, record)
total = len(self.runs)
return {"status": "ok", "session_id": sid, "total_runs": total, "report": report}
def recalculate_run(self, sid: str, params: dict[str, Any]) -> dict[str, Any]:
with self.lock:
if sid not in self.runs:
raise KeyError(f"未找到测试会话: {sid}")
rec = self.runs[sid]
mapping_data = params.get("mapping") or rec.get("mapping") or gui.ChamberMappingConfig.default("6400-v2").to_dict()
cmap = gui.ChamberMappingConfig.from_dict(mapping_data)
old_rep = rec.get("report", {})
old_exp = old_rep.get("experiment_params", {})
pass_min = float(params.get("overall_pass_min_temp_c", old_rep.get("overall_pass_min_temp_c", 70.0)))
raw_c_targets = params.get("chamber_target_temp_c") or old_rep.get("chamber_target_temp_c") or {}
c_targets = {cid: float(raw_c_targets.get(cid, raw_c_targets.get(str(cid), pass_min))) for cid in gui.CHAMBER_IDS}
tt = gui.ThermalTestSession(
product=old_rep.get("product", "6400-v2"),
test_name=str(params.get("test_name", old_rep.get("test_name", sid))),
overall_pass_min_temp_c=pass_min,
chamber_target_temp_c=c_targets,
bmc_eval_mode=str(params.get("bmc_eval_mode", old_rep.get("bmc_eval_mode", "avg"))),
ct_eval_mode=str(params.get("ct_eval_mode", old_rep.get("ct_eval_mode", "avg"))),
ptc_duty_percent=int(params.get("ptc_duty_percent", old_exp.get("ptc_duty_percent", 100))),
ssr_duty_percent=int(params.get("ssr_duty_percent", old_exp.get("ssr_duty_percent", 100))),
initial_fan_duty_percent=int(params.get("initial_fan_duty_percent", old_exp.get("initial_fan_duty_percent", 0))),
active_fan_duty_percent=int(params.get("active_fan_duty_percent", old_exp.get("active_fan_duty_percent", 50))),
fan_intervention_mode=str(params.get("fan_intervention_mode", old_exp.get("fan_intervention_mode", "time_s"))),
fan_intervention_time_s=float(params.get("fan_intervention_time_s", old_exp.get("fan_intervention_time_s", 120.0))),
fan_intervention_ref_temp_c=float(params.get("fan_intervention_ref_temp_c", old_exp.get("fan_intervention_ref_temp_c", 55.0))),
)
tt.session_id = sid
store = gui.TemperatureCurveStore()
for s in rec.get("samples", []):
store.record_raw_arrays(
s.get("bmc", []),
s.get("ct", []),
timestamp=s.get("timestamp"),
time_label=s.get("time_label"),
)
new_report = tt.evaluate_from_store(store, cmap, ignore_zero_ct=bool(params.get("ignore_zero_ct", False)))
updated = {
"session_id": sid,
"report": new_report,
"mapping": cmap.to_dict(),
"samples": rec.get("samples", []),
}
with self.lock:
self.runs[sid] = updated
self._persist_run(sid, updated)
return updated
def start_new_test(self, params: dict[str, Any]) -> dict[str, Any]:
sid = params.get("session_id") or datetime.datetime.now().strftime("TT-%Y%m%d-%H%M%S")
test_name = str(params.get("test_name") or f"远程升温测试 {sid}")
pass_min = float(params.get("overall_pass_min_temp_c", 70.0))
raw_ct = params.get("chamber_target_temp_c") or {}
c_targets = {cid: float(raw_ct.get(cid, raw_ct.get(str(cid), pass_min))) for cid in gui.CHAMBER_IDS}
mapping_dict = params.get("mapping")
cmap = (
gui.ChamberMappingConfig.from_dict(mapping_dict)
if isinstance(mapping_dict, dict)
else gui.ChamberMappingConfig.default("6400-v2")
)
duration_s = max(30, min(3600, int(params.get("duration_s", 360))))
step_s = max(1, min(60, int(params.get("step_s", 5))))
run_data = simulate_thermal_run(
session_id=sid,
test_name=test_name,
product=str(params.get("product", "6400-v2")),
overall_pass_min_temp_c=pass_min,
chamber_target_temp_c=c_targets,
ptc_duty_percent=int(params.get("ptc_duty_percent", 100)),
ssr_duty_percent=int(params.get("ssr_duty_percent", 100)),
initial_fan_duty_percent=int(params.get("initial_fan_duty_percent", 0)),
active_fan_duty_percent=int(params.get("active_fan_duty_percent", 50)),
fan_intervention_mode=str(params.get("fan_intervention_mode", "time_s")),
fan_intervention_time_s=float(params.get("fan_intervention_time_s", 120.0)),
fan_intervention_ref_temp_c=float(params.get("fan_intervention_ref_temp_c", 55.0)),
fan_intervention_ref_source=str(params.get("fan_intervention_ref_source", "ct")),
duration_s=duration_s,
step_s=step_s,
base_timestamp=time.time(),
mapping=cmap,
)
with self.lock:
self.runs[sid] = run_data
self.active_session_id = sid
self._persist_run(sid, run_data)
return run_data
def export_multi_run_comparison_csv(self) -> str:
headers = [
"session_id",
"test_name",
"overall_pass_min_c",
"ptc_duty_pct",
"ssr_duty_pct",
"initial_fan_pct",
"active_fan_pct",
"fan_intervention_mode",
"fan_intervened_elapsed_s",
"fan_intervened_temp_c",
"C1_sensor_reach_s",
"C1_memory_reach_s",
"C2_sensor_reach_s",
"C2_memory_reach_s",
"C3_sensor_reach_s",
"C3_memory_reach_s",
"C4_sensor_reach_s",
"C4_memory_reach_s",
"hood_sensor_reach_s",
"hood_memory_reach_s",
"first_reached_chamber",
"first_reached_elapsed_s",
"total_post_target_samples",
]
rows = [",".join(headers)]
with self.lock:
items = list(self.runs.values())
for item in items:
rep = item.get("report", {})
exp = rep.get("experiment_params", {})
hs = rep.get("hood_summary", {})
fr = rep.get("first_reached", {})
chs = rep.get("chambers", {})
def _fmt(v: Any) -> str:
return "" if v is None else f"{float(v):.1f}"
row = [
str(rep.get("session_id", "")),
str(rep.get("test_name", "")).replace(",", ";"),
_fmt(rep.get("overall_pass_min_temp_c", 70.0)),
str(exp.get("ptc_duty_percent", 100)),
str(exp.get("ssr_duty_percent", 100)),
str(exp.get("initial_fan_duty_percent", 0)),
str(exp.get("active_fan_duty_percent", 50)),
str(exp.get("fan_intervention_mode", "")),
_fmt(exp.get("fan_intervened_elapsed_s")),
_fmt(exp.get("fan_intervened_temp_c")),
]
for cid in ("1", "2", "3", "4"):
c_st = chs.get(cid, {})
row.append(_fmt(c_st.get("sensor_time_to_target_s")))
row.append(_fmt(c_st.get("memory_time_to_target_s")))
row.extend([
_fmt(hs.get("hood_sensor_reach_time_s")),
_fmt(hs.get("hood_memory_reach_time_s")),
"" if fr.get("chamber_id") is None else f"腔体{fr.get('chamber_id')}",
_fmt(fr.get("elapsed_s")),
str(fr.get("total_post_target_samples", 0)),
])
rows.append(",".join(row))
return "\n".join(rows) + "\n"
def build_session_and_store(self, sid: str) -> tuple[gui.ThermalTestSession, gui.TemperatureCurveStore, gui.ChamberMappingConfig]:
with self.lock:
if sid not in self.runs:
raise KeyError(f"未找到测试会话: {sid}")
rec = self.runs[sid]
rep = rec.get("report", {})
exp = rep.get("experiment_params", {})
cmap = gui.ChamberMappingConfig.from_dict(rec.get("mapping") or gui.ChamberMappingConfig.default("6400-v2").to_dict())
store = gui.TemperatureCurveStore()
for s in rec.get("samples", []):
store.record_raw_arrays(
s.get("bmc", []),
s.get("ct", []),
timestamp=s.get("timestamp"),
time_label=s.get("time_label"),
)
raw_ct = rep.get("chamber_target_temp_c") or {}
c_targets = {cid: float(raw_ct.get(cid, raw_ct.get(str(cid), 70.0))) for cid in gui.CHAMBER_IDS}
tt = gui.ThermalTestSession(
product=rep.get("product", "6400-v2"),
test_name=rep.get("test_name", sid),
overall_pass_min_temp_c=float(rep.get("overall_pass_min_temp_c", 70.0)),
chamber_target_temp_c=c_targets,
bmc_eval_mode=rep.get("bmc_eval_mode", "avg"),
ct_eval_mode=rep.get("ct_eval_mode", "avg"),
ptc_duty_percent=int(exp.get("ptc_duty_percent", 100)),
ssr_duty_percent=int(exp.get("ssr_duty_percent", 100)),
initial_fan_duty_percent=int(exp.get("initial_fan_duty_percent", 0)),
active_fan_duty_percent=int(exp.get("active_fan_duty_percent", 50)),
fan_intervention_mode=exp.get("fan_intervention_mode", "time_s"),
fan_intervention_time_s=float(exp.get("fan_intervention_time_s", 120.0)),
fan_intervention_ref_temp_c=float(exp.get("fan_intervention_ref_temp_c", 55.0)),
)
tt.session_id = sid
tt.evaluate_from_store(store, cmap)
return tt, store, cmap
WEB_HTML = r"""
6400V2.0 高温罩四腔温度测试与风扇介入分析系统 (192.168.2.25)
⏱️ 2. 当前实验各腔体 Sensor 温度与内存(BMC)温度达到目标温度所需时间统计
加载中...
| 腔体 / 区域 |
预期目标 / 最低通过标准 |
Sensor(CT) 初始 / 结束 / 峰值 |
Sensor(CT) 达到目标耗时 |
内存(BMC) 初始 / 结束 / 峰值 |
内存(BMC) 达到目标耗时 |
达标状态与持续记录数据验证 |
📈 3. 四腔体内存温度(BMC)与Sensor温度(CT)曲线图 (含目标温度阈值线)
正在渲染四腔体温度曲线...
🔬 4. 风扇转速 / 介入时机 vs 升温达标耗时关系探究对比
📥 导出多轮对比 CSV
| 实验名称 |
风扇转速 (初→介入) |
介入条件 / 实测触发 |
最快达标腔体 |
四腔Sensor全达标 |
四腔内存全达标 |
达标后追记点 |
"""
def create_thermal_test_server(
host: str = "0.0.0.0",
port: int = 8766,
storage_dir: Path | None = None,
) -> tuple[ThreadingHTTPServer, ThermalTestBackendState]:
state = ThermalTestBackendState(storage_dir=storage_dir)
priv_info = detect_container_privileges()
class ThermalHandler(BaseHTTPRequestHandler):
def _send_json(self, payload: Any, status: int = HTTPStatus.OK) -> None:
body = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(body)
def _send_bytes(self, body: bytes, content_type: str, filename: str | None = None) -> None:
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Access-Control-Allow-Origin", "*")
if filename:
self.send_header("Content-Disposition", f'attachment; filename="{filename}"')
self.end_headers()
self.wfile.write(body)
def _read_json(self) -> dict[str, Any]:
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length) if length > 0 else b"{}"
return json.loads(raw.decode("utf-8")) if raw else {}
def do_OPTIONS(self) -> None: # noqa: N802
self.send_response(HTTPStatus.NO_CONTENT)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
def do_GET(self) -> None: # noqa: N802
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
query = urllib.parse.parse_qs(parsed.query)
if path in ("/", "/index.html"):
self._send_bytes(WEB_HTML.encode("utf-8"), "text/html; charset=utf-8")
return
if path == "/api/status":
with state.lock:
total = len(state.runs)
active_id = state.active_session_id
self._send_json({
"status": "pass",
"service": "prod2u-thermal-test-backend",
"privileges": priv_info,
"total_runs": total,
"active_session_id": active_id,
})
return
if path == "/api/runs":
with state.lock:
summaries = [
{
"session_id": sid,
"test_name": r["report"].get("test_name", sid),
"sample_count": r["report"].get("sample_count", 0),
"elapsed_total_s": r["report"].get("elapsed_total_s", 0.0),
"overall_pass_min_temp_c": r["report"].get("overall_pass_min_temp_c", 70.0),
"experiment_params": r["report"].get("experiment_params", {}),
"hood_summary": r["report"].get("hood_summary", {}),
"first_reached": r["report"].get("first_reached", {}),
}
for sid, r in state.runs.items()
]
self._send_json({"status": "ok", "runs": summaries})
return
if path == "/api/compare/csv":
csv_text = state.export_multi_run_comparison_csv()
self._send_bytes(
csv_text.encode("utf-8-sig"),
"text/csv; charset=utf-8",
filename="fan_heating_comparison.csv",
)
return
if path.startswith("/api/runs/"):
parts = [urllib.parse.unquote(p) for p in path.split("/")[3:] if p]
if not parts:
self._send_json({"error": "missing session_id"}, status=HTTPStatus.BAD_REQUEST)
return
sid = parts[0]
try:
if len(parts) == 1:
with state.lock:
if sid not in state.runs:
raise KeyError(sid)
rec = state.runs[sid]
self._send_json(rec)
return
if len(parts) == 3 and parts[1] == "export":
fmt = parts[2].lower()
tt, store, cmap = state.build_session_and_store(sid)
if fmt == "csv":
kind = (query.get("kind") or ["summary"])[0]
if kind == "curves":
csv_str = gui.export_chamber_curves_csv(store, cmap)
self._send_bytes(csv_str.encode("utf-8-sig"), "text/csv; charset=utf-8", f"{sid}_curves.csv")
else:
csv_str = tt.export_summary_csv()
self._send_bytes(csv_str.encode("utf-8-sig"), "text/csv; charset=utf-8", f"{sid}_summary.csv")
return
if fmt == "json":
with state.lock:
rec = state.runs[sid]
self._send_bytes(
(json.dumps(rec, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
"application/json; charset=utf-8",
f"{sid}_report.json",
)
return
if fmt == "png":
png = gui.render_chamber_curves_png(
store, cmap, product=tt.product, board="6400V2.0", thermal_session=tt
)
self._send_bytes(png, "image/png", f"{sid}_curves.png")
return
if fmt == "svg":
svg = gui.render_chamber_curves_svg(
store, cmap, product=tt.product, board="6400V2.0", thermal_session=tt
)
self._send_bytes(svg.encode("utf-8"), "image/svg+xml; charset=utf-8", f"{sid}_curves.svg")
return
except KeyError:
self._send_json({"error": f"run not found: {sid}"}, status=HTTPStatus.NOT_FOUND)
return
self._send_json({"error": f"not found: {path}"}, status=HTTPStatus.NOT_FOUND)
def do_POST(self) -> None: # noqa: N802
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
try:
payload = self._read_json()
if path == "/api/runs":
res = state.save_run(payload)
self._send_json(res)
return
if path == "/api/test/start":
run_data = state.start_new_test(payload)
self._send_json({
"status": "ok",
"session_id": run_data["session_id"],
"report": run_data["report"],
})
return
if path.startswith("/api/runs/") and path.endswith("/recalculate"):
sid = urllib.parse.unquote(path.split("/")[3])
updated = state.recalculate_run(sid, payload)
self._send_json({"status": "ok", "session_id": sid, "report": updated["report"]})
return
self._send_json({"error": f"unsupported POST path: {path}"}, status=HTTPStatus.NOT_FOUND)
except Exception as exc:
self._send_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST)
def log_message(self, format: str, *args: object) -> None: # noqa: A002
return
server = ThreadingHTTPServer((host, port), ThermalHandler)
return server, state
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", default="0.0.0.0", help="Bind address (default 0.0.0.0)")
parser.add_argument("--port", type=int, default=8766, help="Listen port (default 8766)")
parser.add_argument("--storage-dir", type=Path, default=None, help="Directory to persist thermal test runs")
parser.add_argument("--self-test", action="store_true", help="Run self-test of backend & frontend endpoints")
args = parser.parse_args(argv)
if args.self_test:
import tempfile
import urllib.request
with tempfile.TemporaryDirectory() as tmp:
srv, st = create_thermal_test_server("127.0.0.1", 0, storage_dir=Path(tmp))
port = srv.server_address[1]
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
try:
base = f"http://127.0.0.1:{port}"
status_data = json.loads(urllib.request.urlopen(f"{base}/api/status", timeout=5).read().decode("utf-8"))
assert status_data["status"] == "pass"
assert status_data["privileges"]["pwm_unified_hz"] == 20
assert status_data["total_runs"] >= 4
html_text = urllib.request.urlopen(f"{base}/", timeout=5).read().decode("utf-8")
assert "高温罩四腔体温度测试与风扇介入关系分析系统" in html_text
comp_csv = urllib.request.urlopen(f"{base}/api/compare/csv", timeout=5).read().decode("utf-8-sig")
assert "EXP-01-FAN0-TO-40-AT-55C" in comp_csv
finally:
srv.shutdown()
srv.server_close()
print("THERMAL_TEST_SERVER_SELF_TEST_PASS")
return 0
server, _ = create_thermal_test_server(args.host, args.port, storage_dir=args.storage_dir)
print(f"Thermal Test Backend & Web Frontend listening on http://{args.host}:{args.port}", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
return 0
if __name__ == "__main__":
raise SystemExit(main())