forked from drone/command-center-dashboard

罗广辉
2025-04-21 2800fa4f32f3900509cb4d6eefaf2bfaf54efdd7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { getWebsocketUrl } from '@/websocket/util/config'
import { useConnectWebSocket } from '@/utils/websocket/connect-websocket'
 
/**
 * 使用无人机WebSocket连接,根据工作区ID动态管理WebSocket连接。
 *
 * @param {Ref<string>} workspaceIdRef - 工作区ID的引用,用于动态更新WebSocket连接。
 * @returns  {Object} - 包含wsInfo和removeWS的响应式对象。
 */
export const useDroneWS = workspaceIdRef => {
    const wsInfo = ref({})
    let droneWebSocket = null
 
    // ws消息钩子 todo后面加节流参数处理
    const messageHandler = result => {
        let payload = JSON.parse(result)
        if (payload.biz_code) {
            wsInfo.value[payload.biz_code] = payload
        }
    }
 
    function init() {
        let webSocketUrl = getWebsocketUrl() + '&workspace-id=' + workspaceIdRef.value
        // 监听ws 消息
        droneWebSocket = useConnectWebSocket(messageHandler, webSocketUrl)
    }
 
    watch(workspaceIdRef, (newValue, oldValue) => {
        removeWS()
        if (workspaceIdRef.value) {
            init()
        }
    })
 
    // 移除ws 事件
    function removeWS() {
        droneWebSocket?.close()
        droneWebSocket = null
        wsInfo.value = {}
    }
 
    onBeforeUnmount(() => {
        removeWS()
    })
 
    return {wsInfo,removeWS}
}