thermal-console.js 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. // thermal-console.js — Independent Per-Station 1-to-1 6400 High-Temperature Hood Console
  2. // Strictly decoupled from memory test execution; Web-only backend-managed closed-loop control.
  3. (() => {
  4. const MAX_POINTS = 720;
  5. const CT_LABELS = ['腔1前', '腔1后', '腔2前', '腔2后', '腔3前', '腔3后', '腔4前', '腔4后'];
  6. const SERIES_META = [
  7. { key: 'target', label: '目标温度', color: '#cf4b52', dashed: true },
  8. { key: 'bmc_avg', label: 'MCU BMC均温', color: '#0d8b80', dashed: false },
  9. { key: 'bmc_max', label: 'MCU BMC最高', color: '#e67e22', dashed: false },
  10. { key: 'ct_avg', label: 'CT腔体均温', color: '#2980b9', dashed: false },
  11. { key: 'ct_max', label: 'CT腔体最高', color: '#8e44ad', dashed: false },
  12. ];
  13. const el = id => document.getElementById(id);
  14. const rootPanel = document.querySelector('.thermal-console-panel');
  15. if (!rootPanel) return;
  16. let activeStationId = el('nav-station')?.value || 'S1';
  17. let syncedStationId = '';
  18. let lastSnapshot = null;
  19. let scannedPorts = [];
  20. let pollInFlight = false;
  21. let pollTimer = null;
  22. let rafPending = false;
  23. let hoverRatio = null;
  24. let lastFilesSig = '';
  25. let lastStationsSig = '';
  26. let lastMapSig = '';
  27. let mapDirty = false;
  28. let lastAsciiSig = '';
  29. let lastFrameSig = '';
  30. const seqByStation = new Map();
  31. const chartByStation = new Map();
  32. const enabledSeries = new Set(['target', 'bmc_avg', 'bmc_max', 'ct_avg', 'ct_max']);
  33. function escapeHtml(v) {
  34. return String(v ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
  35. }
  36. function setTextIfChanged(node, text) {
  37. if (node && node.textContent !== text) node.textContent = text;
  38. }
  39. function setStatus(msg, isError = false) {
  40. const bar = el('th-local-status');
  41. if (bar) {
  42. bar.textContent = msg;
  43. bar.classList.remove('hidden');
  44. bar.classList.toggle('error', Boolean(isError));
  45. }
  46. }
  47. function fmtBytes(b) {
  48. const n = Number(b) || 0;
  49. if (n < 1024) return `${n} B`;
  50. if (n < 1048576) return `${(n / 1024).toFixed(1)} KB`;
  51. return `${(n / 1048576).toFixed(2)} MB`;
  52. }
  53. function fmtTimeShort(ms) {
  54. if (!ms) return '--:--:--';
  55. const d = new Date(ms);
  56. return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
  57. }
  58. function modeLabel(st) {
  59. switch (st) {
  60. case 'disconnected': return '未连接';
  61. case 'reconnecting': return '断线重连中';
  62. case 'offline': return '串口已开 · 待0xF0';
  63. case 'cpld_lost': return 'CPLD采集失联';
  64. case 'preheating': return '预加热升温中';
  65. case 'pid': return 'PID闭环控温';
  66. case 'manual': return '手动出力保持';
  67. case 'cooling_purge': return '风扇余温吹扫';
  68. case 'idle': return '在线待机 (0W)';
  69. default: return st || '未连接';
  70. }
  71. }
  72. function modeBadgeClass(st) {
  73. if (st === 'preheating' || st === 'pid' || st === 'manual') return 'is-active';
  74. if (st === 'idle' || st === 'cooling_purge') return 'is-ok';
  75. if (st === 'reconnecting' || st === 'offline') return 'is-warn';
  76. if (st === 'cpld_lost') return 'is-err';
  77. return '';
  78. }
  79. // Pre-build 8 CT cells (matching 腔1前..腔4后) and 24 BMC cells (matching BMC0..BMC23)
  80. const ctCells = [];
  81. const ctGrid = el('th-ct8-grid');
  82. for (let i = 0; i < 8; i++) {
  83. const d = document.createElement('div');
  84. d.className = 'th-ct-cell';
  85. const sp = document.createElement('span');
  86. sp.textContent = `CT${i + 1} · ${CT_LABELS[i]}`;
  87. const st = document.createElement('strong');
  88. st.textContent = '--';
  89. d.append(sp, st);
  90. ctGrid.appendChild(d);
  91. ctCells.push({ val: st, prev: '' });
  92. }
  93. const slotCells = [];
  94. const bmcGrid = el('th-bmc24-grid');
  95. for (let i = 0; i < 24; i++) {
  96. const cpu = i < 12 ? 0 : 1;
  97. const ch = String.fromCharCode(65 + (i % 12));
  98. const card = document.createElement('div');
  99. card.className = 'th-slot-card';
  100. const top = document.createElement('div');
  101. top.className = 'th-slot-top';
  102. const lbl = document.createElement('span');
  103. lbl.textContent = `BMC${i} · CPU${cpu}_${ch}`;
  104. const diffSpan = document.createElement('span');
  105. diffSpan.textContent = '';
  106. top.append(lbl, diffSpan);
  107. const vals = document.createElement('div');
  108. vals.className = 'th-slot-vals';
  109. const mcuStrong = document.createElement('span');
  110. mcuStrong.className = 'th-slot-mcu';
  111. mcuStrong.textContent = 'MCU: --';
  112. const ipmiSpan = document.createElement('span');
  113. ipmiSpan.className = 'th-slot-ipmi';
  114. ipmiSpan.textContent = '';
  115. vals.append(mcuStrong, ipmiSpan);
  116. card.append(top, vals);
  117. bmcGrid.appendChild(card);
  118. slotCells.push({ card, mcuStrong, ipmiSpan, diffSpan, prevCls: 'th-slot-card', prevMcu: '', prevIpmi: '', prevDiff: '' });
  119. }
  120. // Legend checkboxes
  121. const legendEl = el('th-chart-legend');
  122. for (const s of SERIES_META) {
  123. const lbl = document.createElement('label');
  124. const cb = document.createElement('input');
  125. cb.type = 'checkbox';
  126. cb.checked = true;
  127. cb.addEventListener('change', () => {
  128. if (cb.checked) enabledSeries.add(s.key);
  129. else enabledSeries.delete(s.key);
  130. scheduleChartDraw();
  131. });
  132. const dot = document.createElement('i');
  133. dot.style.background = s.color;
  134. lbl.append(cb, dot, document.createTextNode(s.label));
  135. legendEl.appendChild(lbl);
  136. }
  137. async function callThermalAction(action, extra = {}) {
  138. const params = Object.assign({
  139. action,
  140. station_id: activeStationId || 'S1',
  141. }, extra);
  142. return window.stlTransport.call('ThermalAction', params, 10000);
  143. }
  144. function updateModeVisibility() {
  145. const mode = el('th-conn-mode').value;
  146. el('th-serial-wrap').classList.toggle('hidden', mode !== 'serial');
  147. el('th-sn-wrap').classList.toggle('hidden', mode !== 'serial');
  148. el('th-tcp-wrap').classList.toggle('hidden', mode !== 'tcp');
  149. }
  150. el('th-conn-mode').addEventListener('change', updateModeVisibility);
  151. updateModeVisibility();
  152. function applyPortSelection(val) {
  153. const match = scannedPorts.find(p => p.path === val || p.resolved_path === val || p.by_id === val || p.by_path === val);
  154. if (match) {
  155. el('th-usb-serial').value = match.usb_serial_unique ? (match.usb_serial || '') : '';
  156. }
  157. }
  158. el('th-serial-path').addEventListener('change', () => {
  159. applyPortSelection(el('th-serial-path').value.trim());
  160. });
  161. el('th-serial-select').addEventListener('change', () => {
  162. const val = el('th-serial-select').value;
  163. if (!val) return;
  164. el('th-serial-path').value = val;
  165. applyPortSelection(val);
  166. });
  167. async function scanPorts(silent = false) {
  168. try {
  169. const res = await callThermalAction('scan_ports');
  170. const ports = Array.isArray(res?.ports) ? res.ports : [];
  171. scannedPorts = ports;
  172. const dl = el('th-serial-datalist');
  173. dl.replaceChildren(...ports.map(p => {
  174. const opt = document.createElement('option');
  175. opt.value = p.path;
  176. const notes = [];
  177. if (p.resolved_path && p.resolved_path !== p.path) notes.push(p.resolved_path);
  178. if (p.bound_station) notes.push(`已绑定 ${p.bound_station}`);
  179. if (p.console_conflict) notes.push('BIOS串口占用中');
  180. opt.label = `${p.label || p.path}${notes.length ? ' [' + notes.join(' · ') + ']' : ''}`;
  181. return opt;
  182. }));
  183. const sel = el('th-serial-select');
  184. if (sel) {
  185. const curVal = el('th-serial-path').value.trim();
  186. const defaultOpt = document.createElement('option');
  187. defaultOpt.value = '';
  188. defaultOpt.textContent = ports.length ? `-- 选择已扫描串口 (${ports.length}) --` : '-- 未发现 USB 串口 --';
  189. sel.replaceChildren(defaultOpt, ...ports.map(p => {
  190. const opt = document.createElement('option');
  191. opt.value = p.path;
  192. const notes = [];
  193. if (p.bound_station) notes.push(`已绑:${p.bound_station}`);
  194. if (p.console_conflict) notes.push('BIOS占用');
  195. opt.textContent = `${p.label || p.path}${notes.length ? ' [' + notes.join(' · ') + ']' : ''}`;
  196. return opt;
  197. }));
  198. if (curVal && ports.some(p => p.path === curVal)) sel.value = curVal;
  199. }
  200. if (!silent) {
  201. setStatus(`扫描完成:共发现 ${ports.length} 个 USB 串口设备`);
  202. }
  203. } catch (err) {
  204. if (!silent) setStatus(`扫描串口失败: ${err.message}`, true);
  205. }
  206. }
  207. function selectStationLocal(sid, syncNav = true) {
  208. if (!sid || sid === activeStationId) return;
  209. activeStationId = sid;
  210. syncedStationId = '';
  211. hoverRatio = null;
  212. if (syncNav) {
  213. const navSel = el('nav-station');
  214. if (navSel && navSel.value !== sid) {
  215. navSel.value = sid;
  216. window.dispatchEvent(new CustomEvent('stl:station-select', { detail: { stationId: sid, fromThermal: true } }));
  217. }
  218. }
  219. void pollConsole(true);
  220. }
  221. function setMapStatus(msg, isError = false) {
  222. const node = el('th-map-status');
  223. if (!node) return;
  224. node.textContent = msg;
  225. node.style.color = isError ? '#b83740' : '#0d6a5f';
  226. }
  227. function renderBmcMappingTable(stationsArr) {
  228. const tbody = el('th-bmc-map-tbody');
  229. if (!tbody || !Array.isArray(stationsArr)) return;
  230. // Live-update status badges without clobbering user input while typing/editing
  231. for (const s of stationsArr) {
  232. const badge = tbody.querySelector(`[data-map-status="${s.station_id}"]`);
  233. if (badge) {
  234. badge.textContent = modeLabel(s.mcu_mode);
  235. badge.className = `th-pill ${modeBadgeClass(s.mcu_mode)}`;
  236. }
  237. }
  238. const activeEl = document.activeElement;
  239. if (mapDirty || (activeEl && tbody.contains(activeEl))) return;
  240. const portSig = scannedPorts.map(p => `${p.path}:${p.bound_station || ''}`).join('|');
  241. const sig = JSON.stringify([portSig, stationsArr.map(s => [
  242. s.station_id, s.bmc_host, s.preferred_mode, s.mode, s.serial_path, s.resolved_path,
  243. s.usb_serial, s.tcp_host, s.tcp_port, s.mcu_mode, s.online, s.uid_hex,
  244. ])]);
  245. if (sig === lastMapSig) return;
  246. lastMapSig = sig;
  247. const makePortOptions = (selectedPath) => {
  248. const opts = ['<option value="">-- 选择已扫描 USB 串口 --</option>'];
  249. for (const p of scannedPorts) {
  250. const notes = [];
  251. if (p.bound_station) notes.push(`已绑:${p.bound_station}`);
  252. if (p.console_conflict) notes.push('BIOS占用');
  253. const lbl = `${p.label || p.path}${notes.length ? ' [' + notes.join('·') + ']' : ''}`;
  254. const selAttr = p.path === selectedPath ? ' selected' : '';
  255. opts.push(`<option value="${escapeHtml(p.path)}"${selAttr}>${escapeHtml(lbl)}</option>`);
  256. }
  257. return opts.join('');
  258. };
  259. tbody.innerHTML = stationsArr.map(s => {
  260. const sid = s.station_id || 'S1';
  261. const rowMode = (s.mode && s.mode !== 'disconnected') ? s.mode : (s.preferred_mode || 'serial');
  262. const isTcp = rowMode === 'tcp';
  263. const isMock = rowMode === 'mock';
  264. const bmcHost = s.bmc_host || s.station_bmc_host || '';
  265. const modeText = modeLabel(s.mcu_mode);
  266. const pillCls = modeBadgeClass(s.mcu_mode);
  267. return `<tr data-map-row="${escapeHtml(sid)}">
  268. <td><strong>${escapeHtml(sid)}</strong><div class="field-note">${escapeHtml((s.station_name || '').replace(/\s*\(.+\)$/, ''))}</div></td>
  269. <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>
  270. <td>
  271. <select data-map-field="mode">
  272. <option value="serial"${rowMode === 'serial' ? ' selected' : ''}>USB 串口</option>
  273. <option value="tcp"${rowMode === 'tcp' ? ' selected' : ''}>TCP 串口</option>
  274. <option value="mock"${rowMode === 'mock' ? ' selected' : ''}>Mock 仿真</option>
  275. </select>
  276. </td>
  277. <td>
  278. <div class="th-map-serial-cell" data-map-serial-box="${escapeHtml(sid)}"${isTcp || isMock ? ' style="display:none"' : ''}>
  279. <select data-map-field="serial_pick">${makePortOptions(s.serial_path || '')}</select>
  280. <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">
  281. </div>
  282. <div class="th-map-tcp-row" data-map-tcp-box="${escapeHtml(sid)}"${!isTcp ? ' style="display:none"' : ''}>
  283. <input type="text" data-map-field="tcp_host" value="${escapeHtml(s.tcp_host || '127.0.0.1')}" placeholder="IP" style="flex:2">
  284. <input type="number" data-map-field="tcp_port" value="${escapeHtml(s.tcp_port || 4002)}" min="1" max="65535" style="flex:1">
  285. </div>
  286. <span class="field-note" data-map-mock-box="${escapeHtml(sid)}"${!isMock ? ' style="display:none"' : ''}>离线虚拟 6400 高温罩仿真</span>
  287. </td>
  288. <td><input type="text" data-map-field="usb_serial" value="${escapeHtml(s.usb_serial || '')}" placeholder="可选防漂移" spellcheck="false"></td>
  289. <td>
  290. <div class="th-map-actions">
  291. <span class="th-pill ${pillCls}" data-map-status="${escapeHtml(sid)}">${escapeHtml(modeText)}</span>
  292. <button type="button" class="btn btn-quiet btn-xs" data-map-act="save" data-map-sid="${escapeHtml(sid)}">保存</button>
  293. <button type="button" class="btn btn-primary btn-xs" data-map-act="connect" data-map-sid="${escapeHtml(sid)}">连接</button>
  294. <button type="button" class="btn btn-secondary btn-xs" data-map-act="disconnect" data-map-sid="${escapeHtml(sid)}">断开</button>
  295. </div>
  296. </td>
  297. </tr>`;
  298. }).join('');
  299. const collectRow = (sid) => {
  300. const tr = tbody.querySelector(`tr[data-map-row="${sid}"]`);
  301. if (!tr) return null;
  302. return {
  303. station_id: sid,
  304. bmc_host: tr.querySelector('[data-map-field="bmc_host"]')?.value.trim() || '',
  305. mode: tr.querySelector('[data-map-field="mode"]')?.value || 'serial',
  306. serial_path: tr.querySelector('[data-map-field="serial_path"]')?.value.trim() || '',
  307. usb_serial: tr.querySelector('[data-map-field="usb_serial"]')?.value.trim() || '',
  308. tcp_host: tr.querySelector('[data-map-field="tcp_host"]')?.value.trim() || '127.0.0.1',
  309. tcp_port: Number(tr.querySelector('[data-map-field="tcp_port"]')?.value) || 4002,
  310. };
  311. };
  312. tbody.querySelectorAll('input, select').forEach(ctrl => {
  313. ctrl.addEventListener('input', () => { mapDirty = true; });
  314. ctrl.addEventListener('change', () => {
  315. mapDirty = true;
  316. const tr = ctrl.closest('tr[data-map-row]');
  317. const sid = tr?.dataset.mapRow;
  318. if (!sid) return;
  319. if (ctrl.dataset.mapField === 'mode') {
  320. const md = ctrl.value;
  321. const sBox = tr.querySelector(`[data-map-serial-box="${sid}"]`);
  322. const tBox = tr.querySelector(`[data-map-tcp-box="${sid}"]`);
  323. const mBox = tr.querySelector(`[data-map-mock-box="${sid}"]`);
  324. if (sBox) sBox.style.display = md === 'serial' ? '' : 'none';
  325. if (tBox) tBox.style.display = md === 'tcp' ? '' : 'none';
  326. if (mBox) mBox.style.display = md === 'mock' ? '' : 'none';
  327. } else if (ctrl.dataset.mapField === 'serial_pick' && ctrl.value) {
  328. const pathInp = tr.querySelector('[data-map-field="serial_path"]');
  329. const snInp = tr.querySelector('[data-map-field="usb_serial"]');
  330. if (pathInp) pathInp.value = ctrl.value;
  331. const match = scannedPorts.find(p => p.path === ctrl.value);
  332. if (match && snInp) snInp.value = match.usb_serial_unique ? (match.usb_serial || '') : '';
  333. }
  334. });
  335. });
  336. tbody.querySelectorAll('[data-map-act]').forEach(btn => {
  337. btn.addEventListener('click', async () => {
  338. const sid = btn.dataset.mapSid;
  339. const act = btn.dataset.mapAct;
  340. const row = collectRow(sid);
  341. if (!row) return;
  342. try {
  343. if (act === 'save') {
  344. await window.stlTransport.call('ThermalAction', { action: 'save_mappings', station_id: sid, ...row }, 10000);
  345. mapDirty = false;
  346. lastMapSig = '';
  347. setMapStatus(`已保存 ${sid} (BMC ${row.bmc_host || '未填'}) ↔ 高温罩串口映射`);
  348. } else if (act === 'connect') {
  349. await window.stlTransport.call('ThermalAction', { action: 'connect', ...row, serial_baud: 115200, auto_reconnect: true }, 10000);
  350. mapDirty = false;
  351. lastMapSig = '';
  352. setMapStatus(`已连接 ${sid} (BMC ${row.bmc_host || '未填'}) 高温罩`);
  353. } else if (act === 'disconnect') {
  354. await window.stlTransport.call('ThermalAction', { action: 'disconnect', station_id: sid }, 10000);
  355. mapDirty = false;
  356. lastMapSig = '';
  357. setMapStatus(`已断开 ${sid} 高温罩串口(不影响内存测试)`);
  358. }
  359. if (sid === activeStationId) syncedStationId = '';
  360. await pollConsole(true);
  361. } catch (err) {
  362. setMapStatus(`${sid} 操作失败: ${err.message}`, true);
  363. }
  364. });
  365. });
  366. }
  367. function renderStationCards(stationsArr) {
  368. if (!Array.isArray(stationsArr)) return;
  369. const container = el('th-station-cards');
  370. if (!container) return;
  371. const sig = JSON.stringify([activeStationId, stationsArr.map(s => [
  372. s.station_id, s.bmc_host, s.mode, s.online, s.mcu_mode, s.serial_path, s.resolved_path,
  373. s.target_c, s.bmc_avg, s.ct_avg, s.recording_active, s.recording_rows,
  374. s.session_samples_count, s.last_error, s.uid_hex,
  375. ])]);
  376. if (sig === lastStationsSig) return;
  377. lastStationsSig = sig;
  378. container.innerHTML = stationsArr.map(s => {
  379. const sid = s.station_id || 'S1';
  380. const activeCls = sid === activeStationId ? ' active' : '';
  381. const modeText = modeLabel(s.mcu_mode);
  382. const pillCls = modeBadgeClass(s.mcu_mode);
  383. const bmcTxt = s.bmc_host ? `BMC ${s.bmc_host}` : 'BMC 未指定';
  384. const portText = s.mode === 'mock'
  385. ? `Mock 仿真 · ${s.uid_hex ? s.uid_hex.slice(-8) : 'v1.1'}`
  386. : s.mode === 'tcp'
  387. ? `TCP ${s.tcp_host}:${s.tcp_port}`
  388. : (s.resolved_path || s.serial_path || '未绑定串口');
  389. const tgt = s.target_c != null ? `${s.target_c}℃` : '--';
  390. const ctAvg = s.ct_avg != null ? `${Number(s.ct_avg).toFixed(1)}℃` : '--';
  391. const bmcAvg = s.bmc_avg != null ? `${Number(s.bmc_avg).toFixed(1)}℃` : '--';
  392. const recStr = s.recording_active
  393. ? `录制中 ${s.recording_rows || 0}行`
  394. : `缓存 ${s.session_samples_count || 0}行`;
  395. return `<div class="th-station-card${activeCls}" data-th-sid="${escapeHtml(sid)}" role="button" tabindex="0">
  396. <div class="th-station-card-top">
  397. <span class="th-station-card-name">${escapeHtml(sid)} · ${escapeHtml(bmcTxt)}</span>
  398. <span class="th-pill ${pillCls}">${escapeHtml(modeText)}</span>
  399. </div>
  400. <div class="th-station-card-port" title="${escapeHtml(portText)}">${escapeHtml(portText)}</div>
  401. <div class="th-station-card-metrics">
  402. <span>目标 <strong>${escapeHtml(tgt)}</strong></span>
  403. <span>腔均 <strong>${escapeHtml(ctAvg)}</strong></span>
  404. <span>BMC均 <strong>${escapeHtml(bmcAvg)}</strong></span>
  405. </div>
  406. <div class="th-station-card-foot">
  407. <span>${escapeHtml(recStr)}</span>
  408. <span title="${escapeHtml(s.last_error || '')}">${s.last_error ? escapeHtml(s.last_error.slice(0, 18)) : (s.station_phase ? `测试:${escapeHtml(s.station_phase)}` : '')}</span>
  409. </div>
  410. </div>`;
  411. }).join('');
  412. container.querySelectorAll('.th-station-card').forEach(card => {
  413. card.addEventListener('click', () => selectStationLocal(card.dataset.thSid, true));
  414. card.addEventListener('keydown', ev => {
  415. if (ev.key === 'Enter' || ev.key === ' ') {
  416. ev.preventDefault();
  417. selectStationLocal(card.dataset.thSid, true);
  418. }
  419. });
  420. });
  421. }
  422. function updateOverviewThermalBadge(stationsArr) {
  423. const badge = el('ov-thermal-badge');
  424. if (!badge || !Array.isArray(stationsArr)) return;
  425. const curSid = el('nav-station')?.value || activeStationId;
  426. const item = stationsArr.find(x => x.station_id === curSid);
  427. if (!item) {
  428. setTextIfChanged(badge, '未配置');
  429. badge.className = 'badge';
  430. return;
  431. }
  432. if (item.online) {
  433. const ctTxt = item.ct_avg != null ? `${Number(item.ct_avg).toFixed(1)}℃` : '--℃';
  434. const tgtTxt = item.target_c != null ? `→${item.target_c}℃` : '';
  435. setTextIfChanged(badge, `${modeLabel(item.mcu_mode)} · 腔均${ctTxt}${tgtTxt}`);
  436. badge.className = item.mcu_mode === 'cpld_lost' ? 'badge error' : 'badge connected';
  437. } else if (item.desired_connected) {
  438. setTextIfChanged(badge, '重连中');
  439. badge.className = 'badge error';
  440. } else {
  441. setTextIfChanged(badge, '未连接');
  442. badge.className = 'badge';
  443. }
  444. }
  445. function renderSnapshot(snap) {
  446. if (!snap) return;
  447. lastSnapshot = snap;
  448. const sid = snap.station_id || activeStationId;
  449. const conn = snap.connection || {};
  450. const mcu = snap.mcu || {};
  451. const ident = snap.identity || {};
  452. const safety = snap.safety || {};
  453. const act = snap.actuators || {};
  454. const rec = snap.recorder || {};
  455. const stCtx = snap.station_context || {};
  456. renderStationCards(snap.stations);
  457. renderBmcMappingTable(snap.stations);
  458. updateOverviewThermalBadge(snap.stations);
  459. setTextIfChanged(
  460. el('th-selected-station-label'),
  461. `${sid} · ${stCtx.station_name || sid}`
  462. );
  463. const switchedStation = syncedStationId !== sid;
  464. if (switchedStation) {
  465. syncedStationId = sid;
  466. if (el('th-bmc-host')) {
  467. el('th-bmc-host').value = conn.bmc_host || stCtx.bmc_host || '';
  468. }
  469. const modeVal = conn.mode && conn.mode !== 'disconnected' ? conn.mode : (conn.preferred_mode || (conn.tcp_host && !conn.serial_path ? 'tcp' : 'serial'));
  470. el('th-conn-mode').value = modeVal;
  471. updateModeVisibility();
  472. el('th-serial-path').value = conn.serial_path || '';
  473. const selPort = el('th-serial-select');
  474. if (selPort) {
  475. const spVal = conn.serial_path || '';
  476. const hasOpt = spVal && scannedPorts.some(p => p.path === spVal);
  477. selPort.value = hasOpt ? spVal : '';
  478. }
  479. el('th-usb-serial').value = conn.usb_serial || '';
  480. el('th-tcp-host').value = conn.tcp_host || '127.0.0.1';
  481. el('th-tcp-port').value = conn.tcp_port || 4002;
  482. el('th-auto-reconnect').checked = conn.auto_reconnect !== false;
  483. el('th-safety-lease').value = String(safety.lease_sec ?? 0);
  484. el('th-overtemp-cutoff').value = String(safety.overtemp_cutoff_c ?? 95);
  485. el('th-target-input').value = String(mcu.last_set_target_c ?? 70);
  486. el('th-rec-auto').checked = rec.auto_record_on_heat !== false;
  487. el('th-rec-interval').value = String(rec.interval_ms ?? 1000);
  488. }
  489. const online = Boolean(conn.online);
  490. const pOnline = el('th-pill-online');
  491. const linkDesc = online
  492. ? `链路: 在线 (${conn.mode === 'serial' ? (conn.resolved_path || conn.serial_path) : conn.mode === 'tcp' ? `${conn.tcp_host}:${conn.tcp_port}` : 'Mock'})`
  493. : conn.desired_connected
  494. ? `链路: 断线重连中 (${conn.last_error || '等待设备'})`
  495. : '链路: 未连接';
  496. setTextIfChanged(pOnline, linkDesc);
  497. pOnline.className = `th-pill ${online ? 'is-ok' : (conn.desired_connected ? 'is-err' : '')}`;
  498. const pState = el('th-pill-state');
  499. setTextIfChanged(pState, `状态: ${modeLabel(mcu.mode)}`);
  500. pState.className = `th-pill ${modeBadgeClass(mcu.mode)}`;
  501. const pCpld = el('th-pill-cpld');
  502. setTextIfChanged(pCpld, !online ? 'CPLD: --' : (mcu.cpld_lost ? 'CPLD: 失联' : 'CPLD: 正常'));
  503. pCpld.className = `th-pill ${!online ? '' : (mcu.cpld_lost ? 'is-err' : 'is-ok')}`;
  504. const pPre = el('th-pill-preheat');
  505. setTextIfChanged(pPre, `预加热: ${mcu.preheating ? '运行中' : '否'}`);
  506. pPre.className = `th-pill ${mcu.preheating ? 'is-active' : ''}`;
  507. const pPid = el('th-pill-pid');
  508. setTextIfChanged(pPid, `PID闭环: ${mcu.pid_running ? '运行中' : '否'}`);
  509. pPid.className = `th-pill ${mcu.pid_running ? 'is-active' : ''}`;
  510. const pH = el('th-pill-hlatch');
  511. setTextIfChanged(pH, `加热锁存: ${mcu.heater_latched_off ? '已锁死' : '正常'}`);
  512. pH.className = `th-pill ${mcu.heater_latched_off ? 'is-warn' : ''}`;
  513. const pF = el('th-pill-flatch');
  514. setTextIfChanged(pF, `风扇锁存: ${mcu.fan_latched_off ? '已锁死' : '正常'}`);
  515. pF.className = `th-pill ${mcu.fan_latched_off ? 'is-warn' : ''}`;
  516. const pBmc = el('th-pill-bmc');
  517. setTextIfChanged(pBmc, !online ? 'BMC温度源: --' : (mcu.bmc_not_ready ? 'BMC温度源: 未就绪' : 'BMC温度源: 就绪'));
  518. pBmc.className = `th-pill ${!online ? '' : (mcu.bmc_not_ready ? 'is-warn' : 'is-ok')}`;
  519. const pMan = el('th-pill-manual');
  520. setTextIfChanged(pMan, `手动保持: ${mcu.manual_active ? (mcu.manual_keepalive ? '保持中' : '10s单次') : '否'}`);
  521. pMan.className = `th-pill ${mcu.manual_active ? 'is-warn' : ''}`;
  522. const bootVer = ident.boot_info?.app_version ? `${ident.boot_info.app_version} (${ident.boot_info.bl_state})` : '--';
  523. setTextIfChanged(el('th-hw-identity'), `UID: ${ident.uid_hex || '--'} · 固件: ${bootVer}`);
  524. setTextIfChanged(el('th-pid-current'), ident.pid_text || '--');
  525. const leaseTxt = safety.lease_sec > 0
  526. ? (safety.lease_remaining_sec > 0 ? `看门狗剩余: ${safety.lease_remaining_sec}s` : `看门狗: ${safety.lease_sec}s (待启动)`)
  527. : '看门狗: 不限时';
  528. setTextIfChanged(
  529. el('th-safety-status'),
  530. `${leaseTxt} · 超温熔断: ${safety.overtemp_cutoff_c ?? 95}℃${safety.overtemp_tripped ? ' [已触发熔断!]' : ''}`
  531. );
  532. setTextIfChanged(el('th-target-badge'), `当前目标: ${mcu.target_c != null ? mcu.target_c + ' ℃' : '-- ℃'}`);
  533. setTextIfChanged(el('th-act-ptc'), act.snap_updated_unix_ms ? `${act.ptc_avg_duty ?? '--'} %` : '-- %');
  534. setTextIfChanged(el('th-act-ff'), act.snap_updated_unix_ms ? `${act.fan_front_avg_duty ?? '--'} %` : '-- %');
  535. setTextIfChanged(el('th-act-fr'), act.snap_updated_unix_ms ? `${act.fan_rear_avg_duty ?? '--'} %` : '-- %');
  536. const ssr = Array.isArray(act.ssr_3) ? act.ssr_3 : [];
  537. setTextIfChanged(el('th-act-ssr'), act.snap_updated_unix_ms && ssr.length === 3 ? `${ssr[0]}% / ${ssr[1]}% / ${ssr[2]}%` : '-- / -- / --');
  538. setTextIfChanged(el('th-act-ct0'), act.ct0_board_c != null ? `${act.ct0_board_c} ℃` : '-- ℃');
  539. setTextIfChanged(el('th-snap-age'), act.snap_updated_unix_ms ? `更新于 ${fmtTimeShort(act.snap_updated_unix_ms)}` : '等待 MCU 快照...');
  540. setTextIfChanged(el('th-session-sample-count'), `当前会话已采集 ${rec.session_samples_count || 0} 行`);
  541. el('btn-th-export-csv').disabled = !(Number(rec.session_samples_count) > 0);
  542. const recBadge = el('th-rec-badge');
  543. setTextIfChanged(recBadge, rec.active ? `录制中 (${rec.rows_written || 0} 行)` : '未开启落盘');
  544. recBadge.className = `badge ${rec.active ? 'connected' : ''}`;
  545. setTextIfChanged(
  546. el('th-rec-stats'),
  547. rec.active
  548. ? `正在写入: ${rec.csv_filename} · 已写入 ${rec.rows_written || 0} 行 (${fmtBytes(rec.bytes_written)}) · 开始于 ${fmtTimeShort(rec.started_unix_ms)}`
  549. : '磁盘记录未开启;已连接读取时可直接点击上方「立即导出当前会话 CSV」。'
  550. );
  551. // Update persisted CSV file table only when changed
  552. const files = Array.isArray(snap.files) ? snap.files : [];
  553. const fSig = JSON.stringify(files.map(f => [f.filename, f.size_bytes, f.active]));
  554. if (fSig !== lastFilesSig) {
  555. lastFilesSig = fSig;
  556. const tbody = el('th-files-tbody');
  557. if (files.length === 0) {
  558. tbody.innerHTML = '<tr><td colspan="5">尚无历史记录文件</td></tr>';
  559. } else {
  560. tbody.innerHTML = files.map(f => {
  561. const activeTag = f.active ? ' <span class="badge connected">写入中</span>' : '';
  562. const stTag = f.station_id ? `<span class="badge">${escapeHtml(f.station_id)}</span>` : '--';
  563. return `<tr>
  564. <td><code>${escapeHtml(f.filename)}</code>${activeTag}</td>
  565. <td>${stTag}</td>
  566. <td>${fmtBytes(f.size_bytes)}</td>
  567. <td>${escapeHtml(f.modified_str || '')}</td>
  568. <td><a class="inline-link" href="${escapeHtml(f.download_url)}" download="${escapeHtml(f.filename)}">下载</a></td>
  569. </tr>`;
  570. }).join('');
  571. }
  572. }
  573. const bStats = snap.bmc_stats || {};
  574. const cStats = snap.ct_stats || {};
  575. setTextIfChanged(
  576. el('th-chart-stats'),
  577. `[${sid}] 目标: ${mcu.target_c != null ? mcu.target_c + '℃' : '--'} · MCU BMC均/最高: ${bStats.avg ?? '--'}/${bStats.max ?? '--'}℃ · CT腔均/最高: ${cStats.avg ?? '--'}/${cStats.max ?? '--'}℃ · 服务器阶段: ${stCtx.phase || '--'}`
  578. );
  579. setTextIfChanged(
  580. el('th-bmc24-summary'),
  581. `有效通道: ${bStats.valid_cnt || 0}/24 (未插槽位导出为 0) · 均值: ${bStats.avg ?? '--'}℃ · 最高: ${bStats.max ?? '--'}℃`
  582. );
  583. const ctArr = Array.isArray(snap.ct7428_8) ? snap.ct7428_8 : [];
  584. for (let i = 0; i < 8; i++) {
  585. const v = ctArr[i];
  586. const txt = v != null ? `${v} ℃` : '--';
  587. if (ctCells[i].prev !== txt) {
  588. ctCells[i].prev = txt;
  589. ctCells[i].val.textContent = txt;
  590. }
  591. }
  592. const mcuArr = Array.isArray(snap.mcu_bmc_24) ? snap.mcu_bmc_24 : [];
  593. const ipmiArr = Array.isArray(snap.ipmi_dimm_24) ? snap.ipmi_dimm_24 : [];
  594. for (let i = 0; i < 24; i++) {
  595. const cell = slotCells[i];
  596. const mv = mcuArr[i];
  597. const iv = ipmiArr[i];
  598. const mTxt = mv != null ? `MCU: ${mv}℃` : 'MCU: --';
  599. const iTxt = iv != null ? `IPMI: ${Number(iv).toFixed(0)}℃` : '';
  600. const dTxt = (mv != null && iv != null) ? `Δ${(mv - iv >= 0 ? '+' : '') + (mv - iv).toFixed(1)}` : '';
  601. const maxT = Math.max(mv ?? -1, iv ?? -1);
  602. const cls = maxT > 80
  603. ? 'th-slot-card is-hot'
  604. : maxT >= 65
  605. ? 'th-slot-card is-warn'
  606. : maxT >= 0
  607. ? 'th-slot-card is-valid'
  608. : 'th-slot-card';
  609. if (cell.prevCls !== cls) { cell.prevCls = cls; cell.card.className = cls; }
  610. if (cell.prevMcu !== mTxt) { cell.prevMcu = mTxt; cell.mcuStrong.textContent = mTxt; }
  611. if (cell.prevIpmi !== iTxt) { cell.prevIpmi = iTxt; cell.ipmiSpan.textContent = iTxt; }
  612. if (cell.prevDiff !== dTxt) { cell.prevDiff = dTxt; cell.diffSpan.textContent = dTxt; }
  613. }
  614. // Per-station bounded delta chart ring
  615. let ring = chartByStation.get(sid) || [];
  616. if (snap.reset_ring) {
  617. ring = Array.isArray(snap.points_delta) ? snap.points_delta.slice(-MAX_POINTS) : [];
  618. } else if (Array.isArray(snap.points_delta) && snap.points_delta.length > 0) {
  619. for (const pt of snap.points_delta) ring.push(pt);
  620. if (ring.length > MAX_POINTS) ring.splice(0, ring.length - MAX_POINTS);
  621. }
  622. chartByStation.set(sid, ring);
  623. if (typeof snap.latest_point_seq === 'number') {
  624. seqByStation.set(sid, snap.latest_point_seq);
  625. }
  626. scheduleChartDraw();
  627. if (el('th-debug-drawer').open) {
  628. const ascii = Array.isArray(snap.ascii_logs) ? snap.ascii_logs : [];
  629. const aSig = `${sid}:${ascii.length ? ascii[0].unix_ms + ':' + ascii.length : 'empty'}`;
  630. if (aSig !== lastAsciiSig) {
  631. lastAsciiSig = aSig;
  632. el('th-ascii-log-pre').textContent = ascii.length
  633. ? ascii.slice(0, 45).map(a => `[${(a.time_str || '').slice(11, 23)}] ${a.line}`).join('\n')
  634. : '暂无 MCU 串口 ASCII 输出...';
  635. }
  636. const evs = Array.isArray(snap.events) ? snap.events.slice(0, 20) : [];
  637. const frms = Array.isArray(snap.frames) ? snap.frames.slice(0, 25) : [];
  638. const fSig = `${sid}:${evs[0]?.unix_ms || 0}:${frms[0]?.unix_ms || 0}:${frms.length}`;
  639. if (fSig !== lastFrameSig) {
  640. lastFrameSig = fSig;
  641. const evTxt = evs.map(e => `[事件 ${(e.time_str || '').slice(11, 19)} ${e.level}] ${e.message}`).join('\n');
  642. const frTxt = frms.map(f => `[${f.dir} ${f.cmd} ${f.len}B] ${f.hex}`).join('\n');
  643. el('th-frame-log-pre').textContent = [evTxt, frTxt].filter(Boolean).join('\n--- 最近协议报文 ---\n') || '暂无事件与协议帧...';
  644. }
  645. }
  646. }
  647. function scheduleChartDraw() {
  648. if (rafPending || document.body.dataset.currentPage !== 'thermal') return;
  649. rafPending = true;
  650. requestAnimationFrame(() => {
  651. rafPending = false;
  652. drawChart();
  653. });
  654. }
  655. function drawChart() {
  656. const canvas = el('th-chart-canvas');
  657. if (!canvas) return;
  658. const rect = canvas.getBoundingClientRect();
  659. const dpr = window.devicePixelRatio || 1;
  660. const w = Math.max(360, Math.round(rect.width || 1100));
  661. const h = 240;
  662. if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) {
  663. canvas.width = Math.round(w * dpr);
  664. canvas.height = Math.round(h * dpr);
  665. }
  666. const ctx = canvas.getContext('2d');
  667. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  668. ctx.clearRect(0, 0, w, h);
  669. const chartRing = chartByStation.get(activeStationId) || [];
  670. const padL = 44, padR = 16, padT = 16, padB = 26;
  671. const plotW = w - padL - padR;
  672. const plotH = h - padT - padB;
  673. let minY = 20, maxY = 95;
  674. for (const pt of chartRing) {
  675. for (const s of SERIES_META) {
  676. if (!enabledSeries.has(s.key)) continue;
  677. const v = pt[s.key];
  678. if (typeof v === 'number') {
  679. if (v - 4 < minY) minY = Math.floor((v - 4) / 5) * 5;
  680. if (v + 5 > maxY) maxY = Math.ceil((v + 5) / 5) * 5;
  681. }
  682. }
  683. }
  684. if (maxY - minY < 15) maxY = minY + 15;
  685. const yFor = val => padT + plotH - ((val - minY) / (maxY - minY)) * plotH;
  686. const xFor = idx => padL + (chartRing.length <= 1 ? 0 : (idx / (chartRing.length - 1)) * plotW);
  687. ctx.strokeStyle = '#e7eff4';
  688. ctx.lineWidth = 1;
  689. ctx.fillStyle = '#6f8493';
  690. ctx.font = '11px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
  691. const steps = 5;
  692. for (let i = 0; i <= steps; i++) {
  693. const val = minY + ((maxY - minY) * i) / steps;
  694. const y = yFor(val);
  695. ctx.beginPath();
  696. ctx.moveTo(padL, y);
  697. ctx.lineTo(w - padR, y);
  698. ctx.stroke();
  699. ctx.fillText(`${Math.round(val)}°`, 6, y + 4);
  700. }
  701. if (chartRing.length === 0) {
  702. ctx.fillStyle = '#8aa0ad';
  703. ctx.font = '13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
  704. ctx.fillText(`当前工位 ${activeStationId} 连接高温罩后自动绘制实时温度曲线...`, padL + 16, padT + plotH / 2);
  705. return;
  706. }
  707. const startT = fmtTimeShort(chartRing[0].t);
  708. const endT = fmtTimeShort(chartRing[chartRing.length - 1].t);
  709. ctx.fillStyle = '#6f8493';
  710. ctx.fillText(startT, padL, h - 7);
  711. ctx.fillText(endT, w - padR - 58, h - 7);
  712. for (const s of SERIES_META) {
  713. if (!enabledSeries.has(s.key)) continue;
  714. ctx.save();
  715. ctx.strokeStyle = s.color;
  716. ctx.lineWidth = s.dashed ? 1.5 : 2;
  717. if (s.dashed) ctx.setLineDash([6, 4]);
  718. ctx.beginPath();
  719. let started = false;
  720. for (let i = 0; i < chartRing.length; i++) {
  721. const v = chartRing[i][s.key];
  722. if (typeof v !== 'number') {
  723. started = false;
  724. continue;
  725. }
  726. const x = xFor(i);
  727. const y = yFor(v);
  728. if (!started) { ctx.moveTo(x, y); started = true; }
  729. else ctx.lineTo(x, y);
  730. }
  731. ctx.stroke();
  732. ctx.restore();
  733. }
  734. const tip = el('th-chart-tooltip');
  735. if (hoverRatio != null && chartRing.length > 0) {
  736. const idx = Math.max(0, Math.min(chartRing.length - 1, Math.round(hoverRatio * (chartRing.length - 1))));
  737. const pt = chartRing[idx];
  738. const hx = xFor(idx);
  739. ctx.save();
  740. ctx.strokeStyle = 'rgba(36, 50, 71, 0.35)';
  741. ctx.setLineDash([3, 3]);
  742. ctx.beginPath();
  743. ctx.moveTo(hx, padT);
  744. ctx.lineTo(hx, padT + plotH);
  745. ctx.stroke();
  746. ctx.restore();
  747. if (tip) {
  748. tip.classList.remove('hidden');
  749. tip.textContent = `${activeStationId} ${fmtTimeShort(pt.t)} · 目标:${pt.target ?? '--'}℃ · BMC均/高:${pt.bmc_avg ?? '--'}/${pt.bmc_max ?? '--'}℃ · CT均/高:${pt.ct_avg ?? '--'}/${pt.ct_max ?? '--'}℃`;
  750. }
  751. } else if (tip) {
  752. tip.classList.add('hidden');
  753. }
  754. }
  755. const canvasEl = el('th-chart-canvas');
  756. canvasEl.addEventListener('mousemove', ev => {
  757. const rect = canvasEl.getBoundingClientRect();
  758. const plotW = Math.max(1, rect.width - 60);
  759. hoverRatio = Math.max(0, Math.min(1, (ev.clientX - rect.left - 44) / plotW));
  760. scheduleChartDraw();
  761. });
  762. canvasEl.addEventListener('mouseleave', () => {
  763. hoverRatio = null;
  764. scheduleChartDraw();
  765. });
  766. // Button bindings
  767. el('btn-th-scan-ports').addEventListener('click', async () => {
  768. await scanPorts(false);
  769. lastMapSig = '';
  770. if (lastSnapshot?.stations) renderBmcMappingTable(lastSnapshot.stations);
  771. });
  772. if (el('btn-th-map-scan')) {
  773. el('btn-th-map-scan').addEventListener('click', async () => {
  774. await scanPorts(false);
  775. lastMapSig = '';
  776. if (lastSnapshot?.stations) renderBmcMappingTable(lastSnapshot.stations);
  777. setMapStatus(`串口扫描完成:共发现 ${scannedPorts.length} 个 USB 串口`);
  778. });
  779. }
  780. if (el('btn-th-map-save-all')) {
  781. el('btn-th-map-save-all').addEventListener('click', async () => {
  782. const tbody = el('th-bmc-map-tbody');
  783. if (!tbody) return;
  784. const mappings = [];
  785. tbody.querySelectorAll('tr[data-map-row]').forEach(tr => {
  786. const sid = tr.dataset.mapRow;
  787. mappings.push({
  788. station_id: sid,
  789. bmc_host: tr.querySelector('[data-map-field="bmc_host"]')?.value.trim() || '',
  790. mode: tr.querySelector('[data-map-field="mode"]')?.value || 'serial',
  791. serial_path: tr.querySelector('[data-map-field="serial_path"]')?.value.trim() || '',
  792. usb_serial: tr.querySelector('[data-map-field="usb_serial"]')?.value.trim() || '',
  793. tcp_host: tr.querySelector('[data-map-field="tcp_host"]')?.value.trim() || '127.0.0.1',
  794. tcp_port: Number(tr.querySelector('[data-map-field="tcp_port"]')?.value) || 4002,
  795. });
  796. });
  797. try {
  798. await window.stlTransport.call('ThermalAction', { action: 'save_mappings', station_id: activeStationId, mappings }, 10000);
  799. mapDirty = false;
  800. lastMapSig = '';
  801. syncedStationId = '';
  802. setMapStatus(`已保存全部 ${mappings.length} 组 BMC 机位 ↔ 高温罩串口映射`);
  803. await pollConsole(true);
  804. } catch (err) {
  805. setMapStatus(`保存映射失败: ${err.message}`, true);
  806. }
  807. });
  808. }
  809. if (el('btn-th-save-binding')) {
  810. el('btn-th-save-binding').addEventListener('click', async () => {
  811. const mode = el('th-conn-mode').value;
  812. const payload = {
  813. action: 'save_mappings',
  814. station_id: activeStationId || 'S1',
  815. bmc_host: el('th-bmc-host')?.value.trim() || '',
  816. mode,
  817. serial_path: el('th-serial-path').value.trim(),
  818. usb_serial: el('th-usb-serial').value.trim(),
  819. serial_baud: 115200,
  820. tcp_host: el('th-tcp-host').value.trim() || '127.0.0.1',
  821. tcp_port: Number(el('th-tcp-port').value) || 4002,
  822. auto_reconnect: el('th-auto-reconnect').checked,
  823. };
  824. try {
  825. await window.stlTransport.call('ThermalAction', payload, 10000);
  826. mapDirty = false;
  827. lastMapSig = '';
  828. setStatus(`已保存工位 ${activeStationId} (BMC ${payload.bmc_host || '未指定'}) ↔ 高温罩串口绑定`);
  829. await pollConsole(true);
  830. } catch (err) {
  831. setStatus(`保存绑定失败: ${err.message}`, true);
  832. }
  833. });
  834. }
  835. el('btn-th-connect').addEventListener('click', async () => {
  836. const mode = el('th-conn-mode').value;
  837. const payload = {
  838. mode,
  839. bmc_host: el('th-bmc-host')?.value.trim() || '',
  840. serial_path: el('th-serial-path').value.trim(),
  841. usb_serial: el('th-usb-serial').value.trim(),
  842. serial_baud: 115200,
  843. tcp_host: el('th-tcp-host').value.trim() || '127.0.0.1',
  844. tcp_port: Number(el('th-tcp-port').value) || 4002,
  845. auto_reconnect: el('th-auto-reconnect').checked,
  846. };
  847. try {
  848. await callThermalAction('connect', payload);
  849. mapDirty = false;
  850. lastMapSig = '';
  851. setStatus(`工位 ${activeStationId} (BMC ${payload.bmc_host || '未指定'}) 高温罩已连接 (${mode === 'serial' ? (payload.serial_path || payload.usb_serial) : mode})`);
  852. await pollConsole(true);
  853. } catch (err) {
  854. setStatus(`连接高温罩失败: ${err.message}`, true);
  855. }
  856. });
  857. el('btn-th-disconnect').addEventListener('click', async () => {
  858. try {
  859. await callThermalAction('disconnect');
  860. setStatus(`已断开工位 ${activeStationId} 高温罩连接(不影响内存测试)`);
  861. await pollConsole(true);
  862. } catch (err) {
  863. setStatus(`断开失败: ${err.message}`, true);
  864. }
  865. });
  866. el('th-auto-reconnect').addEventListener('change', async () => {
  867. try {
  868. await callThermalAction('set_prefs', { auto_reconnect: el('th-auto-reconnect').checked });
  869. } catch {}
  870. });
  871. el('btn-th-zero-probe').addEventListener('click', async () => {
  872. try {
  873. const res = await callThermalAction('zero_power_probe');
  874. setStatus(`零功率自检完成 (0W) · PID应答: ${res?.text || 'OK'}`);
  875. await pollConsole(true);
  876. } catch (err) {
  877. setStatus(`零功率自检失败: ${err.message}`, true);
  878. }
  879. });
  880. el('btn-th-estop').addEventListener('click', async () => {
  881. const ok = window.stlUi ? await window.stlUi.confirm('高温罩一键紧急全停', `确认立即停止工位 ${activeStationId} 的全部加热与控温输出(35 路归零 + 0x05 + 0x0A 锁死加热块)?`, '立即紧急全停', true) : true;
  882. if (!ok) return;
  883. try {
  884. await callThermalAction('emergency_stop');
  885. setStatus(`工位 ${activeStationId} 已执行紧急全停 (35路归零 + 0x05 + 0x0A)`);
  886. await pollConsole(true);
  887. } catch (err) {
  888. setStatus(`紧急全停异常: ${err.message}`, true);
  889. }
  890. });
  891. el('btn-th-save-safety').addEventListener('click', async () => {
  892. const leaseSec = Number(el('th-safety-lease').value) || 0;
  893. const cutoff = Number(el('th-overtemp-cutoff').value) || 95;
  894. try {
  895. await callThermalAction('configure_safety', { lease_sec: leaseSec, overtemp_cutoff_c: cutoff });
  896. setStatus(`安全护栏已更新:看门狗=${leaseSec > 0 ? leaseSec + '秒' : '不限时'},超温熔断=${cutoff}℃`);
  897. await pollConsole(true);
  898. } catch (err) {
  899. setStatus(`保存安全护栏失败: ${err.message}`, true);
  900. }
  901. });
  902. el('btn-th-renew-lease').addEventListener('click', async () => {
  903. try {
  904. const res = await callThermalAction('renew_lease');
  905. setStatus(`看门狗已续期重置 (${res?.lease_remaining_sec || 0} 秒)`);
  906. await pollConsole(true);
  907. } catch (err) {
  908. setStatus(`续期失败: ${err.message}`, true);
  909. }
  910. });
  911. document.querySelectorAll('.th-preset-btn').forEach(btn => {
  912. btn.addEventListener('click', () => {
  913. el('th-target-input').value = btn.dataset.temp;
  914. });
  915. });
  916. el('th-target-input').addEventListener('keydown', ev => {
  917. if (ev.key === 'Enter') {
  918. ev.preventDefault();
  919. el('btn-th-set-temp').click();
  920. }
  921. });
  922. el('btn-th-set-temp').addEventListener('click', async () => {
  923. const targetC = Math.round(Number(el('th-target-input').value));
  924. if (!Number.isFinite(targetC) || targetC < 0 || targetC > 254) {
  925. setStatus('目标温度必须为 0 ~ 254 之间的整数 ℃', true);
  926. return;
  927. }
  928. try {
  929. await callThermalAction('set_temp', {
  930. target_c: targetC,
  931. auto_pre_stop: el('th-chk-auto-prestop').checked,
  932. direct_pid: el('th-chk-direct-pid').checked,
  933. });
  934. setStatus(`工位 ${activeStationId} 已下发目标温度 ${targetC}℃ (0x01)`);
  935. await pollConsole(true);
  936. } catch (err) {
  937. setStatus(`设温失败: ${err.message}`, true);
  938. }
  939. });
  940. el('btn-th-skip-preheat').addEventListener('click', async () => {
  941. try {
  942. await callThermalAction('skip_preheat');
  943. setStatus('已下发跳过预加热进入 PID 指令 (0x06)');
  944. await pollConsole(true);
  945. } catch (err) {
  946. setStatus(`跳过预加热失败: ${err.message}`, true);
  947. }
  948. });
  949. el('btn-th-start-pid').addEventListener('click', async () => {
  950. try {
  951. await callThermalAction('start_pid');
  952. setStatus('已下发直接开启 PID 闭环指令 (0x07)');
  953. await pollConsole(true);
  954. } catch (err) {
  955. setStatus(`开启 PID 失败: ${err.message}`, true);
  956. }
  957. });
  958. el('btn-th-stop-preheat').addEventListener('click', async () => {
  959. try {
  960. await callThermalAction('stop_preheat');
  961. setStatus('已停止预加热与 PID 闭环,输出已清零 (0x05)');
  962. await pollConsole(true);
  963. } catch (err) {
  964. setStatus(`停止控温失败: ${err.message}`, true);
  965. }
  966. });
  967. el('btn-th-finish-purge').addEventListener('click', async () => {
  968. try {
  969. await callThermalAction('finish_control', { cooling_purge: true });
  970. setStatus('已结束控温并开启 8 路风扇 100% 吹扫散热 (0x08 00)');
  971. await pollConsole(true);
  972. } catch (err) {
  973. setStatus(`控温结束失败: ${err.message}`, true);
  974. }
  975. });
  976. el('btn-th-finish-keep').addEventListener('click', async () => {
  977. try {
  978. await callThermalAction('finish_control', { cooling_purge: false });
  979. setStatus('已结束控温且不吹扫 (0x08 01)');
  980. await pollConsole(true);
  981. } catch (err) {
  982. setStatus(`操作失败: ${err.message}`, true);
  983. }
  984. });
  985. el('btn-th-stop-heaters').addEventListener('click', async () => {
  986. try {
  987. await callThermalAction('stop_heaters');
  988. setStatus('已停并锁死全部 24 路加热块 (0x0A)');
  989. await pollConsole(true);
  990. } catch (err) {
  991. setStatus(`停加热块失败: ${err.message}`, true);
  992. }
  993. });
  994. el('btn-th-stop-fans').addEventListener('click', async () => {
  995. try {
  996. await callThermalAction('stop_fans');
  997. setStatus('已停并锁死全部 8 路风扇 (0x0B)');
  998. await pollConsole(true);
  999. } catch (err) {
  1000. setStatus(`停风扇失败: ${err.message}`, true);
  1001. }
  1002. });
  1003. el('btn-th-export-csv').addEventListener('click', () => {
  1004. const sid = activeStationId || 'S1';
  1005. const url = `/api/thermal/export.csv?station_id=${encodeURIComponent(sid)}`;
  1006. const a = document.createElement('a');
  1007. a.href = url;
  1008. a.download = `thermal_${sid}.csv`;
  1009. a.click();
  1010. setStatus(`已触发工位 ${sid} 模板格式 CSV 下载(34 列 UTF-8 BOM)`);
  1011. });
  1012. el('btn-th-clear-session').addEventListener('click', async () => {
  1013. try {
  1014. await callThermalAction('clear_session_samples');
  1015. chartByStation.set(activeStationId, []);
  1016. seqByStation.set(activeStationId, 0);
  1017. setStatus(`已清空工位 ${activeStationId} 当前会话曲线与导出缓存`);
  1018. await pollConsole(true);
  1019. } catch (err) {
  1020. setStatus(`清空失败: ${err.message}`, true);
  1021. }
  1022. });
  1023. el('btn-th-rec-start').addEventListener('click', async () => {
  1024. try {
  1025. const res = await callThermalAction('start_record', {
  1026. tag: el('th-rec-tag').value.trim(),
  1027. interval_ms: Number(el('th-rec-interval').value) || 1000,
  1028. auto_record_on_heat: el('th-rec-auto').checked,
  1029. });
  1030. setStatus(`开始录制模板格式 CSV: ${res?.csv_filename || ''}`);
  1031. await pollConsole(true);
  1032. } catch (err) {
  1033. setStatus(`开始录制失败: ${err.message}`, true);
  1034. }
  1035. });
  1036. el('btn-th-rec-stop').addEventListener('click', async () => {
  1037. try {
  1038. const res = await callThermalAction('stop_record');
  1039. setStatus(`已停止本地落盘: ${res?.csv_filename || ''} (共 ${res?.rows_written || 0} 行)`);
  1040. await pollConsole(true);
  1041. } catch (err) {
  1042. setStatus(`停止录制失败: ${err.message}`, true);
  1043. }
  1044. });
  1045. el('th-rec-auto').addEventListener('change', async () => {
  1046. try {
  1047. await callThermalAction('set_prefs', {
  1048. auto_record_on_heat: el('th-rec-auto').checked,
  1049. record_interval_ms: Number(el('th-rec-interval').value) || 1000,
  1050. });
  1051. } catch {}
  1052. });
  1053. el('th-rec-interval').addEventListener('change', async () => {
  1054. try {
  1055. await callThermalAction('set_prefs', {
  1056. auto_record_on_heat: el('th-rec-auto').checked,
  1057. record_interval_ms: Number(el('th-rec-interval').value) || 1000,
  1058. });
  1059. } catch {}
  1060. });
  1061. el('btn-th-add-mark').addEventListener('click', async () => {
  1062. const note = el('th-mark-note').value.trim();
  1063. if (!note) return;
  1064. try {
  1065. await callThermalAction('add_mark', { note });
  1066. el('th-mark-note').value = '';
  1067. setStatus(`已记录事件标记: ${note}`);
  1068. await pollConsole(true);
  1069. } catch (err) {
  1070. setStatus(`标记写入失败: ${err.message}`, true);
  1071. }
  1072. });
  1073. el('btn-th-pid-read').addEventListener('click', async () => {
  1074. try {
  1075. const res = await callThermalAction('pid_calibrate', { expr: '' });
  1076. setStatus(`当前 PID: ${res?.text || '--'}`);
  1077. await pollConsole(true);
  1078. } catch (err) {
  1079. setStatus(`读取 PID 失败: ${err.message}`, true);
  1080. }
  1081. });
  1082. el('btn-th-pid-write').addEventListener('click', async () => {
  1083. const expr = el('th-pid-expr').value.trim();
  1084. if (!expr) {
  1085. setStatus('请输入 PID 参数表达式(例如 P2.6I0.12D0.04)', true);
  1086. return;
  1087. }
  1088. try {
  1089. const res = await callThermalAction('pid_calibrate', { expr });
  1090. setStatus(`PID 标定成功: ${res?.text || 'OK'}`);
  1091. await pollConsole(true);
  1092. } catch (err) {
  1093. setStatus(`PID 标定失败: ${err.message}`, true);
  1094. }
  1095. });
  1096. el('btn-th-man-apply').addEventListener('click', async () => {
  1097. try {
  1098. await callThermalAction('manual_duty', {
  1099. ptc_all: Number(el('th-man-ptc').value) || 0,
  1100. fan_front_all: Number(el('th-man-fan-in').value) || 0,
  1101. fan_rear_all: Number(el('th-man-fan-out').value) || 0,
  1102. ssr_all: Number(el('th-man-ssr').value) || 0,
  1103. keepalive: el('th-man-keepalive').checked,
  1104. });
  1105. setStatus('已下发 35 路手动占空比测试帧 (0x46)');
  1106. await pollConsole(true);
  1107. } catch (err) {
  1108. setStatus(`手动出力失败: ${err.message}`, true);
  1109. }
  1110. });
  1111. el('btn-th-man-zero').addEventListener('click', async () => {
  1112. el('th-man-ptc').value = '0';
  1113. el('th-man-fan-in').value = '0';
  1114. el('th-man-fan-out').value = '0';
  1115. el('th-man-ssr').value = '0';
  1116. el('th-man-keepalive').checked = false;
  1117. try {
  1118. await callThermalAction('manual_duty', { ptc_all: 0, fan_front_all: 0, fan_rear_all: 0, ssr_all: 0, keepalive: false });
  1119. setStatus('已下发 35 路全部归零 (0x46)');
  1120. await pollConsole(true);
  1121. } catch (err) {
  1122. setStatus(`归零失败: ${err.message}`, true);
  1123. }
  1124. });
  1125. async function pollConsole(forceIncludeDebug = false) {
  1126. if (pollInFlight || document.hidden) return;
  1127. pollInFlight = true;
  1128. try {
  1129. const navSid = el('nav-station')?.value;
  1130. if (document.body.dataset.currentPage !== 'thermal' && navSid && navSid !== activeStationId) {
  1131. activeStationId = navSid;
  1132. syncedStationId = '';
  1133. }
  1134. const sid = activeStationId || navSid || 'S1';
  1135. const sinceSeq = seqByStation.get(sid) || 0;
  1136. const onThermalPage = document.body.dataset.currentPage === 'thermal';
  1137. const includeFrames = Boolean(forceIncludeDebug || (onThermalPage && el('th-debug-drawer')?.open));
  1138. const snap = await window.stlTransport.call('GetThermalConsole', {
  1139. station_id: sid,
  1140. since_seq: sinceSeq,
  1141. include_frames: includeFrames,
  1142. }, 8000);
  1143. if (snap) renderSnapshot(snap);
  1144. } catch {
  1145. // Strictly isolated: thermal transport errors never affect memory testing UI
  1146. } finally {
  1147. pollInFlight = false;
  1148. }
  1149. }
  1150. function resetPollTimer() {
  1151. if (pollTimer) clearInterval(pollTimer);
  1152. const cur = document.body.dataset.currentPage;
  1153. const ms = cur === 'thermal' ? 1000 : cur === 'connections' ? 1500 : 3500;
  1154. pollTimer = setInterval(() => pollConsole(false), ms);
  1155. }
  1156. window.addEventListener('stl:station-select', ev => {
  1157. const nextSid = ev.detail?.stationId;
  1158. if (nextSid && !ev.detail?.fromThermal) {
  1159. selectStationLocal(nextSid, false);
  1160. }
  1161. });
  1162. window.addEventListener('stl:page-change', ev => {
  1163. resetPollTimer();
  1164. const pg = ev.detail?.page;
  1165. if (pg === 'thermal' || pg === 'connections') {
  1166. const navSid = el('nav-station')?.value;
  1167. if (navSid && navSid !== activeStationId) {
  1168. activeStationId = navSid;
  1169. syncedStationId = '';
  1170. }
  1171. void scanPorts(true).then(() => {
  1172. if (lastSnapshot?.stations) renderBmcMappingTable(lastSnapshot.stations);
  1173. });
  1174. void pollConsole(false);
  1175. if (pg === 'thermal') scheduleChartDraw();
  1176. }
  1177. });
  1178. document.addEventListener('visibilitychange', () => {
  1179. if (!document.hidden) void pollConsole(false);
  1180. });
  1181. el('th-debug-drawer').addEventListener('toggle', () => {
  1182. if (el('th-debug-drawer').open) void pollConsole(true);
  1183. });
  1184. resetPollTimer();
  1185. setTimeout(() => {
  1186. void scanPorts(true);
  1187. void pollConsole(false);
  1188. }, 350);
  1189. })();