Просмотр исходного кода

feat(thermal): integrate 24ch MCU thermal console, bounded CSV recorder, and remote safety guardrails (v0.8.1.20)

XJKJ STL 2 недель назад
Родитель
Сommit
2049c1be4d

+ 1 - 1
Dockerfile

@@ -14,7 +14,7 @@ COPY config/ ./config/
 COPY build/native/stl_native_server /usr/local/bin/stl_native_server
 
 ARG STL_BUILD_COMMIT=vd012-native
-ARG STL_VERSION=0.8.1.19
+ARG STL_VERSION=0.8.1.20
 ENV STL_BUILD_COMMIT=${STL_BUILD_COMMIT} \
     STL_VERSION=${STL_VERSION}
 

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.8.1.19
+0.8.1.20

+ 8 - 2
docker-compose.yml

@@ -3,18 +3,24 @@ services:
     build:
       context: .
       args:
-        STL_VERSION: ${STL_VERSION:-0.8.1.19}
+        STL_VERSION: ${STL_VERSION:-0.8.1.20}
         STL_BUILD_COMMIT: ${STL_BUILD_COMMIT:-vd012-native}
-    image: xjkj-stl:0.8.1.19
+    image: xjkj-stl:0.8.1.20
     container_name: xjkj-stl-backend
     restart: unless-stopped
     stop_grace_period: 30s
     network_mode: host
+    device_cgroup_rules:
+      - "c 188:* rmw"
+      - "c 166:* rmw"
     volumes:
       - ./data:/app/data
       - ./config:/app/config:ro
       - ./web:/app/web:ro
       - ./contracts:/app/contracts:ro
+      - /dev:/dev
+      - /sys/class/tty:/sys/class/tty:ro
+      - /sys/devices:/sys/devices:ro
     environment:
       STL_BMC_S1_PASSWORD: ${STL_BMC_S1_PASSWORD:-Admin123@pl}
       STL_BMC_S2_PASSWORD: ${STL_BMC_S2_PASSWORD:-Admin123@pl}

Разница между файлами не показана из-за своего большого размера
+ 1696 - 0
docs/MCU_24CH_THERMAL_PROTOCOL_V1.1.md


+ 33 - 0
native/stl_accel/c_bridge.c

@@ -587,6 +587,39 @@ int c_open_tty_baud_raw(const char *path, int baud) {
     return fd;
 }
 
+/* Open MCU 24-ch thermal controller UART (115200 8N1 default) */
+int c_open_mcu_tty_baud_raw(const char *path, int baud) {
+    if (!path || path[0] == '\0') return -1;
+    int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
+    if (fd < 0) return -1;
+
+    struct termios tio;
+    if (tcgetattr(fd, &tio) != 0) {
+        close(fd);
+        return -1;
+    }
+    cfmakeraw(&tio);
+    speed_t sp = B115200;
+    if (baud == 921600) sp = B921600;
+    else if (baud == 460800) sp = B460800;
+    else if (baud == 230400) sp = B230400;
+    else if (baud == 57600) sp = B57600;
+    else if (baud == 38400) sp = B38400;
+    else if (baud == 9600) sp = B9600;
+    cfsetispeed(&tio, sp);
+    cfsetospeed(&tio, sp);
+    tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
+    tio.c_cflag |= (CS8 | CLOCAL | CREAD);
+    tio.c_iflag &= ~(IXON | IXOFF | IXANY);
+    tio.c_cc[VMIN]  = 0;
+    tio.c_cc[VTIME] = 0;
+    if (tcsetattr(fd, TCSANOW, &tio) != 0) {
+        close(fd);
+        return -1;
+    }
+    return fd;
+}
+
 int c_pty_open_tcp_serial(const char *host, int port, int timeout_ms) {
     if (!host || host[0] == '\0' || port <= 0) return -1;
     struct addrinfo hints, *res = NULL;

+ 25 - 0
native/stl_accel/src/actors.rs

@@ -164,6 +164,12 @@ pub enum StationMsg {
         full_path: String,
         force: bool,
     },
+    UpdateChamberTelemetry {
+        serial_path: String,
+        current_c: Option<f64>,
+        target_c: Option<f64>,
+        state: String,
+    },
 }
 
 pub enum IpmiJob {
@@ -189,6 +195,7 @@ pub enum IpmiJob {
     },
 }
 
+#[derive(Clone)]
 pub struct StationHandle {
     pub station_id: String,
     pub bit_index: u32,
@@ -1579,6 +1586,24 @@ pub fn spawn_station_actor(
                                 push_hub.broadcast_task_complete(&sig);
                             }
                         }
+                        StationMsg::UpdateChamberTelemetry {
+                            serial_path,
+                            current_c,
+                            target_c,
+                            state,
+                        } => {
+                            if st.chamber_serial_path != serial_path
+                                || st.chamber_current_c != current_c
+                                || st.chamber_target_c != target_c
+                                || st.chamber_state != state
+                            {
+                                st.chamber_serial_path = serial_path;
+                                st.chamber_current_c = current_c;
+                                st.chamber_target_c = target_c;
+                                st.chamber_state = state;
+                                state_dirty = true;
+                            }
+                        }
                     }
                 }
 

+ 156 - 2
native/stl_accel/src/api.rs

@@ -58,6 +58,7 @@ pub struct AppHub {
     pub queue_book: RwLock<QueueBook>,
     pub audit_book: Mutex<AuditEventBook>,
     pub pxe_state: RwLock<JsonVal>,
+    pub thermal_hub: Arc<crate::thermal_mcu::ThermalMcuHub>,
 }
 
 pub type ServerContext = AppHub;
@@ -207,6 +208,9 @@ impl AppHub {
             stations.insert(sid, handle);
         }
 
+        let thermal_hub =
+            crate::thermal_mcu::ThermalMcuHub::spawn(args.data_dir.clone(), stations.clone());
+
         let hub = Arc::new(Self {
             version: args.version.clone(),
             commit: args.commit.clone(),
@@ -231,6 +235,7 @@ impl AppHub {
                 client_sessions: BTreeMap::new(),
             }),
             pxe_state: RwLock::new(pxe_state),
+            thermal_hub,
         });
 
         // Prime initial zero-copy QtClean state snapshot immediately
@@ -473,6 +478,89 @@ impl AppHub {
         }
     }
 
+    fn execute_thermal_action(
+        &self,
+        params: &JsonVal,
+        default_operator: &str,
+    ) -> Result<JsonVal, String> {
+        let action = params.get_str_or("action", "");
+        if action.is_empty() {
+            return Err("缺少 action 字段".to_string());
+        }
+        let operator = params.get_str_or("operator", default_operator);
+        let sid = params.get_str_or("station_id", "S1");
+        let res = self.thermal_hub.execute_action(&action, params, &operator)?;
+        let should_audit = matches!(
+            action.as_str(),
+            "connect"
+                | "disconnect"
+                | "set_temp"
+                | "stop_preheat"
+                | "skip_preheat"
+                | "start_pid"
+                | "finish_control"
+                | "stop_heaters"
+                | "stop_fans"
+                | "emergency_stop"
+                | "pid_calibrate"
+                | "manual_duty"
+                | "start_record"
+                | "stop_record"
+        );
+        if should_audit {
+            let summary = match action.as_str() {
+                "connect" => format!(
+                    "连接 MCU 高温罩 ({})",
+                    params.get_str_or("mode", "serial")
+                ),
+                "disconnect" => "断开 MCU 高温罩连接".to_string(),
+                "set_temp" => format!(
+                    "MCU 开启设温控温: {}℃",
+                    params
+                        .get_i64("target_c")
+                        .or_else(|| params.get_i64("temp_c"))
+                        .unwrap_or(0)
+                ),
+                "stop_preheat" => "MCU 停止预加热/退出控温 (0x05)".to_string(),
+                "skip_preheat" => "MCU 跳过预热直接进入 PID (0x06)".to_string(),
+                "start_pid" => "MCU 直接启动 PID 闭环控温 (0x07)".to_string(),
+                "finish_control" => {
+                    let purge = params.get_bool("cooling_purge").unwrap_or(true);
+                    if purge {
+                        "MCU 控温结束并开启风扇吹扫散热 (0x08 00)".to_string()
+                    } else {
+                        "MCU 控温结束不吹扫 (0x08 01)".to_string()
+                    }
+                }
+                "stop_heaters" => "MCU 紧急停止并锁存全部加热块 (0x0A)".to_string(),
+                "stop_fans" => "MCU 停止并锁存全部风扇 (0x0B)".to_string(),
+                "emergency_stop" => "MCU 一键紧急全停(35路归零 + 停控温 + 锁死全部加热块)".to_string(),
+                "pid_calibrate" => format!(
+                    "MCU PID 参数标定: {}",
+                    params.get_str_or("expr", "(回读)")
+                ),
+                "manual_duty" => "MCU 35路全通道手动点火调试 (0x46)".to_string(),
+                "start_record" => format!(
+                    "开始本地高温测试全量记录: {}",
+                    res.get_str_or("csv_filename", "")
+                ),
+                "stop_record" => "停止本地高温测试全量记录".to_string(),
+                _ => format!("执行 MCU 温控动作: {}", action),
+            };
+            self.commit_audit(
+                &sid,
+                &operator,
+                AuditRecordDraft {
+                    category: "thermal_mcu".to_string(),
+                    action: action.clone(),
+                    summary,
+                    details: res.clone(),
+                },
+            );
+        }
+        Ok(res)
+    }
+
     fn execute_actor_command(
         &self,
         sid: &str,
@@ -1174,8 +1262,11 @@ impl AppHub {
                     return Ok(pending_item);
                 }
 
-                let exec_res =
-                    self.execute_actor_command(&sid, &sub_method, &sub_args, &operator);
+                let exec_res = if sub_method == "ThermalAction" {
+                    self.execute_thermal_action(&sub_args, &operator)
+                } else {
+                    self.execute_actor_command(&sid, &sub_method, &sub_args, &operator)
+                };
                 let completed_item = match exec_res {
                     Ok(res_val) => self.finalize_command(&cmd_id, |item| {
                         item.set("state", JsonVal::Str("succeeded".to_string()));
@@ -1285,6 +1376,14 @@ impl AppHub {
                 out.set("has_more", JsonVal::Bool(false));
                 Ok(out)
             }
+            "GetThermalConsole" => self.thermal_hub.get_snapshot(params),
+            "ThermalAction" => match self.execute_thermal_action(params, "web") {
+                Ok(res) => {
+                    self.refresh_and_broadcast_qt_state();
+                    Ok(res)
+                }
+                Err(msg) => Err(("FAILED_PRECONDITION".to_string(), msg)),
+            },
             other => Err((
                 "UNIMPLEMENTED".to_string(),
                 format!("不支持的 RPC 方法: {}", other),
@@ -1659,6 +1758,61 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
         return;
     }
 
+    if let Some(fname) = path_only.strip_prefix("/api/thermal/logs/") {
+        let safe = !fname.is_empty()
+            && !fname.contains("..")
+            && !fname.contains('/')
+            && !fname.contains('\\')
+            && fname
+                .bytes()
+                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'));
+        if !safe {
+            let resp = "HTTP/1.1 400 Bad Request\r\nContent-Length: 11\r\nConnection: close\r\n\r\nBad Request";
+            let _ = stream.write_all(resp.as_bytes());
+            return;
+        }
+        let log_path = hub.thermal_hub.logs_dir.join(fname);
+        let Ok(mut f) = fs::File::open(&log_path) else {
+            let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\nConnection: close\r\n\r\nNot Found";
+            let _ = stream.write_all(resp.as_bytes());
+            return;
+        };
+        let Ok(meta) = f.metadata() else {
+            let resp = "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 21\r\nConnection: close\r\n\r\nInternal Server Error";
+            let _ = stream.write_all(resp.as_bytes());
+            return;
+        };
+        let ctype = if fname.ends_with(".csv") {
+            "text/csv; charset=utf-8"
+        } else if fname.ends_with(".jsonl") {
+            "application/x-ndjson; charset=utf-8"
+        } else {
+            "application/octet-stream"
+        };
+        let hdr = format!(
+            "HTTP/1.1 200 OK\r\nContent-Type: {}\r\nContent-Length: {}\r\nContent-Disposition: attachment; filename=\"{}\"\r\nCache-Control: no-cache\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n",
+            ctype,
+            meta.len(),
+            fname
+        );
+        if stream.write_all(hdr.as_bytes()).is_ok() && method == "GET" {
+            let mut chunk = vec![0u8; 65536];
+            loop {
+                match f.read(&mut chunk) {
+                    Ok(0) => break,
+                    Ok(n) => {
+                        if stream.write_all(&chunk[..n]).is_err() {
+                            break;
+                        }
+                    }
+                    Err(_) => break,
+                }
+            }
+        }
+        let _ = stream.flush();
+        return;
+    }
+
     let rel_path = path_only.trim_start_matches('/');
     let rel_clean = if rel_path.is_empty() {
         "index.html"

+ 1 - 0
native/stl_accel/src/lib.rs

@@ -243,6 +243,7 @@ extern "C" {
 
     pub fn c_pty_open_serial_115200(path: *const u8) -> i32;
     pub fn c_open_tty_baud_raw(path: *const u8, baud: i32) -> i32;
+    pub fn c_open_mcu_tty_baud_raw(path: *const u8, baud: i32) -> i32;
     pub fn c_pty_open_tcp_serial(host: *const u8, port: i32, timeout_ms: i32) -> i32;
     pub fn c_pty_spawn_ssh_console(
         host: *const u8,

+ 270 - 0
native/stl_accel/src/main.rs

@@ -13,6 +13,7 @@ mod lib;
 mod pxe;
 mod results;
 mod storage;
+mod thermal_mcu;
 mod workflow;
 
 use api::{handle_http_client, AppHub};
@@ -1235,4 +1236,273 @@ mod tests {
         drop(dut_sock);
         let _ = std::fs::remove_dir_all(&tmp_dir);
     }
+
+    #[test]
+    fn test_mcu_thermal_protocol_v1_1_mock_and_csv_recorder() {
+        use crate::thermal_mcu::{
+            bytes_to_hex_upper, encode_mcu_frame, uid_bytes_to_std_hex, McuParsedItem,
+            McuStreamParser,
+        };
+
+        // 1. Verify golden protocol v1.1 frames from MCU_24CH_THERMAL_PROTOCOL_V1.1.md
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x01, &[50])), "AA 55 01 01 32 7C");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x01, &[63])), "AA 55 01 01 3F 5F");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x01, &[68])), "AA 55 01 01 44 39");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x01, &[70])), "AA 55 01 01 46 37");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x01, &[72])), "AA 55 01 01 48 1D");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x01, &[77])), "AA 55 01 01 4D 06");
+
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x02, &[])), "AA 55 02 00 AD");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x81, &[0x01])), "AA 55 81 01 01 EE");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x81, &[0x00])), "AA 55 81 01 00 E9");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x81, &[0x02])), "AA 55 81 01 02 E7");
+
+        let mut bmc24_sample = [0x46u8; 24];
+        bmc24_sample[0] = 0x44;
+        bmc24_sample[1] = 0x45;
+        bmc24_sample[2] = 0x46;
+        bmc24_sample[3] = 0x47;
+        assert_eq!(
+            bytes_to_hex_upper(&encode_mcu_frame(0x82, &bmc24_sample)),
+            "AA 55 82 18 44 45 46 47 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 5C"
+        );
+
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x03, &[])), "AA 55 03 00 B8");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x83, &[0x01])), "AA 55 83 01 01 38");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x04, &[])), "AA 55 04 00 D3");
+        assert_eq!(
+            bytes_to_hex_upper(&encode_mcu_frame(
+                0x84,
+                &[0x01, 0x02, 0x03, 0x04, 0x00, 0x64, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]
+            )),
+            "AA 55 84 0C 01 02 03 04 00 64 01 00 00 00 00 00 F8"
+        );
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x05, &[])), "AA 55 05 00 C6");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x06, &[])), "AA 55 06 00 F9");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x07, &[])), "AA 55 07 00 EC");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x08, &[0x00])), "AA 55 08 01 00 D8");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x08, &[0x01])), "AA 55 08 01 01 DF");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x09, &[])), "AA 55 09 00 3A");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x0A, &[])), "AA 55 0A 00 05");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x0B, &[])), "AA 55 0B 00 10");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x0D, &[])), "AA 55 0D 00 6E");
+
+        // ST UID section 12.3 golden samples
+        assert_eq!(
+            bytes_to_hex_upper(&encode_mcu_frame(
+                0x89,
+                &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB]
+            )),
+            "AA 55 89 0C 00 11 22 33 44 55 66 77 88 99 AA BB 25"
+        );
+        let uid_raw: [u8; 12] = [
+            0x3E, 0x00, 0x2B, 0x00, 0x09, 0x51, 0x33, 0x30, 0x35, 0x33, 0x37, 0x36,
+        ];
+        assert_eq!(uid_bytes_to_std_hex(&uid_raw), "002B003E3033510936373335");
+
+        // PID online calibration section 12.5
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x0C, b"")), "AA 55 0C 00 7B");
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0x0C, b"P2.5")), "AA 55 0C 04 50 32 2E 35 0F");
+        assert_eq!(
+            bytes_to_hex_upper(&encode_mcu_frame(0x0C, b"P2.5I0.125D0.04")),
+            "AA 55 0C 0F 50 32 2E 35 49 30 2E 31 32 35 44 30 2E 30 34 B0"
+        );
+        assert_eq!(
+            bytes_to_hex_upper(&encode_mcu_frame(0x8C, b"OK P=2.5 I=0.125 D=0.04")),
+            "AA 55 8C 17 4F 4B 20 50 3D 32 2E 35 20 49 3D 30 2E 31 32 35 20 44 3D 30 2E 30 34 3D"
+        );
+
+        // CT7428 8-ch section 12.6
+        assert_eq!(
+            bytes_to_hex_upper(&encode_mcu_frame(0x8D, &[0x19; 8])),
+            "AA 55 8D 08 19 19 19 19 19 19 19 19 1A"
+        );
+
+        // 35-ch manual duty section 12.7
+        let duty35_zero = [0u8; 35];
+        assert_eq!(
+            bytes_to_hex_upper(&encode_mcu_frame(0x46, &duty35_zero)),
+            "AA 55 46 23 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 AF"
+        );
+        assert_eq!(bytes_to_hex_upper(&encode_mcu_frame(0xC6, &[0x01])), "AA 55 C6 01 01 7E");
+
+        // 0xF0 status vectors section 13.5
+        assert_eq!(
+            bytes_to_hex_upper(&encode_mcu_frame(0xF0, &[0x00, 0x46, 0x00, 0, 0, 0, 0, 0])),
+            "AA 55 F0 08 00 46 00 00 00 00 00 00 F5"
+        );
+        assert_eq!(
+            bytes_to_hex_upper(&encode_mcu_frame(0xF0, &[0x02, 0x46, 0x00, 0, 0, 0, 0, 0])),
+            "AA 55 F0 08 02 46 00 00 00 00 00 00 D3"
+        );
+        assert_eq!(
+            bytes_to_hex_upper(&encode_mcu_frame(0xF0, &[0x04, 0x46, 0x00, 0, 0, 0, 0, 0])),
+            "AA 55 F0 08 04 46 00 00 00 00 00 00 B9"
+        );
+
+        // 2. Verify interleaved ASCII log + fragmented binary stream parser
+        let mut parser = McuStreamParser::new();
+        let f_f0 = encode_mcu_frame(0xF0, &[0x04, 85, 0x12, 0, 0, 0, 0, 0]);
+        let mut stream = b"[MCU] boot ok\r\n".to_vec();
+        stream.extend_from_slice(&f_f0[..4]);
+        let items1 = parser.feed(&stream, 1000);
+        assert_eq!(items1.len(), 1);
+        assert_eq!(items1[0], McuParsedItem::AsciiLine("[MCU] boot ok".to_string()));
+        let items2 = parser.feed(&f_f0[4..], 1010);
+        assert_eq!(items2.len(), 1);
+        match &items2[0] {
+            McuParsedItem::Frame { cmd, payload, .. } => {
+                assert_eq!(*cmd, 0xF0);
+                assert_eq!(payload[0], 0x04);
+                assert_eq!(payload[1], 85);
+            }
+            _ => panic!("expected 0xF0 binary frame"),
+        }
+
+        // 3. Verify path validation + Mock MCU end-to-end control + ASCII SNAP telemetry + CSV/JSONL recording
+        let tmp_dir = std::env::temp_dir().join(format!("stl_mcu_test_{}", now_ms()));
+        let _ = std::fs::create_dir_all(&tmp_dir);
+        let args = ServerArgs {
+            config_path: Path::new("/workspace/XJKJ-STL/config/backend.example.json")
+                .to_path_buf(),
+            data_dir: tmp_dir.clone(),
+            web_dir: Path::new("/workspace/XJKJ-STL/web").to_path_buf(),
+            contracts_path: Path::new("/workspace/XJKJ-STL/contracts/firmware-vd012.json")
+                .to_path_buf(),
+            web_listen: "127.0.0.1:0".to_string(),
+            tftp_listen: "disabled".to_string(),
+            version: "0.8.1.20".to_string(),
+            commit: "test".to_string(),
+        };
+        let hub = AppHub::init_for_test(&args);
+
+        // Qt-Clean must strictly reject GetThermalConsole / ThermalAction
+        assert!(hub
+            .dispatch_rpc("GetThermalConsole", &JsonVal::obj(), true)
+            .is_err());
+
+        // Reject non-/dev traversal paths
+        let bad_path = hub.dispatch_rpc(
+            "ThermalAction",
+            &parse_json(r#"{"action":"connect","mode":"serial","serial_path":"../etc/passwd"}"#)
+                .unwrap(),
+            false,
+        );
+        assert!(bad_path.is_err());
+
+        // Connect Mock MCU
+        let conn_ok = hub
+            .dispatch_rpc(
+                "ThermalAction",
+                &parse_json(r#"{"action":"connect","mode":"mock","station_id":"S1"}"#).unwrap(),
+                false,
+            )
+            .unwrap();
+        assert_eq!(conn_ok.get_str_or("mode", ""), "mock");
+
+        // Configure overtemp cutoff to 120 C, then start 85 C control with auto CSV recording
+        hub.dispatch_rpc(
+            "ThermalAction",
+            &parse_json(r#"{"action":"configure_safety","lease_sec":300,"overtemp_cutoff_c":120}"#)
+                .unwrap(),
+            false,
+        )
+        .unwrap();
+
+        let set_ok = hub
+            .dispatch_rpc(
+                "ThermalAction",
+                &parse_json(
+                    r#"{"action":"set_temp","target_c":85,"auto_pre_stop":true,"direct_pid":true,"station_id":"S1"}"#,
+                )
+                .unwrap(),
+                false,
+            )
+            .unwrap();
+        assert_eq!(set_ok.get_bool("accepted"), Some(true));
+
+        // Let actor sample & flush at least 2 points
+        std::thread::sleep(Duration::from_millis(1250));
+
+        // Add live operator note mark
+        hub.dispatch_rpc(
+            "ThermalAction",
+            &parse_json(r#"{"action":"add_mark","note":"AMT 85C soak mark"}"#).unwrap(),
+            false,
+        )
+        .unwrap();
+        std::thread::sleep(Duration::from_millis(1050));
+
+        let snap1 = hub
+            .dispatch_rpc(
+                "GetThermalConsole",
+                &parse_json(r#"{"since_seq":0,"include_frames":true}"#).unwrap(),
+                false,
+            )
+            .unwrap();
+        assert_eq!(
+            snap1.get("mcu").and_then(|m| m.get_i64("target_c")),
+            Some(85)
+        );
+        assert_eq!(
+            snap1.get("recorder").and_then(|r| r.get_bool("active")),
+            Some(true)
+        );
+        let pts1 = snap1.get_arr("points_delta").unwrap();
+        assert!(!pts1.is_empty());
+        let last_seq = pts1.last().unwrap().get_i64("seq").unwrap();
+
+        // Incremental delta poll returns only newer points (zero O(N) resend!)
+        let snap2 = hub
+            .dispatch_rpc(
+                "GetThermalConsole",
+                &parse_json(&format!(r#"{{"since_seq":{}}}"#, last_seq)).unwrap(),
+                false,
+            )
+            .unwrap();
+        assert_eq!(snap2.get_bool("reset_ring"), Some(false));
+
+        // Finish control + stop recording and verify CSV content on disk
+        hub.dispatch_rpc(
+            "ThermalAction",
+            &parse_json(r#"{"action":"finish_control","cooling_purge":true}"#).unwrap(),
+            false,
+        )
+        .unwrap();
+        hub.dispatch_rpc(
+            "ThermalAction",
+            &parse_json(r#"{"action":"stop_record"}"#).unwrap(),
+            false,
+        )
+        .unwrap();
+
+        let snap3 = hub
+            .dispatch_rpc("GetThermalConsole", &JsonVal::obj(), false)
+            .unwrap();
+        let files = snap3
+            .get("recorder")
+            .and_then(|r| r.get_arr("files"))
+            .unwrap();
+        assert!(!files.is_empty());
+        let csv_name = files
+            .iter()
+            .find(|f| f.get_str_or("filename", "").ends_with(".csv"))
+            .unwrap()
+            .get_str_or("filename", "");
+        let csv_text = std::fs::read_to_string(tmp_dir.join("thermal-logs").join(&csv_name)).unwrap();
+        assert!(csv_text.contains("MCU_CH01"));
+        assert!(csv_text.contains("IPMI_CPU0_A"));
+        assert!(csv_text.contains("CT01"));
+        assert!(csv_text.contains("ptc_avg_duty"));
+        assert!(csv_text.contains("AMT 85C soak mark"));
+
+        // Disconnect cleanly
+        hub.dispatch_rpc(
+            "ThermalAction",
+            &parse_json(r#"{"action":"disconnect"}"#).unwrap(),
+            false,
+        )
+        .unwrap();
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+    }
 }

Разница между файлами не показана из-за своего большого размера
+ 3725 - 0
native/stl_accel/src/thermal_mcu.rs


Разница между файлами не показана из-за своего большого размера
+ 270 - 10
web/index.html


+ 73 - 0
web/style.css

@@ -653,3 +653,76 @@ body:not([data-current-page="overview"]) .workspace-split { grid-template-column
 @media(max-width:750px) { .pxe-variant-grid,.pxe-cfg-grid { grid-template-columns:1fr; } }
 
 
+
+/* 3. MCU 24-Ch High-Temperature Thermal Console & Stream Recorder */
+.thermal-console-panel { display:flex;flex-direction:column;gap:14px; }
+.thermal-top-header { display:flex;justify-content:space-between;align-items:flex-start;gap:16px;flex-wrap:wrap;padding-bottom:10px;border-bottom:1px solid var(--line); }
+.thermal-top-header h2 { display:flex;align-items:center;gap:10px;flex-wrap:wrap; }
+.thermal-top-actions { display:flex;align-items:center;gap:8px;flex-wrap:wrap; }
+.th-card { background:#fff;border:1px solid var(--line);border-radius:10px;padding:15px 17px;display:flex;flex-direction:column;gap:11px;min-width:0; }
+.th-conn-card { background:var(--surface-soft); }
+.th-row { display:flex;flex-wrap:wrap;align-items:flex-end;gap:12px 16px; }
+.th-field { display:flex;flex-direction:column;gap:5px;font-size:12px;color:#556c7a;font-weight:550; }
+.th-inline-group { display:flex;align-items:center;gap:7px; }
+.th-conn-btns { display:flex;align-items:center;gap:8px;margin-left:auto; }
+.th-status-strip { display:flex;flex-wrap:wrap;align-items:center;gap:7px;padding-top:8px;border-top:1px dashed #d8e3ea; }
+.th-pill { display:inline-flex;align-items:center;padding:3px 9px;border-radius:5px;font-size:11.5px;font-weight:550;background:#edf2f6;color:#5d7082; }
+.th-pill.is-ok { background:#e7f6f2;color:#0e7c6d; }
+.th-pill.is-active { background:#e7f3ff;color:#1d6fa5; }
+.th-pill.is-warn { background:#fff5e4;color:#a46b13; }
+.th-pill.is-err { background:#fff0f1;color:#c5424b; }
+.th-meta-text { margin-left:auto;font:11.5px var(--mono);color:#657888; }
+.th-safety-bar { display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:10px;padding:8px 12px;background:#f0f8f6;border:1px solid #cce6df;border-radius:7px;font-size:12px;color:#305c54; }
+.th-safety-left, .th-safety-right { display:flex;flex-wrap:wrap;align-items:center;gap:9px; }
+.th-safety-bar select, .th-safety-bar input { padding:4px 8px;font-size:12px; }
+.th-two-col { display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;align-items:start; }
+.th-card-head { display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap; }
+.th-temp-control-row { display:flex;flex-wrap:wrap;align-items:flex-end;gap:12px; }
+.th-target-input-wrap { display:flex;flex-direction:column;gap:4px;font-size:12px;font-weight:600;color:#2c4d59; }
+.th-target-input-wrap input { width:110px;font:700 18px var(--mono);color:var(--primary);padding:6px 10px; }
+.th-presets { display:flex;flex-wrap:wrap;gap:5px;flex:1; }
+.th-check-row { display:flex;flex-wrap:wrap;gap:14px;font-size:12px;color:#556e7b; }
+.th-cmd-grid { display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:7px; }
+.th-actuator-box { margin-top:4px;padding:10px 12px;background:#f8fbfc;border:1px solid #dde8ee;border-radius:8px;display:flex;flex-direction:column;gap:8px; }
+.th-actuator-head { display:flex;justify-content:space-between;align-items:center;gap:8px;flex-wrap:wrap;font-size:12px;color:#3b5d6a; }
+.th-actuator-metrics { display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:8px; }
+.th-act-item { background:#fff;border:1px solid #e3ecef;border-radius:6px;padding:6px 8px;display:flex;flex-direction:column;gap:2px; }
+.th-act-item span { font-size:10.5px;color:#788c99; }
+.th-act-item strong { font:600 12.5px var(--mono);color:#2d4f5c; }
+.th-act-item.is-hot strong { color:#c95f18; }
+.th-rec-controls { display:flex;flex-wrap:wrap;align-items:flex-end;gap:10px 14px;font-size:12px;color:#546c79; }
+.th-rec-controls>label:not(.check-label) { display:flex;flex-direction:column;gap:4px; }
+.th-rec-btns { display:flex;align-items:center;gap:8px;flex-wrap:wrap; }
+.th-mark-bar { display:flex;gap:8px; }
+.th-mark-bar input { flex:1;font-size:12px; }
+.th-rec-stats { font:11.5px var(--mono);color:#5c7482;background:#f6fafb;padding:7px 10px;border-radius:6px;border:1px solid #e2ecef; }
+.th-files-wrap { max-height:195px;overflow:auto;border:1px solid var(--line);border-radius:7px; }
+.th-files-table th, .th-files-table td { padding:6px 9px;font-size:11.5px; }
+.th-chart-legend { display:flex;flex-wrap:wrap;gap:10px;font-size:11.5px;color:#546c78; }
+.th-chart-legend label { display:inline-flex;align-items:center;gap:5px;cursor:pointer;user-select:none; }
+.th-chart-legend i { width:10px;height:10px;border-radius:2px;display:inline-block; }
+.th-canvas-wrap { position:relative;width:100%;height:240px;background:#fbfdfe;border:1px solid #e1ebf0;border-radius:8px;overflow:hidden; }
+.th-canvas-wrap canvas { width:100%;height:100%;display:block; }
+.th-canvas-tooltip { position:absolute;top:8px;left:56px;background:rgba(30,45,59,.92);color:#fff;padding:6px 10px;border-radius:6px;font:11px/1.5 var(--mono);pointer-events:none;z-index:3; }
+.th-ct8-strip { display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:7px; }
+.th-ct-cell { background:#f4f9fb;border:1px solid #dbe7ee;border-radius:6px;padding:6px 8px;display:flex;justify-content:space-between;align-items:center;font-size:11.5px; }
+.th-ct-cell span { color:#6e8491; }
+.th-ct-cell strong { font:600 13px var(--mono);color:#235b73; }
+.th-bmc24-grid { display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:7px; }
+.th-slot-card { border:1px solid #e1e9ef;border-radius:7px;padding:7px 9px;background:#fafcfd;display:flex;flex-direction:column;gap:3px; }
+.th-slot-card.is-valid { background:#f2fbf8;border-color:#c4e6dc; }
+.th-slot-card.is-warn { background:#fffaf0;border-color:#f0d7a7; }
+.th-slot-card.is-hot { background:#fff3f3;border-color:#efb9bf; }
+.th-slot-top { display:flex;justify-content:space-between;align-items:center;font-size:11px;color:#6c808e; }
+.th-slot-vals { display:flex;justify-content:space-between;align-items:baseline;gap:6px; }
+.th-slot-mcu { font:700 14px var(--mono);color:#1f4f59; }
+.th-slot-ipmi { font:11px var(--mono);color:#6c578c; }
+.th-debug-drawer summary { cursor:pointer;display:flex;align-items:center;gap:10px; }
+.th-debug-body { margin-top:12px;padding-top:12px;border-top:1px solid var(--line); }
+.th-subbox { background:#f8fbfc;border:1px solid #e0eaef;border-radius:8px;padding:11px 13px;display:flex;flex-direction:column;gap:8px;min-width:0; }
+.th-subbox h4 { margin:0;font-size:12.5px;color:#355966; }
+.th-manual-grid { display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px; }
+.th-manual-grid label { display:flex;flex-direction:column;gap:4px;font-size:11.5px;color:#57707d; }
+.th-log-pre { margin:0;height:190px;overflow:auto;padding:9px 10px;background:#1a242f;color:#d6e4f0;border-radius:6px;font:11px/1.55 var(--mono);white-space:pre-wrap;overflow-wrap:anywhere; }
+@media(max-width:1150px) { .th-two-col { grid-template-columns:1fr; }.th-cmd-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }.th-bmc24-grid { grid-template-columns:repeat(4,minmax(0,1fr)); }.th-ct8-strip { grid-template-columns:repeat(4,minmax(0,1fr)); }.th-actuator-metrics { grid-template-columns:repeat(3,minmax(0,1fr)); } }
+@media(max-width:680px) { .th-bmc24-grid,.th-ct8-strip,.th-manual-grid,.th-actuator-metrics { grid-template-columns:repeat(2,minmax(0,1fr)); } }

+ 969 - 0
web/thermal-console.js

@@ -0,0 +1,969 @@
+// thermal-console.js — High-Performance Zero-Lag MCU 24-Ch Thermal Console & Stream Recorder UI (v0.8.1.20)
+(() => {
+  const MAX_POINTS = 720;
+  const SERIES_META = [
+    { key: 'target', label: '目标温度', color: '#cf4b52', dashed: true },
+    { key: 'bmc_avg', label: 'MCU BMC均温', color: '#0d8b80', dashed: false },
+    { key: 'bmc_max', label: 'MCU BMC最高', color: '#e67e22', dashed: false },
+    { key: 'ct_avg', label: 'CT7428腔均温', color: '#2980b9', dashed: false },
+    { key: 'ipmi_avg', label: 'IPMI内存均温', color: '#8e44ad', dashed: false },
+  ];
+
+  const el = id => document.getElementById(id);
+  const rootPanel = document.querySelector('.thermal-console-panel');
+  if (!rootPanel) return;
+
+  let sinceSeq = 0;
+  let chartRing = [];
+  let pollInFlight = false;
+  let pollTimer = null;
+  let rafPending = false;
+  let hoverRatio = null;
+  let prefsSyncedOnce = false;
+  let lastFilesSig = '';
+  let lastAsciiSig = '';
+  let lastFrameSig = '';
+  const enabledSeries = new Set(['target', 'bmc_avg', 'bmc_max', 'ct_avg', 'ipmi_avg']);
+
+  // Pre-build fixed DOM cells once (zero DOM node creation during multi-day runs!)
+  const ctCells = [];
+  const ctGrid = el('th-ct8-grid');
+  for (let i = 0; i < 8; i++) {
+    const d = document.createElement('div');
+    d.className = 'th-ct-cell';
+    const sp = document.createElement('span');
+    sp.textContent = `CT0${i + 1}`;
+    const st = document.createElement('strong');
+    st.textContent = '--';
+    d.append(sp, st);
+    ctGrid.appendChild(d);
+    ctCells.push({ val: st, prev: '' });
+  }
+
+  const slotCells = [];
+  const bmcGrid = el('th-bmc24-grid');
+  for (let i = 0; i < 24; i++) {
+    const cpu = i < 12 ? 0 : 1;
+    const ch = String.fromCharCode(65 + (i % 12));
+    const card = document.createElement('div');
+    card.className = 'th-slot-card';
+    const top = document.createElement('div');
+    top.className = 'th-slot-top';
+    const lbl = document.createElement('span');
+    lbl.textContent = `CH${String(i + 1).padStart(2, '0')} · CPU${cpu}_${ch}`;
+    const diffSpan = document.createElement('span');
+    diffSpan.textContent = '';
+    top.append(lbl, diffSpan);
+
+    const vals = document.createElement('div');
+    vals.className = 'th-slot-vals';
+    const mcuStrong = document.createElement('span');
+    mcuStrong.className = 'th-slot-mcu';
+    mcuStrong.textContent = 'MCU: --';
+    const ipmiSpan = document.createElement('span');
+    ipmiSpan.className = 'th-slot-ipmi';
+    ipmiSpan.textContent = 'IPMI: --';
+    vals.append(mcuStrong, ipmiSpan);
+
+    card.append(top, vals);
+    bmcGrid.appendChild(card);
+    slotCells.push({ card, mcuStrong, ipmiSpan, diffSpan, prevCls: 'th-slot-card', prevMcu: '', prevIpmi: '', prevDiff: '' });
+  }
+
+  function setTextIfChanged(node, text) {
+    if (node && node.textContent !== text) node.textContent = text;
+  }
+
+  function setStatus(msg, isError = false) {
+    const bar = el('action-status');
+    if (!bar) return;
+    bar.textContent = msg;
+    bar.classList.toggle('error', Boolean(isError));
+  }
+
+  function fmtBytes(b) {
+    const n = Number(b) || 0;
+    if (n < 1024) return `${n} B`;
+    if (n < 1048576) return `${(n / 1024).toFixed(1)} KB`;
+    return `${(n / 1048576).toFixed(2)} MB`;
+  }
+
+  function fmtTimeShort(ms) {
+    if (!ms) return '--:--:--';
+    const d = new Date(ms);
+    return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
+  }
+
+  function stateLabel(st) {
+    switch (st) {
+      case 'disconnected': return '未连接';
+      case 'offline': return '串口已开 · 等待0xF0';
+      case 'cpld_lost': return 'CPLD采集失联';
+      case 'preheating': return '预加热升温中';
+      case 'pid': return 'PID闭环控温中';
+      case 'manual': return '手动出力保持';
+      case 'cooling_purge': return '风扇余温吹扫中';
+      case 'idle': return '在线待机 (0W)';
+      default: return st || '未知';
+    }
+  }
+
+  async function callThermalAction(action, extra = {}) {
+    const params = Object.assign({
+      action,
+      station_id: el('th-bound-station')?.value || 'S1',
+    }, extra);
+    return window.stlTransport.call('ThermalAction', params, 10000);
+  }
+
+  function updateModeVisibility() {
+    const mode = el('th-conn-mode').value;
+    el('th-serial-wrap').classList.toggle('hidden', mode !== 'serial');
+    el('th-tcp-wrap').classList.toggle('hidden', mode !== 'tcp');
+  }
+  el('th-conn-mode').addEventListener('change', updateModeVisibility);
+  updateModeVisibility();
+
+  async function scanPorts(silent = false) {
+    try {
+      const res = await callThermalAction('scan_ports');
+      const ports = Array.isArray(res?.ports) ? res.ports : [];
+      const dl = el('th-serial-datalist');
+      dl.replaceChildren();
+      for (const p of ports) {
+        const opt = document.createElement('option');
+        opt.value = p.path;
+        opt.label = p.label || p.path;
+        dl.appendChild(opt);
+      }
+      if (ports.length > 0 && !el('th-serial-path').value) {
+        const usb = ports.find(p => String(p.resolved_path || p.path).includes('ttyUSB')) || ports[0];
+        el('th-serial-path').value = usb.resolved_path || usb.path;
+      }
+      if (!silent) {
+        setStatus(ports.length
+          ? `已扫描到 ${ports.length} 个串口入口: ${ports.map(p => p.path).join(', ')}`
+          : '当前未扫描到 USB 串口设备,可切换为「离线虚拟仿真 (Mock)」测试全部功能');
+      }
+    } catch (err) {
+      if (!silent) setStatus(`扫描串口失败: ${err.message}`, true);
+    }
+  }
+
+  el('btn-th-scan-ports').addEventListener('click', () => scanPorts(false));
+
+  el('btn-th-connect').addEventListener('click', async () => {
+    const mode = el('th-conn-mode').value;
+    const payload = {
+      mode,
+      serial_path: el('th-serial-path').value.trim() || '/dev/ttyUSB0',
+      serial_baud: 115200,
+      tcp_host: el('th-tcp-host').value.trim() || '127.0.0.1',
+      tcp_port: Number(el('th-tcp-port').value) || 4002,
+    };
+    try {
+      await callThermalAction('connect', payload);
+      setStatus(`高温罩连接成功 (${mode === 'serial' ? payload.serial_path : mode}),正在读取 UID / 固件版本 / 实时温度...`);
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`连接高温罩失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-disconnect').addEventListener('click', async () => {
+    try {
+      await callThermalAction('disconnect');
+      setStatus('已断开 MCU 高温罩连接');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`断开失败: ${err.message}`, true);
+    }
+  });
+
+  el('th-bound-station').addEventListener('change', async () => {
+    try {
+      await callThermalAction('bind_station', { station_id: el('th-bound-station').value });
+      setStatus(`已切换高温罩关联工位至 ${el('th-bound-station').value}`);
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`切换关联工位失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-zero-probe').addEventListener('click', async () => {
+    try {
+      const res = await callThermalAction('zero_power_probe');
+      setStatus(`零功率安全链路体检完成 (0W 不动加热/风扇) · PID应答: ${res?.text || 'OK'}`);
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`零功率自检失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-estop').addEventListener('click', async () => {
+    try {
+      await callThermalAction('emergency_stop');
+      setStatus('已执行一键紧急全停:35路占空比清零 + 停止预热/PID (0x05) + 锁死全部加热块 (0x0A)');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`紧急全停命令异常: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-save-safety').addEventListener('click', async () => {
+    const leaseSec = Number(el('th-safety-lease').value) || 0;
+    const cutoff = Number(el('th-overtemp-cutoff').value) || 95;
+    try {
+      await callThermalAction('configure_safety', { lease_sec: leaseSec, overtemp_cutoff_c: cutoff });
+      setStatus(`远程安全护栏已更新:看门狗=${leaseSec > 0 ? leaseSec + '秒' : '不限时'},超温熔断=${cutoff}℃`);
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`保存安全护栏失败: ${err.message}`, true);
+    }
+  });
+
+  el('th-safety-lease').addEventListener('change', () => el('btn-th-save-safety').click());
+
+  el('btn-th-renew-lease').addEventListener('click', async () => {
+    try {
+      const res = await callThermalAction('renew_lease');
+      setStatus(`远程安全限时看门狗已续期重置 (${res?.lease_remaining_sec || 0} 秒)`);
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`续期失败: ${err.message}`, true);
+    }
+  });
+
+  document.querySelectorAll('.th-preset-btn').forEach(btn => {
+    btn.addEventListener('click', () => {
+      el('th-target-input').value = btn.dataset.temp;
+    });
+  });
+
+  el('btn-th-set-temp').addEventListener('click', async () => {
+    const targetC = Math.round(Number(el('th-target-input').value));
+    if (!Number.isFinite(targetC) || targetC < 0 || targetC > 254) {
+      setStatus('目标温度必须为 0 ~ 254 之间的整数 ℃', true);
+      return;
+    }
+    try {
+      await callThermalAction('set_temp', {
+        target_c: targetC,
+        auto_pre_stop: el('th-chk-auto-prestop').checked,
+        direct_pid: el('th-chk-direct-pid').checked,
+      });
+      setStatus(`已向 MCU 下发设温开启指令: ${targetC}℃ (0x01)`);
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`设温失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-skip-preheat').addEventListener('click', async () => {
+    try {
+      await callThermalAction('skip_preheat');
+      setStatus('已下发跳过预加热进入 PID 闭环指令 (0x06)');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`跳过预加热失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-start-pid').addEventListener('click', async () => {
+    try {
+      await callThermalAction('start_pid');
+      setStatus('已下发直接开启 PID 闭环指令 (0x07)');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`开启 PID 失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-stop-preheat').addEventListener('click', async () => {
+    try {
+      await callThermalAction('stop_preheat');
+      setStatus('已停止预加热与 PID 闭环,32路输出已清零 (0x05)');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`停止控温失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-finish-purge').addEventListener('click', async () => {
+    try {
+      await callThermalAction('finish_control', { cooling_purge: true });
+      setStatus('已结束控温并开启 8 路风扇 100% 余温吹扫散热 (0x08 00)');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`控温结束命令失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-finish-nopurge').addEventListener('click', async () => {
+    try {
+      await callThermalAction('finish_control', { cooling_purge: false });
+      setStatus('已结束控温并清零输出,不开启风扇吹扫 (0x08 01)');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`控温结束命令失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-stop-heaters').addEventListener('click', async () => {
+    try {
+      await callThermalAction('stop_heaters');
+      setStatus('已紧急停止并锁存禁用全部 24 路加热块 (0x0A)');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`锁死加热块失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-stop-fans').addEventListener('click', async () => {
+    try {
+      await callThermalAction('stop_fans');
+      setStatus('已停止并锁存禁用全部风扇 (0x0B)');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`锁死风扇失败: ${err.message}`, true);
+    }
+  });
+
+  // Recording controls
+  async function syncRecordPrefs() {
+    try {
+      await callThermalAction('configure_polling', {
+        record_interval_ms: Number(el('th-rec-interval').value) || 1000,
+        auto_record_on_heat: el('th-chk-auto-rec').checked,
+      });
+    } catch {}
+  }
+  el('th-rec-interval').addEventListener('change', syncRecordPrefs);
+  el('th-chk-auto-rec').addEventListener('change', syncRecordPrefs);
+
+  el('btn-th-rec-start').addEventListener('click', async () => {
+    try {
+      const res = await callThermalAction('start_record', {
+        tag: el('th-rec-tag').value.trim(),
+        note: el('th-mark-input').value.trim(),
+        record_interval_ms: Number(el('th-rec-interval').value) || 1000,
+      });
+      setStatus(`已开始本地全量流式记录: ${res?.csv_filename || ''}`);
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`启动记录失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-rec-stop').addEventListener('click', async () => {
+    try {
+      const res = await callThermalAction('stop_record');
+      setStatus(res?.csv_filename
+        ? `已停止并完成刷盘: ${res.csv_filename} (共 ${res.rows_written || 0} 行)`
+        : '当前没有正在运行的记录会话');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`停止记录失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-add-mark').addEventListener('click', async () => {
+    const note = el('th-mark-input').value.trim();
+    if (!note) {
+      setStatus('请先输入打标备注内容', true);
+      return;
+    }
+    try {
+      await callThermalAction('add_mark', { note });
+      setStatus(`已写入测试打标备注: ${note}`);
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`打标失败: ${err.message}`, true);
+    }
+  });
+
+  // Auxiliary remote debug actions
+  el('btn-th-whisper-fan-test').addEventListener('click', async () => {
+    const btn = el('btn-th-whisper-fan-test');
+    btn.disabled = true;
+    try {
+      await callThermalAction('manual_duty', {
+        ptc_all: 0,
+        ssr_all: 0,
+        fan_in_all: 15,
+        fan_out_all: 0,
+        keepalive: false,
+      });
+      setStatus('0W 加热 · 15% 进风微风点测已开启,将在 2 秒后自动归零...');
+      await pollConsole(true);
+      await new Promise(r => setTimeout(r, 2000));
+      await callThermalAction('manual_duty', {
+        ptc_all: 0,
+        ssr_all: 0,
+        fan_in_all: 0,
+        fan_out_all: 0,
+        keepalive: false,
+      });
+      await callThermalAction('stop_preheat');
+      setStatus('0W 微风 2 秒闭环点测已完成,全部 35 路输出已自动恢复归零!');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`微风闭环点测异常: ${err.message}`, true);
+    } finally {
+      btn.disabled = false;
+    }
+  });
+
+  el('btn-th-pid-read').addEventListener('click', async () => {
+    try {
+      const res = await callThermalAction('pid_calibrate', { expr: '' });
+      setStatus(`PID 回读成功: ${res?.text || ''}`);
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`PID 回读失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-pid-write').addEventListener('click', async () => {
+    const expr = el('th-pid-expr').value.trim();
+    try {
+      const res = await callThermalAction('pid_calibrate', { expr });
+      setStatus(`PID 标定成功: ${res?.text || ''}`);
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`PID 标定失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-man-apply').addEventListener('click', async () => {
+    try {
+      await callThermalAction('manual_duty', {
+        ptc_all: Number(el('th-man-ptc').value) || 0,
+        fan_in_all: Number(el('th-man-fan-in').value) || 0,
+        fan_out_all: Number(el('th-man-fan-out').value) || 0,
+        ssr_all: Number(el('th-man-ssr').value) || 0,
+        keepalive: el('th-man-keepalive').checked,
+      });
+      setStatus('已下发 35 路手动占空比 (0x46)');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`下发手动占空比失败: ${err.message}`, true);
+    }
+  });
+
+  el('btn-th-man-zero').addEventListener('click', async () => {
+    el('th-man-ptc').value = '0';
+    el('th-man-fan-in').value = '0';
+    el('th-man-fan-out').value = '0';
+    el('th-man-ssr').value = '0';
+    el('th-man-keepalive').checked = false;
+    try {
+      await callThermalAction('manual_duty', {
+        ptc_all: 0, fan_in_all: 0, fan_out_all: 0, ssr_all: 0, keepalive: false,
+      });
+      setStatus('35 路手动占空比已全部归零');
+      await pollConsole(true);
+    } catch (err) {
+      setStatus(`归零失败: ${err.message}`, true);
+    }
+  });
+
+  // Series visibility checkboxes
+  document.querySelectorAll('.th-chart-legend input[data-series]').forEach(chk => {
+    chk.addEventListener('change', () => {
+      if (chk.checked) enabledSeries.add(chk.dataset.series);
+      else enabledSeries.delete(chk.dataset.series);
+      scheduleChartDraw();
+    });
+  });
+
+  // Canvas hover crosshair
+  const canvas = el('th-trend-canvas');
+  const tooltip = el('th-canvas-tooltip');
+  canvas.addEventListener('mousemove', ev => {
+    const rect = canvas.getBoundingClientRect();
+    const padL = 44, padR = 14;
+    const plotW = Math.max(1, rect.width - padL - padR);
+    const x = ev.clientX - rect.left - padL;
+    if (x < 0 || x > plotW || chartRing.length === 0) {
+      hoverRatio = null;
+      tooltip.classList.add('hidden');
+    } else {
+      hoverRatio = Math.min(1, Math.max(0, x / plotW));
+    }
+    scheduleChartDraw();
+  });
+  canvas.addEventListener('mouseleave', () => {
+    hoverRatio = null;
+    tooltip.classList.add('hidden');
+    scheduleChartDraw();
+  });
+  window.addEventListener('resize', scheduleChartDraw);
+
+  function scheduleChartDraw() {
+    if (rafPending || document.body.dataset.currentPage !== 'thermal') return;
+    rafPending = true;
+    requestAnimationFrame(() => {
+      rafPending = false;
+      drawTrendChart();
+    });
+  }
+
+  function drawTrendChart() {
+    const rect = canvas.parentElement.getBoundingClientRect();
+    if (rect.width < 40 || rect.height < 40) return;
+    const dpr = Math.min(window.devicePixelRatio || 1, 2);
+    const w = Math.floor(rect.width);
+    const h = Math.floor(rect.height);
+    if (canvas.width !== w * dpr || canvas.height !== h * dpr) {
+      canvas.width = w * dpr;
+      canvas.height = h * dpr;
+    }
+    const ctx = canvas.getContext('2d');
+    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+    ctx.clearRect(0, 0, w, h);
+
+    const padL = 44, padR = 14, padT = 14, padB = 26;
+    const plotW = w - padL - padR;
+    const plotH = h - padT - padB;
+
+    if (chartRing.length === 0) {
+      ctx.fillStyle = '#8b9ca8';
+      ctx.font = '12px sans-serif';
+      ctx.textAlign = 'center';
+      ctx.fillText('连接高温罩(或开启服务器 IPMI / 开始记录)后实时绘制温度曲线', w / 2, h / 2);
+      return;
+    }
+
+    let minY = Infinity, maxY = -Infinity;
+    for (let i = 0; i < chartRing.length; i++) {
+      const p = chartRing[i];
+      for (const s of SERIES_META) {
+        if (!enabledSeries.has(s.key)) continue;
+        const v = p[s.key];
+        if (typeof v === 'number' && Number.isFinite(v)) {
+          if (v < minY) minY = v;
+          if (v > maxY) maxY = v;
+        }
+      }
+    }
+    if (!Number.isFinite(minY) || !Number.isFinite(maxY)) {
+      minY = 20;
+      maxY = 80;
+    } else {
+      minY = Math.floor(Math.max(0, minY - 4) / 5) * 5;
+      maxY = Math.ceil((maxY + 4) / 5) * 5;
+      if (maxY - minY < 15) maxY = minY + 15;
+    }
+
+    // Horizontal grid & Y labels
+    ctx.strokeStyle = '#e7eff3';
+    ctx.lineWidth = 1;
+    ctx.fillStyle = '#738896';
+    ctx.font = '11px monospace';
+    ctx.textAlign = 'right';
+    const steps = 4;
+    for (let k = 0; k <= steps; k++) {
+      const val = minY + ((maxY - minY) * (steps - k)) / steps;
+      const y = padT + (plotH * k) / steps;
+      ctx.beginPath();
+      ctx.moveTo(padL, y);
+      ctx.lineTo(padL + plotW, y);
+      ctx.stroke();
+      ctx.fillText(`${Math.round(val)}°`, padL - 6, y + 4);
+    }
+
+    // Time X labels
+    const n = chartRing.length;
+    const xOf = idx => padL + (n <= 1 ? plotW / 2 : (idx / (n - 1)) * plotW);
+    const yOf = val => padT + plotH - ((val - minY) / (maxY - minY)) * plotH;
+
+    ctx.textAlign = 'center';
+    const tickCount = Math.min(5, n);
+    for (let t = 0; t < tickCount; t++) {
+      const idx = tickCount === 1 ? 0 : Math.round((t * (n - 1)) / (tickCount - 1));
+      ctx.fillText(fmtTimeShort(chartRing[idx].t), xOf(idx), h - 7);
+    }
+
+    // Series polylines
+    for (const s of SERIES_META) {
+      if (!enabledSeries.has(s.key)) continue;
+      ctx.save();
+      ctx.strokeStyle = s.color;
+      ctx.lineWidth = s.key === 'bmc_avg' ? 2.2 : 1.6;
+      if (s.dashed) ctx.setLineDash([5, 4]);
+      ctx.beginPath();
+      let penDown = false;
+      for (let i = 0; i < n; i++) {
+        const v = chartRing[i][s.key];
+        if (typeof v === 'number' && Number.isFinite(v)) {
+          const px = xOf(i);
+          const py = yOf(v);
+          if (!penDown) {
+            ctx.moveTo(px, py);
+            penDown = true;
+          } else {
+            ctx.lineTo(px, py);
+          }
+        } else {
+          penDown = false;
+        }
+      }
+      ctx.stroke();
+      ctx.restore();
+    }
+
+    // Hover crosshair
+    if (hoverRatio !== null && n > 0) {
+      const idx = Math.min(n - 1, Math.max(0, Math.round(hoverRatio * (n - 1))));
+      const pt = chartRing[idx];
+      const hx = xOf(idx);
+      ctx.save();
+      ctx.strokeStyle = '#95a8b6';
+      ctx.setLineDash([3, 3]);
+      ctx.beginPath();
+      ctx.moveTo(hx, padT);
+      ctx.lineTo(hx, padT + plotH);
+      ctx.stroke();
+      ctx.restore();
+
+      const parts = [`时间: ${fmtTimeShort(pt.t)} (${pt.phase || 'idle'})`];
+      if (pt.target != null) parts.push(`目标: ${pt.target}℃`);
+      if (pt.bmc_avg != null) parts.push(`MCU均/高: ${pt.bmc_avg} / ${pt.bmc_max ?? '--'}℃`);
+      if (pt.ct_avg != null) parts.push(`CT腔均: ${pt.ct_avg}℃`);
+      if (pt.ipmi_avg != null) parts.push(`IPMI均: ${pt.ipmi_avg}℃`);
+      setTextIfChanged(tooltip, parts.join('  |  '));
+      tooltip.classList.remove('hidden');
+    }
+  }
+
+  function setPill(id, text, tone) {
+    const node = el(id);
+    if (!node) return;
+    setTextIfChanged(node, text);
+    const cls = tone ? `th-pill is-${tone}` : 'th-pill';
+    if (node.className !== cls) node.className = cls;
+  }
+
+  function renderSnapshot(snap) {
+    const conn = snap.connection || {};
+    const mcu = snap.mcu || {};
+    const flags = mcu.flags || {};
+    const stats = snap.stats || {};
+    const act = snap.actuators || {};
+    const safety = snap.safety || {};
+    const rec = snap.recorder || {};
+    const stCtx = snap.station_context || {};
+
+    // Sync saved prefs once on initial load without overwriting user's active typing
+    if (!prefsSyncedOnce) {
+      prefsSyncedOnce = true;
+      if (conn.serial_path) el('th-serial-path').value = conn.serial_path;
+      if (conn.tcp_host) el('th-tcp-host').value = conn.tcp_host;
+      if (conn.tcp_port) el('th-tcp-port').value = String(conn.tcp_port);
+      if (stCtx.station_id) el('th-bound-station').value = stCtx.station_id;
+      if (mcu.last_set_target_c != null) el('th-target-input').value = String(mcu.last_set_target_c);
+      if (rec.interval_ms) el('th-rec-interval').value = String(rec.interval_ms);
+      if (typeof rec.auto_record_on_heat === 'boolean') el('th-chk-auto-rec').checked = rec.auto_record_on_heat;
+      if (safety.lease_sec != null) {
+        const ls = String(safety.lease_sec);
+        if ([...el('th-safety-lease').options].some(o => o.value === ls)) {
+          el('th-safety-lease').value = ls;
+        }
+      }
+      if (safety.overtemp_cutoff_c != null) el('th-overtemp-cutoff').value = String(safety.overtemp_cutoff_c);
+    }
+
+    // Overview quick badge
+    const ovBadge = el('ov-thermal-badge');
+    if (ovBadge) {
+      if (conn.mode === 'disconnected') {
+        setTextIfChanged(ovBadge, rec.active ? '未连接 · 记录中' : '未连接');
+        ovBadge.className = 'badge';
+      } else {
+        const bAvg = stats.mcu_bmc_avg ?? stats.ct_avg;
+        const tStr = mcu.target_c != null ? `/${mcu.target_c}℃` : '';
+        const recMark = rec.active ? ' · REC' : '';
+        setTextIfChanged(
+          ovBadge,
+          `${stateLabel(mcu.state)} ${bAvg != null ? bAvg + '℃' : '--'}${tStr}${recMark}`
+        );
+        ovBadge.className = conn.online ? 'badge connected' : 'badge error';
+      }
+    }
+
+    // Status strip pills
+    const modeDesc = conn.mode === 'serial'
+      ? `串口 ${conn.serial_path}`
+      : conn.mode === 'mock'
+        ? '虚拟仿真 Mock'
+        : conn.mode === 'tcp'
+          ? `TCP ${conn.tcp_host}:${conn.tcp_port}`
+          : '未连接';
+    setPill('th-pill-online', `链路: ${modeDesc}${conn.online ? ' (在线)' : ''}`, conn.online ? 'ok' : (conn.mode === 'disconnected' ? '' : 'err'));
+    setPill('th-pill-state', `状态: ${stateLabel(mcu.state)}`, (flags.preheating || flags.pid_running) ? 'active' : (flags.cpld_lost ? 'err' : ''));
+    setPill('th-pill-cpld', `CPLD: ${!conn.online ? '--' : (flags.cpld_lost ? '失联告警!' : '正常在线')}`, !conn.online ? '' : (flags.cpld_lost ? 'err' : 'ok'));
+    setPill('th-pill-preheat', `预加热: ${flags.preheating ? '运行中' : '否'}`, flags.preheating ? 'warn' : '');
+    setPill('th-pill-pid', `PID闭环: ${flags.pid_running ? '控温中' : '否'}`, flags.pid_running ? 'active' : '');
+    setPill('th-pill-hlatch', `加热锁存: ${flags.heater_latched_off ? '已锁死禁用' : '正常'}`, flags.heater_latched_off ? 'warn' : '');
+    setPill('th-pill-flatch', `风扇锁存: ${flags.fan_latched_off ? '已锁死禁用' : '正常'}`, flags.fan_latched_off ? 'warn' : '');
+    setPill('th-pill-bmc', `BMC温度源: ${!conn.online ? '--' : (flags.bmc_not_ready ? '待就绪(全FF)' : '已就绪')}`, !conn.online ? '' : (flags.bmc_not_ready ? 'warn' : 'ok'));
+    setPill('th-pill-manual', `手动保持: ${flags.manual_hold ? '运行中' : '否'}`, flags.manual_hold ? 'warn' : '');
+
+    const bi = mcu.boot_info;
+    const fwStr = bi ? `${bi.app_version || '--'} (${bi.product_id_hex || ''})` : '--';
+    setTextIfChanged(
+      el('th-hw-identity'),
+      `UID: ${mcu.uid_hex || '--'} · 固件: ${fwStr} · RX:${conn.rx_frames_ok || 0} TX:${conn.tx_frames_sent || 0} CRC错:${conn.crc_errors || 0}`
+    );
+
+    // Safety bar
+    const leaseNode = el('th-lease-countdown');
+    if (safety.overtemp_tripped) {
+      setTextIfChanged(leaseNode, `已触发超温熔断保护 (>=${safety.overtemp_cutoff_c}℃)!`);
+      leaseNode.className = 'badge error';
+    } else if (safety.lease_active) {
+      setTextIfChanged(leaseNode, `看门狗倒计时: ${safety.lease_remaining_sec}s`);
+      leaseNode.className = safety.lease_remaining_sec <= 60 ? 'badge error' : 'badge connected';
+    } else {
+      setTextIfChanged(leaseNode, safety.lease_sec > 0 ? `看门狗待命 (${safety.lease_sec}s)` : '看门狗已设为不限时');
+      leaseNode.className = 'badge';
+    }
+
+    setTextIfChanged(el('th-target-badge'), `当前目标: ${mcu.target_c != null ? mcu.target_c + ' ℃' : '--'}`);
+    setTextIfChanged(el('th-pid-current'), mcu.pid_text || '--');
+
+    // Actuators live feedback
+    const ssrArr = Array.isArray(act.ssr_applied) ? act.ssr_applied : [0, 0, 0];
+    const ffArr = Array.isArray(act.fan_front_applied) ? act.fan_front_applied : [0, 0, 0, 0];
+    const frArr = Array.isArray(act.fan_rear_applied) ? act.fan_rear_applied : [0, 0, 0, 0];
+    const ptcAvg = Number(act.ptc_avg_duty || 0);
+    setTextIfChanged(el('th-act-ssr'), conn.online ? `${ssrArr.join(' / ')} %` : '--');
+    setTextIfChanged(el('th-act-ptc'), conn.online ? `${ptcAvg.toFixed(1)} %` : '--');
+    setTextIfChanged(el('th-act-fan-f'), conn.online ? `${ffArr.join('/')} %` : '--');
+    setTextIfChanged(el('th-act-fan-r'), conn.online ? `${frArr.join('/')} %` : '--');
+    setTextIfChanged(el('th-act-ct0'), act.ct0_board_c != null ? `${act.ct0_board_c} ℃` : '--');
+    el('th-act-ssr').parentElement.classList.toggle('is-hot', conn.online && ssrArr.some(v => v > 0));
+    el('th-act-ptc').parentElement.classList.toggle('is-hot', conn.online && ptcAvg > 0);
+    setTextIfChanged(
+      el('th-diag-note'),
+      act.diag_line ? `CPLD/I2C 诊断: ${act.diag_line}` : (conn.online ? '等待 MCU [SNAP]/[DIAG] 周期状态行...' : '连接后实时显示 24PTC / 8风扇 / 3SSR 真实占空比')
+    );
+
+    // Recorder panel
+    const recBadge = el('th-rec-badge');
+    const dlCur = el('btn-th-rec-download-cur');
+    if (rec.active) {
+      setTextIfChanged(recBadge, `记录中 · ${rec.rows_written || 0} 行`);
+      recBadge.className = 'badge connected';
+      if (rec.download_url) {
+        dlCur.href = rec.download_url;
+        dlCur.classList.remove('hidden');
+      }
+      setTextIfChanged(
+        el('th-rec-stats'),
+        `正在写入: ${rec.csv_filename} (分卷 #${rec.part_index || 1}) · 已写 ${rec.rows_written || 0} 行 (${fmtBytes(rec.bytes_written)}) · 标签备注: ${rec.note || '无'}`
+      );
+    } else {
+      setTextIfChanged(recBadge, '未记录');
+      recBadge.className = 'badge';
+      dlCur.classList.add('hidden');
+      setTextIfChanged(
+        el('th-rec-stats'),
+        '落盘目录: data/thermal-logs/ · 包含 MCU 24路 + CT 8路 + 服务器 IPMI 24路 + 功率占空比 + 测试阶段共 106 列 (UTF-8 BOM 直接用 Excel 打开)'
+      );
+    }
+
+    // Files table (diffed by signature so buttons never flicker!)
+    const files = Array.isArray(rec.files) ? rec.files : [];
+    const filesSig = files
+      .map(f => `${f.filename}:${f.active ? Math.floor((f.size_bytes || 0) / 16384) : f.size_bytes}:${f.active}`)
+      .join('|');
+    if (filesSig !== lastFilesSig) {
+      lastFilesSig = filesSig;
+      const tbody = el('th-files-tbody');
+      tbody.replaceChildren();
+      if (files.length === 0) {
+        const tr = document.createElement('tr');
+        const td = document.createElement('td');
+        td.colSpan = 5;
+        td.textContent = '暂无本地记录文件(点击「开始本地记录」或开启控温自动生成)';
+        tr.appendChild(td);
+        tbody.appendChild(tr);
+      } else {
+        for (const f of files.slice(0, 30)) {
+          const tr = document.createElement('tr');
+          const tdName = document.createElement('td');
+          tdName.style.fontFamily = 'var(--mono)';
+          tdName.textContent = f.filename + (f.active ? ' (写入中)' : '');
+
+          const tdKind = document.createElement('td');
+          tdKind.textContent = f.kind === 'csv' ? '全量 CSV' : '事件 JSONL';
+
+          const tdSize = document.createElement('td');
+          tdSize.textContent = fmtBytes(f.size_bytes);
+
+          const tdTime = document.createElement('td');
+          tdTime.textContent = (f.modified_str || '').slice(5, 19);
+
+          const tdAct = document.createElement('td');
+          const a = document.createElement('a');
+          a.className = 'btn btn-xs';
+          a.href = f.download_url;
+          a.download = f.filename;
+          a.textContent = '下载';
+          tdAct.appendChild(a);
+          if (!f.active) {
+            const delBtn = document.createElement('button');
+            delBtn.type = 'button';
+            delBtn.className = 'btn btn-xs';
+            delBtn.style.marginLeft = '5px';
+            delBtn.textContent = '删除';
+            delBtn.addEventListener('click', async () => {
+              if (!confirm(`确认删除本地记录文件 ${f.filename} 吗?`)) return;
+              try {
+                await callThermalAction('delete_log', { filename: f.filename });
+                lastFilesSig = '';
+                await pollConsole(true);
+              } catch (err) {
+                setStatus(`删除失败: ${err.message}`, true);
+              }
+            });
+            tdAct.appendChild(delBtn);
+          }
+          tr.append(tdName, tdKind, tdSize, tdTime, tdAct);
+          tbody.appendChild(tr);
+        }
+      }
+    }
+
+    // Stats summary & 24-ch + 8-ch grids
+    setTextIfChanged(
+      el('th-stats-summary'),
+      `MCU BMC(${stats.mcu_bmc_valid || 0}/24): 均 ${stats.mcu_bmc_avg ?? '--'}℃ [低 ${stats.mcu_bmc_min ?? '--'} ~ 高 ${stats.mcu_bmc_max ?? '--'}℃, 温差 ${stats.mcu_bmc_spread ?? '--'}℃]  ·  ` +
+      `CT7428(${stats.ct_valid || 0}/8): 均 ${stats.ct_avg ?? '--'}℃ [高 ${stats.ct_max ?? '--'}℃]  ·  ` +
+      `服务器IPMI(${stats.ipmi_valid || 0}/24): 均 ${stats.ipmi_avg ?? '--'}℃ [高 ${stats.ipmi_max ?? '--'}℃]`
+    );
+    setTextIfChanged(
+      el('th-station-sync-note'),
+      `关联工位 ${stCtx.station_id || 'S1'} · 阶段: ${stCtx.phase || 'idle'} · 任务: ${stCtx.task_status || 'not_started'} · 电源: ${stCtx.server_power || '--'} · 累计错误: ${stCtx.stage_error_total || 0}`
+    );
+
+    const ctArr = Array.isArray(snap.ct7428_8) ? snap.ct7428_8 : [];
+    for (let i = 0; i < 8; i++) {
+      const v = ctArr[i];
+      const txt = v != null ? `${v} ℃` : '--';
+      if (ctCells[i].prev !== txt) {
+        ctCells[i].prev = txt;
+        ctCells[i].val.textContent = txt;
+      }
+    }
+
+    const mcuArr = Array.isArray(snap.mcu_bmc_24) ? snap.mcu_bmc_24 : [];
+    const ipmiArr = Array.isArray(snap.ipmi_dimm_24) ? snap.ipmi_dimm_24 : [];
+    for (let i = 0; i < 24; i++) {
+      const cell = slotCells[i];
+      const mv = mcuArr[i];
+      const iv = ipmiArr[i];
+      const mTxt = mv != null ? `MCU: ${mv}℃` : 'MCU: --';
+      const iTxt = iv != null ? `IPMI: ${Number(iv).toFixed(1)}℃` : 'IPMI: --';
+      const dTxt = (mv != null && iv != null) ? `Δ${(mv - iv >= 0 ? '+' : '') + (mv - iv).toFixed(1)}` : '';
+      const maxT = Math.max(mv ?? -1, iv ?? -1);
+      const cls = maxT > 80
+        ? 'th-slot-card is-hot'
+        : maxT >= 65
+          ? 'th-slot-card is-warn'
+          : maxT >= 0
+            ? 'th-slot-card is-valid'
+            : 'th-slot-card';
+      if (cell.prevCls !== cls) { cell.prevCls = cls; cell.card.className = cls; }
+      if (cell.prevMcu !== mTxt) { cell.prevMcu = mTxt; cell.mcuStrong.textContent = mTxt; }
+      if (cell.prevIpmi !== iTxt) { cell.prevIpmi = iTxt; cell.ipmiSpan.textContent = iTxt; }
+      if (cell.prevDiff !== dTxt) { cell.prevDiff = dTxt; cell.diffSpan.textContent = dTxt; }
+    }
+
+    // Incremental ring buffer update (O(1) bounded at 720 points)
+    if (snap.reset_ring) {
+      chartRing = Array.isArray(snap.points_delta) ? snap.points_delta.slice(-MAX_POINTS) : [];
+    } else if (Array.isArray(snap.points_delta) && snap.points_delta.length > 0) {
+      for (const pt of snap.points_delta) {
+        chartRing.push(pt);
+      }
+      if (chartRing.length > MAX_POINTS) {
+        chartRing.splice(0, chartRing.length - MAX_POINTS);
+      }
+    }
+    if (typeof snap.latest_point_seq === 'number') {
+      sinceSeq = snap.latest_point_seq;
+    }
+    scheduleChartDraw();
+
+    // Debug logs (only rendered when drawer is open)
+    if (el('th-debug-drawer').open) {
+      const ascii = Array.isArray(snap.ascii_logs) ? snap.ascii_logs : [];
+      const aSig = ascii.length ? `${ascii[0].unix_ms}:${ascii.length}` : 'empty';
+      if (aSig !== lastAsciiSig) {
+        lastAsciiSig = aSig;
+        el('th-ascii-log-pre').textContent = ascii.length
+          ? ascii.slice(0, 45).map(a => `[${(a.time_str || '').slice(11, 23)}] ${a.line}`).join('\n')
+          : '暂无 MCU 串口 ASCII 输出...';
+      }
+
+      const evs = Array.isArray(snap.events) ? snap.events.slice(0, 20) : [];
+      const frms = Array.isArray(snap.frames) ? snap.frames.slice(0, 25) : [];
+      const fSig = `${evs[0]?.unix_ms || 0}:${frms[0]?.unix_ms || 0}:${frms.length}`;
+      if (fSig !== lastFrameSig) {
+        lastFrameSig = fSig;
+        const evTxt = evs.map(e => `[事件 ${(e.time_str || '').slice(11, 19)} ${e.level}] ${e.message}`).join('\n');
+        const frTxt = frms.map(f => `[${f.dir} ${f.cmd} ${f.len}B] ${f.hex}`).join('\n');
+        el('th-frame-log-pre').textContent = [evTxt, frTxt].filter(Boolean).join('\n--- 最近协议报文 ---\n') || '暂无事件与协议帧...';
+      }
+    }
+  }
+
+  async function pollConsole(forceIncludeDebug = false) {
+    if (pollInFlight || document.hidden) return;
+    pollInFlight = true;
+    try {
+      const onThermalPage = document.body.dataset.currentPage === 'thermal';
+      const includeFrames = Boolean(forceIncludeDebug || (onThermalPage && el('th-debug-drawer')?.open));
+      const snap = await window.stlTransport.call('GetThermalConsole', {
+        since_seq: sinceSeq,
+        include_frames: includeFrames,
+      }, 8000);
+      if (snap) renderSnapshot(snap);
+    } catch {
+      // Transport layer handles reconnects gracefully
+    } finally {
+      pollInFlight = false;
+    }
+  }
+
+  function resetPollTimer() {
+    if (pollTimer) clearInterval(pollTimer);
+    const onThermalPage = document.body.dataset.currentPage === 'thermal';
+    pollTimer = setInterval(() => pollConsole(false), onThermalPage ? 1000 : 3500);
+  }
+
+  window.addEventListener('stl:page-change', ev => {
+    resetPollTimer();
+    if (ev.detail?.page === 'thermal') {
+      scanPorts(true);
+      pollConsole(false);
+      scheduleChartDraw();
+    }
+  });
+  document.addEventListener('visibilitychange', () => {
+    if (!document.hidden) pollConsole(false);
+  });
+  el('th-debug-drawer').addEventListener('toggle', () => {
+    if (el('th-debug-drawer').open) pollConsole(true);
+  });
+
+  // Initial bootstrap
+  resetPollTimer();
+  setTimeout(() => {
+    scanPorts(true);
+    pollConsole(false);
+  }, 300);
+})();

+ 1 - 1
web/ui-navigation.js

@@ -1,6 +1,6 @@
 // Page routing only. Changing the visible page never changes a device session.
 (() => {
-  const pages = new Set(['overview', 'connections', 'plan', 'uip', 'amt', 'testing', 'records', 'queue']);
+  const pages = new Set(['overview', 'thermal', 'connections', 'plan', 'uip', 'amt', 'testing', 'records', 'queue']);
   function show(value, updateHash = true) {
     const page = pages.has(value) ? value : 'overview';
     document.body.dataset.currentPage = page;