| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302 |
- // thermal-console.js — Independent Per-Station 1-to-1 6400 High-Temperature Hood Console
- // Strictly decoupled from memory test execution; Web-only backend-managed closed-loop control.
- (() => {
- const MAX_POINTS = 720;
- const CT_LABELS = ['腔1前', '腔1后', '腔2前', '腔2后', '腔3前', '腔3后', '腔4前', '腔4后'];
- const SERIES_META = [
- { key: 'target', label: '目标温度', color: '#cf4b52', dashed: true },
- { key: 'bmc_avg', label: 'MCU BMC均温', color: '#0d8b80', dashed: false },
- { key: 'bmc_max', label: 'MCU BMC最高', color: '#e67e22', dashed: false },
- { key: 'ct_avg', label: 'CT腔体均温', color: '#2980b9', dashed: false },
- { key: 'ct_max', label: 'CT腔体最高', color: '#8e44ad', dashed: false },
- ];
- const el = id => document.getElementById(id);
- const rootPanel = document.querySelector('.thermal-console-panel');
- if (!rootPanel) return;
- let activeStationId = el('nav-station')?.value || 'S1';
- let syncedStationId = '';
- let lastSnapshot = null;
- let scannedPorts = [];
- let pollInFlight = false;
- let pollTimer = null;
- let rafPending = false;
- let hoverRatio = null;
- let lastFilesSig = '';
- let lastStationsSig = '';
- let lastMapSig = '';
- let mapDirty = false;
- let lastAsciiSig = '';
- let lastFrameSig = '';
- const seqByStation = new Map();
- const chartByStation = new Map();
- const enabledSeries = new Set(['target', 'bmc_avg', 'bmc_max', 'ct_avg', 'ct_max']);
- function escapeHtml(v) {
- return String(v ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
- }
- function setTextIfChanged(node, text) {
- if (node && node.textContent !== text) node.textContent = text;
- }
- function setStatus(msg, isError = false) {
- const bar = el('th-local-status');
- if (bar) {
- bar.textContent = msg;
- bar.classList.remove('hidden');
- bar.classList.toggle('error', Boolean(isError));
- }
- }
- function fmtBytes(b) {
- const n = Number(b) || 0;
- if (n < 1024) return `${n} B`;
- if (n < 1048576) return `${(n / 1024).toFixed(1)} KB`;
- return `${(n / 1048576).toFixed(2)} MB`;
- }
- function fmtTimeShort(ms) {
- if (!ms) return '--:--:--';
- const d = new Date(ms);
- return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
- }
- function modeLabel(st) {
- switch (st) {
- case 'disconnected': return '未连接';
- case 'reconnecting': return '断线重连中';
- case 'offline': return '串口已开 · 待0xF0';
- case 'cpld_lost': return 'CPLD采集失联';
- case 'preheating': return '预加热升温中';
- case 'pid': return 'PID闭环控温';
- case 'manual': return '手动出力保持';
- case 'cooling_purge': return '风扇余温吹扫';
- case 'idle': return '在线待机 (0W)';
- default: return st || '未连接';
- }
- }
- function modeBadgeClass(st) {
- if (st === 'preheating' || st === 'pid' || st === 'manual') return 'is-active';
- if (st === 'idle' || st === 'cooling_purge') return 'is-ok';
- if (st === 'reconnecting' || st === 'offline') return 'is-warn';
- if (st === 'cpld_lost') return 'is-err';
- return '';
- }
- // Pre-build 8 CT cells (matching 腔1前..腔4后) and 24 BMC cells (matching BMC0..BMC23)
- const ctCells = [];
- const ctGrid = el('th-ct8-grid');
- for (let i = 0; i < 8; i++) {
- const d = document.createElement('div');
- d.className = 'th-ct-cell';
- const sp = document.createElement('span');
- sp.textContent = `CT${i + 1} · ${CT_LABELS[i]}`;
- const st = document.createElement('strong');
- st.textContent = '--';
- d.append(sp, st);
- ctGrid.appendChild(d);
- ctCells.push({ val: st, prev: '' });
- }
- const slotCells = [];
- const bmcGrid = el('th-bmc24-grid');
- for (let i = 0; i < 24; i++) {
- const cpu = i < 12 ? 0 : 1;
- const ch = String.fromCharCode(65 + (i % 12));
- const card = document.createElement('div');
- card.className = 'th-slot-card';
- const top = document.createElement('div');
- top.className = 'th-slot-top';
- const lbl = document.createElement('span');
- lbl.textContent = `BMC${i} · CPU${cpu}_${ch}`;
- const diffSpan = document.createElement('span');
- diffSpan.textContent = '';
- top.append(lbl, diffSpan);
- const vals = document.createElement('div');
- vals.className = 'th-slot-vals';
- const mcuStrong = document.createElement('span');
- mcuStrong.className = 'th-slot-mcu';
- mcuStrong.textContent = 'MCU: --';
- const ipmiSpan = document.createElement('span');
- ipmiSpan.className = 'th-slot-ipmi';
- ipmiSpan.textContent = '';
- vals.append(mcuStrong, ipmiSpan);
- card.append(top, vals);
- bmcGrid.appendChild(card);
- slotCells.push({ card, mcuStrong, ipmiSpan, diffSpan, prevCls: 'th-slot-card', prevMcu: '', prevIpmi: '', prevDiff: '' });
- }
- // Legend checkboxes
- const legendEl = el('th-chart-legend');
- for (const s of SERIES_META) {
- const lbl = document.createElement('label');
- const cb = document.createElement('input');
- cb.type = 'checkbox';
- cb.checked = true;
- cb.addEventListener('change', () => {
- if (cb.checked) enabledSeries.add(s.key);
- else enabledSeries.delete(s.key);
- scheduleChartDraw();
- });
- const dot = document.createElement('i');
- dot.style.background = s.color;
- lbl.append(cb, dot, document.createTextNode(s.label));
- legendEl.appendChild(lbl);
- }
- async function callThermalAction(action, extra = {}) {
- const params = Object.assign({
- action,
- station_id: activeStationId || 'S1',
- }, extra);
- return window.stlTransport.call('ThermalAction', params, 10000);
- }
- function updateModeVisibility() {
- const mode = el('th-conn-mode').value;
- el('th-serial-wrap').classList.toggle('hidden', mode !== 'serial');
- el('th-sn-wrap').classList.toggle('hidden', mode !== 'serial');
- el('th-tcp-wrap').classList.toggle('hidden', mode !== 'tcp');
- }
- el('th-conn-mode').addEventListener('change', updateModeVisibility);
- updateModeVisibility();
- function applyPortSelection(val) {
- const match = scannedPorts.find(p => p.path === val || p.resolved_path === val || p.by_id === val || p.by_path === val);
- if (match) {
- el('th-usb-serial').value = match.usb_serial_unique ? (match.usb_serial || '') : '';
- }
- }
- el('th-serial-path').addEventListener('change', () => {
- applyPortSelection(el('th-serial-path').value.trim());
- });
- el('th-serial-select').addEventListener('change', () => {
- const val = el('th-serial-select').value;
- if (!val) return;
- el('th-serial-path').value = val;
- applyPortSelection(val);
- });
- async function scanPorts(silent = false) {
- try {
- const res = await callThermalAction('scan_ports');
- const ports = Array.isArray(res?.ports) ? res.ports : [];
- scannedPorts = ports;
- const dl = el('th-serial-datalist');
- dl.replaceChildren(...ports.map(p => {
- const opt = document.createElement('option');
- opt.value = p.path;
- const notes = [];
- if (p.resolved_path && p.resolved_path !== p.path) notes.push(p.resolved_path);
- if (p.bound_station) notes.push(`已绑定 ${p.bound_station}`);
- if (p.console_conflict) notes.push('BIOS串口占用中');
- opt.label = `${p.label || p.path}${notes.length ? ' [' + notes.join(' · ') + ']' : ''}`;
- return opt;
- }));
- const sel = el('th-serial-select');
- if (sel) {
- const curVal = el('th-serial-path').value.trim();
- const defaultOpt = document.createElement('option');
- defaultOpt.value = '';
- defaultOpt.textContent = ports.length ? `-- 选择已扫描串口 (${ports.length}) --` : '-- 未发现 USB 串口 --';
- sel.replaceChildren(defaultOpt, ...ports.map(p => {
- const opt = document.createElement('option');
- opt.value = p.path;
- const notes = [];
- if (p.bound_station) notes.push(`已绑:${p.bound_station}`);
- if (p.console_conflict) notes.push('BIOS占用');
- opt.textContent = `${p.label || p.path}${notes.length ? ' [' + notes.join(' · ') + ']' : ''}`;
- return opt;
- }));
- if (curVal && ports.some(p => p.path === curVal)) sel.value = curVal;
- }
- if (!silent) {
- setStatus(`扫描完成:共发现 ${ports.length} 个 USB 串口设备`);
- }
- } catch (err) {
- if (!silent) setStatus(`扫描串口失败: ${err.message}`, true);
- }
- }
- function selectStationLocal(sid, syncNav = true) {
- if (!sid || sid === activeStationId) return;
- activeStationId = sid;
- syncedStationId = '';
- hoverRatio = null;
- if (syncNav) {
- const navSel = el('nav-station');
- if (navSel && navSel.value !== sid) {
- navSel.value = sid;
- window.dispatchEvent(new CustomEvent('stl:station-select', { detail: { stationId: sid, fromThermal: true } }));
- }
- }
- void pollConsole(true);
- }
- function setMapStatus(msg, isError = false) {
- const node = el('th-map-status');
- if (!node) return;
- node.textContent = msg;
- node.style.color = isError ? '#b83740' : '#0d6a5f';
- }
- function renderBmcMappingTable(stationsArr) {
- const tbody = el('th-bmc-map-tbody');
- if (!tbody || !Array.isArray(stationsArr)) return;
- // Live-update status badges without clobbering user input while typing/editing
- for (const s of stationsArr) {
- const badge = tbody.querySelector(`[data-map-status="${s.station_id}"]`);
- if (badge) {
- badge.textContent = modeLabel(s.mcu_mode);
- badge.className = `th-pill ${modeBadgeClass(s.mcu_mode)}`;
- }
- }
- const activeEl = document.activeElement;
- if (mapDirty || (activeEl && tbody.contains(activeEl))) return;
- const portSig = scannedPorts.map(p => `${p.path}:${p.bound_station || ''}`).join('|');
- const sig = JSON.stringify([portSig, stationsArr.map(s => [
- s.station_id, s.bmc_host, s.preferred_mode, s.mode, s.serial_path, s.resolved_path,
- s.usb_serial, s.tcp_host, s.tcp_port, s.mcu_mode, s.online, s.uid_hex,
- ])]);
- if (sig === lastMapSig) return;
- lastMapSig = sig;
- const makePortOptions = (selectedPath) => {
- const opts = ['<option value="">-- 选择已扫描 USB 串口 --</option>'];
- for (const p of scannedPorts) {
- const notes = [];
- if (p.bound_station) notes.push(`已绑:${p.bound_station}`);
- if (p.console_conflict) notes.push('BIOS占用');
- const lbl = `${p.label || p.path}${notes.length ? ' [' + notes.join('·') + ']' : ''}`;
- const selAttr = p.path === selectedPath ? ' selected' : '';
- opts.push(`<option value="${escapeHtml(p.path)}"${selAttr}>${escapeHtml(lbl)}</option>`);
- }
- return opts.join('');
- };
- tbody.innerHTML = stationsArr.map(s => {
- const sid = s.station_id || 'S1';
- const rowMode = (s.mode && s.mode !== 'disconnected') ? s.mode : (s.preferred_mode || 'serial');
- const isTcp = rowMode === 'tcp';
- const isMock = rowMode === 'mock';
- const bmcHost = s.bmc_host || s.station_bmc_host || '';
- const modeText = modeLabel(s.mcu_mode);
- const pillCls = modeBadgeClass(s.mcu_mode);
- return `<tr data-map-row="${escapeHtml(sid)}">
- <td><strong>${escapeHtml(sid)}</strong><div class="field-note">${escapeHtml((s.station_name || '').replace(/\s*\(.+\)$/, ''))}</div></td>
- <td><input type="text" list="th-bmc-ip-presets" data-map-field="bmc_host" value="${escapeHtml(bmcHost)}" placeholder="如 192.168.2.166" spellcheck="false"></td>
- <td>
- <select data-map-field="mode">
- <option value="serial"${rowMode === 'serial' ? ' selected' : ''}>USB 串口</option>
- <option value="tcp"${rowMode === 'tcp' ? ' selected' : ''}>TCP 串口</option>
- <option value="mock"${rowMode === 'mock' ? ' selected' : ''}>Mock 仿真</option>
- </select>
- </td>
- <td>
- <div class="th-map-serial-cell" data-map-serial-box="${escapeHtml(sid)}"${isTcp || isMock ? ' style="display:none"' : ''}>
- <select data-map-field="serial_pick">${makePortOptions(s.serial_path || '')}</select>
- <input type="text" list="th-serial-datalist" data-map-field="serial_path" value="${escapeHtml(s.serial_path || '')}" placeholder="/dev/ttyUSB1 或 /dev/serial/by-path/..." spellcheck="false">
- </div>
- <div class="th-map-tcp-row" data-map-tcp-box="${escapeHtml(sid)}"${!isTcp ? ' style="display:none"' : ''}>
- <input type="text" data-map-field="tcp_host" value="${escapeHtml(s.tcp_host || '127.0.0.1')}" placeholder="IP" style="flex:2">
- <input type="number" data-map-field="tcp_port" value="${escapeHtml(s.tcp_port || 4002)}" min="1" max="65535" style="flex:1">
- </div>
- <span class="field-note" data-map-mock-box="${escapeHtml(sid)}"${!isMock ? ' style="display:none"' : ''}>离线虚拟 6400 高温罩仿真</span>
- </td>
- <td><input type="text" data-map-field="usb_serial" value="${escapeHtml(s.usb_serial || '')}" placeholder="可选防漂移" spellcheck="false"></td>
- <td>
- <div class="th-map-actions">
- <span class="th-pill ${pillCls}" data-map-status="${escapeHtml(sid)}">${escapeHtml(modeText)}</span>
- <button type="button" class="btn btn-quiet btn-xs" data-map-act="save" data-map-sid="${escapeHtml(sid)}">保存</button>
- <button type="button" class="btn btn-primary btn-xs" data-map-act="connect" data-map-sid="${escapeHtml(sid)}">连接</button>
- <button type="button" class="btn btn-secondary btn-xs" data-map-act="disconnect" data-map-sid="${escapeHtml(sid)}">断开</button>
- </div>
- </td>
- </tr>`;
- }).join('');
- const collectRow = (sid) => {
- const tr = tbody.querySelector(`tr[data-map-row="${sid}"]`);
- if (!tr) return null;
- return {
- station_id: sid,
- bmc_host: tr.querySelector('[data-map-field="bmc_host"]')?.value.trim() || '',
- mode: tr.querySelector('[data-map-field="mode"]')?.value || 'serial',
- serial_path: tr.querySelector('[data-map-field="serial_path"]')?.value.trim() || '',
- usb_serial: tr.querySelector('[data-map-field="usb_serial"]')?.value.trim() || '',
- tcp_host: tr.querySelector('[data-map-field="tcp_host"]')?.value.trim() || '127.0.0.1',
- tcp_port: Number(tr.querySelector('[data-map-field="tcp_port"]')?.value) || 4002,
- };
- };
- tbody.querySelectorAll('input, select').forEach(ctrl => {
- ctrl.addEventListener('input', () => { mapDirty = true; });
- ctrl.addEventListener('change', () => {
- mapDirty = true;
- const tr = ctrl.closest('tr[data-map-row]');
- const sid = tr?.dataset.mapRow;
- if (!sid) return;
- if (ctrl.dataset.mapField === 'mode') {
- const md = ctrl.value;
- const sBox = tr.querySelector(`[data-map-serial-box="${sid}"]`);
- const tBox = tr.querySelector(`[data-map-tcp-box="${sid}"]`);
- const mBox = tr.querySelector(`[data-map-mock-box="${sid}"]`);
- if (sBox) sBox.style.display = md === 'serial' ? '' : 'none';
- if (tBox) tBox.style.display = md === 'tcp' ? '' : 'none';
- if (mBox) mBox.style.display = md === 'mock' ? '' : 'none';
- } else if (ctrl.dataset.mapField === 'serial_pick' && ctrl.value) {
- const pathInp = tr.querySelector('[data-map-field="serial_path"]');
- const snInp = tr.querySelector('[data-map-field="usb_serial"]');
- if (pathInp) pathInp.value = ctrl.value;
- const match = scannedPorts.find(p => p.path === ctrl.value);
- if (match && snInp) snInp.value = match.usb_serial_unique ? (match.usb_serial || '') : '';
- }
- });
- });
- tbody.querySelectorAll('[data-map-act]').forEach(btn => {
- btn.addEventListener('click', async () => {
- const sid = btn.dataset.mapSid;
- const act = btn.dataset.mapAct;
- const row = collectRow(sid);
- if (!row) return;
- try {
- if (act === 'save') {
- await window.stlTransport.call('ThermalAction', { action: 'save_mappings', station_id: sid, ...row }, 10000);
- mapDirty = false;
- lastMapSig = '';
- setMapStatus(`已保存 ${sid} (BMC ${row.bmc_host || '未填'}) ↔ 高温罩串口映射`);
- } else if (act === 'connect') {
- await window.stlTransport.call('ThermalAction', { action: 'connect', ...row, serial_baud: 115200, auto_reconnect: true }, 10000);
- mapDirty = false;
- lastMapSig = '';
- setMapStatus(`已连接 ${sid} (BMC ${row.bmc_host || '未填'}) 高温罩`);
- } else if (act === 'disconnect') {
- await window.stlTransport.call('ThermalAction', { action: 'disconnect', station_id: sid }, 10000);
- mapDirty = false;
- lastMapSig = '';
- setMapStatus(`已断开 ${sid} 高温罩串口(不影响内存测试)`);
- }
- if (sid === activeStationId) syncedStationId = '';
- await pollConsole(true);
- } catch (err) {
- setMapStatus(`${sid} 操作失败: ${err.message}`, true);
- }
- });
- });
- }
- function renderStationCards(stationsArr) {
- if (!Array.isArray(stationsArr)) return;
- const container = el('th-station-cards');
- if (!container) return;
- const sig = JSON.stringify([activeStationId, stationsArr.map(s => [
- s.station_id, s.bmc_host, s.mode, s.online, s.mcu_mode, s.serial_path, s.resolved_path,
- s.target_c, s.bmc_avg, s.ct_avg, s.recording_active, s.recording_rows,
- s.session_samples_count, s.last_error, s.uid_hex,
- ])]);
- if (sig === lastStationsSig) return;
- lastStationsSig = sig;
- container.innerHTML = stationsArr.map(s => {
- const sid = s.station_id || 'S1';
- const activeCls = sid === activeStationId ? ' active' : '';
- const modeText = modeLabel(s.mcu_mode);
- const pillCls = modeBadgeClass(s.mcu_mode);
- const bmcTxt = s.bmc_host ? `BMC ${s.bmc_host}` : 'BMC 未指定';
- const portText = s.mode === 'mock'
- ? `Mock 仿真 · ${s.uid_hex ? s.uid_hex.slice(-8) : 'v1.1'}`
- : s.mode === 'tcp'
- ? `TCP ${s.tcp_host}:${s.tcp_port}`
- : (s.resolved_path || s.serial_path || '未绑定串口');
- const tgt = s.target_c != null ? `${s.target_c}℃` : '--';
- const ctAvg = s.ct_avg != null ? `${Number(s.ct_avg).toFixed(1)}℃` : '--';
- const bmcAvg = s.bmc_avg != null ? `${Number(s.bmc_avg).toFixed(1)}℃` : '--';
- const recStr = s.recording_active
- ? `录制中 ${s.recording_rows || 0}行`
- : `缓存 ${s.session_samples_count || 0}行`;
- return `<div class="th-station-card${activeCls}" data-th-sid="${escapeHtml(sid)}" role="button" tabindex="0">
- <div class="th-station-card-top">
- <span class="th-station-card-name">${escapeHtml(sid)} · ${escapeHtml(bmcTxt)}</span>
- <span class="th-pill ${pillCls}">${escapeHtml(modeText)}</span>
- </div>
- <div class="th-station-card-port" title="${escapeHtml(portText)}">${escapeHtml(portText)}</div>
- <div class="th-station-card-metrics">
- <span>目标 <strong>${escapeHtml(tgt)}</strong></span>
- <span>腔均 <strong>${escapeHtml(ctAvg)}</strong></span>
- <span>BMC均 <strong>${escapeHtml(bmcAvg)}</strong></span>
- </div>
- <div class="th-station-card-foot">
- <span>${escapeHtml(recStr)}</span>
- <span title="${escapeHtml(s.last_error || '')}">${s.last_error ? escapeHtml(s.last_error.slice(0, 18)) : (s.station_phase ? `测试:${escapeHtml(s.station_phase)}` : '')}</span>
- </div>
- </div>`;
- }).join('');
- container.querySelectorAll('.th-station-card').forEach(card => {
- card.addEventListener('click', () => selectStationLocal(card.dataset.thSid, true));
- card.addEventListener('keydown', ev => {
- if (ev.key === 'Enter' || ev.key === ' ') {
- ev.preventDefault();
- selectStationLocal(card.dataset.thSid, true);
- }
- });
- });
- }
- function updateOverviewThermalBadge(stationsArr) {
- const badge = el('ov-thermal-badge');
- if (!badge || !Array.isArray(stationsArr)) return;
- const curSid = el('nav-station')?.value || activeStationId;
- const item = stationsArr.find(x => x.station_id === curSid);
- if (!item) {
- setTextIfChanged(badge, '未配置');
- badge.className = 'badge';
- return;
- }
- if (item.online) {
- const ctTxt = item.ct_avg != null ? `${Number(item.ct_avg).toFixed(1)}℃` : '--℃';
- const tgtTxt = item.target_c != null ? `→${item.target_c}℃` : '';
- setTextIfChanged(badge, `${modeLabel(item.mcu_mode)} · 腔均${ctTxt}${tgtTxt}`);
- badge.className = item.mcu_mode === 'cpld_lost' ? 'badge error' : 'badge connected';
- } else if (item.desired_connected) {
- setTextIfChanged(badge, '重连中');
- badge.className = 'badge error';
- } else {
- setTextIfChanged(badge, '未连接');
- badge.className = 'badge';
- }
- }
- function renderSnapshot(snap) {
- if (!snap) return;
- lastSnapshot = snap;
- const sid = snap.station_id || activeStationId;
- const conn = snap.connection || {};
- const mcu = snap.mcu || {};
- const ident = snap.identity || {};
- const safety = snap.safety || {};
- const act = snap.actuators || {};
- const rec = snap.recorder || {};
- const stCtx = snap.station_context || {};
- renderStationCards(snap.stations);
- renderBmcMappingTable(snap.stations);
- updateOverviewThermalBadge(snap.stations);
- setTextIfChanged(
- el('th-selected-station-label'),
- `${sid} · ${stCtx.station_name || sid}`
- );
- const switchedStation = syncedStationId !== sid;
- if (switchedStation) {
- syncedStationId = sid;
- if (el('th-bmc-host')) {
- el('th-bmc-host').value = conn.bmc_host || stCtx.bmc_host || '';
- }
- const modeVal = conn.mode && conn.mode !== 'disconnected' ? conn.mode : (conn.preferred_mode || (conn.tcp_host && !conn.serial_path ? 'tcp' : 'serial'));
- el('th-conn-mode').value = modeVal;
- updateModeVisibility();
- el('th-serial-path').value = conn.serial_path || '';
- const selPort = el('th-serial-select');
- if (selPort) {
- const spVal = conn.serial_path || '';
- const hasOpt = spVal && scannedPorts.some(p => p.path === spVal);
- selPort.value = hasOpt ? spVal : '';
- }
- el('th-usb-serial').value = conn.usb_serial || '';
- el('th-tcp-host').value = conn.tcp_host || '127.0.0.1';
- el('th-tcp-port').value = conn.tcp_port || 4002;
- el('th-auto-reconnect').checked = conn.auto_reconnect !== false;
- el('th-safety-lease').value = String(safety.lease_sec ?? 0);
- el('th-overtemp-cutoff').value = String(safety.overtemp_cutoff_c ?? 95);
- el('th-target-input').value = String(mcu.last_set_target_c ?? 70);
- el('th-rec-auto').checked = rec.auto_record_on_heat !== false;
- el('th-rec-interval').value = String(rec.interval_ms ?? 1000);
- }
- const online = Boolean(conn.online);
- const pOnline = el('th-pill-online');
- const linkDesc = online
- ? `链路: 在线 (${conn.mode === 'serial' ? (conn.resolved_path || conn.serial_path) : conn.mode === 'tcp' ? `${conn.tcp_host}:${conn.tcp_port}` : 'Mock'})`
- : conn.desired_connected
- ? `链路: 断线重连中 (${conn.last_error || '等待设备'})`
- : '链路: 未连接';
- setTextIfChanged(pOnline, linkDesc);
- pOnline.className = `th-pill ${online ? 'is-ok' : (conn.desired_connected ? 'is-err' : '')}`;
- const pState = el('th-pill-state');
- setTextIfChanged(pState, `状态: ${modeLabel(mcu.mode)}`);
- pState.className = `th-pill ${modeBadgeClass(mcu.mode)}`;
- const pCpld = el('th-pill-cpld');
- setTextIfChanged(pCpld, !online ? 'CPLD: --' : (mcu.cpld_lost ? 'CPLD: 失联' : 'CPLD: 正常'));
- pCpld.className = `th-pill ${!online ? '' : (mcu.cpld_lost ? 'is-err' : 'is-ok')}`;
- const pPre = el('th-pill-preheat');
- setTextIfChanged(pPre, `预加热: ${mcu.preheating ? '运行中' : '否'}`);
- pPre.className = `th-pill ${mcu.preheating ? 'is-active' : ''}`;
- const pPid = el('th-pill-pid');
- setTextIfChanged(pPid, `PID闭环: ${mcu.pid_running ? '运行中' : '否'}`);
- pPid.className = `th-pill ${mcu.pid_running ? 'is-active' : ''}`;
- const pH = el('th-pill-hlatch');
- setTextIfChanged(pH, `加热锁存: ${mcu.heater_latched_off ? '已锁死' : '正常'}`);
- pH.className = `th-pill ${mcu.heater_latched_off ? 'is-warn' : ''}`;
- const pF = el('th-pill-flatch');
- setTextIfChanged(pF, `风扇锁存: ${mcu.fan_latched_off ? '已锁死' : '正常'}`);
- pF.className = `th-pill ${mcu.fan_latched_off ? 'is-warn' : ''}`;
- const pBmc = el('th-pill-bmc');
- setTextIfChanged(pBmc, !online ? 'BMC温度源: --' : (mcu.bmc_not_ready ? 'BMC温度源: 未就绪' : 'BMC温度源: 就绪'));
- pBmc.className = `th-pill ${!online ? '' : (mcu.bmc_not_ready ? 'is-warn' : 'is-ok')}`;
- const pMan = el('th-pill-manual');
- setTextIfChanged(pMan, `手动保持: ${mcu.manual_active ? (mcu.manual_keepalive ? '保持中' : '10s单次') : '否'}`);
- pMan.className = `th-pill ${mcu.manual_active ? 'is-warn' : ''}`;
- const bootVer = ident.boot_info?.app_version ? `${ident.boot_info.app_version} (${ident.boot_info.bl_state})` : '--';
- setTextIfChanged(el('th-hw-identity'), `UID: ${ident.uid_hex || '--'} · 固件: ${bootVer}`);
- setTextIfChanged(el('th-pid-current'), ident.pid_text || '--');
- const leaseTxt = safety.lease_sec > 0
- ? (safety.lease_remaining_sec > 0 ? `看门狗剩余: ${safety.lease_remaining_sec}s` : `看门狗: ${safety.lease_sec}s (待启动)`)
- : '看门狗: 不限时';
- setTextIfChanged(
- el('th-safety-status'),
- `${leaseTxt} · 超温熔断: ${safety.overtemp_cutoff_c ?? 95}℃${safety.overtemp_tripped ? ' [已触发熔断!]' : ''}`
- );
- setTextIfChanged(el('th-target-badge'), `当前目标: ${mcu.target_c != null ? mcu.target_c + ' ℃' : '-- ℃'}`);
- setTextIfChanged(el('th-act-ptc'), act.snap_updated_unix_ms ? `${act.ptc_avg_duty ?? '--'} %` : '-- %');
- setTextIfChanged(el('th-act-ff'), act.snap_updated_unix_ms ? `${act.fan_front_avg_duty ?? '--'} %` : '-- %');
- setTextIfChanged(el('th-act-fr'), act.snap_updated_unix_ms ? `${act.fan_rear_avg_duty ?? '--'} %` : '-- %');
- const ssr = Array.isArray(act.ssr_3) ? act.ssr_3 : [];
- setTextIfChanged(el('th-act-ssr'), act.snap_updated_unix_ms && ssr.length === 3 ? `${ssr[0]}% / ${ssr[1]}% / ${ssr[2]}%` : '-- / -- / --');
- setTextIfChanged(el('th-act-ct0'), act.ct0_board_c != null ? `${act.ct0_board_c} ℃` : '-- ℃');
- setTextIfChanged(el('th-snap-age'), act.snap_updated_unix_ms ? `更新于 ${fmtTimeShort(act.snap_updated_unix_ms)}` : '等待 MCU 快照...');
- setTextIfChanged(el('th-session-sample-count'), `当前会话已采集 ${rec.session_samples_count || 0} 行`);
- el('btn-th-export-csv').disabled = !(Number(rec.session_samples_count) > 0);
- const recBadge = el('th-rec-badge');
- setTextIfChanged(recBadge, rec.active ? `录制中 (${rec.rows_written || 0} 行)` : '未开启落盘');
- recBadge.className = `badge ${rec.active ? 'connected' : ''}`;
- setTextIfChanged(
- el('th-rec-stats'),
- rec.active
- ? `正在写入: ${rec.csv_filename} · 已写入 ${rec.rows_written || 0} 行 (${fmtBytes(rec.bytes_written)}) · 开始于 ${fmtTimeShort(rec.started_unix_ms)}`
- : '磁盘记录未开启;已连接读取时可直接点击上方「立即导出当前会话 CSV」。'
- );
- // Update persisted CSV file table only when changed
- const files = Array.isArray(snap.files) ? snap.files : [];
- const fSig = JSON.stringify(files.map(f => [f.filename, f.size_bytes, f.active]));
- if (fSig !== lastFilesSig) {
- lastFilesSig = fSig;
- const tbody = el('th-files-tbody');
- if (files.length === 0) {
- tbody.innerHTML = '<tr><td colspan="5">尚无历史记录文件</td></tr>';
- } else {
- tbody.innerHTML = files.map(f => {
- const activeTag = f.active ? ' <span class="badge connected">写入中</span>' : '';
- const stTag = f.station_id ? `<span class="badge">${escapeHtml(f.station_id)}</span>` : '--';
- return `<tr>
- <td><code>${escapeHtml(f.filename)}</code>${activeTag}</td>
- <td>${stTag}</td>
- <td>${fmtBytes(f.size_bytes)}</td>
- <td>${escapeHtml(f.modified_str || '')}</td>
- <td><a class="inline-link" href="${escapeHtml(f.download_url)}" download="${escapeHtml(f.filename)}">下载</a></td>
- </tr>`;
- }).join('');
- }
- }
- const bStats = snap.bmc_stats || {};
- const cStats = snap.ct_stats || {};
- setTextIfChanged(
- el('th-chart-stats'),
- `[${sid}] 目标: ${mcu.target_c != null ? mcu.target_c + '℃' : '--'} · MCU BMC均/最高: ${bStats.avg ?? '--'}/${bStats.max ?? '--'}℃ · CT腔均/最高: ${cStats.avg ?? '--'}/${cStats.max ?? '--'}℃ · 服务器阶段: ${stCtx.phase || '--'}`
- );
- setTextIfChanged(
- el('th-bmc24-summary'),
- `有效通道: ${bStats.valid_cnt || 0}/24 (未插槽位导出为 0) · 均值: ${bStats.avg ?? '--'}℃ · 最高: ${bStats.max ?? '--'}℃`
- );
- const ctArr = Array.isArray(snap.ct7428_8) ? snap.ct7428_8 : [];
- for (let i = 0; i < 8; i++) {
- const v = ctArr[i];
- const txt = v != null ? `${v} ℃` : '--';
- if (ctCells[i].prev !== txt) {
- ctCells[i].prev = txt;
- ctCells[i].val.textContent = txt;
- }
- }
- const mcuArr = Array.isArray(snap.mcu_bmc_24) ? snap.mcu_bmc_24 : [];
- const ipmiArr = Array.isArray(snap.ipmi_dimm_24) ? snap.ipmi_dimm_24 : [];
- for (let i = 0; i < 24; i++) {
- const cell = slotCells[i];
- const mv = mcuArr[i];
- const iv = ipmiArr[i];
- const mTxt = mv != null ? `MCU: ${mv}℃` : 'MCU: --';
- const iTxt = iv != null ? `IPMI: ${Number(iv).toFixed(0)}℃` : '';
- const dTxt = (mv != null && iv != null) ? `Δ${(mv - iv >= 0 ? '+' : '') + (mv - iv).toFixed(1)}` : '';
- const maxT = Math.max(mv ?? -1, iv ?? -1);
- const cls = maxT > 80
- ? 'th-slot-card is-hot'
- : maxT >= 65
- ? 'th-slot-card is-warn'
- : maxT >= 0
- ? 'th-slot-card is-valid'
- : 'th-slot-card';
- if (cell.prevCls !== cls) { cell.prevCls = cls; cell.card.className = cls; }
- if (cell.prevMcu !== mTxt) { cell.prevMcu = mTxt; cell.mcuStrong.textContent = mTxt; }
- if (cell.prevIpmi !== iTxt) { cell.prevIpmi = iTxt; cell.ipmiSpan.textContent = iTxt; }
- if (cell.prevDiff !== dTxt) { cell.prevDiff = dTxt; cell.diffSpan.textContent = dTxt; }
- }
- // Per-station bounded delta chart ring
- let ring = chartByStation.get(sid) || [];
- if (snap.reset_ring) {
- ring = Array.isArray(snap.points_delta) ? snap.points_delta.slice(-MAX_POINTS) : [];
- } else if (Array.isArray(snap.points_delta) && snap.points_delta.length > 0) {
- for (const pt of snap.points_delta) ring.push(pt);
- if (ring.length > MAX_POINTS) ring.splice(0, ring.length - MAX_POINTS);
- }
- chartByStation.set(sid, ring);
- if (typeof snap.latest_point_seq === 'number') {
- seqByStation.set(sid, snap.latest_point_seq);
- }
- scheduleChartDraw();
- if (el('th-debug-drawer').open) {
- const ascii = Array.isArray(snap.ascii_logs) ? snap.ascii_logs : [];
- const aSig = `${sid}:${ascii.length ? ascii[0].unix_ms + ':' + ascii.length : 'empty'}`;
- if (aSig !== lastAsciiSig) {
- lastAsciiSig = aSig;
- el('th-ascii-log-pre').textContent = ascii.length
- ? ascii.slice(0, 45).map(a => `[${(a.time_str || '').slice(11, 23)}] ${a.line}`).join('\n')
- : '暂无 MCU 串口 ASCII 输出...';
- }
- const evs = Array.isArray(snap.events) ? snap.events.slice(0, 20) : [];
- const frms = Array.isArray(snap.frames) ? snap.frames.slice(0, 25) : [];
- const fSig = `${sid}:${evs[0]?.unix_ms || 0}:${frms[0]?.unix_ms || 0}:${frms.length}`;
- if (fSig !== lastFrameSig) {
- lastFrameSig = fSig;
- const evTxt = evs.map(e => `[事件 ${(e.time_str || '').slice(11, 19)} ${e.level}] ${e.message}`).join('\n');
- const frTxt = frms.map(f => `[${f.dir} ${f.cmd} ${f.len}B] ${f.hex}`).join('\n');
- el('th-frame-log-pre').textContent = [evTxt, frTxt].filter(Boolean).join('\n--- 最近协议报文 ---\n') || '暂无事件与协议帧...';
- }
- }
- }
- function scheduleChartDraw() {
- if (rafPending || document.body.dataset.currentPage !== 'thermal') return;
- rafPending = true;
- requestAnimationFrame(() => {
- rafPending = false;
- drawChart();
- });
- }
- function drawChart() {
- const canvas = el('th-chart-canvas');
- if (!canvas) return;
- const rect = canvas.getBoundingClientRect();
- const dpr = window.devicePixelRatio || 1;
- const w = Math.max(360, Math.round(rect.width || 1100));
- const h = 240;
- if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) {
- canvas.width = Math.round(w * dpr);
- canvas.height = Math.round(h * dpr);
- }
- const ctx = canvas.getContext('2d');
- ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
- ctx.clearRect(0, 0, w, h);
- const chartRing = chartByStation.get(activeStationId) || [];
- const padL = 44, padR = 16, padT = 16, padB = 26;
- const plotW = w - padL - padR;
- const plotH = h - padT - padB;
- let minY = 20, maxY = 95;
- for (const pt of chartRing) {
- for (const s of SERIES_META) {
- if (!enabledSeries.has(s.key)) continue;
- const v = pt[s.key];
- if (typeof v === 'number') {
- if (v - 4 < minY) minY = Math.floor((v - 4) / 5) * 5;
- if (v + 5 > maxY) maxY = Math.ceil((v + 5) / 5) * 5;
- }
- }
- }
- if (maxY - minY < 15) maxY = minY + 15;
- const yFor = val => padT + plotH - ((val - minY) / (maxY - minY)) * plotH;
- const xFor = idx => padL + (chartRing.length <= 1 ? 0 : (idx / (chartRing.length - 1)) * plotW);
- ctx.strokeStyle = '#e7eff4';
- ctx.lineWidth = 1;
- ctx.fillStyle = '#6f8493';
- ctx.font = '11px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
- const steps = 5;
- for (let i = 0; i <= steps; i++) {
- const val = minY + ((maxY - minY) * i) / steps;
- const y = yFor(val);
- ctx.beginPath();
- ctx.moveTo(padL, y);
- ctx.lineTo(w - padR, y);
- ctx.stroke();
- ctx.fillText(`${Math.round(val)}°`, 6, y + 4);
- }
- if (chartRing.length === 0) {
- ctx.fillStyle = '#8aa0ad';
- ctx.font = '13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
- ctx.fillText(`当前工位 ${activeStationId} 连接高温罩后自动绘制实时温度曲线...`, padL + 16, padT + plotH / 2);
- return;
- }
- const startT = fmtTimeShort(chartRing[0].t);
- const endT = fmtTimeShort(chartRing[chartRing.length - 1].t);
- ctx.fillStyle = '#6f8493';
- ctx.fillText(startT, padL, h - 7);
- ctx.fillText(endT, w - padR - 58, h - 7);
- for (const s of SERIES_META) {
- if (!enabledSeries.has(s.key)) continue;
- ctx.save();
- ctx.strokeStyle = s.color;
- ctx.lineWidth = s.dashed ? 1.5 : 2;
- if (s.dashed) ctx.setLineDash([6, 4]);
- ctx.beginPath();
- let started = false;
- for (let i = 0; i < chartRing.length; i++) {
- const v = chartRing[i][s.key];
- if (typeof v !== 'number') {
- started = false;
- continue;
- }
- const x = xFor(i);
- const y = yFor(v);
- if (!started) { ctx.moveTo(x, y); started = true; }
- else ctx.lineTo(x, y);
- }
- ctx.stroke();
- ctx.restore();
- }
- const tip = el('th-chart-tooltip');
- if (hoverRatio != null && chartRing.length > 0) {
- const idx = Math.max(0, Math.min(chartRing.length - 1, Math.round(hoverRatio * (chartRing.length - 1))));
- const pt = chartRing[idx];
- const hx = xFor(idx);
- ctx.save();
- ctx.strokeStyle = 'rgba(36, 50, 71, 0.35)';
- ctx.setLineDash([3, 3]);
- ctx.beginPath();
- ctx.moveTo(hx, padT);
- ctx.lineTo(hx, padT + plotH);
- ctx.stroke();
- ctx.restore();
- if (tip) {
- tip.classList.remove('hidden');
- tip.textContent = `${activeStationId} ${fmtTimeShort(pt.t)} · 目标:${pt.target ?? '--'}℃ · BMC均/高:${pt.bmc_avg ?? '--'}/${pt.bmc_max ?? '--'}℃ · CT均/高:${pt.ct_avg ?? '--'}/${pt.ct_max ?? '--'}℃`;
- }
- } else if (tip) {
- tip.classList.add('hidden');
- }
- }
- const canvasEl = el('th-chart-canvas');
- canvasEl.addEventListener('mousemove', ev => {
- const rect = canvasEl.getBoundingClientRect();
- const plotW = Math.max(1, rect.width - 60);
- hoverRatio = Math.max(0, Math.min(1, (ev.clientX - rect.left - 44) / plotW));
- scheduleChartDraw();
- });
- canvasEl.addEventListener('mouseleave', () => {
- hoverRatio = null;
- scheduleChartDraw();
- });
- // Button bindings
- el('btn-th-scan-ports').addEventListener('click', async () => {
- await scanPorts(false);
- lastMapSig = '';
- if (lastSnapshot?.stations) renderBmcMappingTable(lastSnapshot.stations);
- });
- if (el('btn-th-map-scan')) {
- el('btn-th-map-scan').addEventListener('click', async () => {
- await scanPorts(false);
- lastMapSig = '';
- if (lastSnapshot?.stations) renderBmcMappingTable(lastSnapshot.stations);
- setMapStatus(`串口扫描完成:共发现 ${scannedPorts.length} 个 USB 串口`);
- });
- }
- if (el('btn-th-map-save-all')) {
- el('btn-th-map-save-all').addEventListener('click', async () => {
- const tbody = el('th-bmc-map-tbody');
- if (!tbody) return;
- const mappings = [];
- tbody.querySelectorAll('tr[data-map-row]').forEach(tr => {
- const sid = tr.dataset.mapRow;
- mappings.push({
- station_id: sid,
- bmc_host: tr.querySelector('[data-map-field="bmc_host"]')?.value.trim() || '',
- mode: tr.querySelector('[data-map-field="mode"]')?.value || 'serial',
- serial_path: tr.querySelector('[data-map-field="serial_path"]')?.value.trim() || '',
- usb_serial: tr.querySelector('[data-map-field="usb_serial"]')?.value.trim() || '',
- tcp_host: tr.querySelector('[data-map-field="tcp_host"]')?.value.trim() || '127.0.0.1',
- tcp_port: Number(tr.querySelector('[data-map-field="tcp_port"]')?.value) || 4002,
- });
- });
- try {
- await window.stlTransport.call('ThermalAction', { action: 'save_mappings', station_id: activeStationId, mappings }, 10000);
- mapDirty = false;
- lastMapSig = '';
- syncedStationId = '';
- setMapStatus(`已保存全部 ${mappings.length} 组 BMC 机位 ↔ 高温罩串口映射`);
- await pollConsole(true);
- } catch (err) {
- setMapStatus(`保存映射失败: ${err.message}`, true);
- }
- });
- }
- if (el('btn-th-save-binding')) {
- el('btn-th-save-binding').addEventListener('click', async () => {
- const mode = el('th-conn-mode').value;
- const payload = {
- action: 'save_mappings',
- station_id: activeStationId || 'S1',
- bmc_host: el('th-bmc-host')?.value.trim() || '',
- mode,
- serial_path: el('th-serial-path').value.trim(),
- usb_serial: el('th-usb-serial').value.trim(),
- serial_baud: 115200,
- tcp_host: el('th-tcp-host').value.trim() || '127.0.0.1',
- tcp_port: Number(el('th-tcp-port').value) || 4002,
- auto_reconnect: el('th-auto-reconnect').checked,
- };
- try {
- await window.stlTransport.call('ThermalAction', payload, 10000);
- mapDirty = false;
- lastMapSig = '';
- setStatus(`已保存工位 ${activeStationId} (BMC ${payload.bmc_host || '未指定'}) ↔ 高温罩串口绑定`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`保存绑定失败: ${err.message}`, true);
- }
- });
- }
- el('btn-th-connect').addEventListener('click', async () => {
- const mode = el('th-conn-mode').value;
- const payload = {
- mode,
- bmc_host: el('th-bmc-host')?.value.trim() || '',
- serial_path: el('th-serial-path').value.trim(),
- usb_serial: el('th-usb-serial').value.trim(),
- serial_baud: 115200,
- tcp_host: el('th-tcp-host').value.trim() || '127.0.0.1',
- tcp_port: Number(el('th-tcp-port').value) || 4002,
- auto_reconnect: el('th-auto-reconnect').checked,
- };
- try {
- await callThermalAction('connect', payload);
- mapDirty = false;
- lastMapSig = '';
- setStatus(`工位 ${activeStationId} (BMC ${payload.bmc_host || '未指定'}) 高温罩已连接 (${mode === 'serial' ? (payload.serial_path || payload.usb_serial) : mode})`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`连接高温罩失败: ${err.message}`, true);
- }
- });
- el('btn-th-disconnect').addEventListener('click', async () => {
- try {
- await callThermalAction('disconnect');
- setStatus(`已断开工位 ${activeStationId} 高温罩连接(不影响内存测试)`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`断开失败: ${err.message}`, true);
- }
- });
- el('th-auto-reconnect').addEventListener('change', async () => {
- try {
- await callThermalAction('set_prefs', { auto_reconnect: el('th-auto-reconnect').checked });
- } catch {}
- });
- el('btn-th-zero-probe').addEventListener('click', async () => {
- try {
- const res = await callThermalAction('zero_power_probe');
- setStatus(`零功率自检完成 (0W) · PID应答: ${res?.text || 'OK'}`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`零功率自检失败: ${err.message}`, true);
- }
- });
- el('btn-th-estop').addEventListener('click', async () => {
- const ok = window.stlUi ? await window.stlUi.confirm('高温罩一键紧急全停', `确认立即停止工位 ${activeStationId} 的全部加热与控温输出(35 路归零 + 0x05 + 0x0A 锁死加热块)?`, '立即紧急全停', true) : true;
- if (!ok) return;
- try {
- await callThermalAction('emergency_stop');
- setStatus(`工位 ${activeStationId} 已执行紧急全停 (35路归零 + 0x05 + 0x0A)`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`紧急全停异常: ${err.message}`, true);
- }
- });
- el('btn-th-save-safety').addEventListener('click', async () => {
- const leaseSec = Number(el('th-safety-lease').value) || 0;
- const cutoff = Number(el('th-overtemp-cutoff').value) || 95;
- try {
- await callThermalAction('configure_safety', { lease_sec: leaseSec, overtemp_cutoff_c: cutoff });
- setStatus(`安全护栏已更新:看门狗=${leaseSec > 0 ? leaseSec + '秒' : '不限时'},超温熔断=${cutoff}℃`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`保存安全护栏失败: ${err.message}`, true);
- }
- });
- el('btn-th-renew-lease').addEventListener('click', async () => {
- try {
- const res = await callThermalAction('renew_lease');
- setStatus(`看门狗已续期重置 (${res?.lease_remaining_sec || 0} 秒)`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`续期失败: ${err.message}`, true);
- }
- });
- document.querySelectorAll('.th-preset-btn').forEach(btn => {
- btn.addEventListener('click', () => {
- el('th-target-input').value = btn.dataset.temp;
- });
- });
- el('th-target-input').addEventListener('keydown', ev => {
- if (ev.key === 'Enter') {
- ev.preventDefault();
- el('btn-th-set-temp').click();
- }
- });
- el('btn-th-set-temp').addEventListener('click', async () => {
- const targetC = Math.round(Number(el('th-target-input').value));
- if (!Number.isFinite(targetC) || targetC < 0 || targetC > 254) {
- setStatus('目标温度必须为 0 ~ 254 之间的整数 ℃', true);
- return;
- }
- try {
- await callThermalAction('set_temp', {
- target_c: targetC,
- auto_pre_stop: el('th-chk-auto-prestop').checked,
- direct_pid: el('th-chk-direct-pid').checked,
- });
- setStatus(`工位 ${activeStationId} 已下发目标温度 ${targetC}℃ (0x01)`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`设温失败: ${err.message}`, true);
- }
- });
- el('btn-th-skip-preheat').addEventListener('click', async () => {
- try {
- await callThermalAction('skip_preheat');
- setStatus('已下发跳过预加热进入 PID 指令 (0x06)');
- await pollConsole(true);
- } catch (err) {
- setStatus(`跳过预加热失败: ${err.message}`, true);
- }
- });
- el('btn-th-start-pid').addEventListener('click', async () => {
- try {
- await callThermalAction('start_pid');
- setStatus('已下发直接开启 PID 闭环指令 (0x07)');
- await pollConsole(true);
- } catch (err) {
- setStatus(`开启 PID 失败: ${err.message}`, true);
- }
- });
- el('btn-th-stop-preheat').addEventListener('click', async () => {
- try {
- await callThermalAction('stop_preheat');
- setStatus('已停止预加热与 PID 闭环,输出已清零 (0x05)');
- await pollConsole(true);
- } catch (err) {
- setStatus(`停止控温失败: ${err.message}`, true);
- }
- });
- el('btn-th-finish-purge').addEventListener('click', async () => {
- try {
- await callThermalAction('finish_control', { cooling_purge: true });
- setStatus('已结束控温并开启 8 路风扇 100% 吹扫散热 (0x08 00)');
- await pollConsole(true);
- } catch (err) {
- setStatus(`控温结束失败: ${err.message}`, true);
- }
- });
- el('btn-th-finish-keep').addEventListener('click', async () => {
- try {
- await callThermalAction('finish_control', { cooling_purge: false });
- setStatus('已结束控温且不吹扫 (0x08 01)');
- await pollConsole(true);
- } catch (err) {
- setStatus(`操作失败: ${err.message}`, true);
- }
- });
- el('btn-th-stop-heaters').addEventListener('click', async () => {
- try {
- await callThermalAction('stop_heaters');
- setStatus('已停并锁死全部 24 路加热块 (0x0A)');
- await pollConsole(true);
- } catch (err) {
- setStatus(`停加热块失败: ${err.message}`, true);
- }
- });
- el('btn-th-stop-fans').addEventListener('click', async () => {
- try {
- await callThermalAction('stop_fans');
- setStatus('已停并锁死全部 8 路风扇 (0x0B)');
- await pollConsole(true);
- } catch (err) {
- setStatus(`停风扇失败: ${err.message}`, true);
- }
- });
- el('btn-th-export-csv').addEventListener('click', () => {
- const sid = activeStationId || 'S1';
- const url = `/api/thermal/export.csv?station_id=${encodeURIComponent(sid)}`;
- const a = document.createElement('a');
- a.href = url;
- a.download = `thermal_${sid}.csv`;
- a.click();
- setStatus(`已触发工位 ${sid} 模板格式 CSV 下载(34 列 UTF-8 BOM)`);
- });
- el('btn-th-clear-session').addEventListener('click', async () => {
- try {
- await callThermalAction('clear_session_samples');
- chartByStation.set(activeStationId, []);
- seqByStation.set(activeStationId, 0);
- setStatus(`已清空工位 ${activeStationId} 当前会话曲线与导出缓存`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`清空失败: ${err.message}`, true);
- }
- });
- el('btn-th-rec-start').addEventListener('click', async () => {
- try {
- const res = await callThermalAction('start_record', {
- tag: el('th-rec-tag').value.trim(),
- interval_ms: Number(el('th-rec-interval').value) || 1000,
- auto_record_on_heat: el('th-rec-auto').checked,
- });
- setStatus(`开始录制模板格式 CSV: ${res?.csv_filename || ''}`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`开始录制失败: ${err.message}`, true);
- }
- });
- el('btn-th-rec-stop').addEventListener('click', async () => {
- try {
- const res = await callThermalAction('stop_record');
- setStatus(`已停止本地落盘: ${res?.csv_filename || ''} (共 ${res?.rows_written || 0} 行)`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`停止录制失败: ${err.message}`, true);
- }
- });
- el('th-rec-auto').addEventListener('change', async () => {
- try {
- await callThermalAction('set_prefs', {
- auto_record_on_heat: el('th-rec-auto').checked,
- record_interval_ms: Number(el('th-rec-interval').value) || 1000,
- });
- } catch {}
- });
- el('th-rec-interval').addEventListener('change', async () => {
- try {
- await callThermalAction('set_prefs', {
- auto_record_on_heat: el('th-rec-auto').checked,
- record_interval_ms: Number(el('th-rec-interval').value) || 1000,
- });
- } catch {}
- });
- el('btn-th-add-mark').addEventListener('click', async () => {
- const note = el('th-mark-note').value.trim();
- if (!note) return;
- try {
- await callThermalAction('add_mark', { note });
- el('th-mark-note').value = '';
- setStatus(`已记录事件标记: ${note}`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`标记写入失败: ${err.message}`, true);
- }
- });
- el('btn-th-pid-read').addEventListener('click', async () => {
- try {
- const res = await callThermalAction('pid_calibrate', { expr: '' });
- setStatus(`当前 PID: ${res?.text || '--'}`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`读取 PID 失败: ${err.message}`, true);
- }
- });
- el('btn-th-pid-write').addEventListener('click', async () => {
- const expr = el('th-pid-expr').value.trim();
- if (!expr) {
- setStatus('请输入 PID 参数表达式(例如 P2.6I0.12D0.04)', true);
- return;
- }
- try {
- const res = await callThermalAction('pid_calibrate', { expr });
- setStatus(`PID 标定成功: ${res?.text || 'OK'}`);
- await pollConsole(true);
- } catch (err) {
- setStatus(`PID 标定失败: ${err.message}`, true);
- }
- });
- el('btn-th-man-apply').addEventListener('click', async () => {
- try {
- await callThermalAction('manual_duty', {
- ptc_all: Number(el('th-man-ptc').value) || 0,
- fan_front_all: Number(el('th-man-fan-in').value) || 0,
- fan_rear_all: Number(el('th-man-fan-out').value) || 0,
- ssr_all: Number(el('th-man-ssr').value) || 0,
- keepalive: el('th-man-keepalive').checked,
- });
- setStatus('已下发 35 路手动占空比测试帧 (0x46)');
- await pollConsole(true);
- } catch (err) {
- setStatus(`手动出力失败: ${err.message}`, true);
- }
- });
- el('btn-th-man-zero').addEventListener('click', async () => {
- el('th-man-ptc').value = '0';
- el('th-man-fan-in').value = '0';
- el('th-man-fan-out').value = '0';
- el('th-man-ssr').value = '0';
- el('th-man-keepalive').checked = false;
- try {
- await callThermalAction('manual_duty', { ptc_all: 0, fan_front_all: 0, fan_rear_all: 0, ssr_all: 0, keepalive: false });
- setStatus('已下发 35 路全部归零 (0x46)');
- await pollConsole(true);
- } catch (err) {
- setStatus(`归零失败: ${err.message}`, true);
- }
- });
- async function pollConsole(forceIncludeDebug = false) {
- if (pollInFlight || document.hidden) return;
- pollInFlight = true;
- try {
- const navSid = el('nav-station')?.value;
- if (document.body.dataset.currentPage !== 'thermal' && navSid && navSid !== activeStationId) {
- activeStationId = navSid;
- syncedStationId = '';
- }
- const sid = activeStationId || navSid || 'S1';
- const sinceSeq = seqByStation.get(sid) || 0;
- const onThermalPage = document.body.dataset.currentPage === 'thermal';
- const includeFrames = Boolean(forceIncludeDebug || (onThermalPage && el('th-debug-drawer')?.open));
- const snap = await window.stlTransport.call('GetThermalConsole', {
- station_id: sid,
- since_seq: sinceSeq,
- include_frames: includeFrames,
- }, 8000);
- if (snap) renderSnapshot(snap);
- } catch {
- // Strictly isolated: thermal transport errors never affect memory testing UI
- } finally {
- pollInFlight = false;
- }
- }
- function resetPollTimer() {
- if (pollTimer) clearInterval(pollTimer);
- const cur = document.body.dataset.currentPage;
- const ms = cur === 'thermal' ? 1000 : cur === 'connections' ? 1500 : 3500;
- pollTimer = setInterval(() => pollConsole(false), ms);
- }
- window.addEventListener('stl:station-select', ev => {
- const nextSid = ev.detail?.stationId;
- if (nextSid && !ev.detail?.fromThermal) {
- selectStationLocal(nextSid, false);
- }
- });
- window.addEventListener('stl:page-change', ev => {
- resetPollTimer();
- const pg = ev.detail?.page;
- if (pg === 'thermal' || pg === 'connections') {
- const navSid = el('nav-station')?.value;
- if (navSid && navSid !== activeStationId) {
- activeStationId = navSid;
- syncedStationId = '';
- }
- void scanPorts(true).then(() => {
- if (lastSnapshot?.stations) renderBmcMappingTable(lastSnapshot.stations);
- });
- void pollConsole(false);
- if (pg === 'thermal') scheduleChartDraw();
- }
- });
- document.addEventListener('visibilitychange', () => {
- if (!document.hidden) void pollConsole(false);
- });
- el('th-debug-drawer').addEventListener('toggle', () => {
- if (el('th-debug-drawer').open) void pollConsole(true);
- });
- resetPollTimer();
- setTimeout(() => {
- void scanPorts(true);
- void pollConsole(false);
- }, 350);
- })();
|