wsAuth.js 2.38 KB
/*
 * 设备 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))
    }
  }
}