// store-and-ui.js — Unified State Store, Production/Engineering Mode Switcher, // Confirmation Modal, Password Change Modal & Single-DIMM Temperature Curve Modal (() => { const $ = id => document.getElementById(id); const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const listeners = new Set(); const state = { uiMode: localStorage.getItem('stl_ui_mode') === 'production' ? 'production' : 'engineering', page: 'overview', stationId: 'S1', connected: false, sysInfo: null, stations: [], controlByStation: {}, diagnosticsByStation: {}, alarmsByStation: {}, traceConfig: null, hwInfo: null, }; function emit(path, prev, next, trigger = 'ui') { for (const fn of listeners) { try { fn({ path, prev, next, trigger, ts_ms: Date.now() }); } catch (e) { console.error('[stlStore]', e); } } } window.stlStore = { state, get(key) { return state[key]; }, set(key, value, trigger = 'ui') { const prev = state[key]; state[key] = value; emit(key, prev, value, trigger); }, setStationMap(mapKey, sid, value, trigger = 'poll') { if (!state[mapKey] || typeof state[mapKey] !== 'object') state[mapKey] = {}; const prev = state[mapKey][sid]; state[mapKey][sid] = value; emit(`${mapKey}.${sid}`, prev, value, trigger); }, subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); }, }; function formatElapsed(ms) { const n = Math.max(0, Math.floor(Number(ms || 0) / 1000)); const h = Math.floor(n / 3600), m = Math.floor((n % 3600) / 60), s = n % 60; return [h, m, s].map(v => String(v).padStart(2, '0')).join(':'); } function formatClock(ms) { if (!Number(ms)) return '--:--:--'; const d = new Date(Number(ms)); return [d.getHours(), d.getMinutes(), d.getSeconds()].map(v => String(v).padStart(2, '0')).join(':'); } // ---- Universal Confirmation Modal ---- let confirmResolve = null; function closeConfirm(result) { const modal = $('stl-confirm-modal'); if (modal) modal.classList.add('hidden'); if (confirmResolve) { const fn = confirmResolve; confirmResolve = null; fn(result); } } function confirmDialog(title, message, confirmLabel = '确认执行', isDanger = true) { const modal = $('stl-confirm-modal'); if (!modal) return Promise.resolve(true); if (confirmResolve) closeConfirm(false); $('stl-confirm-title').textContent = title || '操作确认'; $('stl-confirm-body').textContent = message || ''; const okBtn = $('stl-confirm-ok'); okBtn.textContent = confirmLabel || '确认执行'; okBtn.className = isDanger ? 'btn btn-danger btn-sm' : 'btn btn-primary btn-sm'; modal.classList.remove('hidden'); okBtn.focus(); return new Promise(resolve => { confirmResolve = resolve; }); } // ---- Password Change Modal ---- function openPasswordModal() { const modal = $('stl-password-modal'); if (!modal) return; $('pw-current').value = ''; $('pw-new').value = ''; $('pw-confirm').value = ''; $('pw-modal-msg').textContent = ''; $('pw-modal-msg').className = 'field-note'; modal.classList.remove('hidden'); $('pw-current').focus(); } function closePasswordModal() { $('stl-password-modal')?.classList.add('hidden'); } // ---- Single-DIMM Temperature Curve Modal ---- let curveState = { stationId: 'S1', slot: 0, label: 'CPU0 CH A' }; let curveRefreshTimer = null; function drawDimmCurveCanvas(canvas, points) { if (!canvas) return; const dpr = window.devicePixelRatio || 1; const rect = canvas.getBoundingClientRect(); const w = Math.max(320, Math.round(rect.width || 720)); const h = Math.max(200, Math.round(rect.height || 260)); canvas.width = w * dpr; canvas.height = h * dpr; const ctx = canvas.getContext('2d'); ctx.scale(dpr, dpr); ctx.clearRect(0, 0, w, h); ctx.fillStyle = '#fbfdfe'; ctx.fillRect(0, 0, w, h); const pad = { l: 48, r: 20, t: 18, b: 30 }; const pw = w - pad.l - pad.r; const ph = h - pad.t - pad.b; if (!points.length) { ctx.fillStyle = '#64748b'; ctx.font = '13px sans-serif'; ctx.textAlign = 'center'; ctx.fillText('当前尚未采集到该槽位温度数据(接入高温罩 MCU 0x82 或 BMC SDR 后自动记录)', w / 2, h / 2); return; } const temps = points.map(p => Number(p.temp_c)).filter(Number.isFinite); const minT = Math.max(0, Math.floor((Math.min(...temps) - 5) / 5) * 5); const maxT = Math.min(130, Math.ceil((Math.max(...temps, minT + 10) + 5) / 5) * 5); const spanT = Math.max(10, maxT - minT); // Grid lines ctx.strokeStyle = '#e2e8f0'; ctx.lineWidth = 1; ctx.fillStyle = '#64748b'; ctx.font = '11px monospace'; ctx.textAlign = 'right'; const yTicks = 5; for (let i = 0; i <= yTicks; i++) { const y = pad.t + (ph * i) / yTicks; const val = maxT - (spanT * i) / yTicks; ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + pw, y); ctx.stroke(); ctx.fillText(`${val.toFixed(0)}°C`, pad.l - 6, y + 4); } // Time labels const t0 = Number(points[0].ts_ms || 0); const t1 = Number(points[points.length - 1].ts_ms || t0); const spanMs = Math.max(1000, t1 - t0); ctx.textAlign = 'center'; for (let i = 0; i <= 4; i++) { const x = pad.l + (pw * i) / 4; const ts = t0 + (spanMs * i) / 4; ctx.fillText(formatClock(ts), x, h - 8); } // Line ctx.strokeStyle = '#0d8b80'; ctx.lineWidth = 2; ctx.beginPath(); points.forEach((p, idx) => { const x = pad.l + (points.length === 1 ? pw / 2 : ((Number(p.ts_ms) - t0) / spanMs) * pw); const y = pad.t + ((maxT - Number(p.temp_c)) / spanT) * ph; if (idx === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); }); ctx.stroke(); // Last point highlight const last = points[points.length - 1]; const lx = pad.l + (points.length === 1 ? pw / 2 : ((Number(last.ts_ms) - t0) / spanMs) * pw); const ly = pad.t + ((maxT - Number(last.temp_c)) / spanT) * ph; ctx.fillStyle = '#c5424b'; ctx.beginPath(); ctx.arc(lx, ly, 4, 0, Math.PI * 2); ctx.fill(); } async function refreshDimmCurve() { const { stationId, slot, label } = curveState; $('dimm-curve-title').textContent = `${stationId} · 槽位 ${label} (BMC${slot}) 实时温度曲线`; $('dimm-curve-stats').textContent = '正在读取温度历史曲线...'; try { const res = await fetch(`/api/stations/${encodeURIComponent(stationId)}/dimm-curve?slot=${slot}`, { credentials: 'same-origin', cache: 'no-store' }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const data = await res.json(); const pts = Array.isArray(data.points) ? data.points : []; if (pts.length) { const vals = pts.map(p => Number(p.temp_c)).filter(Number.isFinite); const minV = Math.min(...vals), maxV = Math.max(...vals); const avgV = vals.reduce((a, b) => a + b, 0) / vals.length; const curV = vals[vals.length - 1]; const srcTag = data.source === 'bmc_sdr_fallback' ? ' · 来源: BMC SDR' : ' · 来源: MCU 0x82'; $('dimm-curve-stats').textContent = `采样点 ${pts.length} · 当前 ${curV.toFixed(1)}°C · 最低 ${minV.toFixed(1)}°C · 最高 ${maxV.toFixed(1)}°C · 均值 ${avgV.toFixed(1)}°C${srcTag}`; } else { $('dimm-curve-stats').textContent = '暂无该槽位历史温度采样点(连接高温罩或启用 BMC 温度轮询后自动记录)'; } drawDimmCurveCanvas($('dimm-curve-canvas'), pts); } catch (err) { $('dimm-curve-stats').textContent = `读取温度曲线失败:${err.message}`; drawDimmCurveCanvas($('dimm-curve-canvas'), []); } } function openDimmCurveModal(stationId, slotIdx, slotLabel) { const modal = $('stl-dimm-curve-modal'); if (!modal) return; const cpu = slotIdx < 12 ? 0 : 1; const ch = String.fromCharCode(65 + (slotIdx % 12)); curveState = { stationId, slot: slotIdx, label: slotLabel || `CPU${cpu} CH ${ch}` }; modal.classList.remove('hidden'); void refreshDimmCurve(); if (curveRefreshTimer) clearInterval(curveRefreshTimer); curveRefreshTimer = setInterval(() => { if (modal.classList.contains('hidden')) { clearInterval(curveRefreshTimer); curveRefreshTimer = null; return; } void refreshDimmCurve(); }, 2000); } function closeDimmCurveModal() { if (curveRefreshTimer) { clearInterval(curveRefreshTimer); curveRefreshTimer = null; } $('stl-dimm-curve-modal')?.classList.add('hidden'); } // ---- Production / Engineering View Mode Switcher (Option B) ---- function applyUiMode(mode, persist = true) { const next = mode === 'production' ? 'production' : 'engineering'; if (persist) localStorage.setItem('stl_ui_mode', next); document.body.dataset.uiMode = next; window.stlStore.set('uiMode', next, 'mode_switch'); const prodBtn = $('btn-mode-production'); const engBtn = $('btn-mode-engineering'); if (prodBtn) prodBtn.classList.toggle('active', next === 'production'); if (engBtn) engBtn.classList.toggle('active', next === 'engineering'); const prodPanel = $('production-dashboard'); if (prodPanel) prodPanel.hidden = next !== 'production'; window.dispatchEvent(new CustomEvent('stl:ui-mode-change', { detail: { mode: next } })); } // ---- Production Dashboard Renderer (Unlimited Dynamic Stations) ---- let prodCallbacks = {}; const prodTargetDraft = new Map(); const prodProfileDraft = new Map(); function renderProductionDashboard(stations = []) { const grid = $('prod-stations-grid'); if (!grid) return; const summaryEl = $('prod-summary-bar'); const total = stations.length; const running = stations.filter(s => s.task_status === 'running').length; const failed = stations.filter(s => s.task_status === 'failed' || s.verdict === 'fail' || s.awaiting_dimm_replacement || s.fault_code).length; const passed = stations.filter(s => s.task_status === 'completed' && s.verdict === 'pass' && !s.fault_code).length; if (summaryEl) { summaryEl.innerHTML = `总工位 ${total}` + `测试中 ${running}` + `PASS ${passed}` + `异常 / FAIL ${failed}`; } const activeEl = document.activeElement; if (activeEl && grid.contains(activeEl) && (activeEl.matches('[data-prod-target]') || activeEl.matches('[data-prod-profile]'))) { return; } grid.innerHTML = stations.map(s => { const sid = s.station_id; const ctrl = window.stlFirmware?.snapshot?.(sid) || {}; const profiles = Array.isArray(ctrl.saved_profiles) ? ctrl.saved_profiles : []; const thPolicy = ctrl.thermal_policy || {}; const defaultTarget = prodTargetDraft.has(sid) ? prodTargetDraft.get(sid) : (s.thermal_target_c ?? thPolicy.target_temp_c ?? 70); const chamberTxt = typeof s.chamber_temp_c === 'number' && Number.isFinite(s.chamber_temp_c) ? `${s.chamber_temp_c.toFixed(1)}°C` : '--.-°C'; const hoodOnline = !!s.thermal_online; const isRunning = s.task_status === 'running'; const isFail = !!(s.awaiting_dimm_replacement || s.task_status === 'failed' || s.verdict === 'fail' || s.fault_code); const isPass = s.task_status === 'completed' && s.verdict === 'pass' && !isFail; const statusCls = isFail ? 'error' : isPass ? 'connected' : isRunning ? 'active' : ''; const statusTxt = s.fault_code ? `异常: ${s.fault_code}` : s.awaiting_dimm_replacement ? 'FAIL · 待换条' : isFail ? 'FAIL' : isPass ? 'PASS' : isRunning ? `运行中 · ${s.phase || 'running'}` : (s.console_online || s.bmc_state === 'online') ? '就绪待测' : '离线'; const dimms = Array.isArray(s.dimm_states) && s.dimm_states.length === 24 ? s.dimm_states : Array.from({ length: 24 }, (_, idx) => ({ slot: idx, state: 'idle', present: false, temp_c: null })); const renderRow = (startIdx, title) => `
${title}${dimms.slice(startIdx, startIdx + 12).map(d => { const ch = String.fromCharCode(65 + (d.slot % 12)); const st = (d.state || 'idle').toLowerCase(); const tVal = typeof d.temp_c === 'number' && Number.isFinite(d.temp_c) ? `${Math.round(d.temp_c)}°` : ''; return ``; }).join('')}
`; const alarmCnt = Number(s.alarm_count || 0); const chosenProf = prodProfileDraft.get(sid) || '__current__'; const profOptions = `` + profiles.map(p => { const val = p.profile_id || p.name; return ``; }).join(''); return `

${esc(sid)} · ${esc(s.name || sid)}

串口 ${s.console_online ? '在线' : '离线'} BMC ${s.bmc_state === 'online' ? '在线' : '离线'} 高温罩 ${hoodOnline ? `在线 · ${esc(s.thermal_mode || 'idle')}` : '未连接'}
${esc(statusTxt)}
腔温 ${esc(chamberTxt)} 用时 ${esc(formatElapsed(s.elapsed_ms || 0))}
${renderRow(0, 'C0')} ${renderRow(12, 'C1')}
异常(${alarmCnt}) · 导出.xlsx
`; }).join('') || '

当前无已配置工位,请切换至工程视图添加工位。

'; grid.querySelectorAll('[data-prod-target]').forEach(inp => { inp.addEventListener('change', () => { const v = Math.max(0, Math.min(254, Number(inp.value || 0))); prodTargetDraft.set(inp.dataset.prodTarget, v); }); }); grid.querySelectorAll('[data-prod-profile]').forEach(sel => { sel.addEventListener('change', () => { prodProfileDraft.set(sel.dataset.prodProfile, sel.value); }); }); grid.querySelectorAll('[data-prod-curve]').forEach(btn => { btn.addEventListener('click', () => { const [sid, slotStr] = btn.dataset.prodCurve.split(':'); const idx = Number(slotStr); const cpu = idx < 12 ? 0 : 1; const ch = String.fromCharCode(65 + (idx % 12)); openDimmCurveModal(sid, idx, `CPU${cpu} CH ${ch}`); }); }); grid.querySelectorAll('[data-prod-action]').forEach(btn => { btn.addEventListener('click', async () => { const act = btn.dataset.prodAction; const sid = btn.dataset.sid; if (act === 'detail') { applyUiMode('engineering', true); prodCallbacks.onSelectStation?.(sid); return; } if (act === 'start') { const targetInp = grid.querySelector(`[data-prod-target="${CSS.escape(sid)}"]`); const profSel = grid.querySelector(`[data-prod-profile="${CSS.escape(sid)}"]`); const targetTemp = Math.max(0, Math.min(254, Number(targetInp?.value ?? 70))); const profId = profSel?.value || '__current__'; btn.disabled = true; try { await prodCallbacks.onStartStation?.(sid, { targetTemp, profileId: profId }); } finally { btn.disabled = false; } } else if (act === 'stop') { const ok = await confirmDialog(`停止工位 ${sid}`, `确认停止工位 ${sid} 当前测试队列并自动联动高温罩降温吗?`, '确认停止', true); if (!ok) return; btn.disabled = true; try { await prodCallbacks.onStopStation?.(sid); } finally { btn.disabled = false; } } }); }); } function initUi(callbacks = {}) { prodCallbacks = callbacks; $('btn-mode-production')?.addEventListener('click', () => applyUiMode('production', true)); $('btn-mode-engineering')?.addEventListener('click', () => applyUiMode('engineering', true)); $('btn-change-password')?.addEventListener('click', openPasswordModal); // Confirm modal events $('stl-confirm-ok')?.addEventListener('click', () => closeConfirm(true)); $('stl-confirm-cancel')?.addEventListener('click', () => closeConfirm(false)); $('stl-confirm-modal')?.addEventListener('click', e => { if (e.target.id === 'stl-confirm-modal') closeConfirm(false); }); // Password modal events $('pw-modal-cancel')?.addEventListener('click', closePasswordModal); $('stl-password-modal')?.addEventListener('click', e => { if (e.target.id === 'stl-password-modal') closePasswordModal(); }); $('pw-modal-form')?.addEventListener('submit', async e => { e.preventDefault(); const cur = $('pw-current').value; const next = $('pw-new').value; const conf = $('pw-confirm').value; const msg = $('pw-modal-msg'); if (next.length < 6) { msg.textContent = '新密码长度不能少于 6 位'; msg.className = 'field-note error-text'; return; } if (next !== conf) { msg.textContent = '两次输入的新密码不一致'; msg.className = 'field-note error-text'; return; } const btn = $('pw-modal-submit'); btn.disabled = true; msg.textContent = '正在更新密码...'; msg.className = 'field-note'; try { const res = await fetch('/api/auth/change-password', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ current_password: cur, new_password: next }), }); const data = await res.json().catch(() => ({})); if (!res.ok || !data.ok) { throw new Error(data?.error?.message || `修改失败 (HTTP ${res.status})`); } msg.textContent = '密码已更新并持久化,新会话已自动生效。'; msg.className = 'field-note ok-text'; setTimeout(closePasswordModal, 900); } catch (err) { msg.textContent = err.message; msg.className = 'field-note error-text'; } finally { btn.disabled = false; } }); // DIMM curve modal events $('dimm-curve-close')?.addEventListener('click', closeDimmCurveModal); $('dimm-curve-refresh')?.addEventListener('click', () => void refreshDimmCurve()); $('stl-dimm-curve-modal')?.addEventListener('click', e => { if (e.target.id === 'stl-dimm-curve-modal') closeDimmCurveModal(); }); // Console expand toggle $('btn-console-expand')?.addEventListener('click', () => { const split = document.querySelector('.workspace-split'); if (!split) return; const expanded = split.classList.toggle('console-expanded'); $('btn-console-expand').textContent = expanded ? '恢复分栏' : '放大终端'; }); // Global Escape closes open modals document.addEventListener('keydown', e => { if (e.key !== 'Escape') return; if (!$('stl-confirm-modal')?.classList.contains('hidden')) closeConfirm(false); else if (!$('stl-password-modal')?.classList.contains('hidden')) closePasswordModal(); else if (!$('stl-dimm-curve-modal')?.classList.contains('hidden')) closeDimmCurveModal(); }); applyUiMode(state.uiMode, false); } window.stlUi = { init: initUi, confirm: confirmDialog, openPasswordModal, openDimmCurveModal, setMode: applyUiMode, getMode: () => state.uiMode, renderProductionDashboard, }; })();