| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240 |
- #!/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"""<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>6400V2.0 高温罩四腔温度测试与风扇介入分析系统 (192.168.2.25)</title>
- <style>
- :root {
- --bg: #f1f5f9;
- --card: #ffffff;
- --navy: #0f2747;
- --blue: #1d4ed8;
- --teal: #0d9488;
- --amber: #d97706;
- --red: #dc2626;
- --green: #15803d;
- --border: #cbd5e1;
- --text: #1e293b;
- --muted: #64748b;
- }
- * { box-sizing: border-box; }
- body {
- margin: 0;
- font-family: "Microsoft YaHei", "PingFang SC", "Noto Sans CJK SC", system-ui, sans-serif;
- background: var(--bg);
- color: var(--text);
- font-size: 13px;
- }
- header {
- background: linear-gradient(90deg, #0f2747 0%, #1e3a8a 100%);
- color: #fff;
- padding: 12px 20px;
- display: flex;
- justify-content: space-between;
- align-items: center;
- flex-wrap: wrap;
- gap: 10px;
- }
- header h1 { margin: 0; font-size: 18px; letter-spacing: 0.3px; }
- header .sub { font-size: 12px; color: #bfdbfe; margin-top: 3px; }
- .badge {
- display: inline-block;
- padding: 4px 10px;
- border-radius: 999px;
- font-size: 12px;
- font-weight: 600;
- background: rgba(255,255,255,0.15);
- color: #fff;
- }
- .badge.ok { background: #15803d; color: #fff; }
- .badge.warn { background: #d97706; color: #fff; }
- main { max-width: 1640px; margin: 12px auto; padding: 0 14px 28px; }
- .card {
- background: var(--card);
- border: 1px solid var(--border);
- border-radius: 8px;
- padding: 12px 14px;
- margin-bottom: 12px;
- box-shadow: 0 1px 2px rgba(15, 39, 71, 0.04);
- }
- .card h2 {
- margin: 0 0 10px 0;
- font-size: 14px;
- color: var(--navy);
- border-bottom: 1px solid #e2e8f0;
- padding-bottom: 6px;
- display: flex;
- justify-content: space-between;
- align-items: center;
- }
- .form-row {
- display: flex;
- flex-wrap: wrap;
- gap: 10px 14px;
- align-items: center;
- margin-bottom: 8px;
- }
- label { font-weight: 600; color: #334155; }
- input[type="text"], input[type="number"], select {
- padding: 5px 8px;
- border: 1px solid #94a3b8;
- border-radius: 4px;
- font-size: 13px;
- font-family: Consolas, monospace;
- }
- input[type="number"] { width: 72px; }
- button, .btn {
- padding: 6px 12px;
- border-radius: 5px;
- border: 1px solid transparent;
- font-size: 12px;
- font-weight: 600;
- cursor: pointer;
- text-decoration: none;
- display: inline-flex;
- align-items: center;
- gap: 4px;
- }
- .btn-primary { background: var(--blue); color: #fff; }
- .btn-primary:hover { background: #1e40af; }
- .btn-teal { background: var(--teal); color: #fff; }
- .btn-amber { background: var(--amber); color: #fff; }
- .btn-outline { background: #f8fafc; border-color: #94a3b8; color: #1e293b; }
- .btn-outline:hover { background: #e2e8f0; }
- table {
- width: 100%;
- border-collapse: collapse;
- font-size: 12px;
- }
- th, td {
- border: 1px solid #cbd5e1;
- padding: 7px 8px;
- text-align: center;
- }
- th { background: #f1f5f9; color: var(--navy); font-weight: 700; }
- tr:nth-child(even) { background: #f8fafc; }
- tr.highlight { background: #fef3c7; font-weight: 700; }
- .status-pass { color: var(--green); font-weight: 700; }
- .status-wait { color: var(--amber); font-weight: 700; }
- .grid-2 { display: grid; grid-template-columns: 1.15fr 0.85fr; gap: 12px; }
- @media (max-width: 1100px) { .grid-2 { grid-template-columns: 1fr; } }
- .svg-box {
- width: 100%;
- overflow-x: auto;
- background: #f8fafc;
- border: 1px solid #cbd5e1;
- border-radius: 6px;
- padding: 6px;
- text-align: center;
- }
- .svg-box svg { max-width: 100%; height: auto; }
- </style>
- </head>
- <body>
- <header>
- <div>
- <h1>🔥 6400V2.0 高温罩四腔体温度测试与风扇介入关系分析系统</h1>
- <div class="sub" id="hdr-sub">后端容器: 192.168.2.25 (全设备/内核栈权限) | 全板 PWM 统一 20Hz (50ms周期) | 先达标腔体锁定耗时后持续记录全腔数据</div>
- </div>
- <div>
- <span class="badge ok" id="priv-badge">内核/设备权限: 已就绪</span>
- <span class="badge" id="runs-badge">已存实验组: 0</span>
- </div>
- </header>
- <main>
- <!-- 1. Test Configuration & Mapping -->
- <div class="card">
- <h2>
- <span>⚙️ 1. 高温罩目标温度、腔体通道映射与风扇介入实验配置</span>
- <span>
- <button class="btn-outline" onclick="syncTargets()">🎯 将最低通过温度同步至四腔目标</button>
- <button class="btn-outline" onclick="swapCtPairs()">🔀 1/2与3/4腔Sensor对调</button>
- </span>
- </h2>
- <div class="form-row">
- <label>测试名称:</label>
- <input type="text" id="cfg-name" value="6400V2.0 风扇介入与升温耗时测试" style="width:230px;" />
- <label style="color:#b45309;">高温罩四腔通过最低温度(°C):</label>
- <input type="number" id="cfg-pass-min" value="70" min="20" max="200" step="1" />
- <label>腔1目标(°C):</label><input type="number" id="cfg-t1" value="70" />
- <label>腔2目标(°C):</label><input type="number" id="cfg-t2" value="70" />
- <label>腔3目标(°C):</label><input type="number" id="cfg-t3" value="70" />
- <label>腔4目标(°C):</label><input type="number" id="cfg-t4" value="70" />
- </div>
- <div class="form-row">
- <label>PTC加热(%):</label><input type="number" id="cfg-ptc" value="100" min="0" max="100" />
- <label>SSR加热(%):</label><input type="number" id="cfg-ssr" value="100" min="0" max="100" />
- <label>初始风扇转速(%):</label><input type="number" id="cfg-fan-init" value="0" min="0" max="100" />
- <label style="color:#1d4ed8;">介入后风扇转速(%):</label><input type="number" id="cfg-fan-active" value="45" min="0" max="100" />
- <label>风扇介入方式:</label>
- <select id="cfg-fan-mode">
- <option value="ref_temp_c">按参考温度触发介入 (°C)</option>
- <option value="time_s">按加热时间触发介入 (s)</option>
- <option value="immediate">立即介入 (0s)</option>
- <option value="manual">仅手动/纯观测</option>
- </select>
- <label>介入时间(s):</label><input type="number" id="cfg-fan-time" value="120" min="0" max="3600" />
- <label>介入参考温度(°C):</label><input type="number" id="cfg-fan-temp" value="55" min="20" max="200" />
- <label>测试总时长(s):</label><input type="number" id="cfg-duration" value="360" min="60" max="3600" />
- </div>
- <div class="form-row">
- <label>腔1映射(BMC / CT):</label>
- <input type="text" id="map-b1" value="0-5" style="width:68px;" /><input type="text" id="map-c1" value="1,2" style="width:58px;" />
- <label>腔2映射:</label>
- <input type="text" id="map-b2" value="6-11" style="width:68px;" /><input type="text" id="map-c2" value="3,4" style="width:58px;" />
- <label>腔3映射:</label>
- <input type="text" id="map-b3" value="12-17" style="width:68px;" /><input type="text" id="map-c3" value="5,6" style="width:58px;" />
- <label>腔4映射:</label>
- <input type="text" id="map-b4" value="18-23" style="width:68px;" /><input type="text" id="map-c4" value="7,8" style="width:58px;" />
- </div>
- <div class="form-row" style="margin-top:10px;">
- <button class="btn-primary" onclick="runNewExperiment()">▶️ 在后端执行升温测试 (先达标腔体持续记录)</button>
- <button class="btn-teal" onclick="recalcCurrentRun()">🔄 对当前选中实验重新应用目标温度/映射统计</button>
- <label style="margin-left:14px;">切换查看已存实验:</label>
- <select id="run-select" onchange="selectRun(this.value)" style="min-width:340px;"></select>
- </div>
- </div>
- <!-- 2. Current Run Reach-Time Table -->
- <div class="card">
- <h2>
- <span id="cur-run-title">⏱️ 2. 当前实验各腔体 Sensor 温度与内存(BMC)温度达到目标温度所需时间统计</span>
- <span id="export-links"></span>
- </h2>
- <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;">
- 加载中...
- </div>
- <table>
- <thead>
- <tr>
- <th>腔体 / 区域</th>
- <th>预期目标 / 最低通过标准</th>
- <th>Sensor(CT) 初始 / 结束 / 峰值</th>
- <th>Sensor(CT) 达到目标耗时</th>
- <th>内存(BMC) 初始 / 结束 / 峰值</th>
- <th>内存(BMC) 达到目标耗时</th>
- <th>达标状态与持续记录数据验证</th>
- </tr>
- </thead>
- <tbody id="chamber-tbody"></tbody>
- </table>
- </div>
- <!-- 3. Curves & Multi-Run Fan Relationship Study -->
- <div class="grid-2">
- <div class="card">
- <h2>
- <span>📈 3. 四腔体内存温度(BMC)与Sensor温度(CT)曲线图 (含目标温度阈值线)</span>
- <span id="img-links"></span>
- </h2>
- <div class="svg-box" id="curve-svg-container">正在渲染四腔体温度曲线...</div>
- </div>
- <div class="card">
- <h2>
- <span>🔬 4. 风扇转速 / 介入时机 vs 升温达标耗时关系探究对比</span>
- <a class="btn btn-outline" href="/api/compare/csv" download="fan_heating_comparison.csv">📥 导出多轮对比 CSV</a>
- </h2>
- <div class="svg-box" id="relation-chart-box" style="margin-bottom:10px;"></div>
- <table>
- <thead>
- <tr>
- <th>实验名称</th>
- <th>风扇转速 (初→介入)</th>
- <th>介入条件 / 实测触发</th>
- <th>最快达标腔体</th>
- <th>四腔Sensor全达标</th>
- <th>四腔内存全达标</th>
- <th>达标后追记点</th>
- </tr>
- </thead>
- <tbody id="compare-tbody"></tbody>
- </table>
- </div>
- </div>
- </main>
- <script>
- let allRuns = [];
- let currentSessionId = null;
- function fmtMMSS(sec) {
- if (sec === null || sec === undefined || sec === "") return "--";
- const s = Number(sec);
- const m = Math.floor(s / 60);
- const r = Math.round(s - m * 60);
- return `${s.toFixed(1)}s (${String(m).padStart(2,'0')}:${String(r).padStart(2,'0')})`;
- }
- function syncTargets() {
- const v = document.getElementById("cfg-pass-min").value || "70";
- for (let i = 1; i <= 4; i++) document.getElementById(`cfg-t${i}`).value = v;
- }
- function swapCtPairs() {
- const c1 = document.getElementById("map-c1").value;
- const c2 = document.getElementById("map-c2").value;
- const c3 = document.getElementById("map-c3").value;
- const c4 = document.getElementById("map-c4").value;
- document.getElementById("map-c1").value = c3;
- document.getElementById("map-c3").value = c1;
- document.getElementById("map-c2").value = c4;
- document.getElementById("map-c4").value = c2;
- }
- function collectConfig() {
- return {
- test_name: document.getElementById("cfg-name").value,
- overall_pass_min_temp_c: Number(document.getElementById("cfg-pass-min").value || 70),
- chamber_target_temp_c: {
- "1": Number(document.getElementById("cfg-t1").value || 70),
- "2": Number(document.getElementById("cfg-t2").value || 70),
- "3": Number(document.getElementById("cfg-t3").value || 70),
- "4": Number(document.getElementById("cfg-t4").value || 70),
- },
- ptc_duty_percent: Number(document.getElementById("cfg-ptc").value || 100),
- ssr_duty_percent: Number(document.getElementById("cfg-ssr").value || 100),
- initial_fan_duty_percent: Number(document.getElementById("cfg-fan-init").value || 0),
- active_fan_duty_percent: Number(document.getElementById("cfg-fan-active").value || 45),
- fan_intervention_mode: document.getElementById("cfg-fan-mode").value,
- fan_intervention_time_s: Number(document.getElementById("cfg-fan-time").value || 120),
- fan_intervention_ref_temp_c: Number(document.getElementById("cfg-fan-temp").value || 55),
- duration_s: Number(document.getElementById("cfg-duration").value || 360),
- mapping: {
- product: "6400-v2",
- chambers: {
- "1": { name: "腔体 1", bmc: document.getElementById("map-b1").value, ct: document.getElementById("map-c1").value },
- "2": { name: "腔体 2", bmc: document.getElementById("map-b2").value, ct: document.getElementById("map-c2").value },
- "3": { name: "腔体 3", bmc: document.getElementById("map-b3").value, ct: document.getElementById("map-c3").value },
- "4": { name: "腔体 4", bmc: document.getElementById("map-b4").value, ct: document.getElementById("map-c4").value }
- }
- }
- };
- }
- async function loadStatusAndRuns(preferId) {
- const stResp = await fetch("/api/status");
- const st = await stResp.json();
- document.getElementById("priv-badge").textContent =
- `容器权限: ${st.privileges.privileged ? "Privileged 全设备/内核栈就绪" : "标准容器"} | 固件 v${st.privileges.software_version} (${st.privileges.pwm_unified_hz}Hz)`;
- const runsResp = await fetch("/api/runs");
- const runsData = await runsResp.json();
- allRuns = runsData.runs || [];
- document.getElementById("runs-badge").textContent = `已存实验组: ${allRuns.length}`;
- const sel = document.getElementById("run-select");
- sel.innerHTML = "";
- allRuns.forEach(r => {
- const opt = document.createElement("option");
- opt.value = r.session_id;
- opt.textContent = `${r.session_id} — ${r.test_name}`;
- sel.appendChild(opt);
- });
- renderComparisonTable();
- renderRelationChart();
- const targetId = preferId || currentSessionId || (allRuns[0] && allRuns[0].session_id);
- if (targetId) {
- sel.value = targetId;
- await selectRun(targetId);
- }
- }
- async function selectRun(sid) {
- if (!sid) return;
- currentSessionId = sid;
- const resp = await fetch(`/api/runs/${encodeURIComponent(sid)}`);
- const data = await resp.json();
- const rep = data.report;
- const exp = rep.experiment_params;
- const hs = rep.hood_summary;
- const fr = rep.first_reached;
- document.getElementById("cur-run-title").textContent =
- `⏱️ 2. [${rep.session_id}] ${rep.test_name} — 四腔 Sensor 与内存达标耗时统计`;
- document.getElementById("export-links").innerHTML = `
- <a class="btn btn-outline" href="/api/runs/${encodeURIComponent(sid)}/export/csv" download="${sid}_summary.csv">📥 达标统计 CSV</a>
- <a class="btn btn-outline" href="/api/runs/${encodeURIComponent(sid)}/export/csv?kind=curves" download="${sid}_curves.csv">📥 全量曲线 CSV</a>
- <a class="btn btn-outline" href="/api/runs/${encodeURIComponent(sid)}/export/json" download="${sid}_report.json">📥 JSON 报告</a>
- `;
- document.getElementById("img-links").innerHTML = `
- <a class="btn btn-teal" href="/api/runs/${encodeURIComponent(sid)}/export/png" target="_blank" download="${sid}_curves.png">🖼 下载高清 PNG 图</a>
- <a class="btn btn-outline" href="/api/runs/${encodeURIComponent(sid)}/export/svg" target="_blank" download="${sid}_curves.svg">📐 下载矢量 SVG 图</a>
- `;
- const fanTxt = exp.fan_intervened
- ? `风扇已由 ${exp.initial_fan_duty_percent}% 切换至 ${exp.active_fan_duty_percent}% (${exp.fan_intervened_reason})`
- : `风扇保持 ${exp.current_fan_duty_percent}% (未触发介入)`;
- const firstTxt = fr.chamber_id
- ? `腔体 ${fr.chamber_id} 于 ${fr.elapsed_s.toFixed(1)}s 率先达到目标温度,系统未停止采集,已持续追加记录 ${fr.total_post_target_samples} 个腔体周期样本点!`
- : `当前尚未有腔体达到目标温度。`;
- document.getElementById("continuous-banner").textContent =
- `📌 实验工况: PTC=${exp.ptc_duty_percent}% | SSR=${exp.ssr_duty_percent}% | ${fanTxt} | ⏱️ ${firstTxt}`;
- const tbody = document.getElementById("chamber-tbody");
- tbody.innerHTML = "";
- for (let cid = 1; cid <= 4; cid++) {
- const st = rep.chambers[String(cid)];
- const tr = document.createElement("tr");
- const sOk = st.sensor_reached;
- const mOk = st.memory_reached;
- tr.innerHTML = `
- <td><b>腔体 ${cid}</b></td>
- <td>目标 ${st.target_temp_c.toFixed(0)}°C / 最低 ≥${st.pass_min_temp_c.toFixed(0)}°C</td>
- <td>${st.sensor_initial_c ?? '--'}°C → ${st.sensor_current_c ?? '--'}°C (峰值 ${st.sensor_peak_c ?? '--'}°C)</td>
- <td class="${sOk ? 'status-pass' : 'status-wait'}">${sOk ? '✅ ' + fmtMMSS(st.sensor_time_to_target_s) : '⏳ 未达标'}</td>
- <td>${st.memory_initial_c ?? '--'}°C → ${st.memory_current_c ?? '--'}°C (峰值 ${st.memory_peak_c ?? '--'}°C)</td>
- <td class="${mOk ? 'status-pass' : 'status-wait'}">${mOk ? '✅ ' + fmtMMSS(st.memory_time_to_target_s) : '⏳ 未达标'}</td>
- <td>${st.both_reached ? '✅ 双项达标' : '⏳ 部分/未达标'} (达标后持续记录 <b>+${st.post_target_samples}</b> 点)</td>
- `;
- tbody.appendChild(tr);
- }
- const sumTr = document.createElement("tr");
- sumTr.className = "highlight";
- sumTr.innerHTML = `
- <td>🏆 高温罩四腔整体</td>
- <td>四腔通过温度最低值 ≥${rep.overall_pass_min_temp_c.toFixed(0)}°C</td>
- <td>Sensor 已达标: ${hs.sensor_reached_count}/4 腔</td>
- <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>
- <td>内存 已达标: ${hs.memory_reached_count}/4 腔</td>
- <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>
- <td>总采样 ${rep.sample_count} 点 (总耗时 ${rep.elapsed_total_s.toFixed(0)}s)</td>
- `;
- tbody.appendChild(sumTr);
- const svgResp = await fetch(`/api/runs/${encodeURIComponent(sid)}/export/svg`);
- document.getElementById("curve-svg-container").innerHTML = await svgResp.text();
- }
- function renderComparisonTable() {
- const tbody = document.getElementById("compare-tbody");
- tbody.innerHTML = "";
- allRuns.forEach(r => {
- const exp = r.experiment_params || {};
- const hs = r.hood_summary || {};
- const fr = r.first_reached || {};
- const tr = document.createElement("tr");
- tr.style.cursor = "pointer";
- tr.onclick = () => {
- document.getElementById("run-select").value = r.session_id;
- selectRun(r.session_id);
- };
- const intv = exp.fan_intervened
- ? `${exp.fan_intervened_elapsed_s?.toFixed(0) ?? 0}s / ${exp.fan_intervened_temp_c ?? '--'}°C`
- : exp.fan_intervention_mode;
- tr.innerHTML = `
- <td style="text-align:left;"><b>${r.test_name}</b></td>
- <td>${exp.initial_fan_duty_percent}% → <b>${exp.active_fan_duty_percent}%</b></td>
- <td>${intv}</td>
- <td>${fr.chamber_id ? '腔' + fr.chamber_id + ' (' + fr.elapsed_s.toFixed(0) + 's)' : '--'}</td>
- <td class="${hs.sensor_all_4_reached ? 'status-pass' : 'status-wait'}">${fmtMMSS(hs.hood_sensor_reach_time_s)}</td>
- <td class="${hs.memory_all_4_reached ? 'status-pass' : 'status-wait'}">${fmtMMSS(hs.hood_memory_reach_time_s)}</td>
- <td>+${fr.total_post_target_samples ?? 0}</td>
- `;
- tbody.appendChild(tr);
- });
- }
- function renderRelationChart() {
- const box = document.getElementById("relation-chart-box");
- if (!allRuns.length) {
- box.textContent = "暂无实验数据";
- return;
- }
- const w = 680, h = 230, px0 = 55, py0 = 28, px1 = 650, py1 = 185;
- const pw = px1 - px0, ph = py1 - py0;
- const maxTime = Math.max(240, ...allRuns.map(r => Math.max(
- r.hood_summary?.hood_sensor_reach_time_s || 0,
- r.hood_summary?.hood_memory_reach_time_s || 0
- ))) * 1.15;
- let svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">`;
- svg += `<rect width="${w}" height="${h}" fill="#ffffff"/>`;
- svg += `<text x="${w/2}" y="17" text-anchor="middle" font-size="12" font-weight="bold" fill="#0f2747">各实验组【四腔Sensor全达标耗时】与【四腔内存全达标耗时】对比 (越短越快)</text>`;
- svg += `<rect x="${px0}" y="${py0}" width="${pw}" height="${ph}" fill="#f8fafc" stroke="#cbd5e1"/>`;
- for (let i = 0; i <= 4; i++) {
- const val = Math.round((maxTime * i) / 4);
- const y = py1 - (i / 4) * ph;
- svg += `<line x1="${px0}" y1="${y}" x2="${px1}" y2="${y}" stroke="#e2e8f0" stroke-dasharray="3,3"/>`;
- svg += `<text x="${px0-6}" y="${y+4}" text-anchor="end" font-size="10" fill="#64748b">${val}s</text>`;
- }
- const slotW = pw / allRuns.length;
- allRuns.forEach((r, idx) => {
- const cx = px0 + (idx + 0.5) * slotW;
- const sTime = r.hood_summary?.hood_sensor_reach_time_s;
- const mTime = r.hood_summary?.hood_memory_reach_time_s;
- const bw = Math.min(28, slotW * 0.32);
- if (sTime) {
- const bh = (sTime / maxTime) * ph;
- const by = py1 - bh;
- svg += `<rect x="${cx - bw - 2}" y="${by}" width="${bw}" height="${bh}" fill="#dc2626" rx="2"/>`;
- 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>`;
- }
- if (mTime) {
- const bh = (mTime / maxTime) * ph;
- const by = py1 - bh;
- svg += `<rect x="${cx + 2}" y="${by}" width="${bw}" height="${bh}" fill="#1d4ed8" rx="2"/>`;
- 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>`;
- }
- const exp = r.experiment_params || {};
- const lbl = `风扇${exp.initial_fan_duty_percent}→${exp.active_fan_duty_percent}%`;
- svg += `<text x="${cx}" y="${py1 + 15}" text-anchor="middle" font-size="10" fill="#1e293b" font-weight="bold">${lbl}</text>`;
- const sub = exp.fan_intervened ? `@${exp.fan_intervened_elapsed_s?.toFixed(0)}s/${exp.fan_intervened_temp_c ?? ''}°C` : exp.fan_intervention_mode;
- svg += `<text x="${cx}" y="${py1 + 29}" text-anchor="middle" font-size="9" fill="#64748b">${sub}</text>`;
- });
- 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>`;
- 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>`;
- svg += `</svg>`;
- box.innerHTML = svg;
- }
- async function runNewExperiment() {
- const cfg = collectConfig();
- const resp = await fetch("/api/test/start", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(cfg),
- });
- const res = await resp.json();
- await loadStatusAndRuns(res.session_id);
- }
- async function recalcCurrentRun() {
- if (!currentSessionId) return;
- const cfg = collectConfig();
- await fetch(`/api/runs/${encodeURIComponent(currentSessionId)}/recalculate`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(cfg),
- });
- await loadStatusAndRuns(currentSessionId);
- }
- loadStatusAndRuns();
- </script>
- </body>
- </html>
- """
- 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())
|