$(document).ready(function() { const topic_control = '/dev/control/hsv'; const topic_status = '/dev/status/hsv'; const topic_response = '/dev/response/hsv'; // ================== 控制面板相关 ================== // 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 connectWebSocket() { ws = new WebSocket(wsuri); ws.onopen = function() { showToast('已连接到WebSocket服务器'); ws.send(JSON.stringify({ action: 'subscribe', topic: topic_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_status)) { try { const value = typeof message === 'string' ? JSON.parse(message) : message; var iin = parseFloat(value.value.Iin); if (iin > 65) { iin = 0; } var vinState = parseFloat(value.value.Vin).toFixed(1) + 'V ' + parseFloat(iin).toFixed(2) + 'A'; $('#vinState').text(vinState) $('#hvState').text(value.value.hv == 'on' ? '高压已打开' : '高压已关闭'); $('#rayState').text(value.value.xray == 'on' ? '射线已打开' : '射线已关闭'); $('#feedbackVoltage').text(parseFloat(value.value.kV).toFixed(2)); $('#feedbackCurrent').text(parseFloat(value.value.mA).toFixed(2)); $('#filamentVoltage').text(parseFloat(value.value.fV).toFixed(3)); $('#filamentCurrent').text(parseFloat(value.value.fI).toFixed(3)); } catch (e) { showToast('解析消息失败: ' + e.message); } } else if (topic.startsWith(topic_response)) { try { const value = typeof message === 'string' ? JSON.parse(message) : message; if (value.command == 'get_params') { $('#setVoltage').val(parseFloat(value.value.kV).toFixed(2)); $('#setCurrent').val(parseFloat(value.value.mA).toFixed(2)); $('#filaPreheatCurrent').val(parseFloat(value.value.filament.preheat / 1000).toFixed(2)); $('#filaLimitCurrent').val(parseFloat(value.value.filament.limit / 1000).toFixed(2)); showToast('参数已更新'); } else if (value.command == 'get_var') { // 处理变量配置响应 if (varEditor) { try { const varData = JSON.stringify(value.value, null, 2); varEditor.value = varData; showToast('变量配置已加载'); } catch (e) { showToast('解析变量配置失败:' + e.message); } } } else { showToast('请求已发送'); } } catch (e) { showToast('解析消息失败: ' + e.message); } } } }; ws.onerror = function() { showToast('WebSocket连接错误'); }; ws.onclose = function() { showToast('WebSocket连接已关闭,正在尝试重连...'); // 仅在没有活跃定时器时创建新的重连定时器 if (!reconnectTimer) { reconnectTimer = setTimeout(connectWebSocket, 5000); } }; return ws; } // 初始连接 connectWebSocket(); // 定期检查连接状态(每10秒) setInterval(function() { if (!ws || ws.readyState === WebSocket.CLOSED) { showToast('定期检查发现连接已关闭,尝试重连...'); if (!reconnectTimer) { reconnectTimer = setTimeout(connectWebSocket, 5000); } } }, 10000); // 替换 client.publish 为 ws.send function wsPublish(topic, msg) { ws.send(JSON.stringify({ action: 'publish', topic: topic, message: msg })); } // 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(); } $('#setParams').click(function() { const setVoltage = parseFloat($('#setVoltage').val()); const setCurrent = parseFloat($('#setCurrent').val()); const filaPreheatCurrent = parseFloat($('#filaPreheatCurrent').val()) * 1000; const filaLimitCurrent = parseFloat($('#filaLimitCurrent').val()) * 1000; var msg = { device_id: '2', device_code: '2#HVS', command: 'set_params', value: { kV: setVoltage, mA: setCurrent, filament : { preheat: filaPreheatCurrent, limit: filaLimitCurrent } } } wsPublish(topic_control, msg); showToast('请求已发送!'); }); $('#getParams').click(function() { var msg = { device_id: '1', device_code: '2#HVS', command: 'get_params' } wsPublish(topic_control, msg); showToast('请求已发送!'); }); $('#hvEnable').click(function() { var msg = { device_id: '1', device_code: '1#HVS', command: 'hv_control', value: 'on' } wsPublish(topic_control, msg); showToast('请求已发送!'); }); $('#hvDisable').click(function() { var msg = { device_id: '1', device_code: '1#HVS', command: 'hv_control', value: 'off' } wsPublish(topic_control, msg); showToast('请求已发送!'); }); $('#rayEnable').click(function() { var msg = { device_id: '1', device_code: '1#HVS', command: 'ray_control', value: 'on' } wsPublish(topic_control, msg); showToast('请求已发送!'); }); $('#rayDisable').click(function() { var msg = { device_id: '1', device_code: '1#HVS', command: 'ray_control', value: 'off' } 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('请求失败:服务器错误'); } }); }); $('#hv_service_start').click(function() { $.ajax({ url: '/api/hv_service/start', type: 'GET', success: function(response) { if (response.success) { showToast('请求已发送'); } else { showToast('请求失败:' + response.message); } }, error: function(jqXHR, textStatus, errorThrown) { showToast('请求失败:服务器错误'); } }); }); $('#hv_service_stop').click(function() { $.ajax({ url: '/api/hv_service/stop', 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; // ================== 变量设置相关 ================== let varTabInited = false; let varEditor = 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) { $.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); $('#currentFile').text(path); $('#saveFile, #deleteFile').prop('disabled', false); } else { showToast('加载文件失败:' + response.message); } }).fail(function(jqXHR, textStatus, errorThrown) { showToast('加载文件失败:服务器错误'); }); } // 保存文件 $('#saveFile').click(function() { const path = $('#currentFile').text(); // 使用js-base64库编码 const content = Base64.encode(editor.getValue()); $.ajax({ url: '/api/script/write', type: 'POST', contentType: 'application/json', data: JSON.stringify({ path: path, content: content }), success: function(response) { if (response.success) { showToast('文件保存成功'); } else { showToast('保存文件失败:' + response.message); } }, error: function(jqXHR, textStatus, errorThrown) { showToast('保存文件失败:服务器错误'); } }); }); // 删除文件 $('#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; } if (target === '#var' && !varTabInited) { // 初始化变量设置标签页 varEditor = document.getElementById('varEditor'); // 设置初始提示文本 varEditor.value = "点击'读取变量'按钮来加载当前变量配置..."; // 绑定读取变量按钮事件 $('#getVar').click(function() { var msg = { device_id: '1', device_code: '1#HVS', command: 'get_var' } wsPublish(topic_control, msg); showToast('正在读取变量配置...'); }); // 绑定保存变量按钮事件 $('#setVar').click(function() { try { // 验证JSON格式 const varContent = varEditor.value.trim(); if (!varContent) { showToast('请输入变量配置内容'); return; } // 尝试解析JSON const varData = JSON.parse(varContent); var msg = { device_id: '1', device_code: '1#HVS', command: 'set_var', value: varData } wsPublish(topic_control, msg); showToast('正在保存变量配置...'); } catch (e) { showToast('JSON格式错误:' + e.message); } }); varTabInited = true; } }); });