Files
klp-mono/apps/hand-factory/utils/socketMeasure.js
砂糖 166afcb959 feat: 更新生产线配置并优化WebSocket连接
- 移除未使用的生产线组件和配置
- 添加WebSocket URL配置项
- 将WebSocket连接改为使用uni.connectSocket
- 添加连接状态日志便于调试
2026-01-15 15:08:12 +08:00

72 lines
1.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import config from '@/config'
/**
* 测量数据 WebSocket与 l2/socket/index.vue 类似)
* 默认订阅 type=track_measure
*/
export function createMeasureSocket({
type = 'track_measure',
onOpen,
onClose,
onError,
onMessage
} = {}) {
let socket = null
let manualClose = false
const wsBase = (config.wsUrl || config.baseUrl || '').replace(/^http/, 'ws')
const url = `${wsBase}/websocket?type=${type}`
console.log(url)
function connect() {
manualClose = false
// socket = new WebSocket(url)
socket = uni.connectSocket({
url,
success() {
console.log('连接成功')
}
})
console.log(socket)
socket.onOpen = () => {
console.log('连接成功')
onOpen && onOpen()
}
socket.onMessage = (evt) => {
onMessage && onMessage(evt.data)
}
socket.onError = (err) => {
onError && onError(err)
}
socket.onClose = (evt) => {
onClose && onClose(evt)
if (!manualClose) {
setTimeout(connect, 3000)
}
}
}
function close() {
manualClose = true
if (socket) {
socket.close(1000, 'client close')
socket = null
}
}
function send(data) {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(data));
} else {
console.error('WebSocket is not open. Cannot send message.');
}
}
return { connect, close, send }
}