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

feat(6400-v1.1): standalone No-MCU CPLD (20Hz PWM, no BMC UART, 4-baud, DIAG fmt3) + Windows Adaptive PID & BMC NET RMCP+ host app

Prod2U Recovery 1 неделя назад
Родитель
Сommit
edd6801d36

+ 8 - 5
constraints/prod2u_6400_front_back.adc

@@ -1,13 +1,16 @@
-# 6400-front-rear-v1 V1.1 confirmed pins for the CON78 RS-232-only physical top.
+# 6400 V1.1 (FCB_FPGA+MCU_V1.1_20260625.brd) — Standalone Branch 6400-v1.1 (No-MCU Edition)
+# Host UART: CON78 RS-232 (M10/N11) & CON30 3.3V TTL (A10/B9), RX internal PULLUP.
+# BMC UART (CON77 L10/M9) intentionally REMOVED: Windows host reads DIMM temps via BMC NET.
+# CT7428 3-chip I2C master on M8/N9 (U6=0x49, U24=0x48, U25=0x4B); B14/A15 held Hi-Z.
 set_pin_assignment { sys_clk } { LOCATION = J1; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
-set_pin_assignment { bmc_rs232_tx } { LOCATION = L10; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
-set_pin_assignment { bmc_rs232_rx } { LOCATION = M9; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
 set_pin_assignment { host_rs232_tx } { LOCATION = M10; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
-set_pin_assignment { host_rs232_rx } { LOCATION = N11; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { host_rs232_rx } { LOCATION = N11; IOSTANDARD = LVCMOS33; PULLTYPE = PULLUP; }
 set_pin_assignment { host_ttl_tx } { LOCATION = A10; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
-set_pin_assignment { host_ttl_rx } { LOCATION = B9; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { host_ttl_rx } { LOCATION = B9; IOSTANDARD = LVCMOS33; PULLTYPE = PULLUP; }
 set_pin_assignment { temp_scl } { LOCATION = M8; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
 set_pin_assignment { temp_sda } { LOCATION = N9; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { temp_scl_alt } { LOCATION = B14; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { temp_sda_alt } { LOCATION = A15; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
 set_pin_assignment { ptc_pwm_out[0] } { LOCATION = R7; IOSTANDARD = LVCMOS33; }
 set_pin_assignment { ptc_pwm_out[1] } { LOCATION = T6; IOSTANDARD = LVCMOS33; }
 set_pin_assignment { ptc_pwm_out[2] } { LOCATION = R5; IOSTANDARD = LVCMOS33; }

+ 11 - 1
products/6400-front-rear/project.json

@@ -2,11 +2,17 @@
   "schema": "prod2u-6400-profile-v1",
   "project_id": "6400-front-rear",
   "product": "6400-front-rear",
+  "branch_policy": "standalone_branch_6400_v1_1_never_merge_to_dev",
+  "architecture": "no_mcu_windows_adaptive_pid_bmc_net",
   "top": "prod2u_6400_final_top",
   "device": "EF2L45BG256B",
   "clock_hz": 25000000,
+  "pwm_hz": 20,
+  "host_baud_default": 921600,
+  "supported_build_bauds": [921600, 460800, 230400, 115200],
   "source_closure": "products/6400-front-rear/source-closure.json",
   "board_id": "fcb_fpga_mcu_v1_1_20260625",
+  "board_brd_sha256": "db02938f7943b2ae532aa18208f61588364d32a70a0cc72f74b4a94aaab7e258",
   "board_evidence": "tools/board-viewer/generated-v1_1/board-data.json",
   "board_evidence_sha256": "22de83156505752fb5cd07f7744083714711555a809e843ffb30afc3db9742f9",
   "constraints": "constraints/prod2u_6400_front_back.adc",
@@ -17,7 +23,11 @@
   "host_ttl_connector": "CON30",
   "host_ttl_tx": {"connector_pin": 4, "fpga_ball": "A10", "status": "locked"},
   "host_ttl_rx": {"connector_pin": 3, "fpga_ball": "B9", "status": "locked"},
-  "ct_physical_map_status": "verified_ct_master_contract",
+  "bmc_uart_removed": true,
+  "dimm_temp_source": "bmc_net_ipmi_rmcp_plus_udp_623",
+  "ct_physical_map_status": "verified_ct_master_3chip_27ch_m8_n9",
+  "diagnostic_format": 3,
+  "diagnostic_board_id": "0x61",
   "control_watchdog_seconds": 30,
   "fan_safe_connector_duty": 20,
   "fan_board_invert_mask": "0x0F",

+ 2 - 3
products/6400-front-rear/source-closure.json

@@ -3,10 +3,9 @@
   "project_id": "6400-front-rear",
   "top_module": "prod2u_6400_final_top",
   "sources": [
+    "src/common/prod2u_build_config.vh",
     "src/common/uart_rx_byte.v",
     "src/common/uart_tx_byte.v",
-    "src/common/uart_rx_byte_fractional.v",
-    "src/common/uart_tx_byte_fractional.v",
     "src/common/crc16_serial.v",
     "src/common/ef2_bram_dp.v",
     "src/common/frame_rx.v",
@@ -18,7 +17,6 @@
     "src/transport/reply_arbiter.v",
     "src/transport/reply_ram.v",
     "src/acquisition/temp_ram.v",
-    "src/acquisition/bmc_ascii_poll.v",
     "src/acquisition/ct7428_scan.v",
     "src/control/duty_register_bank.v",
     "src/control/watchdog_30s.v",
@@ -35,6 +33,7 @@
     "EF2_PHY_PLL",
     "SET_TARGET",
     "stimulus_atomic_bank",
+    "bmc_ascii_poll",
     "PID",
     "pid_",
     "pi_"

+ 115 - 119
src/top/prod2u_6400_final_top.v

@@ -1,43 +1,51 @@
 `timescale 1ns/1ps
+`include "src/common/prod2u_build_config.vh"
 
-// 6400 final top: shared host UART endpoint + transaction core + duty bank +
-// PWM carrier + temperature chain + watchdog, on the single new frame
-// protocol (A5 5A | TYPE | LEN:u8 | PAYLOAD | CRC16-CCITT-FALSE, low first).
-//
-// Data path:
-//   host RS232/TTL -> host_uart_endpoint (RX parse, TX broadcast, independent
-//   RX/TX CRC) -> request RAM -> m6400_transaction_core (validate, atomic
-//   SET commit, GET assembly, NACK) -> duty_register_bank -> pwm_bitmap_engine
-//   (+ fan_board_output_adapter) -> PTC/FAN pins.
-//   temp_ram <- bmc_ascii_poll / ct7428_scan; get_data_6400 reads the bank and
-//   temp_ram into reply_ram; reply_arbiter serialises reply groups vs DONEs
-//   (6400 never produces DONEs; the port is tied off).
-//   watchdog_30s reloads on SET_ACCEPT / GET_ACCEPT and invalidates the bank
-//   on expiry (defaults PTC 0 / FAN 20 at the connector).
-//
-// Bank read-port arbitration: the duty bank has one read port.  The PWM
-// scanner owns it except while a GET group is being assembled, when the GET
-// assembler owns it.  The bitmap source is therefore fixed for a whole PWM
-// period except across a GET assembly window, which never overlaps a commit
-// (the core serialises transactions).
-module prod2u_6400_final_top (
+// =============================================================================
+// Product:       Prod2U 6400 V1.1 (Standalone Branch: 6400-v1.1, No-MCU Edition)
+// Board:         FCB_FPGA+MCU_V1.1_20260625.brd (EF2L45BG256B, 25 MHz, No PLL)
+// Architecture:  Ultra-low-LUT No-MCU thermal actuator + 27-ch CT7428 scanner.
+//                - Windows host runs adaptive PID & acquires 24-DIMM temps
+//                  directly over BMC NET (IPMI v2.0 RMCP+ UDP:623).
+//                - CPLD removes BMC UART & bmc_ascii_poll completely (~360+ LUT
+//                  saved); GET_DATA bytes 32..55 stay deterministically 0xFF.
+//                - Unified 20 Hz PWM (50 ms period, 12,500 clks / 1% @ 25 MHz)
+//                  for 24 PTC (CON18/27/28/29) + 4 Front (inverted, CON25/8/24/26)
+//                  + 4 Rear (non-inverted, CON64/66/62/60), MASK = 8'h0F.
+//                - Host RS-232 (CON78 M10/N11) & 3.3V TTL (CON30 A10/B9) with
+//                  compile-time baud (921600/460800/230400/115200 8N1).
+//                - Always-on 1s autonomous debug: 0x42 (83B) + 0x52 (20B,
+//                  format=3, board_id=0x61, fw=3.3.0).
+// =============================================================================
+module prod2u_6400_final_top #(
+    parameter integer HOST_BAUD      = `PROD2U_HOST_BAUD,
+    parameter integer PWM_PHASE_CLKS = 12500,
+    parameter [31:0]  BEACON_PERIOD  = 32'd25_000_000,
+    parameter integer WD_TIMEOUT_CLKS = 750_000_000
+)(
     input  wire        sys_clk,
     input  wire        host_rs232_rx,
     output wire        host_rs232_tx,
     input  wire        host_ttl_rx,
     output wire        host_ttl_tx,
-    input  wire        bmc_rs232_rx,
-    output wire        bmc_rs232_tx,
     output wire [23:0] ptc_pwm_out,
     output wire [3:0]  front_fan_pwm_out,
     output wire [3:0]  rear_fan_pwm_out,
     inout  wire        temp_scl,
-    inout  wire        temp_sda
+    inout  wire        temp_sda,
+    inout  wire        temp_scl_alt,
+    inout  wire        temp_sda_alt
 );
+    localparam integer HOST_CLKS_PER_BIT = (25000000 + (HOST_BAUD / 2)) / HOST_BAUD;
+
+    // Hold alternate I2C bus (B14/A15) permanently Hi-Z to prevent bus contention.
+    assign temp_scl_alt = 1'bz;
+    assign temp_sda_alt = 1'bz;
+
     wire sys_rst_n;
     prod2u_por u_por (.sys_clk(sys_clk), .sys_rst_n(sys_rst_n));
 
-    // ---------- host UART endpoint ----------
+    // ---------- host UART endpoint (RS-232 CON78 + 3.3V TTL CON30) ----------
     wire        req_valid;
     wire        req_ready;
     wire [7:0]  req_type;
@@ -54,8 +62,14 @@ module prod2u_6400_final_top (
     wire        tx_done;
     wire [7:0]  tx_ram_rd_addr;
     wire [7:0]  tx_ram_rd_data;
+    wire [7:0]  arb_base;
 
-    host_uart_endpoint u_host (
+    host_uart_endpoint #(
+        .CLKS_PER_BIT(HOST_CLKS_PER_BIT),
+        .INTER_BYTE_TIMEOUT_CYCLES(250000),
+        .MAX_PAYLOAD(128),
+        .ADDR_WIDTH(8)
+    ) u_host (
         .clk(sys_clk), .rst_n(sys_rst_n),
         .rs232_rx(host_rs232_rx), .rs232_tx(host_rs232_tx),
         .ttl_rx(host_ttl_rx), .ttl_tx(host_ttl_tx),
@@ -70,7 +84,7 @@ module prod2u_6400_final_top (
         .tx_ram_rd_addr(tx_ram_rd_addr), .tx_ram_rd_data(tx_ram_rd_data)
     );
 
-    // ---------- request staging RAM (128 x 8, synchronous read) ----------
+    // ---------- request staging RAM (128 x 8 BRAM9K) ----------
     ef2_bram_dp #(.DATA_WIDTH(8), .ADDR_WIDTH(7), .DATA_DEPTH(128)) u_req_ram (
         .clk(sys_clk),
         .a_en(req_ram_wr_en), .a_we(req_ram_wr_en),
@@ -79,28 +93,24 @@ module prod2u_6400_final_top (
         .b_addr(req_ram_rd_addr_core[6:0]), .b_wdata(8'd0), .b_rdata(req_ram_rd_data)
     );
 
-    // ---------- reply staging RAM (128 x 8) ----------
-    wire        reply_wr_en;
-    wire [7:0]  reply_wr_addr;
-    wire [7:0]  reply_wr_data;
+    // ---------- reply staging RAM (128 x 8 BRAM9K; 0..82 GET_DATA, 96..115 DIAG) ----------
     wire        gd_reply_we;
     wire [7:0]  gd_reply_addr;
     wire [7:0]  gd_reply_data;
     wire        nack_we;
     wire [7:0]  nack_addr;
     wire [7:0]  nack_data;
-    // Reply write-port share: GET assembly and NACK staging never run together.
-    assign reply_wr_en = gd_reply_we | nack_we;
-    assign reply_wr_addr = gd_reply_we ? gd_reply_addr : nack_addr;
-    assign reply_wr_data = gd_reply_we ? gd_reply_data : nack_data;
+    wire        reply_wr_en   = gd_reply_we | nack_we;
+    wire [7:0]  reply_wr_addr = gd_reply_we ? gd_reply_addr : nack_addr;
+    wire [7:0]  reply_wr_data = gd_reply_we ? gd_reply_data : nack_data;
+
     reply_ram u_reply_ram (
         .clk(sys_clk),
         .wr_en(reply_wr_en), .wr_addr(reply_wr_addr), .wr_data(reply_wr_data),
-        .rd_addr(tx_ram_rd_addr), .rd_data(tx_ram_rd_data)
+        .rd_addr(tx_ram_rd_addr + arb_base), .rd_data(tx_ram_rd_data)
     );
 
-    // ---------- duty bank ----------
-    wire [4:0]  bank_rd_addr;
+    // ---------- dual duty banks (trade abundant BRAM9K to eliminate read mux) ----------
     wire [7:0]  pwm_duty;
     wire [4:0]  pwm_addr;
     wire        stage_we;
@@ -108,11 +118,8 @@ module prod2u_6400_final_top (
     wire [4:0]  stage_addr = stage_addr_full[4:0];
     wire [7:0]  stage_data;
     wire        bank_valid;
-    // Read-port arbitration: GET assembly owns the port while it runs.
-    wire        get_assembling;
     wire [5:0]  gd_bank_addr_full;
     wire [4:0]  gd_bank_addr = gd_bank_addr_full[4:0];
-    assign bank_rd_addr = get_assembling ? gd_bank_addr : pwm_addr;
     wire [7:0]  gd_bank_duty;
 
     wire        commit_req;
@@ -122,10 +129,10 @@ module prod2u_6400_final_top (
     reg         wd_reload_d;
     wire        wd_reload;
     wire        wd_expired;
-
     wire        pwm_phase_boundary;
     wire        pwm_phase_boundary_advance;
     wire [6:0]  pwm_phase_value;
+    wire        pwm_scan_idle;
 
     always @(posedge sys_clk or negedge sys_rst_n) begin
         if (!sys_rst_n) begin
@@ -145,99 +152,80 @@ module prod2u_6400_final_top (
                 commit_pending <= 1'b1;
             end
 
-            if (duty_commit_r) begin
-                commit_ack_r   <= 1'b1;
-            end
+            if (duty_commit_r)
+                commit_ack_r <= 1'b1;
         end
     end
 
     wire suppress_invalidate = wd_reload | wd_reload_d | duty_commit_r | commit_pending;
     wire duty_invalidate = wd_expired & ~suppress_invalidate;
 
-    duty_register_bank #(.CHANNEL_COUNT(32), .ADDR_WIDTH(5),
-        .DEFAULT_PTC_MASK(32'h00FFFFFF)) u_bank (
+    duty_register_bank #(
+        .CHANNEL_COUNT(32), .ADDR_WIDTH(5),
+        .PTC_DEFAULT(8'd0), .FAN_DEFAULT(8'd20),
+        .DEFAULT_PTC_MASK(32'h00FFFFFF)
+    ) u_bank (
         .clk(sys_clk), .rst_n(sys_rst_n),
-        .pwm_addr(bank_rd_addr), .pwm_duty(pwm_duty),
+        .pwm_addr(pwm_addr), .pwm_duty(pwm_duty),
         .stage_we(stage_we), .stage_addr(stage_addr), .stage_data(stage_data),
         .commit(duty_commit_r), .invalidate(duty_invalidate),
         .valid(bank_valid), .active_bank()
     );
-    // The GET assembler sees the bank output one clock after its address;
-    // its present/settle/commit rhythm already accounts for that.
-    assign gd_bank_duty = pwm_duty;
-
-    // ---------- temperature RAM + sensors ----------
-    wire        bmc_tx_valid;
-    wire [7:0]  bmc_tx_data;
-    wire        bmc_tx_busy;
-    wire        bmc_rx_valid;
-    wire [7:0]  bmc_rx_data;
-    wire        bmc_rx_error;
-
-    uart_rx_byte #(.CLKS_PER_BIT(217)) u_bmc_rx (
-        .clk(sys_clk), .rst_n(sys_rst_n), .rx_i(bmc_rs232_rx),
-        .byte_valid(bmc_rx_valid), .byte_data(bmc_rx_data), .framing_error(bmc_rx_error)
-    );
-
-    uart_tx_byte #(.CLKS_PER_BIT(217)) u_bmc_tx (
-        .clk(sys_clk), .rst_n(sys_rst_n),
-        .byte_valid(bmc_tx_valid), .byte_data(bmc_tx_data),
-        .tx_o(bmc_rs232_tx), .busy(bmc_tx_busy), .byte_done()
-    );
-
-    wire        bmc_wr_en;
-    wire [5:0]  bmc_wr_addr;
-    wire [7:0]  bmc_wr_data;
 
-    bmc_ascii_poll #(
-        .CLOCK_HZ(25000000),
-        .POLL_SECONDS(1),
-        .ROUND_TIMEOUT_CLKS(12500000),
-        .INTER_BYTE_TIMEOUT_CLKS(250000)
-    ) u_bmc_poll (
+    duty_register_bank #(
+        .CHANNEL_COUNT(32), .ADDR_WIDTH(5),
+        .PTC_DEFAULT(8'd0), .FAN_DEFAULT(8'd20),
+        .DEFAULT_PTC_MASK(32'h00FFFFFF)
+    ) u_telemetry_bank (
         .clk(sys_clk), .rst_n(sys_rst_n),
-        .tx_valid(bmc_tx_valid), .tx_data(bmc_tx_data), .tx_ready(!bmc_tx_busy),
-        .rx_valid(bmc_rx_valid), .rx_data(bmc_rx_data),
-        .wr_en(bmc_wr_en), .wr_addr(bmc_wr_addr), .wr_data(bmc_wr_data)
+        .pwm_addr(gd_bank_addr), .pwm_duty(gd_bank_duty),
+        .stage_we(stage_we), .stage_addr(stage_addr), .stage_data(stage_data),
+        .commit(duty_commit_r), .invalidate(duty_invalidate),
+        .valid(), .active_bank()
     );
 
-    wire        ct_scl_drive_low, ct_sda_drive_low;
-    wire        ct_wr_en;
-    wire [5:0]  ct_wr_addr;
-    wire [7:0]  ct_wr_data;
-    wire        scl_in = (temp_scl === 1'b0) ? 1'b0 : 1'b1;
-    wire        sda_in = (temp_sda === 1'b0) ? 1'b0 : 1'b1;
+    // ---------- CT7428 3-chip 27-channel scanner (U6=0x49, U24=0x48, U25=0x4B) ----------
+    // Note: No CPLD BMC UART in 6400 V1.1 No-MCU mode; Windows host polls DIMMs via BMC NET.
+    wire         ct_scl_drive_low, ct_sda_drive_low, ct_wr_en;
+    wire [5:0]   ct_wr_addr;
+    wire [7:0]   ct_wr_data;
+    wire [103:0] ct_diagnostic_data;
+    wire         scl_in = (temp_scl === 1'b0) ? 1'b0 : 1'b1;
+    wire         sda_in = (temp_sda === 1'b0) ? 1'b0 : 1'b1;
 
     ct7428_scan #(
         .HALF_PERIOD_CLKS(125),
         .TIMEOUT_CLKS(25000),
         .GAP_CLKS(250),
-        .TEMP_BASE(32)
+        .TEMP_BASE(32),
+        .CHANNEL_LAST(5'd26),
+        .DIAGNOSTIC_REGISTERS(0),
+        .DEVICE_49(7'h49),
+        .DEVICE_48(7'h48),
+        .DEVICE_4B(7'h4b)
     ) u_ct_scan (
         .clk(sys_clk), .rst_n(sys_rst_n),
         .scl_i(scl_in), .sda_i(sda_in),
         .scl_drive_low(ct_scl_drive_low), .sda_drive_low(ct_sda_drive_low),
         .temp_wr_addr(ct_wr_addr), .temp_wr_data(ct_wr_data), .temp_wr_en(ct_wr_en),
-        .scan_channel(), .scan_round_done()
+        .scan_channel(), .scan_round_done(),
+        .diagnostic_data(ct_diagnostic_data)
     );
 
     assign temp_scl = ct_scl_drive_low ? 1'b0 : 1'bz;
     assign temp_sda = ct_sda_drive_low ? 1'b0 : 1'bz;
 
-    wire        temp_wr_en = bmc_wr_en | ct_wr_en;
-    wire [5:0]  temp_wr_addr = bmc_wr_en ? bmc_wr_addr : ct_wr_addr;
-    wire [7:0]  temp_wr_data = bmc_wr_en ? bmc_wr_data : ct_wr_data;
-    wire [5:0]  gd_temp_addr;
-    wire [7:0]  gd_temp_data;
-    wire        gd_temp_valid;
-    temp_ram u_temp_ram (
-        .clk(sys_clk),
-        .rst_n(sys_rst_n),
-        .wr_en(temp_wr_en), .wr_addr(temp_wr_addr), .wr_data(temp_wr_data),
+    wire [5:0] gd_temp_addr;
+    wire [7:0] gd_temp_data;
+    wire       gd_temp_valid;
+
+    temp_ram #(.CT_ACTIVE_COUNT(6'd27)) u_temp_ram (
+        .clk(sys_clk), .rst_n(sys_rst_n),
+        .wr_en(ct_wr_en), .wr_addr(ct_wr_addr), .wr_data(ct_wr_data),
         .rd_addr(gd_temp_addr), .rd_data(gd_temp_data), .rd_valid(gd_temp_valid)
     );
 
-    // ---------- transaction core ----------
+    // ---------- transaction core (SET 32B / GET 83B / 1s AUTO 0x42 + 0x52 format 3) ----------
     wire        group_valid;
     wire        group_second;
     wire [7:0]  group_type;
@@ -252,14 +240,22 @@ module prod2u_6400_final_top (
     wire        wd_arm;
     wire        wd_counting;
 
+    wire [7:0]   diagnostic_flags = {3'b0, bank_valid, wd_expired, 3'b0};
+    wire [119:0] diagnostic_data  = {diagnostic_flags, 8'd0, ct_diagnostic_data};
+
     m6400_transaction_core #(
         .DUTY_COUNT(32),
         .GET_DUTY_PREFIX_COUNT(32),
-        .DIAG_ENABLE(0),
-        .EXTRA_IO_ENABLE(0)
+        .DIAG_ENABLE(1),
+        .EXTRA_IO_ENABLE(0),
+        .BMC_COUNT(24),
+        .CT_COUNT(27),
+        .BEACON_PERIOD(BEACON_PERIOD),
+        .DIAG_FORMAT(8'd3),
+        .DIAG_BOARD_ID(8'h61)
     ) u_core (
         .clk(sys_clk), .rst_n(sys_rst_n),
-        .diagnostic_data(120'd0),
+        .diagnostic_data(diagnostic_data),
         .req_valid(req_valid), .req_ready(req_ready),
         .req_type(req_type), .req_length(req_length),
         .req_ram_rd_addr(req_ram_rd_addr_core), .req_ram_rd_data(req_ram_rd_data),
@@ -285,14 +281,10 @@ module prod2u_6400_final_top (
         .hood_close_btn_sync(1'b0),
         .buzzer_ctrl_out()
     );
-    // The core raises get_busy while a GET group is being assembled; that flag
-    // owns the bank read port for the duration.
-    assign get_assembling = get_busy;
 
     // ---------- reply arbiter ----------
     wire [3:0]  done_grant;
     wire        done_launch;
-    wire [7:0]  arb_base;
     reply_arbiter u_arb (
         .clk(sys_clk), .rst_n(sys_rst_n),
         .group_valid(group_valid), .group_second(group_second),
@@ -307,18 +299,24 @@ module prod2u_6400_final_top (
         .tx_busy(tx_busy), .tx_done(tx_done)
     );
 
-    // ---------- watchdog ----------
-    watchdog_30s #(.TIMEOUT_CLKS(750000000)) u_wd (
+    // ---------- 30s watchdog ----------
+    watchdog_30s #(.TIMEOUT_CLKS(WD_TIMEOUT_CLKS)) u_wd (
         .clk(sys_clk), .rst_n(sys_rst_n),
         .arm(wd_arm), .reload(wd_reload),
         .expired(wd_expired), .counting(wd_counting)
     );
 
-    // ---------- PWM carrier + board adapter (existing, reused) ----------
+    // ---------- Unified 20 Hz PWM carrier + V1.1 fan polarity adapter (8'h0F) ----------
     wire [31:0] logical_bitmap;
     wire        pwm_deadline_miss;
-    wire        pwm_scan_idle;
-    pwm_bitmap_engine #(.CHANNEL_COUNT(32)) u_pwm (
+    pwm_bitmap_engine #(
+        .CHANNEL_COUNT(32),
+        .PTC_PHASE_CLKS(PWM_PHASE_CLKS),
+        .FAN_PHASE_CLKS(PWM_PHASE_CLKS),
+        .ADDR_WIDTH(5),
+        .RESET_FAN_DUTY(8'd20),
+        .RESET_FAN_MASK(32'hFF000000)
+    ) u_pwm (
         .clk(sys_clk), .rst_n(sys_rst_n),
         .runtime_duty_ready(bank_valid),
         .duty_rd_addr(pwm_addr), .duty_rd_data(pwm_duty),
@@ -332,15 +330,13 @@ module prod2u_6400_final_top (
 
     wire [3:0] front_ball;
     wire [3:0] rear_ball;
-    fan_board_output_adapter u_fan_adapter (
+    fan_board_output_adapter #(.BOARD_INVERT_MASK(8'h0F)) u_fan_adapter (
         .logical_fan_on(logical_bitmap[31:24]),
         .front_fan_ball(front_ball),
         .rear_fan_ball(rear_ball)
     );
 
-    // PTC: channels 0..23, active high.  Front/Rear: the board adapter maps
-    // the 8 fan bitmap bits (24..31) through FAN_BOARD_INVERT_MASK to balls.
-    assign ptc_pwm_out = logical_bitmap[23:0];
+    assign ptc_pwm_out       = logical_bitmap[23:0];
     assign front_fan_pwm_out = front_ball;
-    assign rear_fan_pwm_out = rear_ball;
+    assign rear_fan_pwm_out  = rear_ball;
 endmodule

+ 3 - 4
td/bitgen/prod2u_6400_front_back.tcl

@@ -9,8 +9,7 @@ if {![file isfile $routed_db]} {
 
 import_device ef2_4.db -package EF2L45BG256B
 import_db $routed_db
-# The V1.1 hardware top exposes only the fully constrained CON78 Host RS-232
-# interface.  Do not permit any unbound package port to be auto-placed.
-bitgen -bit prod2u_6400_front_back.bit
+# V1.1 No-MCU production bitstream + matching .bmk mask for 200 kHz SRAM readback verify
+bitgen -bit prod2u_6400_front_back.bit -gen_mask -version 31
 puts "6400_BITGEN_DONE=1"
-exit
+exit

+ 5 - 1
td/syn/prod2u_6400_front_back.tcl

@@ -12,7 +12,11 @@ proc src {relative} {
 }
 proc analyze_src {relative} {
     global source_root
-    analyze -file [src $relative] -include_dir $source_root -define PROD2U_TD_VENDOR_RAM
+    if {[info exists ::env(PROD2U_BUILD_INCLUDE)]} {
+        analyze -file [src $relative] -include_dir $source_root -define PROD2U_TD_VENDOR_RAM -global_include $::env(PROD2U_BUILD_INCLUDE)
+    } else {
+        analyze -file [src $relative] -include_dir $source_root -define PROD2U_TD_VENDOR_RAM
+    }
 }
 
 import_device ef2_4.db -package EF2L45BG256B

+ 3 - 3
tests/sim/prod2u_6400_final_e2e_tb.v

@@ -49,13 +49,13 @@ module prod2u_6400_final_e2e_tb;
         .host_rs232_tx(host_rs232_tx),
         .host_ttl_rx(1'b1),
         .host_ttl_tx(),
-        .bmc_rs232_rx(1'b1),
-        .bmc_rs232_tx(),
         .ptc_pwm_out(ptc_pwm_out),
         .front_fan_pwm_out(front_fan_pwm_out),
         .rear_fan_pwm_out(rear_fan_pwm_out),
         .temp_scl(),
-        .temp_sda()
+        .temp_sda(),
+        .temp_scl_alt(),
+        .temp_sda_alt()
     );
 
     // ---------- independent CRC ----------

+ 399 - 0
tests/sim/prod2u_6400_v11_nomcu_tb.v

@@ -0,0 +1,399 @@
+`timescale 1ns/1ps
+
+// =============================================================================
+// 1:1 Verification Testbench for 6400 V1.1 Standalone No-MCU CPLD
+// Verifies:
+//   1) Unified 20 Hz PWM carrier (accelerated PWM_PHASE_CLKS=10 for sim speed,
+//      default 12500 checked at parameter level) + FAN_BOARD_INVERT_MASK = 8'h0F
+//      (Front0..3 inverted, Rear0..3 non-inverted).
+//   2) No CPLD BMC UART: GET_DATA bytes 32..55 are deterministically 0xFF.
+//   3) 3-chip CT7428 I2C master on M8/N9 (U6=0x49, U24=0x48, U25=0x4B -> all
+//      27 CT channels in GET_DATA bytes 56..82), with temp_scl_alt/temp_sda_alt
+//      permanently Hi-Z.
+//   4) 32-byte SET_ALL -> SET_ACK (0x81), GET_ALL -> GET_ACK (0x82) + 83B GET_DATA
+//      over both RS-232 (CON78) and 3.3V TTL (CON30) with TX broadcast mirroring.
+//   5) Always-on autonomous debug burst: 0x42 (83B) + 0x52 (20B, format=3,
+//      board_id=0x61, fw=3.3.0) with valid independent CRC16.
+//   6) Watchdog expiry reverts outputs to PTC=0% / FAN=20% and direct SET recovers.
+// =============================================================================
+module prod2u_6400_v11_nomcu_tb;
+    localparam integer HOST_BAUD = 921600;
+    localparam integer CLKS_PER_BIT = 27;
+    localparam real    BIT_NS = 1000000000.0 / HOST_BAUD;
+
+    reg clk = 1'b0;
+    always #20 clk = ~clk; // 25 MHz
+
+    reg  rs232_rx = 1'b1;
+    wire rs232_tx;
+    reg  ttl_rx = 1'b1;
+    wire ttl_tx;
+    wire [23:0] ptc_pwm_out;
+    wire [3:0]  front_fan_pwm_out;
+    wire [3:0]  rear_fan_pwm_out;
+    tri1 temp_scl;
+    tri1 temp_sda;
+    wire temp_scl_alt;
+    wire temp_sda_alt;
+
+    // Accelerated PWM/beacon/watchdog for fast full-chain simulation
+    prod2u_6400_final_top #(
+        .HOST_BAUD(HOST_BAUD),
+        .PWM_PHASE_CLKS(10),
+        .BEACON_PERIOD(32'd180000),
+        .WD_TIMEOUT_CLKS(80000)
+    ) dut (
+        .sys_clk(clk),
+        .host_rs232_rx(rs232_rx), .host_rs232_tx(rs232_tx),
+        .host_ttl_rx(ttl_rx),     .host_ttl_tx(ttl_tx),
+        .ptc_pwm_out(ptc_pwm_out),
+        .front_fan_pwm_out(front_fan_pwm_out),
+        .rear_fan_pwm_out(rear_fan_pwm_out),
+        .temp_scl(temp_scl),      .temp_sda(temp_sda),
+        .temp_scl_alt(temp_scl_alt), .temp_sda_alt(temp_sda_alt)
+    );
+
+    // -------------------------------------------------------------------------
+    // Behavioral 3-chip CT7428 I2C Slave Responder (0x49, 0x48, 0x4B)
+    // Returns unique temperature per chip/register:
+    //   0x49 reg r -> (30 + r) C
+    //   0x48 reg r -> (40 + r) C
+    //   0x4B reg r -> (50 + r) C
+    // -------------------------------------------------------------------------
+    reg sda_slave_low = 1'b0;
+    assign temp_sda = sda_slave_low ? 1'b0 : 1'bz;
+
+    reg [1:0]  i2c_st = 2'd0; // 0=idle, 1=addr, 2=reg, 3=read_data
+    reg [7:0]  i2c_shift = 8'd0;
+    reg [3:0]  i2c_bit = 4'd0;
+    reg [6:0]  i2c_addr = 7'd0;
+    reg        i2c_rw = 1'b0;
+    reg [7:0]  i2c_reg = 8'd0;
+    reg [15:0] i2c_rd_word = 16'd0;
+    reg        i2c_byte_hi = 1'b1;
+    reg        prev_scl = 1'b1, prev_sda = 1'b1;
+
+    function [15:0] ct_word_for;
+        input [6:0] dev;
+        input [7:0] rg;
+        reg [7:0] deg;
+        begin
+            if (dev == 7'h49)      deg = 8'd30 + rg;
+            else if (dev == 7'h48) deg = 8'd40 + rg;
+            else                   deg = 8'd50 + rg;
+            ct_word_for = {1'b0, deg, 7'b0100000}; // +0.25 C fraction discarded -> exact deg
+        end
+    endfunction
+
+    always @(posedge clk) begin
+        prev_scl <= temp_scl;
+        prev_sda <= temp_sda;
+        // START condition: SDA falling while SCL high
+        if (temp_scl && prev_scl && prev_sda && !temp_sda) begin
+            i2c_st        <= 2'd1;
+            i2c_bit       <= 4'd0;
+            sda_slave_low <= 1'b0;
+        end else if (temp_scl && prev_scl && !prev_sda && temp_sda) begin
+            // STOP condition
+            i2c_st        <= 2'd0;
+            sda_slave_low <= 1'b0;
+        end else if (!prev_scl && temp_scl) begin
+            // Rising SCL: sample master bits
+            if (i2c_st == 2'd1) begin
+                if (i2c_bit < 4'd8) begin
+                    i2c_shift <= {i2c_shift[6:0], temp_sda};
+                    i2c_bit   <= i2c_bit + 4'd1;
+                end else begin
+                    i2c_bit <= 4'd0;
+                    if (i2c_rw) begin
+                        i2c_rd_word <= ct_word_for(i2c_addr, i2c_reg);
+                        i2c_byte_hi <= 1'b1;
+                        i2c_st      <= 2'd3;
+                    end else begin
+                        i2c_st <= 2'd2;
+                    end
+                end
+            end else if (i2c_st == 2'd2) begin
+                if (i2c_bit < 4'd8) begin
+                    i2c_shift <= {i2c_shift[6:0], temp_sda};
+                    i2c_bit   <= i2c_bit + 4'd1;
+                end else begin
+                    i2c_bit <= 4'd0;
+                    i2c_st  <= 2'd0;
+                end
+            end else if (i2c_st == 2'd3) begin
+                if (i2c_bit < 4'd8) begin
+                    i2c_bit <= i2c_bit + 4'd1;
+                end else begin
+                    i2c_bit <= 4'd0;
+                    if (i2c_byte_hi) i2c_byte_hi <= 1'b0;
+                    else             i2c_st      <= 2'd0;
+                end
+            end
+        end else if (prev_scl && !temp_scl) begin
+            // Falling SCL: drive ACK or read data bit
+            sda_slave_low <= 1'b0;
+            if (i2c_st == 2'd1 && i2c_bit == 4'd8) begin
+                i2c_addr <= i2c_shift[7:1];
+                i2c_rw   <= i2c_shift[0];
+                if (i2c_shift[7:1] == 7'h49 || i2c_shift[7:1] == 7'h48 || i2c_shift[7:1] == 7'h4B)
+                    sda_slave_low <= 1'b1; // ACK
+            end else if (i2c_st == 2'd2 && i2c_bit == 4'd8) begin
+                i2c_reg       <= i2c_shift;
+                sda_slave_low <= 1'b1; // ACK
+            end else if (i2c_st == 2'd3 && i2c_bit < 4'd8) begin
+                if (i2c_byte_hi)
+                    sda_slave_low <= ~i2c_rd_word[15 - i2c_bit];
+                else
+                    sda_slave_low <= ~i2c_rd_word[7 - i2c_bit];
+            end
+        end
+    end
+
+    // -------------------------------------------------------------------------
+    // Independent CRC16 & UART helpers
+    // -------------------------------------------------------------------------
+    function [15:0] crc16_step;
+        input [15:0] cur;
+        input [7:0]  b;
+        integer k;
+        reg [15:0] c;
+        begin
+            c = cur ^ {b, 8'h00};
+            for (k = 0; k < 8; k = k + 1)
+                c = c[15] ? ({c[14:0], 1'b0} ^ 16'h1021) : {c[14:0], 1'b0};
+            crc16_step = c;
+        end
+    endfunction
+
+    task automatic send_byte;
+        input       use_ttl;
+        input [7:0] val;
+        integer k;
+        begin
+            if (use_ttl) ttl_rx = 1'b0; else rs232_rx = 1'b0;
+            #(BIT_NS);
+            for (k = 0; k < 8; k = k + 1) begin
+                if (use_ttl) ttl_rx = val[k]; else rs232_rx = val[k];
+                #(BIT_NS);
+            end
+            if (use_ttl) ttl_rx = 1'b1; else rs232_rx = 1'b1;
+            #(BIT_NS);
+        end
+    endtask
+
+    reg [7:0] tx_pl [0:63];
+    task automatic send_frame;
+        input       use_ttl;
+        input [7:0] ftype;
+        input [7:0] flen;
+        integer k;
+        reg [15:0] crc;
+        begin
+            crc = crc16_step(crc16_step(16'hFFFF, ftype), flen);
+            send_byte(use_ttl, 8'hA5);
+            send_byte(use_ttl, 8'h5A);
+            send_byte(use_ttl, ftype);
+            send_byte(use_ttl, flen);
+            for (k = 0; k < flen; k = k + 1) begin
+                crc = crc16_step(crc, tx_pl[k]);
+                send_byte(use_ttl, tx_pl[k]);
+            end
+            send_byte(use_ttl, crc[7:0]);
+            send_byte(use_ttl, crc[15:8]);
+        end
+    endtask
+
+    // Continuous TX stream frame collector
+    reg [7:0] rx_buf [0:255];
+    integer   rx_pos = 0;
+    integer   got_set_ack = 0;
+    integer   got_get_ack = 0;
+    integer   got_get_data = 0;
+    integer   got_diag = 0;
+    reg [7:0] last_get_data [0:82];
+    reg [7:0] last_diag [0:19];
+    integer   failures = 0;
+
+    // Verify TX mirroring continuously
+    always @(posedge clk) begin
+        if ($time > 200000 && rs232_tx !== ttl_tx) begin
+            $display("FAIL mirror: rs232_tx=%b ttl_tx=%b", rs232_tx, ttl_tx);
+            failures = failures + 1;
+        end
+        if (temp_scl_alt !== 1'bz || temp_sda_alt !== 1'bz) begin
+            $display("FAIL alt_i2c_hiz: scl_alt=%b sda_alt=%b", temp_scl_alt, temp_sda_alt);
+            failures = failures + 1;
+        end
+    end
+
+    // Decode FPGA TX bytes into verified frames
+    initial begin : tx_monitor
+        reg [7:0] b;
+        integer bit_i, k;
+        reg [15:0] crc;
+        reg [7:0] ftype, flen;
+        forever begin
+            @(negedge rs232_tx);
+            #(1080.0 * 1.5);
+            for (bit_i = 0; bit_i < 8; bit_i = bit_i + 1) begin
+                b[bit_i] = rs232_tx;
+                #(1080.0);
+            end
+            if (rx_pos == 0) begin
+                if (b == 8'hA5) begin rx_buf[0] = b; rx_pos = 1; end
+            end else if (rx_pos == 1) begin
+                if (b == 8'h5A) begin rx_buf[1] = b; rx_pos = 2; end
+                else if (b == 8'hA5) rx_pos = 1;
+                else rx_pos = 0;
+            end else begin
+                rx_buf[rx_pos] = b;
+                rx_pos = rx_pos + 1;
+                if (rx_pos >= 4) begin
+                    flen = rx_buf[3];
+                    if (rx_pos == (flen + 6)) begin
+                        ftype = rx_buf[2];
+                        crc = 16'hFFFF;
+                        for (k = 2; k < flen + 4; k = k + 1)
+                            crc = crc16_step(crc, rx_buf[k]);
+                        if (crc[7:0] !== rx_buf[flen + 4] || crc[15:8] !== rx_buf[flen + 5]) begin
+                            $display("FAIL tx_crc: type=%02h len=%0d", ftype, flen);
+                            failures = failures + 1;
+                        end else begin
+                            if (ftype == 8'h81 && flen == 8'd0) got_set_ack = got_set_ack + 1;
+                            else if (ftype == 8'h82 && flen == 8'd0) got_get_ack = got_get_ack + 1;
+                            else if (ftype == 8'h42 && flen == 8'd83) begin
+                                for (k = 0; k < 83; k = k + 1) last_get_data[k] = rx_buf[4 + k];
+                                got_get_data = got_get_data + 1;
+                            end else if (ftype == 8'h52 && flen == 8'd20) begin
+                                for (k = 0; k < 20; k = k + 1) last_diag[k] = rx_buf[4 + k];
+                                got_diag = got_diag + 1;
+                            end
+                        end
+                        rx_pos = 0;
+                    end
+                end
+            end
+        end
+    end
+
+    integer k, cyc, ptc0_hi, front0_hi, rear0_hi;
+    integer prev_ack, prev_gd, prev_diag;
+
+    initial begin
+        // Wait for POR + 1 full 27-channel 3-chip CT7428 scan round (~13 ms sim time)
+        wait (dut.u_ct_scan.scan_round_done === 1'b1);
+        repeat (500) @(posedge clk);
+
+        // 1. Check power-on default PWM polarity (PTC=0%, Front0=20% inverted -> 80% HIGH on ball, Rear0=20% non-inverted -> 20% HIGH)
+        ptc0_hi = 0; front0_hi = 0; rear0_hi = 0;
+        for (cyc = 0; cyc < 1000; cyc = cyc + 1) begin
+            @(posedge clk);
+            if (ptc_pwm_out[0])       ptc0_hi   = ptc0_hi + 1;
+            if (front_fan_pwm_out[0]) front0_hi = front0_hi + 1;
+            if (rear_fan_pwm_out[0])  rear0_hi  = rear0_hi + 1;
+        end
+        if (ptc0_hi != 0 || front0_hi < 780 || front0_hi > 820 || rear0_hi < 180 || rear0_hi > 220) begin
+            $display("FAIL boot_pwm: ptc0=%0d front0=%0d rear0=%0d", ptc0_hi, front0_hi, rear0_hi);
+            failures = failures + 1;
+        end
+
+        // 2. Send 32B SET_ALL over RS-232 (CON78): PTC[i]=10+i, Front=40,50,60,70, Rear=30,45,65,80
+        for (k = 0; k < 24; k = k + 1) tx_pl[k] = 8'd10 + k[7:0];
+        tx_pl[24] = 8'd40; tx_pl[25] = 8'd50; tx_pl[26] = 8'd60; tx_pl[27] = 8'd70;
+        tx_pl[28] = 8'd30; tx_pl[29] = 8'd45; tx_pl[30] = 8'd65; tx_pl[31] = 8'd80;
+        prev_ack = got_set_ack;
+        send_frame(1'b0, 8'h01, 8'd32);
+        repeat (3000) @(posedge clk);
+        if (got_set_ack != prev_ack + 1) begin
+            $display("FAIL set_ack_rs232: got=%0d", got_set_ack);
+            failures = failures + 1;
+        end
+
+        // 3. Send GET_ALL over 3.3V TTL (CON30) -> verify 83B GET_DATA (duties + 24xFF BMC + 27 live CT7428!)
+        // Note: 6B GET_ACK + 89B GET_DATA = 95 bytes * 10 bits * 27 clks = 25,650 clks.
+        prev_gd = got_get_data;
+        send_frame(1'b1, 8'h02, 8'd0);
+        repeat (35000) @(posedge clk);
+        if (got_get_data <= prev_gd || got_get_ack < 1) begin
+            $display("FAIL get_all_ttl: ack=%0d data=%0d", got_get_ack, got_get_data);
+            failures = failures + 1;
+        end else begin
+            for (k = 0; k < 24; k = k + 1) begin
+                if (last_get_data[k] !== (8'd10 + k[7:0])) begin
+                    $display("FAIL get_ptc[%0d]=%0d", k, last_get_data[k]);
+                    failures = failures + 1;
+                end
+            end
+            if (last_get_data[24] !== 8'd40 || last_get_data[31] !== 8'd80) begin
+                $display("FAIL get_fan: front0=%0d rear3=%0d", last_get_data[24], last_get_data[31]);
+                failures = failures + 1;
+            end
+            for (k = 32; k < 56; k = k + 1) begin
+                if (last_get_data[k] !== 8'hFF) begin
+                    $display("FAIL bmc_must_be_FF[%0d]=%02h", k - 32, last_get_data[k]);
+                    failures = failures + 1;
+                end
+            end
+            // Verify all 3 CT7428 chips (U6=30..38, U24=40..48, U25=50..58)
+            for (k = 0; k < 9; k = k + 1) begin
+                if (last_get_data[56 + k] !== (8'd30 + k[7:0])) begin
+                    $display("FAIL ct_u6[%0d]=%0d exp=%0d", k, last_get_data[56 + k], 30 + k);
+                    failures = failures + 1;
+                end
+                if (last_get_data[65 + k] !== (8'd40 + k[7:0])) begin
+                    $display("FAIL ct_u24[%0d]=%0d exp=%0d", k, last_get_data[65 + k], 40 + k);
+                    failures = failures + 1;
+                end
+                if (last_get_data[74 + k] !== (8'd50 + k[7:0])) begin
+                    $display("FAIL ct_u25[%0d]=%0d exp=%0d", k, last_get_data[74 + k], 50 + k);
+                    failures = failures + 1;
+                end
+            end
+        end
+
+        // 4. Wait for watchdog expiry (80,000 clks) + autonomous 0x52 DIAGNOSTIC (format=3, board=0x61, fw=3.3.0)
+        prev_diag = got_diag;
+        repeat (190000) @(posedge clk);
+        if (got_diag <= prev_diag) begin
+            $display("FAIL auto_diag: no 0x52 diagnostic emitted");
+            failures = failures + 1;
+        end else begin
+            if (last_diag[0] !== 8'd3 || last_diag[1] !== 8'h61 ||
+                last_diag[2] !== 8'd3 || last_diag[3] !== 8'd3 || last_diag[4] !== 8'd0) begin
+                $display("FAIL diag_id: fmt=%0d bid=%02h fw=%0d.%0d.%0d",
+                         last_diag[0], last_diag[1], last_diag[2], last_diag[3], last_diag[4]);
+                failures = failures + 1;
+            end
+        end
+
+        // Verify watchdog reverted PTC0 to 0% and Rear0 to 20%
+        ptc0_hi = 0; rear0_hi = 0;
+        for (cyc = 0; cyc < 1000; cyc = cyc + 1) begin
+            @(posedge clk);
+            if (ptc_pwm_out[0])      ptc0_hi  = ptc0_hi + 1;
+            if (rear_fan_pwm_out[0]) rear0_hi = rear0_hi + 1;
+        end
+        if (ptc0_hi != 0 || rear0_hi < 180 || rear0_hi > 220) begin
+            $display("FAIL wd_revert: ptc0=%0d rear0=%0d", ptc0_hi, rear0_hi);
+            failures = failures + 1;
+        end
+
+        // 5. Direct SET recovery after watchdog expiry (no reset required)
+        tx_pl[0] = 8'd60;
+        prev_ack = got_set_ack;
+        send_frame(1'b0, 8'h01, 8'd32);
+        repeat (3000) @(posedge clk);
+        if (got_set_ack != prev_ack + 1) begin
+            $display("FAIL wd_recover_set");
+            failures = failures + 1;
+        end
+
+        if (failures == 0) begin
+            $display("PASS prod2u_6400_v11_nomcu_tb: 32B SET, 83B GET (BMC=24xFF, 3-chip CT27 live), 20Hz PWM 8'h0F, RS232<->TTL, AUTO 0x52 format=3 board=0x61 fw=3.3.0, WD recovery");
+        end else begin
+            $fatal(1, "prod2u_6400_v11_nomcu_tb FAIL (%0d errors)", failures);
+        end
+        $finish;
+    end
+endmodule

+ 77 - 0
tests/unit/test_6400_v11_nomcu_pid.py

@@ -0,0 +1,77 @@
+"""Unit tests for 6400 V1.1 standalone branch (No-MCU + BMC NET + Adaptive PID)."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+if str(ROOT / "tools") not in sys.path:
+    sys.path.insert(0, str(ROOT / "tools"))
+
+import v11_bmc_net as bmc_net
+import v11_adaptive_pid as pid
+import v11_nomcu_gui as v11_gui
+
+
+def test_fips197_aes128_and_oem_dimm_parser():
+    res = bmc_net.self_test_crypto_and_decoder()
+    assert res["aes128_fips197_kat"] == "PASS"
+    assert res["oem_dimm_parser"] == "PASS"
+
+
+def test_6400_v11_wire_codec_and_diag_format3():
+    # Golden 32B standby SET_ALL
+    f = v11_gui.encode_frame(0x01, bytes([0] * 24 + [20] * 8))
+    assert f[:4] == bytes([0xA5, 0x5A, 0x01, 0x20])
+    assert f[-2:] == bytes([0xE7, 0x0A])
+
+    # 83B GET_DATA (BMC=24xFF, CT27 live) + 20B DIAG format=3 board_id=0x61
+    get_pl = bytes([10] * 24 + [30] * 4 + [35] * 4 + [0xFF] * 24 + [28 + (i % 5) for i in range(27)])
+    diag_pl = bytes([3, 0x61, 3, 3, 0, 0x27, 0x10, 1, 0x49, 1, 0, 0x80, 0x0C, 25, 0xFF, 1, 1, 0, 0, 0x10])
+    dec = v11_gui.V11StreamDecoder()
+    # Feed byte-by-byte with leading noise
+    stream = b"\xAA\xBB\xA5\x00" + v11_gui.encode_frame(0x42, get_pl) + v11_gui.encode_frame(0x52, diag_pl)
+    frames = []
+    for i in range(0, len(stream), 7):
+        frames.extend(dec.feed(stream[i : i + 7]))
+    assert len(frames) == 2
+    g = v11_gui.decode_v11_get_data(frames[0][1])
+    assert g["ptc"] == [10] * 24 and g["front"] == [30] * 4 and g["rear"] == [35] * 4
+    assert all(x is None for x in g["bmc_cpld"])
+    assert g["ct"][0] == 28.0 and g["ct"][1] == 29.0
+    d = v11_gui.decode_v11_diagnostic(frames[1][1])
+    assert d["supported"] is True and d["format"] == 3 and d["board_id"] == 0x61
+    assert d["firmware_version"] == "3.3.0" and d["duty_bank_valid"] is True
+
+
+def test_adaptive_pid_convergence_disturbance_budget_and_dropout():
+    res = v11_gui.run_self_test()
+    assert res["status"] == "PASS"
+    assert res["overall_passed_at_s"] is not None
+    assert res["max_overshoot_c"] < 3.0
+    assert res["bmc_dropout_ct_fallback"] is True
+    for err in res["final_abs_errors_c"].values():
+        assert err < 1.2
+
+
+def test_bumpless_auto_manual_and_spatial_uniformity_trim():
+    cfg = pid.AdaptivePidConfig(uniformity_spread_c=2.0, uniformity_ptc_trim_pct=10.0)
+    ctrl = pid.AdaptiveThermalController(cfg)
+    ctrl.reset(initial_ptc=[40] * 24, initial_front=[25] * 4, initial_rear=[25] * 4)
+    # Manual step
+    dimms = [55.0, 56.0, 58.0, 60.0, 62.0, 64.0] * 4  # 9 C spread inside each chamber!
+    cts = [50.0] * 27
+    out_man = ctrl.step(dt_s=1.0, bmc_dimm_temps_c=dimms, ct_temps_c=cts, bmc_ok=True)
+    assert out_man["chambers"][1]["regime"] == "MANUAL"
+    # Bumpless engage AUTO: first step must stay smooth (bounded by slew limit)
+    ctrl.set_auto_mode(True)
+    out_auto = ctrl.step(dt_s=1.0, bmc_dimm_temps_c=dimms, ct_temps_c=cts, bmc_ok=True)
+    assert abs(out_auto["chambers"][1]["ptc_cmd"] - 40.0) <= cfg.max_ptc_slew_per_s + 0.1
+    # Cooler DIMM0 gets higher PTC duty than hotter DIMM5 in same chamber
+    assert out_auto["ptc_24"][0] > out_auto["ptc_24"][5]
+    # Below fan_intervention_ref_temp_c (55 C), preheat fan floor stays 20%
+    assert out_auto["front_4"][0] == 20
+    # Once chamber air reaches 58 C (> 55 C intervention), 9 C DIMM spread triggers mixing fan boost
+    out_hot = ctrl.step(dt_s=1.0, bmc_dimm_temps_c=dimms, ct_temps_c=[58.0] * 27, bmc_ok=True)
+    assert out_hot["front_4"][0] > 20

+ 678 - 0
tools/v11_adaptive_pid.py

@@ -0,0 +1,678 @@
+#!/usr/bin/env python3
+"""Advanced Multi-Chamber Adaptive PID Thermal Controller for 6400 V1.1 (No-MCU).
+
+All complex control logic lives on the Windows host PC so the 6400 V1.1 CPLD
+remains ultra-simple and minimal-LUT:
+  - CPLD accepts plain 32-byte SET_ALL: [PTC0..23, Front0..3, Rear0..3] @ 20 Hz.
+  - DIMM temperatures (24 slots, 0.25 C resolution) come directly via BMC NET.
+  - Chamber air temperatures (27 CT7428 channels) come from CPLD GET_DATA.
+
+Control Architecture:
+  1. Per-chamber smooth setpoint trajectory planner (target temp + ramp rate +
+     S-curve approach + ETA estimator).
+  2. Dual-sensor cascade & Smith-predictor air-lead compensation fusing BMC NET
+     DIMM temp (precision outer loop) with CT7428 air temp (fast inner loop),
+     plus automatic CT-based virtual-DIMM fallback during BMC NET dropouts.
+  3. Online Recursive Least Squares (RLS) thermal plant estimator identifying
+     per-chamber heating gain, cooling gain, and DIMM self-heating disturbance
+     (e.g. MemTest86 burn-in load steps) with automatic gain scheduling.
+  4. 3-regime Adaptive PID (PREHEAT_BOOST / APPROACH_BRAKE / PRECISION_HOLD),
+     derivative-on-measurement, low-pass derivative filter, back-calculation
+     anti-windup, cross-chamber thermal crosstalk compensation, and bumpless
+     Auto <-> Manual transfer.
+  5. Coordinated split-range actuator allocator:
+     - 24 PTCs with global power-budget cap & intra-chamber spatial uniformity
+       trim across each chamber's 6 heaters.
+     - 4 Front (intake) + 4 Rear (exhaust) fans with fan-intervention rule
+       (delay time or ref-temp threshold), intra-chamber uniformity mixing boost,
+       configurable rear/front pressure ratio, and slew-rate limiting.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import math
+from typing import Any
+
+
+def _clamp(val: float, lo: float, hi: float) -> float:
+    return lo if val < lo else (hi if val > hi else val)
+
+
+# Default 6400 V1.1 channel mapping (4 chambers x 6 PTC + 6 BMC DIMMs + CT air)
+DEFAULT_V11_CHAMBER_MAP: dict[int, dict[str, Any]] = {
+    1: {"name": "腔体 1", "ptc": [0, 1, 2, 3, 4, 5], "bmc": [0, 1, 2, 3, 4, 5], "ct": [1, 2], "front_fan": 0, "rear_fan": 0},
+    2: {"name": "腔体 2", "ptc": [6, 7, 8, 9, 10, 11], "bmc": [6, 7, 8, 9, 10, 11], "ct": [3, 4], "front_fan": 1, "rear_fan": 1},
+    3: {"name": "腔体 3", "ptc": [12, 13, 14, 15, 16, 17], "bmc": [12, 13, 14, 15, 16, 17], "ct": [5, 6], "front_fan": 2, "rear_fan": 2},
+    4: {"name": "腔体 4", "ptc": [18, 19, 20, 21, 22, 23], "bmc": [18, 19, 20, 21, 22, 23], "ct": [7, 8], "front_fan": 3, "rear_fan": 3},
+}
+
+
+@dataclass
+class AdaptivePidConfig:
+    # Target & trajectory
+    chamber_targets_c: dict[int, float] = field(default_factory=lambda: {1: 70.0, 2: 70.0, 3: 70.0, 4: 70.0})
+    overall_pass_min_temp_c: float = 70.0
+    max_ramp_c_per_min: float = 18.0          # 0 = unconstrained step target
+    ambient_temp_c: float = 25.0
+    pv_aggregation: str = "blend"             # "max", "avg", or "blend" (0.6*max + 0.4*avg)
+
+    # Base PID gains (auto-scheduled & RLS-adapted around these nominal values)
+    kp: float = 10.5
+    ki: float = 0.24
+    kd: float = 16.0
+    air_lead_gain: float = 1.6                # Smith-predictor air-temperature lead weight
+    cross_coupling_gain: float = 0.08         # Neighbor chamber thermal bleed feedforward
+
+    # Regime thresholds
+    approach_band_c: float = 8.0
+    hold_band_c: float = 2.0
+    overshoot_cool_band_c: float = 0.8
+
+    # Adaptive RLS estimator settings
+    adaptive_enabled: bool = True
+    rls_forgetting: float = 0.985
+    gain_scale_min: float = 0.65
+    gain_scale_max: float = 1.65
+
+    # Actuator coordination & limits
+    max_ptc_duty: float = 100.0
+    global_ptc_avg_cap: float = 88.0          # Global 24-PTC power budget cap (%)
+    min_fan_duty: float = 20.0                # Safe baseline / hold circulation floor
+    preheat_fan_duty: float = 20.0            # Fan duty before intervention threshold
+    max_fan_duty: float = 100.0
+    rear_to_front_ratio: float = 1.05         # Slight exhaust bias for chamber airflow
+    fan_intervention_mode: str = "ref_temp_c" # "immediate", "time_s", "ref_temp_c"
+    fan_intervention_delay_s: float = 30.0
+    fan_intervention_ref_temp_c: float = 55.0
+
+    # Spatial uniformity (intra-chamber 6-DIMM balance)
+    uniformity_spread_c: float = 2.5          # Boost mixing fan if DIMM max-min > 2.5 C
+    uniformity_fan_boost_per_c: float = 6.0
+    uniformity_ptc_trim_pct: float = 12.0     # Per-PTC individual trim +/-%
+
+    # Slew & safety fallback
+    max_ptc_slew_per_s: float = 35.0
+    max_fan_slew_per_s: float = 25.0
+    bmc_stale_timeout_s: float = 8.0
+    max_safe_dimm_temp_c: float = 95.0        # Software hard ceiling (PTC->0, FAN->100%)
+
+
+class ChamberThermalRLS:
+    """3-parameter Recursive Least Squares thermal plant identifier per chamber.
+
+    Discrete model:
+        dT/dt = theta[0] * u_ptc_norm + theta[1] * (u_fan_norm * (T - T_amb)) + theta[2]
+    where:
+        theta[0] > 0 : heating gain (C/s at 100% PTC)
+        theta[1] < 0 : forced-convection cooling coefficient (1/s at 100% FAN)
+        theta[2]     : net ambient leak + DIMM self-heating disturbance (C/s)
+    """
+
+    def __init__(self, forgetting: float = 0.985) -> None:
+        self.lam = _clamp(forgetting, 0.92, 0.999)
+        self.theta = [0.22, -0.0045, 0.0]
+        # 3x3 covariance matrix P initialized moderately
+        self.P = [
+            [0.04, 0.0, 0.0],
+            [0.0, 0.002, 0.0],
+            [0.0, 0.0, 0.05],
+        ]
+        self.updates = 0
+        self.last_residual = 0.0
+
+    def update(self, dT_dt: float, u_ptc_pct: float, u_fan_pct: float, temp_above_amb: float) -> None:
+        phi = [
+            u_ptc_pct / 100.0,
+            (u_fan_pct / 100.0) * max(temp_above_amb, 1.0),
+            1.0,
+        ]
+        # Prediction & innovation
+        y_hat = phi[0] * self.theta[0] + phi[1] * self.theta[1] + phi[2] * self.theta[2]
+        err = _clamp(dT_dt - y_hat, -1.5, 1.5)
+        self.last_residual = err
+
+        # P * phi
+        Pphi = [sum(self.P[i][j] * phi[j] for j in range(3)) for i in range(3)]
+        denom = self.lam + sum(phi[i] * Pphi[i] for i in range(3))
+        if denom <= 1e-9:
+            return
+        K = [p / denom for p in Pphi]
+
+        # Parameter update with physical sign/range projection
+        self.theta[0] = _clamp(self.theta[0] + K[0] * err, 0.06, 0.85)
+        self.theta[1] = _clamp(self.theta[1] + K[1] * err, -0.025, -0.0008)
+        self.theta[2] = _clamp(self.theta[2] + K[2] * err, -0.25, 0.45)
+
+        # Covariance update P = (P - K * phi^T * P) / lam with trace guard
+        newP = [[0.0] * 3 for _ in range(3)]
+        for i in range(3):
+            for j in range(3):
+                val = (self.P[i][j] - K[i] * Pphi[j]) / self.lam
+                newP[i][j] = _clamp(val, -1.0, 1.0)
+        # Keep positive diagonal floor so adaptation stays alive for load changes
+        for i, floor in enumerate((1e-4, 1e-6, 5e-4)):
+            if newP[i][i] < floor:
+                newP[i][i] = floor
+        self.P = newP
+        self.updates += 1
+
+    def gain_scale(self, nominal_heat_gain: float = 0.22, lo: float = 0.65, hi: float = 1.65) -> float:
+        # Lower heating gain -> higher proportional effort needed; higher gain -> gentler gain
+        if self.updates < 6:
+            return 1.0
+        return _clamp(nominal_heat_gain / max(self.theta[0], 0.05), lo, hi)
+
+
+@dataclass
+class ChamberRuntimeState:
+    chamber_id: int
+    regime: str = "IDLE"
+    pv_dimm_c: float | None = None
+    pv_air_c: float | None = None
+    pv_control_c: float | None = None
+    using_ct_fallback: bool = False
+    dimm_min_c: float | None = None
+    dimm_max_c: float | None = None
+    dimm_spread_c: float = 0.0
+    target_final_c: float = 70.0
+    target_traj_c: float = 70.0
+    error_c: float = 0.0
+    integral: float = 0.0
+    d_filt: float = 0.0
+    prev_pv: float | None = None
+    prev_air: float | None = None
+    delta_dimm_air_ewma: float = 4.0
+    last_bmc_ok_t: float = -1e9
+    ptc_cmd: float = 0.0
+    front_fan_cmd: float = 20.0
+    rear_fan_cmd: float = 20.0
+    ptc_channel_duties: list[int] = field(default_factory=lambda: [0] * 6)
+    eta_seconds: float | None = None
+    reached_target_at_s: float | None = None
+    rls_heat_gain: float = 0.22
+    rls_cool_gain: float = -0.0045
+    rls_disturbance_c_per_s: float = 0.0
+    rls_gain_scale: float = 1.0
+
+
+class AdaptiveThermalController:
+    """4-chamber coordinated adaptive PID controller outputting 32B 6400-V1.1 SET_ALL."""
+
+    def __init__(
+        self,
+        config: AdaptivePidConfig | None = None,
+        chamber_map: dict[int, dict[str, Any]] | None = None,
+    ) -> None:
+        self.cfg = config or AdaptivePidConfig()
+        self.cmap = {
+            cid: {
+                "name": spec["name"],
+                "ptc": list(spec["ptc"]),
+                "bmc": list(spec["bmc"]),
+                "ct": list(spec["ct"]),
+                "front_fan": int(spec["front_fan"]),
+                "rear_fan": int(spec["rear_fan"]),
+            }
+            for cid, spec in (chamber_map or DEFAULT_V11_CHAMBER_MAP).items()
+        }
+        self.auto_enabled = False
+        self.elapsed_s = 0.0
+        self.states: dict[int, ChamberRuntimeState] = {
+            cid: ChamberRuntimeState(chamber_id=cid, target_final_c=self.cfg.chamber_targets_c.get(cid, 70.0))
+            for cid in (1, 2, 3, 4)
+        }
+        self.rls: dict[int, ChamberThermalRLS] = {
+            cid: ChamberThermalRLS(forgetting=self.cfg.rls_forgetting)
+            for cid in (1, 2, 3, 4)
+        }
+        self.last_ptc_24: list[int] = [0] * 24
+        self.last_front_4: list[int] = [20] * 4
+        self.last_rear_4: list[int] = [20] * 4
+        self.overall_passed_at_s: float | None = None
+
+    def reset(self, *, initial_ptc: list[int] | None = None, initial_front: list[int] | None = None, initial_rear: list[int] | None = None) -> None:
+        self.elapsed_s = 0.0
+        self.overall_passed_at_s = None
+        if initial_ptc is not None and len(initial_ptc) == 24:
+            self.last_ptc_24 = [int(_clamp(v, 0, 100)) for v in initial_ptc]
+        else:
+            self.last_ptc_24 = [0] * 24
+        if initial_front is not None and len(initial_front) == 4:
+            self.last_front_4 = [int(_clamp(v, 0, 100)) for v in initial_front]
+        else:
+            self.last_front_4 = [20] * 4
+        if initial_rear is not None and len(initial_rear) == 4:
+            self.last_rear_4 = [int(_clamp(v, 0, 100)) for v in initial_rear]
+        else:
+            self.last_rear_4 = [20] * 4
+        for cid in (1, 2, 3, 4):
+            st = ChamberRuntimeState(
+                chamber_id=cid,
+                target_final_c=self.cfg.chamber_targets_c.get(cid, 70.0),
+            )
+            ptc_idx = self.cmap[cid]["ptc"]
+            st.ptc_cmd = sum(self.last_ptc_24[i] for i in ptc_idx) / max(len(ptc_idx), 1)
+            st.front_fan_cmd = float(self.last_front_4[self.cmap[cid]["front_fan"]])
+            st.rear_fan_cmd = float(self.last_rear_4[self.cmap[cid]["rear_fan"]])
+            st.ptc_channel_duties = [self.last_ptc_24[i] for i in ptc_idx]
+            self.states[cid] = st
+            self.rls[cid] = ChamberThermalRLS(forgetting=self.cfg.rls_forgetting)
+
+    def set_auto_mode(self, enabled: bool) -> None:
+        """Bumpless Auto <-> Manual transfer."""
+        if enabled and not self.auto_enabled:
+            for cid in (1, 2, 3, 4):
+                st = self.states[cid]
+                # Pre-load integral with current actuator bias so output jumps 0% on engage
+                st.integral = _clamp(st.ptc_cmd - (st.front_fan_cmd - self.cfg.min_fan_duty), -60.0, 90.0)
+                if st.pv_control_c is not None:
+                    st.target_traj_c = st.pv_control_c
+        self.auto_enabled = enabled
+
+    def _aggregate_dimm(self, vals: list[float]) -> float:
+        if self.cfg.pv_aggregation == "max":
+            return max(vals)
+        if self.cfg.pv_aggregation == "avg":
+            return sum(vals) / len(vals)
+        return 0.6 * max(vals) + 0.4 * (sum(vals) / len(vals))
+
+    def step(
+        self,
+        *,
+        dt_s: float,
+        bmc_dimm_temps_c: list[float | None],
+        ct_temps_c: list[float | None],
+        bmc_ok: bool = True,
+        manual_ptc_24: list[int] | None = None,
+        manual_front_4: list[int] | None = None,
+        manual_rear_4: list[int] | None = None,
+    ) -> dict[str, Any]:
+        """Compute one control step and return 32-byte SET_ALL outputs + full telemetry."""
+        dt = _clamp(float(dt_s), 0.05, 10.0)
+        self.elapsed_s += dt
+
+        # 1. Sensor fusion & per-chamber state observation
+        chamber_raw_dimms: dict[int, list[float | None]] = {}
+        for cid in (1, 2, 3, 4):
+            st = self.states[cid]
+            spec = self.cmap[cid]
+            st.target_final_c = float(self.cfg.chamber_targets_c.get(cid, 70.0))
+
+            dimm_list = [bmc_dimm_temps_c[i] if i < len(bmc_dimm_temps_c) else None for i in spec["bmc"]]
+            chamber_raw_dimms[cid] = dimm_list
+            valid_dimms = [v for v in dimm_list if v is not None]
+
+            ct_list = [ct_temps_c[i] if i < len(ct_temps_c) else None for i in spec["ct"]]
+            valid_cts = [float(v) for v in ct_list if v is not None]
+            st.pv_air_c = (sum(valid_cts) / len(valid_cts)) if valid_cts else None
+
+            if bmc_ok and valid_dimms:
+                st.pv_dimm_c = self._aggregate_dimm(valid_dimms)
+                st.dimm_min_c = min(valid_dimms)
+                st.dimm_max_c = max(valid_dimms)
+                st.dimm_spread_c = round(st.dimm_max_c - st.dimm_min_c, 2)
+                st.last_bmc_ok_t = self.elapsed_s
+                st.using_ct_fallback = False
+                st.pv_control_c = st.pv_dimm_c
+                if st.pv_air_c is not None:
+                    # Track steady offset between DIMM and chamber air for dropout survival
+                    obs_delta = _clamp(st.pv_dimm_c - st.pv_air_c, -15.0, 25.0)
+                    st.delta_dimm_air_ewma = 0.90 * st.delta_dimm_air_ewma + 0.10 * obs_delta
+            else:
+                stale_s = self.elapsed_s - st.last_bmc_ok_t
+                if stale_s > self.cfg.bmc_stale_timeout_s and st.pv_air_c is not None:
+                    st.using_ct_fallback = True
+                    st.pv_control_c = st.pv_air_c + st.delta_dimm_air_ewma
+                elif st.pv_dimm_c is not None:
+                    st.using_ct_fallback = False
+                    st.pv_control_c = st.pv_dimm_c
+                elif st.pv_air_c is not None:
+                    st.using_ct_fallback = True
+                    st.pv_control_c = st.pv_air_c + st.delta_dimm_air_ewma
+                else:
+                    st.pv_control_c = None
+
+            # Record first time chamber hits its target (continue logging afterwards!)
+            if st.pv_control_c is not None and st.reached_target_at_s is None and st.pv_control_c >= st.target_final_c:
+                st.reached_target_at_s = round(self.elapsed_s, 2)
+
+        # Check overall 4-chamber pass condition
+        if self.overall_passed_at_s is None:
+            pvs = [self.states[c].pv_control_c for c in (1, 2, 3, 4)]
+            if all(v is not None and v >= self.cfg.overall_pass_min_temp_c for v in pvs):
+                self.overall_passed_at_s = round(self.elapsed_s, 2)
+
+        # Manual passthrough (keeps bumpless state updated!)
+        if not self.auto_enabled:
+            ptc_out = list(manual_ptc_24) if manual_ptc_24 and len(manual_ptc_24) == 24 else list(self.last_ptc_24)
+            front_out = list(manual_front_4) if manual_front_4 and len(manual_front_4) == 4 else list(self.last_front_4)
+            rear_out = list(manual_rear_4) if manual_rear_4 and len(manual_rear_4) == 4 else list(self.last_rear_4)
+            for cid in (1, 2, 3, 4):
+                st = self.states[cid]
+                st.regime = "MANUAL"
+                idx = self.cmap[cid]["ptc"]
+                st.ptc_cmd = sum(ptc_out[i] for i in idx) / max(len(idx), 1)
+                st.front_fan_cmd = float(front_out[self.cmap[cid]["front_fan"]])
+                st.rear_fan_cmd = float(rear_out[self.cmap[cid]["rear_fan"]])
+                st.ptc_channel_duties = [int(ptc_out[i]) for i in idx]
+                if st.pv_control_c is not None:
+                    st.target_traj_c = st.pv_control_c
+                    st.prev_pv = st.pv_control_c
+                    st.error_c = round(st.target_final_c - st.pv_control_c, 2)
+                st.prev_air = st.pv_air_c
+            self.last_ptc_24, self.last_front_4, self.last_rear_4 = ptc_out, front_out, rear_out
+            return self._pack_output()
+
+        # 2. Online RLS identification + per-chamber adaptive PID demand
+        raw_ptc_demand: dict[int, float] = {}
+        raw_fan_demand: dict[int, float] = {}
+
+        for cid in (1, 2, 3, 4):
+            st = self.states[cid]
+            rls = self.rls[cid]
+            pv = st.pv_control_c
+            if pv is None:
+                st.regime = "SENSOR_FAULT_SAFE"
+                raw_ptc_demand[cid] = 0.0
+                raw_fan_demand[cid] = max(self.cfg.min_fan_duty, 50.0)
+                continue
+
+            # Software over-temperature ceiling
+            if pv >= self.cfg.max_safe_dimm_temp_c:
+                st.regime = "OVERTEMP_CLAMP"
+                raw_ptc_demand[cid] = 0.0
+                raw_fan_demand[cid] = self.cfg.max_fan_duty
+                st.integral = min(st.integral, 0.0)
+                st.prev_pv = pv
+                st.prev_air = st.pv_air_c
+                continue
+
+            # Compute derivatives & run RLS thermal plant identification
+            d_pv_dt = 0.0
+            if st.prev_pv is not None:
+                d_pv_dt = (pv - st.prev_pv) / dt
+                if self.cfg.adaptive_enabled and not st.using_ct_fallback:
+                    eff_fan = 0.5 * (st.front_fan_cmd + st.rear_fan_cmd)
+                    rls.update(d_pv_dt, st.ptc_cmd, eff_fan, pv - self.cfg.ambient_temp_c)
+            alpha_d = dt / (dt + 2.5)
+            st.d_filt = (1.0 - alpha_d) * st.d_filt + alpha_d * d_pv_dt
+
+            d_air_dt = 0.0
+            if st.pv_air_c is not None and st.prev_air is not None:
+                d_air_dt = _clamp((st.pv_air_c - st.prev_air) / dt, -2.0, 2.0)
+
+            st.rls_heat_gain = round(rls.theta[0], 4)
+            st.rls_cool_gain = round(rls.theta[1], 5)
+            st.rls_disturbance_c_per_s = round(rls.theta[2], 4)
+            g_scale = rls.gain_scale(0.22, self.cfg.gain_scale_min, self.cfg.gain_scale_max) if self.cfg.adaptive_enabled else 1.0
+            st.rls_gain_scale = round(g_scale, 3)
+
+            # Setpoint trajectory planner (smooth approach, prevents integral windup on large jumps)
+            if self.cfg.max_ramp_c_per_min <= 0.0:
+                st.target_traj_c = st.target_final_c
+            else:
+                if st.prev_pv is None:
+                    st.target_traj_c = pv
+                max_step = (self.cfg.max_ramp_c_per_min / 60.0) * dt
+                diff_sp = st.target_final_c - st.target_traj_c
+                if abs(diff_sp) <= max_step:
+                    st.target_traj_c = st.target_final_c
+                else:
+                    st.target_traj_c += math.copysign(max_step, diff_sp)
+                # Don't let trajectory run arbitrarily far ahead of actual PV
+                st.target_traj_c = _clamp(st.target_traj_c, pv - 6.0, min(st.target_final_c, pv + 8.0))
+
+            err_final = st.target_final_c - pv
+            err_traj = st.target_traj_c - pv
+            st.error_c = round(err_final, 2)
+
+            # ETA estimation
+            if err_final <= 0.5:
+                st.eta_seconds = 0.0
+            elif st.d_filt > 0.01:
+                st.eta_seconds = round(_clamp(err_final / st.d_filt, 0.0, 3600.0), 1)
+            else:
+                st.eta_seconds = None
+
+            # 3-regime gain scheduling
+            if err_final > self.cfg.approach_band_c:
+                st.regime = "PREHEAT_BOOST"
+                kp_eff = self.cfg.kp * 1.25 * g_scale
+                ki_eff = self.cfg.ki * 0.65 * g_scale
+                kd_eff = self.cfg.kd * 0.70 * g_scale
+            elif err_final > self.cfg.hold_band_c:
+                st.regime = "APPROACH_BRAKE"
+                kp_eff = self.cfg.kp * 1.00 * g_scale
+                ki_eff = self.cfg.ki * 0.90 * g_scale
+                kd_eff = self.cfg.kd * 1.25 * g_scale
+            else:
+                st.regime = "PRECISION_HOLD"
+                kp_eff = self.cfg.kp * 0.90 * g_scale
+                ki_eff = self.cfg.ki * 1.15 * g_scale
+                kd_eff = self.cfg.kd * 1.10 * g_scale
+
+            # Feedforward: steady heat loss + RLS disturbance cancellation + cross-chamber crosstalk
+            steady_cool_ff = (-rls.theta[1] * (self.cfg.min_fan_duty / 100.0) * max(st.target_final_c - self.cfg.ambient_temp_c, 0.0))
+            disturb_ff = -rls.theta[2] if (self.cfg.adaptive_enabled and rls.updates >= 8) else 0.0
+            ff_ptc = _clamp((steady_cool_ff + disturb_ff) / max(rls.theta[0], 0.08) * 100.0, -35.0, 55.0)
+
+            # Neighbor thermal crosstalk compensation
+            neighbors = [n for n in (cid - 1, cid + 1) if n in self.states and self.states[n].pv_control_c is not None]
+            cross_ff = 0.0
+            if neighbors:
+                avg_nbr = sum(self.states[n].pv_control_c for n in neighbors) / len(neighbors)  # type: ignore[arg-type]
+                cross_ff = self.cfg.cross_coupling_gain * (pv - avg_nbr)
+
+            # Smith-predictor / air-lead derivative term (anticipates heat wave before DIMM sees it)
+            air_lead = self.cfg.air_lead_gain * d_air_dt * 10.0
+
+            # Combined bipolar thermal effort u_effort in [-100, +100]
+            p_term = kp_eff * err_traj
+            d_term = -kd_eff * st.d_filt - air_lead
+            u_raw = ff_ptc + cross_ff + p_term + st.integral + d_term
+
+            # Back-calculation anti-windup (clamped to [-100, +100])
+            u_sat = _clamp(u_raw, -100.0, self.cfg.max_ptc_duty)
+            aw_corr = 0.35 * (u_sat - u_raw)
+            if not st.using_ct_fallback:
+                st.integral = _clamp(st.integral + (ki_eff * err_traj + aw_corr) * dt, -65.0, 85.0)
+            else:
+                # Freeze/decay integral conservatively during BMC NET dropout
+                st.integral = _clamp(st.integral * 0.98, -40.0, 60.0)
+
+            # Split-range allocation between PTC (heating) and FAN (cooling + mixing)
+            ptc_req = _clamp(u_sat, 0.0, self.cfg.max_ptc_duty)
+
+            # Fan intervention schedule
+            fan_intervened = True
+            if self.cfg.fan_intervention_mode == "time_s":
+                fan_intervened = self.elapsed_s >= self.cfg.fan_intervention_delay_s
+            elif self.cfg.fan_intervention_mode == "ref_temp_c":
+                ref_t = st.pv_air_c if st.pv_air_c is not None else pv
+                fan_intervened = (ref_t >= self.cfg.fan_intervention_ref_temp_c) or (err_final <= self.cfg.hold_band_c)
+
+            if not fan_intervened:
+                fan_req = self.cfg.preheat_fan_duty
+            else:
+                base_fan = self.cfg.min_fan_duty
+                # Active cooling when u_sat < 0 or temperature exceeds target + overshoot band
+                cool_effort = max(0.0, -u_sat) + max(0.0, (-err_final - self.cfg.overshoot_cool_band_c) * 18.0)
+                # Intra-chamber DIMM uniformity mixing boost
+                spread_excess = max(0.0, st.dimm_spread_c - self.cfg.uniformity_spread_c)
+                mix_boost = spread_excess * self.cfg.uniformity_fan_boost_per_c
+                fan_req = _clamp(base_fan + cool_effort * 0.85 + mix_boost, self.cfg.min_fan_duty, self.cfg.max_fan_duty)
+
+            raw_ptc_demand[cid] = ptc_req
+            raw_fan_demand[cid] = fan_req
+            st.prev_pv = pv
+            st.prev_air = st.pv_air_c
+
+        # 3. Global 24-PTC Power Budget Allocator (prioritizes chambers furthest below target)
+        avg_ptc_req = sum(raw_ptc_demand.values()) / 4.0
+        if avg_ptc_req > self.cfg.global_ptc_avg_cap and avg_ptc_req > 1e-6:
+            scale = self.cfg.global_ptc_avg_cap / avg_ptc_req
+            for cid in (1, 2, 3, 4):
+                raw_ptc_demand[cid] *= scale
+
+        # 4. Slew-rate smoothing + per-PTC intra-chamber spatial uniformity trim + Front/Rear ratio
+        ptc_24 = list(self.last_ptc_24)
+        front_4 = list(self.last_front_4)
+        rear_4 = list(self.last_rear_4)
+
+        max_ptc_step = self.cfg.max_ptc_slew_per_s * dt
+        max_fan_step = self.cfg.max_fan_slew_per_s * dt
+
+        for cid in (1, 2, 3, 4):
+            st = self.states[cid]
+            spec = self.cmap[cid]
+            # Slew limit chamber commands
+            st.ptc_cmd = _clamp(
+                st.ptc_cmd + _clamp(raw_ptc_demand[cid] - st.ptc_cmd, -max_ptc_step, max_ptc_step),
+                0.0,
+                self.cfg.max_ptc_duty,
+            )
+            front_target = _clamp(raw_fan_demand[cid], self.cfg.min_fan_duty, self.cfg.max_fan_duty)
+            rear_target = _clamp(raw_fan_demand[cid] * self.cfg.rear_to_front_ratio, self.cfg.min_fan_duty, self.cfg.max_fan_duty)
+            st.front_fan_cmd = _clamp(
+                st.front_fan_cmd + _clamp(front_target - st.front_fan_cmd, -max_fan_step, max_fan_step),
+                0.0,
+                self.cfg.max_fan_duty,
+            )
+            st.rear_fan_cmd = _clamp(
+                st.rear_fan_cmd + _clamp(rear_target - st.rear_fan_cmd, -max_fan_step, max_fan_step),
+                0.0,
+                self.cfg.max_fan_duty,
+            )
+
+            # Intra-chamber 6-PTC spatial uniformity trim based on individual DIMMs
+            dimms = chamber_raw_dimms[cid]
+            valid_d = [v for v in dimms if v is not None]
+            avg_d = (sum(valid_d) / len(valid_d)) if valid_d else None
+            ch_duties: list[int] = []
+            for local_i, ptc_ch in enumerate(spec["ptc"]):
+                trim = 0.0
+                if avg_d is not None and local_i < len(dimms) and dimms[local_i] is not None and st.ptc_cmd > 1.0:
+                    # Cooler DIMM gets positive trim, hotter DIMM gets negative trim
+                    trim = _clamp((avg_d - dimms[local_i]) * 4.0, -self.cfg.uniformity_ptc_trim_pct, self.cfg.uniformity_ptc_trim_pct)  # type: ignore[operator]
+                duty_i = int(round(_clamp(st.ptc_cmd + trim, 0.0, self.cfg.max_ptc_duty)))
+                ptc_24[ptc_ch] = duty_i
+                ch_duties.append(duty_i)
+
+            st.ptc_channel_duties = ch_duties
+            front_4[spec["front_fan"]] = int(round(st.front_fan_cmd))
+            rear_4[spec["rear_fan"]] = int(round(st.rear_fan_cmd))
+
+        self.last_ptc_24 = ptc_24
+        self.last_front_4 = front_4
+        self.last_rear_4 = rear_4
+        return self._pack_output()
+
+    def _pack_output(self) -> dict[str, Any]:
+        payload_32 = bytes(self.last_ptc_24 + self.last_front_4 + self.last_rear_4)
+        return {
+            "elapsed_s": round(self.elapsed_s, 2),
+            "auto_enabled": self.auto_enabled,
+            "ptc_24": list(self.last_ptc_24),
+            "front_4": list(self.last_front_4),
+            "rear_4": list(self.last_rear_4),
+            "set_all_payload_32": payload_32,
+            "overall_passed_at_s": self.overall_passed_at_s,
+            "chambers": {
+                cid: {
+                    "regime": st.regime,
+                    "pv_dimm_c": None if st.pv_dimm_c is None else round(st.pv_dimm_c, 2),
+                    "pv_air_c": None if st.pv_air_c is None else round(st.pv_air_c, 2),
+                    "pv_control_c": None if st.pv_control_c is None else round(st.pv_control_c, 2),
+                    "using_ct_fallback": st.using_ct_fallback,
+                    "dimm_spread_c": st.dimm_spread_c,
+                    "target_final_c": st.target_final_c,
+                    "target_traj_c": round(st.target_traj_c, 2),
+                    "error_c": st.error_c,
+                    "ptc_cmd": round(st.ptc_cmd, 1),
+                    "front_fan_cmd": round(st.front_fan_cmd, 1),
+                    "rear_fan_cmd": round(st.rear_fan_cmd, 1),
+                    "eta_seconds": st.eta_seconds,
+                    "reached_target_at_s": st.reached_target_at_s,
+                    "rls_heat_gain": st.rls_heat_gain,
+                    "rls_cool_gain": st.rls_cool_gain,
+                    "rls_disturbance_c_per_s": st.rls_disturbance_c_per_s,
+                    "rls_gain_scale": st.rls_gain_scale,
+                }
+                for cid, st in self.states.items()
+            },
+        }
+
+
+# ---------------------------------------------------------------------------
+# Coupled 4-Chamber Physical Thermal Plant Simulator (for Bench Test & Demo)
+# ---------------------------------------------------------------------------
+class SimulatedV11Plant:
+    """Two-node (air + 6 DIMMs per chamber) coupled 4-chamber thermal plant."""
+
+    def __init__(self, ambient_c: float = 25.0) -> None:
+        self.ambient_c = ambient_c
+        self.air_c = [ambient_c + 1.0, ambient_c + 1.5, ambient_c + 1.2, ambient_c + 0.8]
+        self.dimm_c = [ambient_c + 3.0 + (i % 6) * 0.4 for i in range(24)]
+        # Slight physical heterogeneity per chamber (realistic hardware tolerance)
+        self.heat_gain = [0.34, 0.30, 0.28, 0.32]
+        self.cool_gain = [0.0085, 0.0078, 0.0082, 0.0080]
+        self.dimm_self_heat = [0.04, 0.04, 0.04, 0.04]  # Increased when MemTest load active
+
+    def set_workload_step(self, extra_c_per_s: float) -> None:
+        self.dimm_self_heat = [0.04 + extra_c_per_s] * 4
+
+    def step(self, dt_s: float, ptc_24: list[int], front_4: list[int], rear_4: list[int]) -> tuple[list[float | None], list[float | None]]:
+        sub_steps = max(1, int(math.ceil(dt_s / 0.25)))
+        h = dt_s / sub_steps
+        for _ in range(sub_steps):
+            new_air = list(self.air_c)
+            for c in range(4):
+                ptc_avg = sum(ptc_24[6 * c : 6 * c + 6]) / 600.0
+                fan_eff = (front_4[c] + rear_4[c]) / 200.0
+                nbr_sum = 0.0
+                nbr_cnt = 0
+                for n in (c - 1, c + 1):
+                    if 0 <= n < 4:
+                        nbr_sum += self.air_c[n] - self.air_c[c]
+                        nbr_cnt += 1
+                dimm_avg = sum(self.dimm_c[6 * c : 6 * c + 6]) / 6.0
+                d_air = (
+                    self.heat_gain[c] * ptc_avg * 1.45
+                    - (0.002 + self.cool_gain[c] * fan_eff) * (self.air_c[c] - self.ambient_c)
+                    + 0.015 * (dimm_avg - self.air_c[c])
+                    + 0.004 * (nbr_sum / max(nbr_cnt, 1))
+                )
+                new_air[c] = _clamp(self.air_c[c] + d_air * h, self.ambient_c, 120.0)
+            self.air_c = new_air
+
+            for c in range(4):
+                fan_eff = (front_4[c] + rear_4[c]) / 200.0
+                h_conv = 0.045 + 0.055 * fan_eff
+                for k in range(6):
+                    idx = 6 * c + k
+                    local_ptc = ptc_24[idx] / 100.0
+                    # Slight edge-to-center airflow gradient across 6 DIMMs
+                    spatial_bias = (k - 2.5) * 0.012
+                    d_dimm = (
+                        h_conv * (self.air_c[c] - self.dimm_c[idx])
+                        + 0.06 * local_ptc
+                        + self.dimm_self_heat[c]
+                        + spatial_bias
+                        - (0.0012 + 0.0038 * fan_eff) * (self.dimm_c[idx] - self.ambient_c)
+                    )
+                    self.dimm_c[idx] = _clamp(self.dimm_c[idx] + d_dimm * h, self.ambient_c, 120.0)
+
+        # Quantize DIMMs to real SPD5118 0.25 C steps; CT7428 to integer Celsius (27 channels)
+        bmc_out: list[float | None] = [round(round(v * 4.0) / 4.0, 2) for v in self.dimm_c]
+        ct_out: list[float | None] = [float(int(self.ambient_c + 5.0))]
+        for c in range(4):
+            # Intake and exhaust sensor probes per chamber
+            t_in = int(max(0, self.air_c[c] - 2.0))
+            t_ex = int(max(0, self.air_c[c] + 1.5))
+            ct_out.extend([float(t_in), float(t_ex)])
+        # Remaining 18 CT channels (U24/U25 on 6400 V1.1 3-chip bus) mirror chamber zones
+        for ch in range(18):
+            c = ch % 4
+            ct_out.append(float(int(self.air_c[c])))
+        return bmc_out, ct_out

+ 634 - 0
tools/v11_bmc_net.py

@@ -0,0 +1,634 @@
+#!/usr/bin/env python3
+"""Zero-dependency BMC NET DIMM Temperature Client for 6400 V1.1 No-MCU Mode.
+
+Directly acquires all 24 DIMM temperatures over the BMC management network
+(no MCU, no CPLD BMC UART) via:
+  1. Built-in pure-Python IPMI v2.0 RMCP+ (UDP:623, Cipher Suite 17 HMAC-SHA256
+     + AES-128-CBC, with automatic fallback to Cipher Suite 3 HMAC-SHA1).
+     Reads OEM raw NetFn=0x36 Cmd=0x6C Data=0xDF 0xDD 0x00 0x03 -> 48 bytes
+     (24 DIMMs x 2 bytes [int_c, frac_hundredths], 0.25 C SPD5118 precision).
+     Supports persistent authenticated session with auto-reconnect.
+  2. Optional external `ipmitool -I lanplus` fallback.
+  3. Optional Redfish HTTPS `/redfish/v1/Chassis/1/Thermal` fallback.
+  4. Offline simulated backend for bench testing and `--self-test`.
+"""
+
+from __future__ import annotations
+
+import argparse
+from dataclasses import dataclass, field
+import hashlib
+import hmac
+import json
+import os
+import socket
+import ssl
+import struct
+import subprocess
+import time
+import urllib.request
+from typing import Any
+
+
+# ---------------------------------------------------------------------------
+# Compact pure-Python FIPS-197 AES-128-CBC (zero external crypto packages)
+# ---------------------------------------------------------------------------
+_SBOX = (
+    0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
+    0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
+    0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
+    0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
+    0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
+    0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
+    0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
+    0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
+    0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
+    0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
+    0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
+    0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
+    0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
+    0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
+    0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
+    0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
+)
+_INV_SBOX = [0] * 256
+for _idx, _val in enumerate(_SBOX):
+    _INV_SBOX[_val] = _idx
+_RCON = (0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36)
+
+
+def _xtime(a: int) -> int:
+    return ((a << 1) ^ 0x1B) & 0xFF if (a & 0x80) else (a << 1)
+
+
+def _gf_mul(a: int, b: int) -> int:
+    r = 0
+    for _ in range(8):
+        if b & 1:
+            r ^= a
+        a = _xtime(a)
+        b >>= 1
+    return r
+
+
+def _aes128_expand(key: bytes) -> list[list[int]]:
+    if len(key) != 16:
+        raise ValueError(f"AES-128 key must be 16 bytes, got {len(key)}")
+    w = [list(key[i : i + 4]) for i in range(0, 16, 4)]
+    for i in range(4, 44):
+        t = list(w[i - 1])
+        if i % 4 == 0:
+            t = [_SBOX[t[1]] ^ _RCON[i // 4 - 1], _SBOX[t[2]], _SBOX[t[3]], _SBOX[t[0]]]
+        w.append([w[i - 4][j] ^ t[j] for j in range(4)])
+    return [sum(w[4 * r : 4 * r + 4], []) for r in range(11)]
+
+
+def _aes128_enc_block(block: bytes, rks: list[list[int]]) -> bytes:
+    s = [block[i] ^ rks[0][i] for i in range(16)]
+    for rnd in range(1, 11):
+        s = [_SBOX[b] for b in s]
+        s = [
+            s[0], s[5], s[10], s[15],
+            s[4], s[9], s[14], s[3],
+            s[8], s[13], s[2], s[7],
+            s[12], s[1], s[6], s[11],
+        ]
+        if rnd < 10:
+            ns = [0] * 16
+            for c in range(4):
+                a0, a1, a2, a3 = s[4 * c : 4 * c + 4]
+                ns[4 * c + 0] = _gf_mul(a0, 2) ^ _gf_mul(a1, 3) ^ a2 ^ a3
+                ns[4 * c + 1] = a0 ^ _gf_mul(a1, 2) ^ _gf_mul(a2, 3) ^ a3
+                ns[4 * c + 2] = a0 ^ a1 ^ _gf_mul(a2, 2) ^ _gf_mul(a3, 3)
+                ns[4 * c + 3] = _gf_mul(a0, 3) ^ a1 ^ a2 ^ _gf_mul(a3, 2)
+            s = ns
+        rk = rks[rnd]
+        s = [s[i] ^ rk[i] for i in range(16)]
+    return bytes(s)
+
+
+def _aes128_dec_block(block: bytes, rks: list[list[int]]) -> bytes:
+    s = [block[i] ^ rks[10][i] for i in range(16)]
+    for rnd in range(9, -1, -1):
+        s = [
+            s[0], s[13], s[10], s[7],
+            s[4], s[1], s[14], s[11],
+            s[8], s[5], s[2], s[15],
+            s[12], s[9], s[6], s[3],
+        ]
+        s = [_INV_SBOX[b] for b in s]
+        rk = rks[rnd]
+        s = [s[i] ^ rk[i] for i in range(16)]
+        if rnd > 0:
+            ns = [0] * 16
+            for c in range(4):
+                a0, a1, a2, a3 = s[4 * c : 4 * c + 4]
+                ns[4 * c + 0] = _gf_mul(a0, 14) ^ _gf_mul(a1, 11) ^ _gf_mul(a2, 13) ^ _gf_mul(a3, 9)
+                ns[4 * c + 1] = _gf_mul(a0, 9) ^ _gf_mul(a1, 14) ^ _gf_mul(a2, 11) ^ _gf_mul(a3, 13)
+                ns[4 * c + 2] = _gf_mul(a0, 13) ^ _gf_mul(a1, 9) ^ _gf_mul(a2, 14) ^ _gf_mul(a3, 11)
+                ns[4 * c + 3] = _gf_mul(a0, 11) ^ _gf_mul(a1, 13) ^ _gf_mul(a2, 9) ^ _gf_mul(a3, 14)
+            s = ns
+    return bytes(s)
+
+
+def aes128_cbc_encrypt(key: bytes, iv: bytes, pt: bytes) -> bytes:
+    if len(pt) % 16 != 0:
+        raise ValueError("AES-128-CBC plaintext must be multiple of 16 bytes")
+    rks = _aes128_expand(key)
+    out = bytearray()
+    prev = iv
+    for i in range(0, len(pt), 16):
+        blk = bytes(pt[i + j] ^ prev[j] for j in range(16))
+        enc = _aes128_enc_block(blk, rks)
+        out.extend(enc)
+        prev = enc
+    return bytes(out)
+
+
+def aes128_cbc_decrypt(key: bytes, iv: bytes, ct: bytes) -> bytes:
+    if len(ct) % 16 != 0:
+        raise ValueError("AES-128-CBC ciphertext must be multiple of 16 bytes")
+    rks = _aes128_expand(key)
+    out = bytearray()
+    prev = iv
+    for i in range(0, len(ct), 16):
+        blk = ct[i : i + 16]
+        dec = _aes128_dec_block(blk, rks)
+        out.extend(bytes(dec[j] ^ prev[j] for j in range(16)))
+        prev = blk
+    return bytes(out)
+
+
+def _ipmi_checksum(data: bytes) -> int:
+    return (-sum(data)) & 0xFF
+
+
+# ---------------------------------------------------------------------------
+# DIMM Payload Decoding (OEM 0x36 0x6C 0xDF 0xDD 0x00 0x03 -> 48 bytes)
+# ---------------------------------------------------------------------------
+OEM_DIMM_NETFN = 0x36
+OEM_DIMM_CMD = 0x6C
+OEM_DIMM_DATA = bytes([0xDF, 0xDD, 0x00, 0x03])
+
+
+def parse_oem_dimm_payload(raw: bytes, max_dimms: int = 24) -> list[float | None]:
+    """Decode 48-byte OEM DIMM thermal response into 24 float temperatures (0.25 C precision).
+
+    Each DIMM occupies 2 bytes: [integer_celsius, frac_hundredths].
+    0xFF (or integer > 125 C) indicates an unpopulated/invalid DIMM slot -> None.
+    """
+    temps: list[float | None] = [None] * max_dimms
+    pairs = min(max_dimms, len(raw) // 2)
+    for i in range(pairs):
+        hi = raw[2 * i]
+        lo = raw[2 * i + 1]
+        if hi == 0xFF or hi > 125:
+            temps[i] = None
+        else:
+            frac = (lo / 100.0) if lo < 100 else 0.0
+            temps[i] = round(float(hi) + frac, 2)
+    return temps
+
+
+@dataclass
+class BmcNetSample:
+    ok: bool
+    temps_c: list[float | None] = field(default_factory=lambda: [None] * 24)
+    raw_hex: str = ""
+    backend: str = "rmcp+"
+    cipher_suite: int = 17
+    rtt_ms: float = 0.0
+    timestamp: float = field(default_factory=time.time)
+    error: str = ""
+
+    @property
+    def valid_count(self) -> int:
+        return sum(1 for t in self.temps_c if t is not None)
+
+
+# ---------------------------------------------------------------------------
+# Persistent IPMI v2.0 RMCP+ Session (UDP:623)
+# ---------------------------------------------------------------------------
+class RmcpPlusClient:
+    """Pure-Python IPMI v2.0 RMCP+ client supporting Cipher Suite 17 & 3."""
+
+    def __init__(
+        self,
+        host: str,
+        user: str = "ADMIN",
+        password: str = "Admin123@pl",
+        port: int = 623,
+        cipher_suite: int = 17,
+        timeout: float = 2.5,
+    ) -> None:
+        self.host = host.strip()
+        self.user = user
+        self.password = password
+        self.port = int(port)
+        self.cipher_suite = int(cipher_suite)
+        self.timeout = float(timeout)
+        self._sock: socket.socket | None = None
+        self._ms_sid: int = 0
+        self._k1: bytes = b""
+        self._k2: bytes = b""
+        self._seq: int = 1
+        self._rq_seq: int = 1
+        self._active_cipher: int = self.cipher_suite
+
+    def _cipher_params(self, cipher: int):
+        if cipher == 17:
+            return 3, 4, 1, hashlib.sha256, 16
+        if cipher == 3:
+            return 1, 1, 1, hashlib.sha1, 12
+        raise ValueError(f"Unsupported RMCP+ cipher suite: {cipher}")
+
+    def close(self) -> None:
+        if self._sock is not None:
+            if self._ms_sid:
+                try:
+                    self._send_ipmi(0x06, 0x3C, struct.pack("<I", self._ms_sid))
+                except Exception:
+                    pass
+            try:
+                self._sock.close()
+            except Exception:
+                pass
+        self._sock = None
+        self._ms_sid = 0
+        self._k1 = b""
+        self._k2 = b""
+
+    def _xchg_open(self, payload_type: int, payload: bytes) -> bytes:
+        assert self._sock is not None
+        hdr = b"\x06\x00\xff\x07" + struct.pack("<BBIIH", 0x06, payload_type, 0, 0, len(payload))
+        self._sock.sendto(hdr + payload, (self.host, self.port))
+        resp, _ = self._sock.recvfrom(4096)
+        if len(resp) < 18:
+            raise RuntimeError(f"Short RMCP+ response ({len(resp)} bytes)")
+        return resp[16:]
+
+    def connect(self) -> int:
+        self.close()
+        last_err: Exception | None = None
+        candidates = [self.cipher_suite] + [c for c in (17, 3) if c != self.cipher_suite]
+        for cs in candidates:
+            try:
+                self._connect_with_cipher(cs)
+                self._active_cipher = cs
+                return cs
+            except Exception as exc:
+                last_err = exc
+                self.close()
+        raise RuntimeError(f"RMCP+ connect failed to {self.host}:{self.port}: {last_err}")
+
+    def _connect_with_cipher(self, cipher: int) -> None:
+        auth_alg, int_alg, conf_alg, hmod, _ = self._cipher_params(cipher)
+        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+        sock.settimeout(self.timeout)
+        self._sock = sock
+
+        rc_sid = (struct.unpack("<I", os.urandom(4))[0] | 0x01000000) & 0xFFFFFFFF
+        open_pl = struct.pack("<BBHI", 0x01, 0x04, 0x0000, rc_sid)
+        open_pl += struct.pack("<BBBBBBBB", 0x00, 0, 0, 8, auth_alg, 0, 0, 0)
+        open_pl += struct.pack("<BBBBBBBB", 0x01, 0, 0, 8, int_alg, 0, 0, 0)
+        open_pl += struct.pack("<BBBBBBBB", 0x02, 0, 0, 8, conf_alg, 0, 0, 0)
+        pl = self._xchg_open(0x10, open_pl)
+        if pl[1] != 0:
+            raise RuntimeError(f"OpenSession status=0x{pl[1]:02X}")
+        ms_sid = struct.unpack_from("<I", pl, 8)[0]
+
+        rc_rand = os.urandom(16)
+        u_bytes = self.user.encode("ascii")
+        role_m = 0x14  # ADMIN (4), name+priv lookup
+        rakp1 = (
+            struct.pack("<B3sI", 0x02, b"\x00\x00\x00", ms_sid)
+            + rc_rand
+            + struct.pack("<BHB", role_m, 0, len(u_bytes))
+            + u_bytes
+        )
+        pl = self._xchg_open(0x12, rakp1)
+        if pl[1] != 0:
+            raise RuntimeError(f"RAKP2 status=0x{pl[1]:02X}")
+        ms_rand = pl[8:24]
+        ms_guid = pl[24:40]
+        ms_auth = pl[40:]
+
+        k_uid = self.password.encode("ascii")
+        if cipher == 3 and len(k_uid) < 20:
+            k_uid = k_uid.ljust(20, b"\x00")
+        rakp2_msg = (
+            struct.pack("<II", rc_sid, ms_sid)
+            + rc_rand
+            + ms_rand
+            + ms_guid
+            + struct.pack("<BB", role_m, len(u_bytes))
+            + u_bytes
+        )
+        expected_rakp2 = hmac.new(k_uid, rakp2_msg, hmod).digest()
+        if not hmac.compare_digest(ms_auth[: len(expected_rakp2)], expected_rakp2):
+            raise RuntimeError("RAKP2 auth mismatch (invalid BMC credentials)")
+
+        sik_msg = rc_rand + ms_rand + struct.pack("<BB", role_m, len(u_bytes)) + u_bytes
+        sik = hmac.new(k_uid, sik_msg, hmod).digest()
+        k1 = hmac.new(sik, b"\x01" * 20, hmod).digest()
+        k2 = hmac.new(sik, b"\x02" * 20, hmod).digest()
+
+        rakp3_msg = ms_rand + struct.pack("<IBB", rc_sid, role_m, len(u_bytes)) + u_bytes
+        rakp3_auth = hmac.new(k_uid, rakp3_msg, hmod).digest()
+        rakp3 = struct.pack("<BBHI", 0x03, 0x00, 0x0000, ms_sid) + rakp3_auth
+        pl = self._xchg_open(0x14, rakp3)
+        if pl[1] != 0:
+            raise RuntimeError(f"RAKP4 status=0x{pl[1]:02X}")
+
+        self._ms_sid = ms_sid
+        self._k1 = k1
+        self._k2 = k2
+        self._seq = 1
+        self._rq_seq = 1
+        self._active_cipher = cipher
+        # Elevate session privilege level to ADMIN (NetFn=0x06 Cmd=0x3B Data=0x04)
+        self._send_ipmi(0x06, 0x3B, b"\x04")
+
+    def _send_ipmi(self, netfn: int, cmd: int, data: bytes = b"") -> bytes:
+        if self._sock is None or not self._ms_sid:
+            raise RuntimeError("RMCP+ session not open")
+        _, _, _, hmod, int_len = self._cipher_params(self._active_cipher)
+        seq_num = self._seq
+        rq_seq = self._rq_seq & 0x3F
+        self._seq = (self._seq + 1) & 0xFFFFFFFF
+        self._rq_seq = (self._rq_seq + 1) & 0x3F
+
+        h1 = bytes([0x20, (netfn << 2) & 0xFC])
+        c1 = _ipmi_checksum(h1)
+        body = bytes([0x81, (rq_seq << 2) & 0xFC, cmd]) + data
+        c2 = _ipmi_checksum(body)
+        ipmi_msg = h1 + bytes([c1]) + body + bytes([c2])
+
+        pad_len = (16 - ((len(ipmi_msg) + 1) % 16)) % 16
+        padded = ipmi_msg + bytes(range(1, pad_len + 1)) + bytes([pad_len])
+        iv = os.urandom(16)
+        ct = aes128_cbc_encrypt(self._k2[:16], iv, padded)
+        enc_payload = iv + ct
+
+        sess_hdr = struct.pack("<BBIIH", 0x06, 0xC0, self._ms_sid, seq_num, len(enc_payload))
+        auth_input = sess_hdr + enc_payload
+        ipad_len = (4 - ((len(auth_input) + 2) % 4)) % 4
+        auth_input += (b"\xff" * ipad_len) + bytes([ipad_len, 0x07])
+        icv = hmac.new(self._k1, auth_input, hmod).digest()[:int_len]
+        pkt = b"\x06\x00\xff\x07" + auth_input + icv
+
+        self._sock.sendto(pkt, (self.host, self.port))
+        resp, _ = self._sock.recvfrom(4096)
+        if len(resp) < 16 + 32:
+            raise RuntimeError(f"Short encrypted IPMI reply ({len(resp)} bytes)")
+        r_plen = struct.unpack_from("<H", resp, 14)[0]
+        r_enc = resp[16 : 16 + r_plen]
+        if len(r_enc) < 32 or (len(r_enc) - 16) % 16 != 0:
+            raise RuntimeError("Malformed encrypted IPMI payload")
+        r_pt = aes128_cbc_decrypt(self._k2[:16], r_enc[:16], r_enc[16:])
+        r_pad = r_pt[-1]
+        if r_pad + 1 >= len(r_pt):
+            raise RuntimeError(f"Invalid AES pad length {r_pad}")
+        r_msg = r_pt[: -(r_pad + 1)]
+        if len(r_msg) < 8:
+            raise RuntimeError(f"Short decrypted IPMI message ({len(r_msg)} bytes)")
+        comp = r_msg[6]
+        if comp != 0:
+            raise RuntimeError(f"IPMI completion code 0x{comp:02X}")
+        return r_msg[7:-1]
+
+    def raw_command(self, netfn: int, cmd: int, data: bytes = b"") -> bytes:
+        for attempt in range(2):
+            try:
+                if self._sock is None or not self._ms_sid:
+                    self.connect()
+                return self._send_ipmi(netfn, cmd, data)
+            except Exception:
+                self.close()
+                if attempt == 1:
+                    raise
+        raise RuntimeError("unreachable")
+
+    def read_dimm_temps(self) -> BmcNetSample:
+        t0 = time.monotonic()
+        try:
+            raw = self.raw_command(OEM_DIMM_NETFN, OEM_DIMM_CMD, OEM_DIMM_DATA)
+            rtt_ms = (time.monotonic() - t0) * 1000.0
+            temps = parse_oem_dimm_payload(raw)
+            return BmcNetSample(
+                ok=True,
+                temps_c=temps,
+                raw_hex=raw.hex(" ").upper(),
+                backend="rmcp+",
+                cipher_suite=self._active_cipher,
+                rtt_ms=round(rtt_ms, 2),
+            )
+        except Exception as exc:
+            rtt_ms = (time.monotonic() - t0) * 1000.0
+            return BmcNetSample(
+                ok=False,
+                backend="rmcp+",
+                cipher_suite=self._active_cipher,
+                rtt_ms=round(rtt_ms, 2),
+                error=str(exc),
+            )
+
+
+# ---------------------------------------------------------------------------
+# Unified BMC NET Reader (RMCP+ / ipmitool / Redfish)
+# ---------------------------------------------------------------------------
+class BmcNetReader:
+    """High-level DIMM temperature reader supporting RMCP+, ipmitool, Redfish."""
+
+    def __init__(
+        self,
+        host: str = "192.168.2.168",
+        user: str = "ADMIN",
+        password: str = "Admin123@pl",
+        backend: str = "rmcp+",
+        port: int = 623,
+        cipher_suite: int = 17,
+        timeout: float = 2.5,
+        ipmitool_path: str = "ipmitool",
+    ) -> None:
+        self.host = host.strip()
+        self.user = user
+        self.password = password
+        self.backend = backend.lower().strip()
+        self.port = int(port)
+        self.cipher_suite = int(cipher_suite)
+        self.timeout = float(timeout)
+        self.ipmitool_path = ipmitool_path
+        self._rmcp: RmcpPlusClient | None = None
+
+    def close(self) -> None:
+        if self._rmcp is not None:
+            self._rmcp.close()
+            self._rmcp = None
+
+    def configure(
+        self,
+        *,
+        host: str | None = None,
+        user: str | None = None,
+        password: str | None = None,
+        backend: str | None = None,
+        port: int | None = None,
+        cipher_suite: int | None = None,
+    ) -> None:
+        self.close()
+        if host is not None:
+            self.host = host.strip()
+        if user is not None:
+            self.user = user
+        if password is not None:
+            self.password = password
+        if backend is not None:
+            self.backend = backend.lower().strip()
+        if port is not None:
+            self.port = int(port)
+        if cipher_suite is not None:
+            self.cipher_suite = int(cipher_suite)
+
+    def poll(self) -> BmcNetSample:
+        if self.backend == "rmcp+":
+            if self._rmcp is None:
+                self._rmcp = RmcpPlusClient(
+                    host=self.host,
+                    user=self.user,
+                    password=self.password,
+                    port=self.port,
+                    cipher_suite=self.cipher_suite,
+                    timeout=self.timeout,
+                )
+            return self._rmcp.read_dimm_temps()
+        if self.backend == "ipmitool":
+            return self._poll_ipmitool()
+        if self.backend == "redfish":
+            return self._poll_redfish()
+        return BmcNetSample(ok=False, backend=self.backend, error=f"Unsupported backend: {self.backend}")
+
+    def _poll_ipmitool(self) -> BmcNetSample:
+        t0 = time.monotonic()
+        cmd = [
+            self.ipmitool_path,
+            "-I", "lanplus",
+            "-C", str(self.cipher_suite),
+            "-H", self.host,
+            "-U", self.user,
+            "-P", self.password,
+            "raw", "0x36", "0x6c", "0xdf", "0xdd", "0x00", "0x03",
+        ]
+        try:
+            res = subprocess.run(cmd, capture_output=True, text=True, timeout=self.timeout + 1.0, check=True)
+            tokens = res.stdout.strip().split()
+            raw = bytes(int(tok, 16) for tok in tokens)
+            rtt_ms = (time.monotonic() - t0) * 1000.0
+            return BmcNetSample(
+                ok=True,
+                temps_c=parse_oem_dimm_payload(raw),
+                raw_hex=raw.hex(" ").upper(),
+                backend="ipmitool",
+                cipher_suite=self.cipher_suite,
+                rtt_ms=round(rtt_ms, 2),
+            )
+        except Exception as exc:
+            return BmcNetSample(
+                ok=False,
+                backend="ipmitool",
+                cipher_suite=self.cipher_suite,
+                rtt_ms=round((time.monotonic() - t0) * 1000.0, 2),
+                error=str(exc),
+            )
+
+    def _poll_redfish(self) -> BmcNetSample:
+        import base64
+
+        t0 = time.monotonic()
+        url = f"https://{self.host}/redfish/v1/Chassis/1/Thermal"
+        auth = base64.b64encode(f"{self.user}:{self.password}".encode("utf-8")).decode("ascii")
+        req = urllib.request.Request(url, headers={"Authorization": f"Basic {auth}", "Accept": "application/json"})
+        ctx = ssl._create_unverified_context()
+        try:
+            with urllib.request.urlopen(req, timeout=self.timeout, context=ctx) as resp:
+                doc = json.loads(resp.read().decode("utf-8"))
+            temps: list[float | None] = [None] * 24
+            idx = 0
+            for item in doc.get("Temperatures", []):
+                name = str(item.get("Name", "")).upper()
+                val = item.get("ReadingCelsius")
+                if "DIMM" in name and idx < 24:
+                    temps[idx] = float(val) if val is not None else None
+                    idx += 1
+            return BmcNetSample(
+                ok=True,
+                temps_c=temps,
+                raw_hex=f"redfish:{idx}_dimm_entries",
+                backend="redfish",
+                cipher_suite=0,
+                rtt_ms=round((time.monotonic() - t0) * 1000.0, 2),
+            )
+        except Exception as exc:
+            return BmcNetSample(
+                ok=False,
+                backend="redfish",
+                cipher_suite=0,
+                rtt_ms=round((time.monotonic() - t0) * 1000.0, 2),
+                error=str(exc),
+            )
+
+
+def self_test_crypto_and_decoder() -> dict[str, Any]:
+    """Verify FIPS-197 AES-128 known-answer test vector + OEM DIMM payload parser."""
+    # NIST FIPS-197 Appendix B AES-128 test vector
+    key = bytes.fromhex("2b7e151628aed2a6abf7158809cf4f3c")
+    pt = bytes.fromhex("3243f6a8885a308d313198a2e0370734")
+    iv = bytes(16)
+    expected_ct = bytes.fromhex("3925841d02dc09fbdc118597196a0b32")
+    ct = aes128_cbc_encrypt(key, iv, pt)
+    assert ct == expected_ct, f"AES-128 KAT encrypt mismatch: {ct.hex()}"
+    rt = aes128_cbc_decrypt(key, iv, ct)
+    assert rt == pt, f"AES-128 KAT decrypt mismatch: {rt.hex()}"
+
+    # Multi-block CBC round-trip
+    iv2 = bytes.fromhex("000102030405060708090a0b0c0d0e0f")
+    pt2 = bytes(range(48))
+    assert aes128_cbc_decrypt(key, iv2, aes128_cbc_encrypt(key, iv2, pt2)) == pt2
+
+    # OEM 48-byte DIMM parser (matches real 192.168.2.168 captured byte pattern)
+    sample_raw = bytearray([0xFF, 0xFF] * 24)
+    sample_raw[0], sample_raw[1] = 0x22, 0x4B  # 34.75 C
+    sample_raw[24], sample_raw[25] = 0x25, 0x19  # 37.25 C
+    sample_raw[46], sample_raw[47] = 0x46, 0x00  # 70.00 C
+    parsed = parse_oem_dimm_payload(bytes(sample_raw))
+    assert parsed[0] == 34.75 and parsed[1] is None and parsed[12] == 37.25 and parsed[23] == 70.0
+    return {"aes128_fips197_kat": "PASS", "oem_dimm_parser": "PASS", "valid_test_dimms": 3}
+
+
+def main(argv: list[str] | None = None) -> int:
+    ap = argparse.ArgumentParser(description="6400 V1.1 BMC NET DIMM temperature client (RMCP+ UDP:623)")
+    ap.add_argument("--host", default="192.168.2.168")
+    ap.add_argument("--user", default="ADMIN")
+    ap.add_argument("--password", default="Admin123@pl")
+    ap.add_argument("--backend", choices=("rmcp+", "ipmitool", "redfish"), default="rmcp+")
+    ap.add_argument("--cipher", type=int, default=17, choices=(17, 3))
+    ap.add_argument("--self-test", action="store_true")
+    args = ap.parse_args(argv)
+    if args.self_test:
+        print(json.dumps(self_test_crypto_and_decoder(), indent=2))
+        return 0
+    reader = BmcNetReader(host=args.host, user=args.user, password=args.password, backend=args.backend, cipher_suite=args.cipher)
+    try:
+        s = reader.poll()
+        print(json.dumps({
+            "ok": s.ok, "backend": s.backend, "cipher_suite": s.cipher_suite,
+            "rtt_ms": s.rtt_ms, "valid_count": s.valid_count,
+            "temps_c": s.temps_c, "raw_hex": s.raw_hex, "error": s.error,
+        }, indent=2))
+        return 0 if s.ok else 1
+    finally:
+        reader.close()
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 643 - 0
tools/v11_nomcu_gui.py

@@ -0,0 +1,643 @@
+#!/usr/bin/env python3
+"""Prod2U 6400 V1.1 No-MCU Windows Adaptive PID + BMC NET Host Application.
+
+Standalone branch (`6400-v1.1`) host tool — ZERO third-party crypto or plotting
+dependencies (pure stdlib + optional pyserial) so PyInstaller builds a single
+self-contained native Windows EXE (`Prod2U-6400-V11-PID-GUI-v3.3.0.exe`):
+  - Directly controls 6400 V1.1 CPLD over RS-232 (CON78) or 3.3V TTL (CON30)
+    using 32B SET_ALL / 83B GET_DATA / 20B DIAGNOSTIC (format=3, board_id=0x61).
+  - Directly acquires 24 DIMM temperatures (0.25 C precision) over BMC NET
+    (built-in IPMI v2.0 RMCP+ UDP:623 Cipher Suite 17/3, plus ipmitool/Redfish).
+  - Runs 4-chamber coordinated Adaptive PID (online RLS identification, Smith
+    air-lead prediction, 3-regime gain scheduling, global PTC budget cap,
+    intra-chamber spatial uniformity balancing, BMC dropout CT fallback).
+  - Live Tkinter Canvas 4-chamber DIMM + CT7428 charts, 70 C target thermal test
+    (continuous recording after chambers reach target), and CSV/JSON/SVG export.
+"""
+
+from __future__ import annotations
+
+import argparse
+from collections import deque
+from datetime import datetime
+import json
+from pathlib import Path
+import queue
+import sys
+import threading
+import time
+from typing import Any
+
+ROOT = Path(__file__).resolve().parents[1]
+if str(ROOT) not in sys.path:
+    sys.path.insert(0, str(ROOT))
+if str(Path(__file__).resolve().parent) not in sys.path:
+    sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+try:
+    import serial
+    import serial.tools.list_ports
+    HAVE_SERIAL = True
+except ImportError:
+    HAVE_SERIAL = False
+
+from v11_bmc_net import BmcNetReader, self_test_crypto_and_decoder
+from v11_adaptive_pid import (
+    AdaptivePidConfig,
+    AdaptiveThermalController,
+    DEFAULT_V11_CHAMBER_MAP,
+    SimulatedV11Plant,
+)
+
+SOFTWARE_VERSION = (
+    (ROOT / "VERSION").read_text(encoding="utf-8").strip()
+    if (ROOT / "VERSION").is_file()
+    else "3.3.0"
+)
+HOST_BAUDRATES = (921600, 460800, 230400, 115200)
+
+
+# ---------------------------------------------------------------------------
+# 6400 V1.1 Wire Frame Codec (A5 5A | TYPE | LEN:u8 | PAYLOAD | CRC16_LE)
+# ---------------------------------------------------------------------------
+def crc16_ccitt_false(data: bytes | bytearray) -> int:
+    crc = 0xFFFF
+    for b in data:
+        crc ^= (b & 0xFF) << 8
+        for _ in range(8):
+            crc = ((crc << 1) ^ 0x1021) & 0xFFFF if (crc & 0x8000) else ((crc << 1) & 0xFFFF)
+    return crc
+
+
+def encode_frame(frame_type: int, payload: bytes = b"") -> bytes:
+    body = bytes([frame_type & 0xFF, len(payload) & 0xFF]) + bytes(payload)
+    crc = crc16_ccitt_false(body)
+    return bytes([0xA5, 0x5A]) + body + bytes([crc & 0xFF, (crc >> 8) & 0xFF])
+
+
+def decode_v11_get_data(payload: bytes) -> dict[str, Any]:
+    if len(payload) != 83:
+        raise ValueError(f"6400 V1.1 GET_DATA must be 83 bytes, got {len(payload)}")
+    ptc = list(payload[0:24])
+    front = list(payload[24:28])
+    rear = list(payload[28:32])
+    bmc_raw = list(payload[32:56])
+    ct_raw = list(payload[56:83])
+    return {
+        "ptc": ptc,
+        "front": front,
+        "rear": rear,
+        "bmc_cpld": [None if b == 0xFF else float(b) for b in bmc_raw],
+        "ct": [None if b == 0xFF else float(b) for b in ct_raw],
+        "ct_raw": ct_raw,
+    }
+
+
+def decode_v11_diagnostic(payload: bytes) -> dict[str, Any]:
+    if len(payload) != 20:
+        raise ValueError(f"6400 V1.1 DIAGNOSTIC must be 20 bytes, got {len(payload)}")
+    fmt, bid = payload[0], payload[1]
+    fw = f"{payload[2]}.{payload[3]}.{payload[4]}"
+    flags = payload[19]
+    return {
+        "format": fmt,
+        "board_id": bid,
+        "supported": (fmt == 3 and bid == 0x61),
+        "firmware_version": fw,
+        "scl_high": bool(payload[5] & 1),
+        "sda_high": bool(payload[5] & 2),
+        "sample_seen": bool(payload[5] & 32),
+        "last_channel": payload[7],
+        "device_address": payload[8],
+        "i2c_error": payload[10],
+        "temp_c": None if payload[13] == 0xFF else int(payload[13]),
+        "scan_round": payload[16],
+        "watchdog_expired": bool(flags & 8),
+        "duty_bank_valid": bool(flags & 16),
+    }
+
+
+class V11StreamDecoder:
+    """Streaming byte parser for 6400 V1.1 (never drops frames on partial/glued reads)."""
+
+    def __init__(self) -> None:
+        self._buf = bytearray()
+
+    def feed(self, data: bytes) -> list[tuple[int, bytes]]:
+        self._buf.extend(data)
+        frames: list[tuple[int, bytes]] = []
+        while True:
+            idx = self._buf.find(b"\xA5\x5A")
+            if idx < 0:
+                if len(self._buf) > 1:
+                    del self._buf[:-1]
+                break
+            if idx > 0:
+                del self._buf[:idx]
+            if len(self._buf) < 6:
+                break
+            ftype = self._buf[2]
+            flen = self._buf[3]
+            total = flen + 6
+            if len(self._buf) < total:
+                break
+            body = bytes(self._buf[2 : 4 + flen])
+            rx_crc = self._buf[4 + flen] | (self._buf[5 + flen] << 8)
+            if crc16_ccitt_false(body) == rx_crc:
+                frames.append((ftype, bytes(self._buf[4 : 4 + flen])))
+                del self._buf[:total]
+            else:
+                del self._buf[:2]
+        return frames
+
+
+# ---------------------------------------------------------------------------
+# SVG Curve & CSV Session Exporter (pure stdlib)
+# ---------------------------------------------------------------------------
+def export_history_csv(records: list[dict[str, Any]]) -> str:
+    cols = ["elapsed_s", "time_label", "mode"]
+    for c in (1, 2, 3, 4):
+        cols.extend([
+            f"C{c}_DIMM_C", f"C{c}_AIR_C", f"C{c}_TARGET_C",
+            f"C{c}_PTC_PCT", f"C{c}_FRONT_PCT", f"C{c}_REAR_PCT",
+            f"C{c}_REGIME", f"C{c}_RLS_HEAT", f"C{c}_RLS_DIST",
+        ])
+    lines = [",".join(cols)]
+    for rec in records:
+        row = [f"{rec['elapsed_s']:.2f}", rec.get("time_label", ""), rec.get("mode", "AUTO")]
+        for c in (1, 2, 3, 4):
+            ch = rec["chambers"][c]
+            row.extend([
+                "" if ch["pv_dimm_c"] is None else f"{ch['pv_dimm_c']:.2f}",
+                "" if ch["pv_air_c"] is None else f"{ch['pv_air_c']:.1f}",
+                f"{ch['target_final_c']:.1f}",
+                f"{ch['ptc_cmd']:.1f}",
+                f"{ch['front_fan_cmd']:.1f}",
+                f"{ch['rear_fan_cmd']:.1f}",
+                ch["regime"],
+                f"{ch['rls_heat_gain']:.4f}",
+                f"{ch['rls_disturbance_c_per_s']:.4f}",
+            ])
+        lines.append(",".join(row))
+    return "\n".join(lines) + "\n"
+
+
+def render_history_svg(records: list[dict[str, Any]], width: int = 1000, height: int = 620) -> str:
+    colors = {1: ("#ef4444", "#fca5a5"), 2: ("#2563eb", "#93c5fd"), 3: ("#16a34a", "#86efac"), 4: ("#d97706", "#fcd34d")}
+    parts = [
+        f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
+        '<rect width="100%" height="100%" fill="#0f172a"/>',
+        f'<text x="20" y="28" fill="#f8fafc" font-family="sans-serif" font-size="16" font-weight="bold">Prod2U 6400 V1.1 No-MCU Adaptive PID (v{SOFTWARE_VERSION}) — 4-Chamber DIMM (BMC NET) + CT7428 Curves</text>',
+    ]
+    pw, ph = (width - 60) // 2, (height - 90) // 2
+    max_t = max((r["elapsed_s"] for r in records), default=10.0)
+    max_t = max(max_t, 10.0)
+    for idx, cid in enumerate((1, 2, 3, 4)):
+        col = idx % 2
+        row = idx // 2
+        x0 = 20 + col * (pw + 20)
+        y0 = 46 + row * (ph + 20)
+        parts.append(f'<rect x="{x0}" y="{y0}" width="{pw}" height="{ph}" rx="6" fill="#1e293b" stroke="#334155"/>')
+        parts.append(f'<text x="{x0+10}" y="{y0+20}" fill="#e2e8f0" font-family="sans-serif" font-size="13" font-weight="bold">Chamber {cid} (Solid=BMC NET DIMM, Dash=CT7428 Air)</text>')
+        gx0, gy0, gw, gh = x0 + 40, y0 + 30, pw - 55, ph - 50
+        t_min, t_max = 15.0, 95.0
+        for tick in (20, 40, 60, 70, 80, 90):
+            yy = gy0 + gh - (tick - t_min) / (t_max - t_min) * gh
+            stroke = "#eab308" if tick == 70 else "#334155"
+            parts.append(f'<line x1="{gx0}" y1="{yy:.1f}" x2="{gx0+gw}" y2="{yy:.1f}" stroke="{stroke}" stroke-dasharray="3,3"/>')
+            parts.append(f'<text x="{gx0-6}" y="{yy+4:.1f}" fill="#94a3b8" font-size="10" text-anchor="end">{tick}</text>')
+        dimm_pts: list[str] = []
+        air_pts: list[str] = []
+        for r in records:
+            xx = gx0 + (r["elapsed_s"] / max_t) * gw
+            ch = r["chambers"][cid]
+            if ch["pv_dimm_c"] is not None:
+                yy = gy0 + gh - max(0.0, min(1.0, (ch["pv_dimm_c"] - t_min) / (t_max - t_min))) * gh
+                dimm_pts.append(f"{xx:.1f},{yy:.1f}")
+            if ch["pv_air_c"] is not None:
+                yy = gy0 + gh - max(0.0, min(1.0, (ch["pv_air_c"] - t_min) / (t_max - t_min))) * gh
+                air_pts.append(f"{xx:.1f},{yy:.1f}")
+        c_dimm, c_air = colors[cid]
+        if air_pts:
+            parts.append(f'<polyline fill="none" stroke="{c_air}" stroke-width="1.5" stroke-dasharray="5,3" points="{" ".join(air_pts)}"/>')
+        if dimm_pts:
+            parts.append(f'<polyline fill="none" stroke="{c_dimm}" stroke-width="2.2" points="{" ".join(dimm_pts)}"/>')
+    parts.append("</svg>")
+    return "\n".join(parts)
+
+
+# ---------------------------------------------------------------------------
+# Closed-Loop Self-Test (Crypto + V1.1 Wire + Adaptive PID + Dropout Survival)
+# ---------------------------------------------------------------------------
+def run_self_test() -> dict[str, Any]:
+    # 1. Verify FIPS-197 AES-128 & OEM DIMM parser
+    crypto_res = self_test_crypto_and_decoder()
+
+    # 2. Verify 6400 V1.1 wire codec (32B SET, 83B GET, 20B DIAG format=3 board_id=0x61)
+    set_pl = bytes([0] * 24 + [20] * 8)
+    set_frame = encode_frame(0x01, set_pl)
+    assert set_frame.hex(" ").upper().endswith("E7 0A")
+    dec = V11StreamDecoder()
+    get_pl = bytes([50] * 24 + [40] * 4 + [45] * 4 + [0xFF] * 24 + [35] * 27)
+    diag_pl = bytes([3, 0x61, 3, 3, 0, 0x27, 0x10, 1, 0x49, 1, 0, 0x80, 0x0C, 25, 0xFF, 1, 1, 0, 0, 0x10])
+    parsed = dec.feed(b"\x00\xFF" + encode_frame(0x42, get_pl) + encode_frame(0x52, diag_pl))
+    assert len(parsed) == 2 and parsed[0][0] == 0x42 and parsed[1][0] == 0x52
+    g = decode_v11_get_data(parsed[0][1])
+    assert all(v is None for v in g["bmc_cpld"]) and g["ct"][0] == 35.0
+    d = decode_v11_diagnostic(parsed[1][1])
+    assert d["supported"] and d["firmware_version"] == "3.3.0" and d["duty_bank_valid"]
+
+    # 3. Closed-loop 4-chamber Adaptive PID verification (preheat -> 70 C hold -> MemTest load step -> BMC NET dropout)
+    cfg = AdaptivePidConfig(
+        chamber_targets_c={1: 70.0, 2: 70.0, 3: 70.0, 4: 70.0},
+        overall_pass_min_temp_c=70.0,
+        global_ptc_avg_cap=85.0,
+        max_ramp_c_per_min=0.0,
+    )
+    ctrl = AdaptiveThermalController(cfg)
+    plant = SimulatedV11Plant(ambient_c=25.0)
+    ctrl.reset()
+    ctrl.set_auto_mode(True)
+
+    history: list[dict[str, Any]] = []
+    max_overshoot = 0.0
+    fallback_seen = False
+    for sec in range(1, 520):
+        # Inject MemTest86 DIMM self-heating step at t=300s
+        if sec == 300:
+            plant.set_workload_step(0.16)
+        # Inject 14s BMC NET dropout at t=420..433s (must switch to CT fallback seamlessly)
+        bmc_ok = not (420 <= sec <= 433)
+        bmc_temps, ct_temps = plant.step(1.0, ctrl.last_ptc_24, ctrl.last_front_4, ctrl.last_rear_4)
+        out = ctrl.step(
+            dt_s=1.0,
+            bmc_dimm_temps_c=bmc_temps if bmc_ok else [None] * 24,
+            ct_temps_c=ct_temps,
+            bmc_ok=bmc_ok,
+        )
+        # Enforce global PTC power cap invariant
+        assert sum(out["ptc_24"]) / 24.0 <= cfg.global_ptc_avg_cap + 2.0
+        assert len(out["set_all_payload_32"]) == 32
+        for cid in (1, 2, 3, 4):
+            pv = out["chambers"][cid]["pv_dimm_c"]
+            if pv is not None:
+                max_overshoot = max(max_overshoot, pv - 70.0)
+            if out["chambers"][cid]["using_ct_fallback"]:
+                fallback_seen = True
+        if sec % 5 == 0:
+            out["time_label"] = f"{sec:04d}s"
+            out["mode"] = "AUTO"
+            history.append(out)
+
+    final_errs = {cid: abs(ctrl.states[cid].error_c) for cid in (1, 2, 3, 4)}
+    assert ctrl.overall_passed_at_s is not None, "Chambers did not reach 70 C target"
+    assert max_overshoot < 3.0, f"Excessive overshoot: {max_overshoot:.2f} C"
+    assert max(final_errs.values()) < 1.2, f"Steady-state error too large: {final_errs}"
+    assert fallback_seen, "BMC NET dropout fallback to CT7428 never triggered"
+
+    csv_str = export_history_csv(history)
+    svg_str = render_history_svg(history)
+    assert "C1_DIMM_C" in csv_str and "<svg" in svg_str and "<polyline" in svg_str
+
+    return {
+        "status": "PASS",
+        "software_version": SOFTWARE_VERSION,
+        "product": "6400-front-rear (6400 V1.1 No-MCU)",
+        "crypto": crypto_res,
+        "wire_protocol": "PASS (SET32 / GET83 / DIAG20 format=3 board=0x61 fw=3.3.0)",
+        "overall_passed_at_s": ctrl.overall_passed_at_s,
+        "max_overshoot_c": round(max_overshoot, 2),
+        "final_abs_errors_c": {str(k): round(v, 2) for k, v in final_errs.items()},
+        "bmc_dropout_ct_fallback": fallback_seen,
+    }
+
+
+# ---------------------------------------------------------------------------
+# Tkinter Desktop GUI (Zero matplotlib dependency — pure Canvas charts)
+# ---------------------------------------------------------------------------
+def launch_gui() -> int:
+    import tkinter as tk
+    from tkinter import filedialog, messagebox, ttk
+
+    root = tk.Tk()
+    root.title(f"Prod2U 6400 V1.1 无MCU 自适应PID + BMC NET 温控上位机 v{SOFTWARE_VERSION}")
+    root.geometry("1380x880")
+    root.configure(bg="#0f172a")
+
+    cfg = AdaptivePidConfig()
+    ctrl = AdaptiveThermalController(cfg)
+    plant = SimulatedV11Plant(ambient_c=25.0)
+    ctrl.reset()
+
+    state: dict[str, Any] = {
+        "ser": None,
+        "decoder": V11StreamDecoder(),
+        "bmc_reader": BmcNetReader(),
+        "running": False,
+        "sim_mode": True,
+        "history": deque(maxlen=1800),
+        "last_ct": [None] * 27,
+        "last_bmc": [None] * 24,
+        "last_diag": {},
+        "last_bmc_info": "未连接",
+        "log_q": queue.Queue(),
+    }
+
+    style = ttk.Style()
+    try:
+        style.theme_use("clam")
+    except Exception:
+        pass
+
+    # Top Control Strip: Serial (CPLD) + BMC NET + Mode
+    top = tk.Frame(root, bg="#1e293b", padx=10, pady=8)
+    top.pack(fill="x", padx=8, pady=(8, 4))
+
+    tk.Label(top, text="6400 V1.1 串口:", fg="#e2e8f0", bg="#1e293b").grid(row=0, column=0, sticky="w")
+    port_var = tk.StringVar(value="SIMULATION")
+    baud_var = tk.StringVar(value="921600")
+    port_cb = ttk.Combobox(top, textvariable=port_var, width=16)
+    port_cb.grid(row=0, column=1, padx=4)
+    ttk.Combobox(top, textvariable=baud_var, values=[str(b) for b in HOST_BAUDRATES], width=9, state="readonly").grid(row=0, column=2, padx=4)
+
+    def refresh_ports() -> None:
+        ports = ["SIMULATION"]
+        if HAVE_SERIAL:
+            ports.extend(p.device for p in serial.tools.list_ports.comports())
+        port_cb["values"] = ports
+
+    refresh_ports()
+    ttk.Button(top, text="刷新串口", command=refresh_ports).grid(row=0, column=3, padx=3)
+
+    tk.Label(top, text="BMC NET IP:", fg="#e2e8f0", bg="#1e293b").grid(row=0, column=4, padx=(12, 2))
+    bmc_host_var = tk.StringVar(value="192.168.2.168")
+    tk.Entry(top, textvariable=bmc_host_var, width=15).grid(row=0, column=5, padx=2)
+    tk.Label(top, text="用户:", fg="#e2e8f0", bg="#1e293b").grid(row=0, column=6, padx=2)
+    bmc_user_var = tk.StringVar(value="ADMIN")
+    tk.Entry(top, textvariable=bmc_user_var, width=9).grid(row=0, column=7, padx=2)
+    tk.Label(top, text="密码:", fg="#e2e8f0", bg="#1e293b").grid(row=0, column=8, padx=2)
+    bmc_pass_var = tk.StringVar(value="Admin123@pl")
+    tk.Entry(top, textvariable=bmc_pass_var, width=12, show="*").grid(row=0, column=9, padx=2)
+    bmc_backend_var = tk.StringVar(value="rmcp+")
+    ttk.Combobox(top, textvariable=bmc_backend_var, values=["rmcp+", "ipmitool", "redfish"], width=9, state="readonly").grid(row=0, column=10, padx=4)
+
+    status_var = tk.StringVar(value="就绪(可切换 SIMULATION 离线仿真或直连 6400 V1.1 串口 + BMC NET)")
+
+    def probe_bmc_once() -> None:
+        r = BmcNetReader(host=bmc_host_var.get(), user=bmc_user_var.get(), password=bmc_pass_var.get(), backend=bmc_backend_var.get())
+        try:
+            s = r.poll()
+        finally:
+            r.close()
+        if s.ok:
+            vals = [f"D{i}:{v:.2f}" for i, v in enumerate(s.temps_c) if v is not None]
+            status_var.set(f"BMC NET 探测成功 ({s.backend} CS{s.cipher_suite}, {s.rtt_ms}ms, {s.valid_count} DIMMs): " + ", ".join(vals[:8]))
+        else:
+            status_var.set(f"BMC NET 探测失败: {s.error}")
+
+    ttk.Button(top, text="测试 BMC NET", command=probe_bmc_once).grid(row=0, column=11, padx=4)
+
+    # Row 2: Adaptive PID targets & actions
+    row2 = tk.Frame(root, bg="#1e293b", padx=10, pady=6)
+    row2.pack(fill="x", padx=8, pady=(0, 4))
+
+    target_vars: dict[int, tk.StringVar] = {}
+    for c in (1, 2, 3, 4):
+        tk.Label(row2, text=f"腔{c}目标(°C):", fg="#cbd5e1", bg="#1e293b").pack(side="left", padx=(6, 2))
+        v = tk.StringVar(value="70.0")
+        target_vars[c] = v
+        tk.Entry(row2, textvariable=v, width=6).pack(side="left")
+
+    tk.Label(row2, text="总通过最低(°C):", fg="#fbbf24", bg="#1e293b").pack(side="left", padx=(10, 2))
+    pass_min_var = tk.StringVar(value="70.0")
+    tk.Entry(row2, textvariable=pass_min_var, width=6).pack(side="left")
+
+    tk.Label(row2, text="总PTC功率上限(%):", fg="#cbd5e1", bg="#1e293b").pack(side="left", padx=(10, 2))
+    cap_var = tk.StringVar(value="88")
+    tk.Entry(row2, textvariable=cap_var, width=5).pack(side="left")
+
+    rls_var = tk.BooleanVar(value=True)
+    tk.Checkbutton(row2, text="RLS在线自适应", variable=rls_var, fg="#e2e8f0", bg="#1e293b", selectcolor="#0f172a").pack(side="left", padx=8)
+
+    load_var = tk.BooleanVar(value=False)
+    tk.Checkbutton(row2, text="仿真MemTest负载阶跃", variable=load_var, fg="#e2e8f0", bg="#1e293b", selectcolor="#0f172a").pack(side="left", padx=4)
+
+    def apply_pid_params() -> None:
+        try:
+            for c in (1, 2, 3, 4):
+                cfg.chamber_targets_c[c] = float(target_vars[c].get())
+            cfg.overall_pass_min_temp_c = float(pass_min_var.get())
+            cfg.global_ptc_avg_cap = float(cap_var.get())
+            cfg.adaptive_enabled = bool(rls_var.get())
+            plant.set_workload_step(0.16 if load_var.get() else 0.0)
+            status_var.set("已应用自适应 PID 参数")
+        except Exception as exc:
+            messagebox.showerror("参数错误", str(exc))
+
+    def start_loop() -> None:
+        apply_pid_params()
+        port = port_var.get().strip()
+        state["sim_mode"] = (port.upper() == "SIMULATION")
+        if not state["sim_mode"]:
+            if not HAVE_SERIAL:
+                messagebox.showerror("缺少 pyserial", "请安装 pyserial 后连接物理串口")
+                return
+            try:
+                if state["ser"] is not None:
+                    state["ser"].close()
+                state["ser"] = serial.Serial(port, int(baud_var.get()), timeout=0.05)
+                state["bmc_reader"].configure(
+                    host=bmc_host_var.get(), user=bmc_user_var.get(),
+                    password=bmc_pass_var.get(), backend=bmc_backend_var.get(),
+                )
+            except Exception as exc:
+                messagebox.showerror("打开串口失败", str(exc))
+                return
+        ctrl.reset()
+        ctrl.set_auto_mode(True)
+        state["history"].clear()
+        state["running"] = True
+        status_var.set("自适应 PID 温控运行中 (" + ("离线仿真" if state["sim_mode"] else f"{port} + BMC {bmc_host_var.get()}") + ")")
+
+    def stop_loop() -> None:
+        state["running"] = False
+        ctrl.set_auto_mode(False)
+        if state["ser"] is not None:
+            try:
+                # Safe standby: PTC=0%, FAN=20%
+                state["ser"].write(encode_frame(0x01, bytes([0] * 24 + [20] * 8)))
+                state["ser"].close()
+            except Exception:
+                pass
+            state["ser"] = None
+        state["bmc_reader"].close()
+        status_var.set("已停止并恢复安全待机 (PTC=0%, FAN=20%)")
+
+    def export_data() -> None:
+        recs = list(state["history"])
+        if not recs:
+            messagebox.showinfo("无数据", "当前尚无记录数据可导出")
+            return
+        path = filedialog.asksaveasfilename(defaultextension=".csv", filetypes=[("CSV", "*.csv"), ("SVG", "*.svg"), ("JSON", "*.json")])
+        if not path:
+            return
+        p = Path(path)
+        if p.suffix.lower() == ".svg":
+            p.write_text(render_history_svg(recs), encoding="utf-8")
+        elif p.suffix.lower() == ".json":
+            p.write_text(json.dumps(recs, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
+        else:
+            p.write_text(export_history_csv(recs), encoding="utf-8")
+        status_var.set(f"已导出 {len(recs)} 条数据至 {p}")
+
+    ttk.Button(row2, text="▶ 启动自适应温控", command=start_loop).pack(side="left", padx=4)
+    ttk.Button(row2, text="■ 停止/安全待机", command=stop_loop).pack(side="left", padx=4)
+    ttk.Button(row2, text="应用参数", command=apply_pid_params).pack(side="left", padx=4)
+    ttk.Button(row2, text="导出 CSV/SVG/JSON", command=export_data).pack(side="left", padx=4)
+
+    # Main Workspace: 4-Chamber Canvas Charts + Telemetry Table
+    canvas = tk.Canvas(root, bg="#0f172a", highlightthickness=0, height=540)
+    canvas.pack(fill="both", expand=True, padx=8, pady=4)
+
+    info_frame = tk.Frame(root, bg="#1e293b", padx=10, pady=6)
+    info_frame.pack(fill="x", padx=8, pady=(0, 6))
+    chamber_labels: dict[int, tk.Label] = {}
+    for c in (1, 2, 3, 4):
+        lbl = tk.Label(info_frame, text=f"腔体{c}: 等待数据...", fg="#e2e8f0", bg="#1e293b", font=("Consolas", 10), anchor="w")
+        lbl.pack(fill="x")
+        chamber_labels[c] = lbl
+
+    tk.Label(root, textvariable=status_var, fg="#38bdf8", bg="#0f172a", anchor="w", padx=10).pack(fill="x", pady=(0, 6))
+
+    def draw_charts() -> None:
+        canvas.delete("all")
+        w = max(canvas.winfo_width(), 900)
+        h = max(canvas.winfo_height(), 460)
+        recs = list(state["history"])
+        pw, ph = (w - 30) // 2, (h - 24) // 2
+        max_t = max((r["elapsed_s"] for r in recs), default=60.0)
+        max_t = max(max_t, 60.0)
+        colors = {1: ("#ef4444", "#fca5a5"), 2: ("#3b82f6", "#93c5fd"), 3: ("#22c55e", "#86efac"), 4: ("#f59e0b", "#fcd34d")}
+
+        for idx, cid in enumerate((1, 2, 3, 4)):
+            x0 = 10 + (idx % 2) * (pw + 10)
+            y0 = 8 + (idx // 2) * (ph + 8)
+            canvas.create_rectangle(x0, y0, x0 + pw, y0 + ph, fill="#1e293b", outline="#334155")
+            st = ctrl.states[cid]
+            hit_txt = f"达标:{st.reached_target_at_s:.0f}s" if st.reached_target_at_s is not None else (f"ETA:{st.eta_seconds:.0f}s" if st.eta_seconds else "升温中")
+            hdr = f"腔体 {cid} | {st.regime} | DIMM={st.pv_dimm_c or 0:.2f}°C Air={st.pv_air_c or 0:.1f}°C -> {st.target_final_c:.0f}°C ({hit_txt})"
+            canvas.create_text(x0 + 10, y0 + 14, text=hdr, fill="#f8fafc", anchor="w", font=("Sans", 10, "bold"))
+
+            gx0, gy0, gw, gh = x0 + 38, y0 + 28, pw - 50, ph - 42
+            t_min, t_max = 15.0, 95.0
+            for tick in (20, 40, 60, 70, 80, 90):
+                yy = gy0 + gh - (tick - t_min) / (t_max - t_min) * gh
+                col = "#eab308" if abs(tick - st.target_final_c) < 0.5 else "#334155"
+                canvas.create_line(gx0, yy, gx0 + gw, yy, fill=col, dash=(3, 3))
+                canvas.create_text(gx0 - 4, yy, text=str(tick), fill="#94a3b8", anchor="e", font=("Consolas", 8))
+
+            dimm_coords: list[float] = []
+            air_coords: list[float] = []
+            for r in recs:
+                xx = gx0 + (r["elapsed_s"] / max_t) * gw
+                ch = r["chambers"][cid]
+                if ch["pv_dimm_c"] is not None:
+                    yy = gy0 + gh - max(0.0, min(1.0, (ch["pv_dimm_c"] - t_min) / (t_max - t_min))) * gh
+                    dimm_coords.extend([xx, yy])
+                if ch["pv_air_c"] is not None:
+                    yy = gy0 + gh - max(0.0, min(1.0, (ch["pv_air_c"] - t_min) / (t_max - t_min))) * gh
+                    air_coords.extend([xx, yy])
+            c_dimm, c_air = colors[cid]
+            if len(air_coords) >= 4:
+                canvas.create_line(*air_coords, fill=c_air, width=1.5, dash=(4, 2))
+            if len(dimm_coords) >= 4:
+                canvas.create_line(*dimm_coords, fill=c_dimm, width=2.2)
+
+    def tick() -> None:
+        if state["running"]:
+            plant.set_workload_step(0.16 if load_var.get() else 0.0)
+            if state["sim_mode"]:
+                bmc_temps, ct_temps = plant.step(1.0, ctrl.last_ptc_24, ctrl.last_front_4, ctrl.last_rear_4)
+                bmc_ok = True
+            else:
+                # 1. Acquire 24 DIMM temps directly via BMC NET
+                bmc_s = state["bmc_reader"].poll()
+                bmc_ok = bmc_s.ok
+                bmc_temps = bmc_s.temps_c if bmc_s.ok else [None] * 24
+                # 2. Acquire 27 CT7428 temps from 6400 V1.1 CPLD via GET_ALL
+                ser = state["ser"]
+                if ser is not None:
+                    try:
+                        ser.write(encode_frame(0x02, b""))
+                        raw = ser.read(256)
+                        for ftype, pl in state["decoder"].feed(raw):
+                            if ftype == 0x42 and len(pl) == 83:
+                                state["last_ct"] = decode_v11_get_data(pl)["ct"]
+                            elif ftype == 0x52 and len(pl) == 20:
+                                state["last_diag"] = decode_v11_diagnostic(pl)
+                    except Exception as exc:
+                        status_var.set(f"串口读取异常: {exc}")
+                ct_temps = state["last_ct"]
+
+            out = ctrl.step(dt_s=1.0, bmc_dimm_temps_c=bmc_temps, ct_temps_c=ct_temps, bmc_ok=bmc_ok)
+            if not state["sim_mode"] and state["ser"] is not None:
+                try:
+                    state["ser"].write(encode_frame(0x01, out["set_all_payload_32"]))
+                except Exception as exc:
+                    status_var.set(f"串口发送 SET_ALL 失败: {exc}")
+
+            out["time_label"] = datetime.now().strftime("%H:%M:%S")
+            out["mode"] = "SIM" if state["sim_mode"] else "LIVE"
+            state["history"].append(out)
+            for c in (1, 2, 3, 4):
+                ch = out["chambers"][c]
+                fb = " [CT回退]" if ch["using_ct_fallback"] else ""
+                chamber_labels[c].configure(
+                    text=(
+                        f"腔体{c}{fb}: DIMM={ch['pv_dimm_c'] if ch['pv_dimm_c'] is not None else '--'}°C "
+                        f"Air={ch['pv_air_c'] if ch['pv_air_c'] is not None else '--'}°C "
+                        f"Δ={ch['error_c']:+.2f}°C | PTC={ch['ptc_cmd']:5.1f}% "
+                        f"前风={ch['front_fan_cmd']:4.1f}% 后风={ch['rear_fan_cmd']:4.1f}% | "
+                        f"RLS(heat={ch['rls_heat_gain']:.3f}, dist={ch['rls_disturbance_c_per_s']:+.3f}, scale={ch['rls_gain_scale']:.2f}) | {ch['regime']}"
+                    )
+                )
+            draw_charts()
+        root.after(500 if state["sim_mode"] else 1000, tick)
+
+    root.protocol("WM_DELETE_WINDOW", lambda: (stop_loop(), root.destroy()))
+    root.after(200, tick)
+    root.mainloop()
+    return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+    ap = argparse.ArgumentParser(description="Prod2U 6400 V1.1 No-MCU Adaptive PID + BMC NET Host Tool")
+    ap.add_argument("--self-test", action="store_true", help="Run non-GUI crypto, wire codec, and closed-loop PID self-test")
+    ap.add_argument("--probe-bmc", metavar="HOST", help="Live-probe a real BMC IP via RMCP+ UDP:623 and print 24 DIMM temps")
+    ap.add_argument("--user", default="ADMIN")
+    ap.add_argument("--password", default="Admin123@pl")
+    ap.add_argument("--cipher", type=int, default=17, choices=(17, 3))
+    args = ap.parse_args(argv)
+
+    if args.self_test:
+        res = run_self_test()
+        print(json.dumps(res, ensure_ascii=False, indent=2))
+        return 0
+    if args.probe_bmc:
+        r = BmcNetReader(host=args.probe_bmc, user=args.user, password=args.password, backend="rmcp+", cipher_suite=args.cipher)
+        try:
+            s = r.poll()
+            print(json.dumps({
+                "ok": s.ok, "host": args.probe_bmc, "backend": s.backend,
+                "cipher_suite": s.cipher_suite, "rtt_ms": s.rtt_ms,
+                "valid_count": s.valid_count, "temps_c": s.temps_c,
+                "raw_hex": s.raw_hex, "error": s.error,
+            }, ensure_ascii=False, indent=2))
+            return 0 if s.ok else 1
+        finally:
+            r.close()
+    return launch_gui()
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())