Ws.js
4.57 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import io from '@/uni_modules/hyoga-uni-socket_io/uni-socket.io.js'
import { WsTyps } from '../utils/common'
import CommandFactory from './CommandFactory'
import config from '@/config.js'
import { serializeIfObject,deepClone } from '@/utils/utils.js'
import { getSystemInfo, hasPrivacyConsent } from '@/utils/deviceInfo'
export class Ws {
wsAddress
loginAddress
token
deviceId
onMessage
ws
constructor() {
this.wsAddress = config.SOCKET_SERVER
this.loginAddress =`${config.HTTP_SERVER}/login`
}
async connect() {
if (!hasPrivacyConsent()) {
uni.$logger.local.warn('WS连接已跳过:用户未同意隐私协议')
return false
}
const loginResult = await this.login()
if (!loginResult) return false
const { code, data, o } = loginResult
if (code == 200) {
this.deviceId = data.id
this.token = data.token
this.ws = io(this.wsAddress, {
path:'/websocket/',
auth: { token: this.token, deviceId: this.deviceId },
transports: ['websocket'],
timeout: 5000
})
this.subscribe()
return true
} else {
uni.$logger.local.error(`登录失败 -> ${serializeIfObject({ code, data, o })}`)
return false
}
}
async connectWhenReady() {
return this.connect()
}
async login(retryCount = 3, retryDelay = 2000) {
if (!hasPrivacyConsent()) {
uni.$logger.local.warn('WS登录已跳过:用户未同意隐私协议')
return null
}
const tryLogin = async (attemptCount) => {
try {
if (!hasPrivacyConsent()) {
uni.$logger.local.warn('WS登录重试已停止:用户未同意隐私协议')
return null
}
const sysInfo = getSystemInfo()
if (!sysInfo?.deviceId) {
throw new Error('未获取到系统设备信息')
}
// sysInfo.deviceId = '4DF8801064461802495A2452CCD04EE4'
uni.$logger.local.info(`========WS,用户登录(第${attemptCount}次尝试) ${JSON.stringify({deviceId:sysInfo.deviceId})}========`)
return new Promise((resolve, reject) => {
uni.request({
url: this.loginAddress,
data: { sn: sysInfo.deviceId },
method: 'POST',
dataType: 'json',
success(response) {
resolve(response.data)
},
fail(err) {
reject(err)
}
})
})
} catch (error) {
throw error
}
}
for (let attempt = 1; attempt <= retryCount; attempt++) {
try {
const result = await tryLogin(attempt)
if (!result) return null
return result
} catch (err) {
if (attempt === retryCount) {
uni.$logger.local.error(`登录失败(已重试${retryCount}次), 请检查网络或联系管理员! err->${serializeIfObject(err)}`)
throw err
}
uni.$logger.local.warn(`登录失败(第${attempt}次), ${retryDelay/1000}秒后重试... err->${serializeIfObject(err)}`)
await new Promise(resolve => setTimeout(resolve, retryDelay))
}
}
}
disconnect() {
if (this.ws) {
if (typeof this.ws.disconnect === 'function') {
this.ws.disconnect()
} else if (typeof this.ws.close === 'function') {
this.ws.close()
}
this.ws = null
}
}
subscribe() {
this.ws.on(WsTyps.Connected, () => {
uni.$logger.local.warn('========WebSocket 连接成功========')
})
this.ws.on(
WsTyps.MessageTypes.Private,
function (data) {
uni.$logger.local.info(`WebSocket 收到消息 -> ${JSON.stringify(data)}`)
if (data.errorCode && data.errorCode == 907) return this.connect()
const _data = deepClone(data)
const worker = CommandFactory.getInstance().dispatch(_data.command)
worker.work(this.deviceId, _data, this)
this.onMessage && this.onMessage(_data)
}.bind(this)
)
this.ws.on(WsTyps.MessageTypes.System, function (data) {
uni.$logger.local.info(`========WebSocket 收到系统消息 ${serializeIfObject(data)}========`)
})
this.ws.on(WsTyps.Disconnected, () => {
CommandFactory.getInstance().clear()
uni.$logger.local.warn(`========WebSocket 断开连接 device_id->${this.deviceId}========`)
})
this.ws.on(WsTyps.Eroor, msg => {
CommandFactory.getInstance().clear()
uni.$logger.error(`========WebSocket 异常 device_id->${this.deviceId} msg ->${serializeIfObject(msg)}========`)
})
}
send(data, type = WsTyps.MessageTypes.Private) {
this.ws.emit(type, { device_id: this.deviceId, ...data })
}
}