dezhou-screen/src/utils/wsClass.js
2023-05-14 16:12:59 +08:00

95 lines
2.4 KiB
JavaScript

function handleOpen() {
console.log('[*] WebSocket 成功连接...')
}
function handleData(e) {
// this: WsClient 实例
if ('data' in e && e.data !== '') {
let latestData = null
try {
const latestData = JSON.parse(e.data)
console.log('处理数据: ', latestData)
for (const [key, value] of Object.entries(latestData)) {
console.log('kkk', key, WsClient.tableMap[key])
this.update({ target: WsClient.tableMap[key], data: value })
}
} catch (err) {
console.log(e)
}
}
else {
console.log('[x] 没有data数据')
return;
}
}
function handleError(err) {
console.log('[x] 出错:', err, err.data)
}
function handleClose() {
console.log('[x] 服务器关闭连接')
}
export default class WsClient {
static wsServer = 'ws://172.16.1.112:8081/dz-screen/websocket/1'
// static wsServer = 'ws://m306416y13.yicp.fun:48978/dz-screen/websocket/1'
static tableMap = {
// 窑顶温度
'kilnTempTopT1': 'kiln-top-1',
'kilnTempTopT2': 'kiln-top-2',
'kilnTempBottomT1': 'kiln-btm-1',
'kilnTempBottomT2': 'kiln-btm-2',
'inWater': 'kiln-water-in',
'outWater': 'kiln-water-out',
'kilnTempTinbathT1': 'xicao-1',
'kilnTempTinbathT2': 'xicao-2',
'kilnGasT1': 'gas-1',
'kilnGasT2': 'gas-2',
'kilnOilT1': 'oil-1',
'kilnOilT2': 'oil-2',
'fan': 'fan',
'fireDirection': 'fire-direction',
'lastFireChangeTime': 'last-fire-change-time',
'kilnPressure': 'kiln-pressure',
'fireChangeTime': 'fire-change-time',
'waterInTemp': 'water-in-temp',
'waterOutTemp': 'water-out-temp'
}
static socket = null
constructor(vm) {
WsClient.socket = WsClient.createSocket()
this.vueInstance = vm
}
closeSocket() {
WsClient.socket.close()
}
registerListeners() {
// 注册监听器
if (!WsClient.socket) {
WsClient.createSocket()
}
if (!WsClient.socket.onopen) WsClient.socket.onopen = handleOpen
if (!WsClient.socket.onmessage) WsClient.socket.onmessage = handleData.bind(this.vueInstance)
if (!WsClient.socket.onerror) WsClient.socket.onerror = handleError
if (!WsClient.socket.onclose) WsClient.socket.onclose = handleClose
}
static createSocket() {
if (WsClient.socket) return;
WsClient.socket = new WebSocket(WsClient.wsServer)
}
send(value) {
WsClient.socket.send(value)
}
update() {
}
}