From b62c1725edd991b2e8371eef0af3cb4a2aa5e5f8 Mon Sep 17 00:00:00 2001 From: mmc <1556375442@qq.com> Date: Tue, 12 May 2026 08:48:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=98=BE=E7=A4=BA=E8=AE=BE=E5=A4=87=20?= =?UTF-8?q?=E7=BB=8F=E7=BA=AC=E5=BA=A6=E5=9C=B0=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/WebSocketManager.ts | 239 ++++++++++++++++++++ src/components/devices/DeviceStatusPage.tsx | 20 +- 2 files changed, 257 insertions(+), 2 deletions(-) create mode 100644 src/components/WebSocketManager.ts diff --git a/src/components/WebSocketManager.ts b/src/components/WebSocketManager.ts new file mode 100644 index 0000000..8b6805a --- /dev/null +++ b/src/components/WebSocketManager.ts @@ -0,0 +1,239 @@ +// src/utils/WebSocketManager.ts + +type WSStatus = 'disconnected' | 'connecting' | 'connected'; + +type MessageHandler = (data: any) => void; + +interface WSMessage { + type: string; + [key: string]: any; +} + +class WebSocketManager { + private static instance: WebSocketManager | null = null; + + private ws: WebSocket | null = null; + private status: WSStatus = 'disconnected'; + private messageHandlers: MessageHandler[] = []; + private reconnectTimer: NodeJS.Timeout | null = null; + private currentSerialRef: string | null = null; + private isManualCloseRef: boolean = false; + private wsSerialRef: string | null = null; + + // 状态监听器 + private statusListeners: ((status: WSStatus) => void)[] = []; + + // 🔒 私有构造函数,防止外部 new + private constructor() {} + + // 🎯 获取单例实例 + public static getInstance(): WebSocketManager { + if (!WebSocketManager.instance) { + WebSocketManager.instance = new WebSocketManager(); + } + return WebSocketManager.instance; + } + + // ==================== 状态管理 ==================== + + public getStatus(): WSStatus { + return this.status; + } + + public setStatus(status: WSStatus) { + this.status = status; + // 通知所有状态监听器 + this.statusListeners.forEach(listener => listener(status)); + } + + public onStatusChange(listener: (status: WSStatus) => void): () => void { + this.statusListeners.push(listener); + listener(this.status); + // 返回取消订阅函数 + return () => { + const index = this.statusListeners.indexOf(listener); + if (index > -1) { + this.statusListeners.splice(index, 1); + } + }; + } + + // ==================== 连接管理 ==================== + + public connect(serialNumber: string, wsUrl: string): void { + console.log("创建开始");//ws://192.168.2.56:9002/ws/ + // 清除之前的重连计时器 + if (this.reconnectTimer) { + clearTimeout(this.reconnectTimer); + this.reconnectTimer = null; + } + + // 如果序列号相同且已连接,跳过 + if (this.ws && this.currentSerialRef === serialNumber && this.status === 'connected') { + console.log('WebSocket already connected for this device'); + return; + } + + // 如果序列号不同,先关闭旧连接 + if (this.ws && this.currentSerialRef !== serialNumber) { + this.close(); + } + + this.currentSerialRef = serialNumber; + this.setStatus('connecting'); + this.isManualCloseRef = false; + + console.log('Connecting WebSocket for', serialNumber); + + + if (serialNumber == null || serialNumber.trim() === "") { + console.log("serialNumber 是空/空白,停止执行"); + return; + } + + this.ws = new WebSocket(wsUrl); + this.wsSerialRef = serialNumber; + + this.ws.onopen = () => { + console.log('WebSocket Connected'); + this.setStatus('connected'); + + + const dataStr = localStorage.getItem('userInfo'); + if(!dataStr){ + console.error('用户信息未找到,无法发送认证包'); + return; + } + let parse = JSON.parse(dataStr); + var token=parse?.token; + + console.log('WebSocket%',token); + console.log('WebSocket%',parse); + console.log("开始发送认证包");//ws://192.168.2.56:9002/ws/ + // 发送 AUTH 认证消息 + this.send({ + type: 'AUTH', + token: token, + userName: parse.username, + deviceId: serialNumber, + }); + + }; + + this.ws.onmessage = (event) => { + try { + const data = JSON.parse(event.data); + this.handleMessage(data); + } catch (e) { + console.error('WS message parse error', e); + } + }; + + this.ws.onerror = (err) => { + console.error('WebSocket error', err); + }; + + this.ws.onclose = (event) => { + const { code, reason, wasClean } = event; + console.log('[WebSocket closed]', 'code =', code, 'reason =', reason || '(no reason)', 'wasClean =', wasClean); + + // 如果不是当前设备的 ws,忽略 + if (this.wsSerialRef !== this.currentSerialRef) { + console.log('🟡 ignore old ws close'); + return; + } + + this.ws = null; + this.setStatus('disconnected'); + + // 主动关闭不重连 + if (this.isManualCloseRef || !this.currentSerialRef) { + return; + } + + // 5 秒后自动重连 + this.reconnectTimer = setTimeout(() => { + if (this.currentSerialRef === this.wsSerialRef) { + this.connect(this.currentSerialRef, wsUrl); + } + }, 5000); + }; + } + + // ==================== 断开连接 ==================== + + public close(): void { + this.isManualCloseRef = true; + + if (this.reconnectTimer) { + clearTimeout(this.reconnectTimer); + this.reconnectTimer = null; + } + + if (this.ws) { + console.log('Closing WebSocket'); + this.ws.close(); + this.ws = null; + } + + this.currentSerialRef = null; + this.wsSerialRef = null; + this.setStatus('disconnected'); + } + + // ==================== 消息发送 ==================== + + public send(data: WSMessage): boolean { + if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { + console.log('WebSocket not connected, cannot send message'); + return false; + } + console.log('WebSocket send message'); + this.ws.send(JSON.stringify(data)); + return true; + } + + // ==================== 消息接收 ==================== + + private handleMessage(data: WSMessage): void { + console.log('WS message received', data); + // 通知所有消息处理器 + this.messageHandlers.forEach(handler => handler(data)); + } + + public onMessage(handler: MessageHandler): () => void { + this.messageHandlers.push(handler); + // 返回取消订阅函数 + return () => { + const index = this.messageHandlers.indexOf(handler); + if (index > -1) { + this.messageHandlers.splice(index, 1); + } + }; + } + + // ==================== 工具方法 ==================== + + public getCurrentSerial(): string | null { + return this.currentSerialRef; + } + + public isConnected(): boolean { + return this.status === 'connected' && this.ws?.readyState === WebSocket.OPEN; + } + + // ==================== 销毁单例(测试用)==================== + + public static destroyInstance(): void { + if (WebSocketManager.instance) { + WebSocketManager.instance.close(); + WebSocketManager.instance = null; + } + } +} + +// 🎯 导出单例实例 +export const wsManager = WebSocketManager.getInstance(); + +// 导出类型 +export type { WSStatus, MessageHandler, WSMessage }; diff --git a/src/components/devices/DeviceStatusPage.tsx b/src/components/devices/DeviceStatusPage.tsx index 12ebe9c..98702a3 100644 --- a/src/components/devices/DeviceStatusPage.tsx +++ b/src/components/devices/DeviceStatusPage.tsx @@ -128,6 +128,23 @@ export default function DeviceStatusPage({ devicesAll, serialNumber, onDeviceCha return ; } + // 归一化地图显示的设备列表 + const mapDevices = useMemo(() => { + if (!device) return []; + // 确保地图组件能正确读取到经纬度 + const normalizedDevice = { + ...device, + lastRunningStatus: { + ...device.lastRunningStatus, + longitude: device.lastRunningStatus?.longitude || device.longitude, + latitude: device.lastRunningStatus?.latitude || device.latitude, + }, + name: device.deviceAlias || device.callsign || device.deviceName || '当前设备', + type: isUAV ? 'drone' : (device.productName?.includes('割草机') ? 'mower' : 'robot') + }; + return [normalizedDevice]; + }, [device, isUAV]); + return (
@@ -205,8 +222,7 @@ export default function DeviceStatusPage({ devicesAll, serialNumber, onDeviceCha style={{ borderRadius: 12 }} bodyStyle={{ padding: 12, height: 400 }} > - +