wsAuth.js
2.38 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
/*
* 设备 WS 登录:POST {HTTP_SERVER}/login,body { sn: deviceId }
* 对齐 venus uniapp-x-tape/ws/Ws.uts login()
*
* 使用方:
* - utils/socket/NativeWsClient(原生 SocketTask / 音频 Demo)
* - utils/socket/NativeHttpClient(仅在 auth=true 时)
* 不使用方:
* - ws/Ws.js 主业务 socket.io(自带 login(),未引用本文件)
*/
import config from '@/config.js'
import { serializeIfObject } from '@/utils/utils.js'
function assertLoginResponse(body, loginAddress) {
if (body == null || typeof body !== 'object' || Array.isArray(body)) {
const preview = typeof body === 'string' ? body.slice(0, 80) : serializeIfObject(body)
throw new Error(`登录返回非 JSON,HTTP_SERVER 可能配错: ${loginAddress} -> ${preview}`)
}
if (body.code == null && body.data == null) {
throw new Error(
`登录返回无 code(多为前端 HTML 或地址错误): ${loginAddress}`
)
}
}
/**
* @param {number} retryCount
* @param {number} retryDelay
* @returns {Promise<object>}
*/
export async function loginDevice(retryCount = 3, retryDelay = 2000) {
const loginAddress = `${config.HTTP_SERVER}/login`
const tryLogin = async (attemptCount) => {
const sysInfo = uni.getSystemInfoSync()
if (!sysInfo?.deviceId) {
throw new Error('未获取到系统设备信息')
}
uni.$logger?.local?.info(
`WS登录(第${attemptCount}次) ${loginAddress} ${JSON.stringify({ deviceId: sysInfo.deviceId })}`
)
return new Promise((resolve, reject) => {
uni.request({
url: loginAddress,
data: { sn: sysInfo.deviceId },
method: 'POST',
dataType: 'json',
success: (response) => {
try {
assertLoginResponse(response.data, loginAddress)
resolve(response.data)
} catch (e) {
reject(e)
}
},
fail: reject
})
})
}
for (let attempt = 1; attempt <= retryCount; attempt++) {
try {
return await tryLogin(attempt)
} catch (err) {
if (attempt === retryCount) {
uni.$logger?.local?.error(
`WS登录失败(已重试${retryCount}次) err->${serializeIfObject(err)}`
)
throw err
}
uni.$logger?.local?.warn(
`WS登录失败(第${attempt}次), ${retryDelay / 1000}s后重试...`
)
await new Promise((r) => setTimeout(r, retryDelay))
}
}
}