小兵仍在前行,英雄怎能放弃!

基本参数

1、申领ws客户端ID:http请求获取
2、获取ws连接地址:http请求获取
3、真实ws请求URL=获取ws连接地址+申领ws客户端ID

调用流程

1、初次连接成功:state.data === "连接成功!"
2、订阅:通过客户端点位id发起http请求订阅
3、订阅成功重连WebSocket:获取真实推送消息
4、回调方法获取:message:()=>{}

//获取本地服务点位id
const getDevicePoint = () => {
    return new Promise((resolve, reject) => {
        const hasIfeame = document.getElementById("device-iframe")
        if (hasIfeame) {
            hasIfeame.parentNode.removeChild(hasIfeame)
        }
        const iframe = document.createElement("iframe")
        iframe.setAttribute("src", "http://127.0.0.1:7683/point")
        iframe.setAttribute("id", "device-iframe")
        iframe.style.position = "fixed"
        iframe.style.zIndex = "-1"
        document.body.appendChild(iframe)
        let result = null;
        window.addEventListener('message', (evt) => {
            if (evt.data && evt.data.msg) {
                result = evt.data.msg

            } else {
                console.log('%c 缺少订阅参数客户端点位ID %c 请检查本地点位服务是否正常启动', "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #ff0000; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0; color: #ff0000; background: #fafafa; border:1px solid #f0f0f0;");
                resolve(null)
            }
        })
        setTimeout(() => {
            if (!result) {
                resolve(null)
            } else {
                resolve(result)
            }
        }, 1000)
    })

}
//调用WebSocket方法
const requestWebSocket = (url, options) => {
    let socket = null;
    let timer = null;
    let devicePointIds = options.devicePointIds || null;
    const WebSocketObject = {
        send: function (data) {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.send(JSON.stringify(data));
            }
        },
        disconnect: function () {
            if (socket) {
                socket.close();
            }
        },
        reconnect: function () {
            if (socket && (socket.readyState === WebSocket.CONNECTING || socket.readyState === WebSocket.OPEN)) {
                return;
            }
            clearTimeout(timer);
            timer = setTimeout(function () {
                WebSocketObject.connect();
            }, 1000);
        },
        connect: function () {
            socket = new WebSocket(url);
            socket.addEventListener('open', async function (event) {
                let str = '%c WebSocket连接已建立 %c ' + url
                console.log(str, "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #326DE3; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0; color: #000000; background: #fafafa;border:1px solid #f0f0f0;");
                clearTimeout(timer);
                if (!devicePointIds) {
                    console.log('%c WebSocket通信异常 %c 本地设备服务未启动', "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #ff0000; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0; color: #ff0000; background: #fafafa; border:1px solid #f0f0f0;");
                    WebSocketObject.disconnect();
                } else {
                    console.log('%c WebSocket通信正常 %c 本地设备服务启动成功', "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #000; background: #b7eb8f; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0;color: #000000; background: #f6ffed; border:1px solid #b7eb8f;");
                }
            });

            socket.addEventListener('message', async function (event) {
                if (event.data) {
                    const state = JSON.parse(event.data)
                    if (state.code !== 200) {
                        console.log(`%c webSocket消息推送失败 %c ${state.data}`, "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #ff0000; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0; color: #ff0000; background: #fafafa;border:1px solid #f0f0f0;");
                        WebSocketObject.disconnect();
                        return false
                    }
                    if (state.data === "连接成功!") {
                        //设备数据订阅
                        if (!options.clientId) {
                            console.log('%c 缺少订阅参数clientId %c clientId属性值为服务器返回的客户端id', "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #ff0000; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0; color: #ff0000; background: #fafafa;border:1px solid #f0f0f0;");
                            WebSocketObject.disconnect();
                            return
                        }

                        if (!devicePointIds) return
                        const params = {
                            devicePointIds: devicePointIds,
                            wsClientId: options.clientId
                        }
                        const res = await proxy.$OpenAPIEngine.requestByName("openapi_10723", { body: params })
                        if (res.status === 200) {
                            // WebSocketObject.disconnect();
                            WebSocketObject.reconnect();
                            console.log(`%c webSocket订阅成功 %c 本客户机开启实时数据获取`, "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #000; background: #b7eb8f; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0; color: #000000; background: #f6ffed; border:1px solid #b7eb8f;");
                        } else {
                            console.log(`%c ${res.status}-消息订阅失败 %c ${res ? res.data.msg : 'webSocket已自动断开连接'}`, "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #ff0000; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0;  color: #ff0000; background: #fafafa;border:1px solid #f0f0f0;");
                            WebSocketObject.disconnect();
                        }

                    } else if (state.data.includes("Connected")) {

                    } else {
                        console.log(`%c webSocket连接成功 %c 实时数据已正常推送`, "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #000; background: #b7eb8f; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0; color: #000000; background: #f6ffed; border:1px solid #b7eb8f;");
                        options.message && options.message(JSON.parse(state.data))
                    }
                }

            });

            socket.addEventListener('close', function (event) {
                console.log(`%c webSocket连接已断开 %c 如需继续接收则需要手动连接`, "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #000; background: #ffe58f; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0; color: #000000; background: #fffbe6; border:1px solid #ffe58f;");
                WebSocketObject.disconnect();
            });

            socket.addEventListener('error', function (event) {
                console.log('%c webSocket异常 %c webSocket已自动断开,请手动重连', "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #ff0000; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0; color: #ff0000; background: #fafafa;border:1px solid #f0f0f0;");
                WebSocketObject.disconnect();
            });
        }
    };
    try {
        WebSocketObject.connect();
    } catch (error) {
        console.log('%c webSocket异常 %c webSocket已自动断开,请手动重连', "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #ff0000; font-weight: bold;", "padding: 2px 4px; border-radius: 0 3px 3px 0; color: #ff0000; background: #fafafa;border:1px solid #f0f0f0;");
    }
    return WebSocketObject;
}
//WebSocket路径参数等信息获取
const webSocket = ref(null)
const getWebSocketConfig = async () => {
    const webSocketconfig = {}
    //申领ws客户端ID
    const wsClient = await proxy.$OpenAPIEngine.requestByName("openapi_10722")
    if (wsClient.status !== 200) return
    webSocketconfig["wsClientId"] = wsClient.data
    //查询客户端连接地址
    const wsClientUrl = await proxy.$OpenAPIEngine.requestByName("openapi_10721")
    webSocketconfig["URL"] = wsClientUrl.data
    const url = webSocketconfig["URL"] + webSocketconfig["wsClientId"]
    const devicePointIds = await getDevicePoint()
    webSocket.value = requestWebSocket(url, {
        clientId: webSocketconfig["wsClientId"],
        devicePointIds: devicePointIds ? devicePointIds.split(",") : null,
        message: (jsonObj) => {
            const result = {
                "TareWeight": jsonObj.TareWeight || 0,
                "GrossWeight": jsonObj.GrossWeight || 0,
                "GrossWeightTime": jsonObj.GrossWeightTime || '',
                "TareWeightTime": jsonObj.TareWeightTime || '',
                "ScalesNo": jsonObj.ScalesNo || ''
            }
            actionSfc({ asyncData: result })
        }
    })
}

//WebSocket重新连接
const handleReloadCard = async () => {
    if (!webSocket.value) return
    webSocket.value.disconnect()
    actionSfc({ asyncData: {} })
    await nextTick()
    getWebSocketConfig()
}