import { Message } from 'element-ui'; // 定义 WebSocket 和扫描客户端的通信模块 const scanCommon = { // 扫描客户端WebSocket 服务器地址 url: 'ws://127.0.0.1:9999',//扫描端口9999 图片服务端口9998 // WebSocket 实例 ws: null, // 当前客户端连接状态 isOnline:false, isScanned:false,//是否有扫描仪 是否可以扫描 // 心跳定时器 timerPing: null, timerClose: null, connectionInterval:null,//监听连接状态变化的定时器 // 心跳间隔时间(单位:毫秒) intervalPing: 10000, // 每隔10秒发送一次ping intervalClose: 5000, // 等待5秒未收到pong则判定断开 isManuallyStopped:false,//是否手动停止,防止重复连接 /** * 初始化 WebSocket 连接 * @param {Function} callback - 接收扫描结果的回调函数 */ init(callback) { // Message({ // type: 'success', // message: '扫描程序正在启动,请稍后……' // }); try { this.ws = new WebSocket(this.url); } catch (error) { // console.error('WebSocket 初始化失败:', error); Message({ type: 'error', message: '无法初始化 WebSocket 连接,请检查网络设置', duration: 5000 }); // if (callback) callback({ success: false, message: 'WebSocket 初始化失败' }); return; } /** * WebSocket 连接建立成功时触发 */ this.ws.onopen = () => { this.isOnline = true; // 添加状态检查 if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send("client connect success"); } else { // console.warn('WebSocket 尚未就绪,延迟发送消息'); setTimeout(() => { if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send("client connect success"); } }, 500); // 延迟发送,等待连接真正建立 } this.startHeartbeat(); // 启动心跳检测 }; /** * 接收到服务端消息时触发 * @param {MessageEvent} evt - WebSocket 返回的消息事件对象 */ this.ws.onmessage = (evt) => { // console.log("打印扫描仪返回的 evt:", evt.data); if(evt.data!=null) { if (evt.data === "ping") { this.send("pong"); // 回复 pong } else if (evt.data === "pong") { // 收到 pong 不做处理 } else { // try { const objectData = JSON.parse(evt.data); console.log("处理扫描结果的objectData:", objectData); if(objectData!=null) { if (objectData.code === 200) { if(objectData.action=='connectMessage') { Message({ type: 'success', message: '客户端连接成功……' }); } else if(objectData.action=='getScannerList') { //获取扫描仪结果 // console.log("打印扫描仪返回的 objectData:", objectData); if(objectData.data.length>0) { //有扫描仪连接 this.isScanned=true; Message({ type: 'success', message: '扫描仪连接成功……' }); } else { //没有扫描仪连接 this.isScanned=false; } } else { callback(objectData); // 可选:通过回调函数返回扫描结果 } } else if (objectData.code === 509) { // Message({ // type: 'error', // message: '扫描仪未连接,请检查网络设置' // }); callback(objectData); // 可选:通过回调函数返回扫描结果 } else if (objectData.code === 502) { // Message({ // type: 'error', // message: '未检测到纸张或卡纸' // }); callback(objectData); // 可选:通过回调函数返回扫描结果 // this.ws.close(); // 关闭链接 } } // } catch (error) { // console.error("解析消息失败:", error); // } } } this.resetHeartbeat(); // 重置心跳 }; /** * WebSocket 连接关闭时触发 */ this.ws.onclose = () => { // console.log("连接关闭"); // if(callback) callback({success: false, message: '客户端已关闭!'}) this.handleOffline(); }; /** * WebSocket 发生错误时触发 * @param {Event} evt - 错误事件对象 */ this.ws.onerror = (evt) => { // console.error("WebSocket 错误:", evt); // Message({ // type: 'error', // message: 'WebSocket 发生错误,请检查扫描仪是否运行正常' // }); // if(callback) callback({success: false, message: '客户端未启动!'}) // console.log("扫描客户端未启动"); this.isOnline=false; this.ws.close(); }; }, /** * 发送消息给 WebSocket 服务端 * @param {string} data - 要发送的消息内容 */ send(data) { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { // Message({ // type: 'error', // message: '请确认扫描客户端是否已经启动', // duration: 5000 // }); return; } try { // console.log("发送数据:" + data); this.ws.send(data); } catch (e) { // console.error("发送数据失败:", e); Message({ type: 'error', message: '发送数据失败,请检查连接状态', duration: 5000 }); } }, /** * 启动心跳机制 */ startHeartbeat() { this.timerPing = setTimeout(() => { if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.send("ping"); // 发送心跳 ping this.timerClose = setTimeout(() => { if (this.ws) { this.ws.close(); // 若长时间无响应,主动断开连接 } this.isOnline = false; this.handleOffline(); // 处理离线逻辑 }, this.intervalClose); } }, this.intervalPing); }, /** * 重置心跳定时器 */ resetHeartbeat() { clearTimeout(this.timerPing); clearTimeout(this.timerClose); this.startHeartbeat(); // 重新启动心跳 }, /** * 停止 WebSocket 连接并清除所有定时器 */ stop() { // 清除心跳定时器 clearTimeout(this.timerPing); clearTimeout(this.timerClose); // 清除连接状态监听定时器 this.stopWatchingConnection(); // 关闭 WebSocket 连接 if (this.ws) { this.ws.onclose = () => {}; // 移除原有 onclose 处理 this.ws.close(); // 主动关闭连接 this.ws = null; } // 标记为手动停止,防止后续自动重连 this.isManuallyStopped = true; // 重置连接状态 this.isOnline = false; // console.log('WebSocket 已被手动停止'); }, /** * 处理设备离线逻辑,尝试自动重连 */ handleOffline() { // 如果是手动停止,则不再尝试重连 if (this.isManuallyStopped) { return; } // console.log("客户端未开启,尝试重新连接..."); // Message({ // type: 'warning', // message: '扫描仪已断开连接,尝试重新连接...', // duration: 3000 // }); // console.log("当前连接状态",this.isOnline); this.isOnline=false; // 延迟尝试重连 setTimeout(() => { if (!this.isOnline && !this.isManuallyStopped) { this.init(); // 重新初始化连接 } }, this.intervalClose * 2); }, /** * 检查客户端是否已连接 * @returns {boolean} */ isClientConnected() { return this.ws && this.ws.readyState === WebSocket.OPEN; }, /** * 监听连接状态变化 * @param {Function} callback - 回调函数,接收 isOnline 布尔值参数 */ watchConnection(callback) { if (this.connectionInterval) { clearInterval(this.connectionInterval); // 防止重复启动 } const checkStatus = () => { const isOnline = this.isClientConnected(); //调用检测扫描仪指令 if(isOnline) { // console.log("开始检测扫描仪状态",this.isScanned); // console.log("开始检查客户端状态",isOnline); if(this.isScanned) { //有扫描仪连接 就不发送指令了 } else { //没有扫描仪连接 实时发送指令获取状态 let json={ action:'getScannerList',//获取扫描仪信息 }; // console.log("发送指令获取扫描仪信息",json); this.ws.send(JSON.stringify(json)); } callback(isOnline);//告诉网页 客户端打开状态 } else { callback(false);//告诉网页 连接已经断开 } }; checkStatus(); // 立即执行一次 this.connectionInterval = setInterval(checkStatus, 3000); // 每3秒检测一次 }, /** * 停止监听连接状态 */ stopWatchingConnection() { if (this.connectionInterval) { clearInterval(this.connectionInterval); this.connectionInterval = null; } } }; export default scanCommon;