$(document).ready(function() { const topic_control = '/dev/control'; const topic_status = '/dev/status'; const topic_response = '/dev/response'; const topic_scanner_status = '/dev/status/scanner'; // 扫描器状态英文到中文的映射 const scannerStateMap = { 'stop': '停止', 'moving_up': '向上扫描', 'moving_down': '向下扫描', 'stop_at_upper': '顶部', 'stop_at_bottom': '底部', 'stop_at_origin': '原点' }; // Toast初始化 const toastEl = document.getElementById('toast'); const toast = new bootstrap.Toast(toastEl, { autohide: true, delay: 3000 }); function showToast(message) { $('.toast-body').text(message); toast.show(); } // ================== 控制面板相关 ================== // WebSocket客户端配置 const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsHost = location.hostname + (location.port ? ':' + location.port : ''); const wsuri = wsProtocol + '//' + wsHost + '/ws'; console.log('WebSocket URI:', wsuri); // 创建WebSocket连接 let ws; let reconnectTimer; function msToReadable(ms) { // 严格校验输入:必须是整数且非负 if (!Number.isInteger(ms) || ms < 0) { return "--"; } // 定义时间单位换算(毫秒) const SECOND = 1000; const MINUTE = 60 * SECOND; const HOUR = 60 * MINUTE; const DAY = 24 * HOUR; // 计算各时间单位的数值 let days = Math.floor(ms / DAY); let remaining = ms % DAY; let hours = Math.floor(remaining / HOUR); remaining %= HOUR; let minutes = Math.floor(remaining / MINUTE); remaining %= MINUTE; let seconds = Math.floor(remaining / SECOND); // 构建结果数组(只保留非零单位) const parts = []; if (days > 0) parts.push(`${days}天`); if (hours > 0) parts.push(`${hours}时`); if (minutes > 0) parts.push(`${minutes}分`); // 若前面无内容,至少显示秒(包括0秒) if (seconds > 0 || parts.length === 0) parts.push(`${seconds}秒`); // 拼接成最终字符串 return parts.join(""); } // 替换 client.publish 为 ws.send function wsPublish(topic, msg) { ws.send(JSON.stringify({ action: 'publish', topic: topic, message: msg })); } function connectWebSocket() { ws = new WebSocket(wsuri); ws.onopen = function() { showToast('已连接到WebSocket服务器'); ws.send(JSON.stringify({ action: 'subscribe', topic: topic_status })); ws.send(JSON.stringify({ action: 'subscribe', topic: topic_scanner_status })); // 清除重连定时器 if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; } }; ws.onmessage = function(event) { let data; try { data = JSON.parse(event.data); } catch (e) { showToast('解析消息失败: ' + e.message); return; } const topic = data.topic; const message = data.message; if (topic && message) { if (topic.startsWith(topic_response)) { } else if (topic.startsWith(topic_scanner_status)) { try { const scannerData = typeof message === 'string' ? JSON.parse(message) : message; // 更新扫描器状态数据 $('#scannerId').text(scannerData.id || '--'); $('#runTime').text(msToReadable(scannerData.run_time)); // 将英文状态映射为中文 const chineseState = scannerStateMap[scannerData.state] || scannerData.state || '--'; var run_flag = "" if (scannerData.run_flag == true) { run_flag = " 扫描中"; } else if (scannerData.run_flag == false) { run_flag = " 停止扫描"; } $('#scannerState').text(chineseState + run_flag); $('#scannerPos').text(scannerData.pos ? scannerData.pos.toFixed(2) + ' mm' : '--'); $('#scannerSpeed').text(scannerData.speed !== undefined ? scannerData.speed.toFixed(4) : '--'); $('#scannerUpperAndLowerPos').text(scannerData.upper_pos ? scannerData.upper_pos.toFixed(2) + '<-->' + scannerData.bottom_pos.toFixed(2) : '--'); $('#scannerScanRange').text(scannerData.scan_range ? scannerData.scan_range.toFixed(2) + ' mm' : '--'); daq_state = scannerData.daq_online ? '在线' : '离线'; daq_temp = scannerData.daq_temp / 10.0; daq_state += scannerData.daq_online ? ` 温度: ${daq_temp.toFixed(1)}°C` : ''; $('#daqState').text(daq_state); } catch (e) { showToast('解析扫描器状态消息失败: ' + e.message); } } } }; ws.onerror = function() { showToast('WebSocket连接错误'); }; ws.onclose = function() { showToast('WebSocket连接已关闭,正在尝试重连...'); // 仅在没有活跃定时器时创建新的重连定时器 if (!reconnectTimer) { reconnectTimer = setTimeout(connectWebSocket, 5000); } }; return ws; } // 初始连接 connectWebSocket(); setInterval(function() { if (ws && ws.readyState === WebSocket.OPEN) { wsPublish(topic_control, {cmd: 'status'}); } }, 500); $('#start_scan').click(function() { var msg = { cmd: 'start' } wsPublish(topic_control, msg); showToast('请求已发送!'); }); $('#stop_scan').click(function() { var msg = { cmd: 'stop' } wsPublish(topic_control, msg); showToast('请求已发送!'); }); $('#reset_scan').click(function() { var msg = { cmd: 'reset' } wsPublish(topic_control, msg); showToast('请求已发送!'); }); $('#emer_stop').click(function() { var msg = { cmd: 'emer_stop' } wsPublish(topic_control, msg); showToast('紧急停止请求已发送!'); }); $('#reboot').click(function() { $.ajax({ url: '/api/device/reboot', type: 'GET', success: function(response) { if (response.success) { showToast('请求已发送'); } else { showToast('请求失败:' + response.message); } }, error: function(jqXHR, textStatus, errorThrown) { showToast('请求失败:服务器错误'); } }); }); $(window).on('beforeunload', function() { ws.close(); }); // ================== 脚本编辑器相关 ================== let scriptTabInited = false; let editor = null; $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) { console.log('tab shown', e); const target = $(e.target).attr('data-bs-target'); if (target === '#script' && !scriptTabInited) { // 初始化CodeMirror editor = CodeMirror.fromTextArea(document.getElementById('editor'), { mode: 'text/x-python', theme: 'monokai', lineNumbers: true, indentUnit: 4, lineWrapping: true, matchBrackets: true, autoCloseBrackets: true }); editor.setValue("请选择一个文件"); // 初始化文件树 $('#fileTree').jstree({ 'core': { 'data': { 'url': function(node) { const url = node.id === '#' ? '/api/script/list' : '/api/script/list?path=' + node.id; return url; }, 'data': function(node) { return { 'id': node.id }; }, 'dataFilter': function(data) { var json = {}; try { json = JSON.parse(data); } catch (e) { return "[]"; } if (json.success && Array.isArray(json.data)) { return JSON.stringify(json.data); } return "[]"; }, 'error': function(jqXHR, textStatus, errorThrown) { showToast('加载文件列表失败:' + textStatus); } }, 'themes': { 'name': 'default', 'responsive': true }, 'check_callback': true, 'multiple': false }, 'types': { 'default': { 'icon': 'bi bi-file-text' }, 'folder': { 'icon': 'bi bi-folder' }, 'python': { 'icon': 'bi bi-filetype-py' }, 'json': { 'icon': 'bi bi-filetype-json' }, 'shell': { 'icon': 'bi bi-filetype-sh' } }, 'plugins': ['types'] }).on('ready.jstree', function() { // 文件树初始化完成 }); // 文件树节点点击事件 $('#fileTree').on('select_node.jstree', function(e, data) { const node = data.node; if (node.original.type != 'folder') { loadFile(node.id); } }); // 加载文件内容 - 分段读取 function loadFile(path) { // 先清空编辑器 editor.setValue(""); $('#currentFile').text(path); showToast('正在加载文件...'); // 首先获取文件信息 $.get('/api/script/info?path=' + encodeURIComponent(path), function(infoResponse) { if (infoResponse.success) { const fileSize = infoResponse.size; const chunkSize = 4096; // 4K 分段 let totalChunks = Math.ceil(fileSize / chunkSize); let loadedChunks = 0; let fileContent = ''; // 显示加载进度 let progressToast = showToast('正在加载文件... (0%)'); // 分段读取函数 function readChunk(offset) { if (offset >= fileSize) { // 所有分块读取完成 const ext = path.split('.').pop().toLowerCase(); switch(ext) { case 'py': editor.setOption('mode', 'text/x-python'); break; case 'json': editor.setOption('mode', 'application/json'); break; case 'sh': editor.setOption('mode', 'text/x-sh'); break; case 'html': editor.setOption('mode', 'text/html'); break; case 'js': editor.setOption('mode', 'javascript'); break; case 'css': editor.setOption('mode', 'css'); break; default: editor.setOption('mode', 'text/plain'); } editor.setValue(fileContent); $('#saveFile, #deleteFile').prop('disabled', false); showToast('文件加载成功'); return; } $.get('/api/script/read?path=' + encodeURIComponent(path) + '&offset=' + offset + '&size=' + chunkSize, function(response) { if (response.success) { // 使用js-base64库解码 const chunkContent = Base64.decode(response.data); fileContent += chunkContent; loadedChunks++; // 更新进度 const progress = Math.min(100, Math.round((loadedChunks / totalChunks) * 100)); showToast('正在加载文件... (' + progress + '%)'); // 继续读取下一个分块 setTimeout(function() { readChunk(response.offset + response.size); }, 10); // 短暂延迟,避免请求过于密集 } else { showToast('加载文件失败:' + response.message); } }).fail(function(jqXHR, textStatus, errorThrown) { showToast('加载文件失败:服务器错误'); }); } // 开始读取第一个分块 readChunk(0); } else { // 如果获取文件信息失败,尝试使用旧的一次性读取方式作为降级方案 $.get('/api/script/read?path=' + encodeURIComponent(path), function(response) { if (response.success) { // 使用js-base64库解码 const content = Base64.decode(response.data); const ext = path.split('.').pop().toLowerCase(); switch(ext) { case 'py': editor.setOption('mode', 'text/x-python'); break; case 'json': editor.setOption('mode', 'application/json'); break; case 'sh': editor.setOption('mode', 'text/x-sh'); break; case 'html': editor.setOption('mode', 'text/html'); break; case 'js': editor.setOption('mode', 'javascript'); break; case 'css': editor.setOption('mode', 'css'); break; default: editor.setOption('mode', 'text/plain'); } editor.setValue(content); $('#saveFile, #deleteFile').prop('disabled', false); showToast('文件加载成功'); } else { showToast('加载文件失败:' + response.message); } }).fail(function(jqXHR, textStatus, errorThrown) { showToast('加载文件失败:服务器错误'); }); } }).fail(function() { // 如果获取文件信息接口失败,尝试使用旧的一次性读取方式 $.get('/api/script/read?path=' + encodeURIComponent(path), function(response) { if (response.success) { const content = Base64.decode(response.data); const ext = path.split('.').pop().toLowerCase(); switch(ext) { case 'py': editor.setOption('mode', 'text/x-python'); break; case 'json': editor.setOption('mode', 'application/json'); break; case 'sh': editor.setOption('mode', 'text/x-sh'); break; case 'html': editor.setOption('mode', 'text/html'); break; case 'js': editor.setOption('mode', 'javascript'); break; case 'css': editor.setOption('mode', 'css'); break; default: editor.setOption('mode', 'text/plain'); } editor.setValue(content); $('#saveFile, #deleteFile').prop('disabled', false); showToast('文件加载成功'); } else { showToast('加载文件失败:' + response.message); } }).fail(function() { showToast('加载文件失败:服务器错误'); }); }); } // 保存文件 - 分段写入 $('#saveFile').click(function() { const path = $('#currentFile').text(); const fullContent = editor.getValue(); const chunkSize = 4096; // 4K 分段(字节数) let currentChunk = 0; let currentByteOffset = 0; showToast('正在保存文件...'); // 使用TextEncoder API进行更高效的UTF-8字节处理 const encoder = new TextEncoder(); const decoder = new TextDecoder('utf-8'); // 基于字节数的字符串截取函数 - 优化版本 function substrBytes(str, startByte, lengthBytes) { console.time('substrBytes_optimized'); // 将整个字符串编码为Uint8Array以获取字节数据 const bytes = encoder.encode(str); // 确保截取范围在有效范围内 const endByte = Math.min(startByte + lengthBytes, bytes.length); // 截取指定范围的字节 const chunkBytes = bytes.subarray(startByte, endByte); // 将截取的字节解码回字符串 const result = decoder.decode(chunkBytes); console.timeEnd('substrBytes_optimized'); return result; } // 计算字符串的UTF-8字节长度 - 优化版本 function getByteLength(str) { console.time('getByteLength_optimized'); const length = encoder.encode(str).length; console.timeEnd('getByteLength_optimized'); return length; } // 分段写入函数 function writeChunk(byteOffset) { console.time('writeChunk'); console.log('开始处理分块,字节偏移量:', byteOffset); const totalBytes = getByteLength(fullContent); if (byteOffset >= totalBytes) { // 所有分块写入完成,请求服务器进行最终校验和重命名 $.ajax({ url: '/api/script/write/finalize', type: 'POST', contentType: 'application/json', data: JSON.stringify({ path: path, total_size: totalBytes }), success: function(response) { if (response.success) { showToast('文件保存成功'); } else { showToast('文件保存成功,但最终校验失败:' + response.message); console.warn('文件校验失败,但内容可能已保存:', response.message); } }, error: function() { // 即使最终校验请求失败,我们仍然告知用户文件已保存 // 因为分块已经写入,只是可能没有进行最后的重命名和校验 showToast('文件内容已保存,但最终处理请求失败'); console.warn('最终处理请求失败'); } }); return; } // 获取当前分块内容(按字节数截取) const chunkContent = substrBytes(fullContent, byteOffset, chunkSize); // 使用js-base64库编码 console.time('Base64_encode'); const encodedContent = Base64.encode(chunkContent); console.timeEnd('Base64_encode'); console.time('calculateNextOffset'); const nextByteOffset = byteOffset + getByteLength(chunkContent); const isFinal = nextByteOffset >= totalBytes; console.timeEnd('calculateNextOffset'); // 更新进度 currentChunk++; // 重新计算总块数(基于字节数) const totalByteChunks = Math.ceil(totalBytes / chunkSize); const progress = Math.min(100, Math.round((currentChunk / totalByteChunks) * 100)); showToast('正在保存文件... (' + progress + '%)'); console.time('prepareAjaxRequest'); const ajaxData = JSON.stringify({ path: path, content: encodedContent, offset: byteOffset, final: isFinal }); console.timeEnd('prepareAjaxRequest'); console.time('ajaxRequest'); $.ajax({ url: '/api/script/write', type: 'POST', contentType: 'application/json', data: ajaxData, success: function(response) { console.timeEnd('ajaxRequest'); if (response.success) { // 继续写入下一个分块 console.log('分块处理完成,准备处理下一个分块,响应偏移量:', response.offset); setTimeout(function() { writeChunk(response.offset); }, 10); // 短暂延迟,避免请求过于密集 } else { showToast('保存文件失败:' + response.message); } }, error: function(jqXHR, textStatus, errorThrown) { console.timeEnd('ajaxRequest'); console.log('分段写入失败:', textStatus, errorThrown); showToast('保存文件失败:网络错误'); // 如果分段写入失败,尝试使用旧的一次性写入方式作为降级方案 console.log('分段写入失败,尝试一次性写入'); const fullEncodedContent = Base64.encode(fullContent); $.ajax({ url: '/api/script/write', type: 'POST', contentType: 'application/json', data: JSON.stringify({ path: path, content: fullEncodedContent }), success: function(backupResponse) { if (backupResponse.success) { showToast('文件保存成功'); } else { showToast('保存文件失败:' + backupResponse.message); } }, error: function() { showToast('保存文件失败:服务器错误'); } }); } }); console.timeEnd('writeChunk'); } // 开始写入第一个分块 writeChunk(currentByteOffset); }); // 删除文件 $('#deleteFile').click(function() { if (confirm('确定要删除这个文件吗?')) { const path = $('#currentFile').text(); $.ajax({ url: '/api/script/delete', type: 'POST', contentType: 'application/json', data: JSON.stringify({ path: path }), success: function(response) { if (response.success) { showToast('文件删除成功'); $('#currentFile').text('未选择文件'); editor.setValue(''); $('#saveFile, #deleteFile').prop('disabled', true); $('#fileTree').jstree('refresh'); } else { showToast('删除文件失败:' + response.message); } }, error: function(jqXHR, textStatus, errorThrown) { showToast('删除文件失败:服务器错误'); } }); } }); // 刷新文件树 $('#refreshTree').click(function() { console.log('刷新文件树'); $('#fileTree').jstree('refresh'); }); scriptTabInited = true; } }); });