// websocket.js - WebSocket通信模块 const WebSocketManager = (function() { // DAQ相关的topic const topic_daq_control = '/dev/daq/control'; const topic_daq_data = '/dev/daq/data'; const topic_daq_status = '/dev/daq/status'; // WebSocket客户端配置 const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsHost = location.hostname + (location.port ? ':' + location.port : ''); const wsuri = wsProtocol + '//' + wsHost + '/ws'; console.log('WebSocket连接URL:', wsuri); let ws; let reconnectTimer; let status_str = ''; // 初始化WebSocket连接 function init() { connectWebSocket(); // 定期检查连接状态(每10秒) setInterval(monitorConnection, 10000); // 页面关闭前关闭WebSocket连接 $(window).on('beforeunload', function() { if (ws) { ws.close(); } }); } // 建立WebSocket连接 function connectWebSocket() { console.log('WebSocket URI:', wsuri); ws = new WebSocket(wsuri); ws.onopen = function() { showToast('已连接到WebSocket服务器'); // 订阅DAQ相关的主题 ws.send(JSON.stringify({ action: 'subscribe', topic: topic_daq_status })); ws.send(JSON.stringify({ action: 'subscribe', topic: topic_daq_data })); // 清除重连定时器 if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; } }; ws.onmessage = function(event) { handleMessage(event); }; ws.onerror = function(error) { console.error('WebSocket错误:', error); showToast('WebSocket连接错误: ' + (error.message || '未知错误')); }; ws.onclose = function(event) { console.log('WebSocket关闭原因:', event.code, event.reason); showToast('WebSocket连接已关闭,正在尝试重连... 代码: ' + event.code + ', 原因: ' + event.reason); // 仅在没有活跃定时器时创建新的重连定时器 if (!reconnectTimer) { reconnectTimer = setTimeout(connectWebSocket, 5000); } }; return ws; } // 处理WebSocket消息 function handleMessage(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_daq_data)) { try { const daqData = typeof message === 'string' ? JSON.parse(message) : message; // 处理DAQ数据 if (window.handleDaqData) { window.handleDaqData(daqData); } } catch (e) { showToast('解析DAQ数据失败: ' + e.message); } } else if (topic.startsWith(topic_daq_status)) { try { const daqStatus = typeof message === 'string' ? JSON.parse(message) : message; // 更新DAQ状态 updateDaqStatus(daqStatus); } catch (e) { showToast('解析DAQ状态消息失败: ' + e.message); } } } } // 更新DAQ状态 function updateDaqStatus(daqStatus) { status_str = ''; if (!daqStatus.online) { status_str += '采集板通讯异常'; } else { if (daqStatus.run) { status_str += '采集中 '; } else { status_str += '停止采集 '; } if (daqStatus.temp) { daqStatus.temp = daqStatus.temp / 10.0; status_str += '温度:' + daqStatus.temp.toFixed(1) + '℃ '; } if (daqStatus.info) { $('#daq_info').text(daqStatus.info.date + '-' + daqStatus.info.sn); if (daqStatus.info.version) { $('#currentVersion').text(daqStatus.info.version); } } } $('#daq_status').text(status_str || '--'); } // 监控连接状态 function monitorConnection() { if (!ws || ws.readyState === WebSocket.CLOSED) { showToast('定期检查发现连接已关闭,尝试重连...'); if (!reconnectTimer) { reconnectTimer = setTimeout(connectWebSocket, 5000); } } } // 发布消息到WebSocket function wsPublish(topic, msg) { if (ws && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ action: 'publish', topic: topic, message: msg })); } else { showToast('WebSocket连接未建立,无法发送消息'); } } // 获取当前WebSocket连接 function getWebSocket() { return ws; } // 暴露公共方法 return { init: init, publish: wsPublish, getWebSocket: getWebSocket, topic_daq_control: topic_daq_control, topic_daq_data: topic_daq_data, topic_daq_status: topic_daq_status }; })();