Commit a7f52ad5 by 岑成威

fix: websocket

1 parent 19745580
<template>
<!-- #ifdef APP-PLUS -->
<view class="audio-demo-root">
<view
class="audio-demo-fab"
:class="{ running: isRunning }"
@tap.stop="onFabClick"
>
<text class="fab-label">{{ fabText }}</text>
<text class="fab-sub">PCM</text>
</view>
<view v-if="panelVisible" class="audio-demo-mask" @tap="panelVisible = false">
<view class="audio-demo-panel" @tap.stop>
<view class="panel-head">
<text class="panel-title">录音 / WS Demo</text>
<text class="panel-status">{{ statusText }}</text>
<view class="panel-actions">
<text class="act" @tap.stop="clearLogs">清空</text>
<text class="act danger" @tap.stop="panelVisible = false">关闭</text>
</view>
</view>
<scroll-view class="panel-scroll" scroll-y :scroll-into-view="scrollIntoView">
<view
v-for="(line, idx) in logs"
:key="line.time + '_' + idx"
:id="'demo-log-' + idx"
:class="['log-line', 'lv-' + line.level]"
>
<text class="log-text">{{ line.text }}</text>
</view>
<view v-if="!logs.length" class="log-empty">点击悬浮按钮开始:录音 5s → WS 上传</view>
</scroll-view>
<view class="panel-foot">
<text class="hint">日志同步至 uni.$logger 与悬浮「日志」球(若已开启)</text>
</view>
</view>
</view>
</view>
<!-- #endif -->
</template>
<script>
// #ifdef APP-PLUS
import AudioStreamDemoRunner from '@/utils/audioStream/AudioStreamDemoRunner.js'
// #endif
const STATUS_MAP = {
idle: '待命',
connecting: '连接 WS…',
recording: '录音中(5s)',
uploading: '上传中…',
done: '完成'
}
export default {
name: 'AudioStreamDemo',
data() {
return {
panelVisible: false,
status: 'idle',
logs: [],
scrollIntoView: '',
// #ifdef APP-PLUS
runner: null
// #endif
}
},
computed: {
isRunning() {
return this.status === 'connecting' || this.status === 'recording' || this.status === 'uploading'
},
fabText() {
if (this.status === 'recording') return '录'
if (this.status === 'uploading') return '传'
return '测'
},
statusText() {
return STATUS_MAP[this.status] || this.status
}
},
created() {
// #ifdef APP-PLUS
this.runner = new AudioStreamDemoRunner({
onLog: (entry) => this.appendLog(entry),
onStatus: (s) => {
this.status = s
}
})
// #endif
},
beforeDestroy() {
// #ifdef APP-PLUS
this.runner?.cancel()
// #endif
},
methods: {
onFabClick() {
// #ifndef APP-PLUS
uni.showToast({ title: '仅 App 端', icon: 'none' })
return
// #endif
this.panelVisible = true
if (this.isRunning) return
this.startDemo()
},
async startDemo() {
// #ifdef APP-PLUS
this.appendLog({ level: 'info', text: '[AudioDemo] 点击开始', time: Date.now() })
const ok = await this.runner.start()
if (!ok && this.status === 'idle') {
uni.showToast({ title: '启动失败,看日志', icon: 'none' })
}
// #endif
},
appendLog(entry) {
this.logs.push(entry)
if (this.logs.length > 300) {
this.logs.splice(0, this.logs.length - 300)
}
this.$nextTick(() => {
this.scrollIntoView = 'demo-log-' + (this.logs.length - 1)
})
},
clearLogs() {
this.logs = []
}
}
}
</script>
<style lang="scss" scoped>
/* 全屏占位但不挡点击,仅悬浮钮可点(与 FloatLogPanel 同模式) */
.audio-demo-root {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 100010;
pointer-events: none;
}
.audio-demo-fab {
position: fixed;
left: 24rpx;
top: 120rpx;
pointer-events: auto;
width: 112rpx;
height: 112rpx;
border-radius: 56rpx;
background: linear-gradient(135deg, #3b82f6, #2563eb);
box-shadow: 0 8rpx 24rpx rgba(37, 99, 235, 0.55);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
&.running {
background: linear-gradient(135deg, #ef4444, #dc2626);
animation: pulse 1s ease-in-out infinite;
}
}
.fab-label {
color: #fff;
font-size: 34rpx;
font-weight: 600;
line-height: 1.1;
}
.fab-sub {
color: rgba(255, 255, 255, 0.85);
font-size: 18rpx;
margin-top: 4rpx;
}
@keyframes pulse {
0%,
100% {
transform: scale(1);
}
50% {
transform: scale(1.06);
}
}
.audio-demo-mask {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
pointer-events: auto;
background: rgba(0, 0, 0, 0.45);
display: flex;
align-items: flex-end;
}
.audio-demo-panel {
width: 100%;
max-height: 70vh;
background: #1e1e1e;
border-radius: 24rpx 24rpx 0 0;
display: flex;
flex-direction: column;
}
.panel-head {
padding: 24rpx 28rpx 16rpx;
border-bottom: 1px solid #333;
}
.panel-title {
color: #f5f5f5;
font-size: 30rpx;
font-weight: 600;
}
.panel-status {
display: block;
margin-top: 8rpx;
color: #93c5fd;
font-size: 24rpx;
}
.panel-actions {
margin-top: 16rpx;
display: flex;
gap: 24rpx;
}
.act {
color: #60a5fa;
font-size: 26rpx;
&.danger {
color: #f87171;
}
}
.panel-scroll {
flex: 1;
max-height: 50vh;
padding: 16rpx 24rpx;
box-sizing: border-box;
}
.log-line {
margin-bottom: 12rpx;
font-size: 22rpx;
line-height: 1.45;
word-break: break-all;
}
.log-text {
color: #d4d4d4;
}
.lv-warn .log-text {
color: #fbbf24;
}
.lv-error .log-text {
color: #f87171;
}
.lv-debug .log-text {
color: #9ca3af;
}
.log-empty {
color: #6b7280;
font-size: 24rpx;
padding: 40rpx 0;
text-align: center;
}
.panel-foot {
padding: 16rpx 24rpx 32rpx;
border-top: 1px solid #333;
}
.hint {
color: #6b7280;
font-size: 22rpx;
}
</style>
...@@ -126,11 +126,17 @@ ...@@ -126,11 +126,17 @@
</view> </view>
</template> </template>
</ErrorOrderPopup> </ErrorOrderPopup>
<!-- #ifdef APP-PLUS -->
<AudioStreamDemo />
<!-- #endif -->
<FloatLogPanel v-if="showFloatLog" /> <FloatLogPanel v-if="showFloatLog" />
</view> </view>
</template> </template>
<script> <script>
import FloatLogPanel from '@/components/FloatLogPanel/FloatLogPanel.vue' import FloatLogPanel from '@/components/FloatLogPanel/FloatLogPanel.vue'
// #ifdef APP-PLUS
import AudioStreamDemo from '@/components/AudioStreamDemo/AudioStreamDemo.vue'
// #endif
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js' import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
import ReceptionCenter from './components/ReceptionCenter/index.vue' import ReceptionCenter from './components/ReceptionCenter/index.vue'
import SceneMarket from './components/SceneMarket/index.vue' import SceneMarket from './components/SceneMarket/index.vue'
...@@ -172,6 +178,9 @@ export default { ...@@ -172,6 +178,9 @@ export default {
mixins: [ recorder, versionCheck, interceptionMixin, merge], mixins: [ recorder, versionCheck, interceptionMixin, merge],
components: { components: {
FloatLogPanel, FloatLogPanel,
// #ifdef APP-PLUS
AudioStreamDemo,
// #endif
ReceptionCenter, ReceptionCenter,
StudyCenter, StudyCenter,
SceneMarket, SceneMarket,
......
...@@ -2,7 +2,7 @@ module.exports = { ...@@ -2,7 +2,7 @@ module.exports = {
// 请求域名 格式:https://xxx.xxx.com // 请求域名 格式:https://xxx.xxx.com
HTTP_REQUEST_URL: 'http://127.0.0.1:8000/api', HTTP_REQUEST_URL: 'http://127.0.0.1:8000/api',
// 阿里云oss域名 格式:https://xxx.oss-cn-xxx.aliyuncs.com // 阿里云oss域名 格式:https://xxx.oss-cn-shenzhen.aliyuncs.com
OSS_DOMAIN: 'https://glsk-oss.oss-cn-shenzhen.aliyuncs.com', OSS_DOMAIN: 'https://glsk-oss.oss-cn-shenzhen.aliyuncs.com',
// 文件直传到阿里云oss时需用到 // 文件直传到阿里云oss时需用到
......
...@@ -43,6 +43,10 @@ export default { ...@@ -43,6 +43,10 @@ export default {
}, },
updateCustomerInfo(data){ updateCustomerInfo(data){
this.recordService.updateCustomerInfo(data) this.recordService.updateCustomerInfo(data)
},
/** 订阅接待中的实时 PCM 音频帧 */
onAudioStreamChunk(callback) {
return this.recordService?.getAudioStreamService()?.onChunk(callback) || (() => {})
} }
} }
} }
## 1.0.0
- Android AudioRecord PCM 实时采集
- 支持 onPcmFrame 帧回调(base64)
{
"id": "gl-pcm-capture",
"displayName": "gl-pcm-capture",
"version": "1.0.0",
"description": "Android PCM 实时采集,通过回调输出音频帧(base64)",
"keywords": ["pcm", "audio", "record", "stream"],
"repository": "",
"engines": {
"HBuilderX": "^3.94"
},
"dcloudext": {
"type": "uts",
"sale": {
"regular": { "price": "0.00" },
"sourcecode": { "price": "0.00" }
},
"contact": { "qq": "" },
"declaration": {
"ads": "无",
"data": "插件不采集任何数据,仅在本地回调 PCM 帧",
"permissions": "android.permission.RECORD_AUDIO"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": { "tcb": "n", "aliyun": "n" },
"client": {
"Vue": { "vue2": "y", "vue3": "y" },
"App": {
"app-android": { "minVersion": "21" },
"app-ios": "n"
},
"H5-mobile": {
"Safari": "n",
"Android Browser": "n",
"微信浏览器(Android)": "n",
"QQ浏览器(Android)": "n"
},
"H5-pc": {
"Chrome": "n",
"IE": "n",
"Edge": "n",
"Firefox": "n",
"Safari": "n"
},
"小程序": {
"微信": "n",
"阿里": "n",
"百度": "n",
"字节跳动": "n",
"QQ": "n",
"钉钉": "n",
"快手": "n",
"飞书": "n",
"京东": "n"
},
"快应用": { "华为": "n", "联盟": "n" }
}
}
}
}
# gl-pcm-capture
Android 端 PCM 实时采集 UTS 插件。通过 `AudioRecord` 在后台线程读取音频帧,以 base64 形式回调给 JS 层。
## 使用
```javascript
import {
startPcmCapture,
stopPcmCapture,
onPcmFrame,
offPcmFrame
} from '@/uni_modules/gl-pcm-capture'
onPcmFrame((frame) => {
console.log('pcm frame', frame.seq, frame.byteLength)
})
startPcmCapture({
sampleRate: 16000,
frameSize: 4096,
success: () => console.log('started'),
fail: (err) => console.error(err)
})
// 停止
stopPcmCapture()
offPcmFrame()
```
推荐通过 `utils/audioStream/AudioStreamService.js` 封装使用。
## 注意
- 仅支持 Android App 自定义基座 / 正式包
- 需要 `RECORD_AUDIO` 权限
- 与 `MediaRecorder` 同时占用 MIC 时,部分机型可能冲突,后续将统一采集层
package uts.sdk.modules.glPcmCapture
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.util.Base64
/**
* PCM 读帧结果(供 UTS 层回调 JS)
*/
class PcmFrameData(
val base64: String,
val byteLength: Int
)
object PcmCaptureNative {
@JvmStatic
fun getMinBufferSize(sampleRate: Int): Int {
return AudioRecord.getMinBufferSize(
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT
)
}
@JvmStatic
fun createRecorder(sampleRate: Int, bufferSize: Int): AudioRecord {
return AudioRecord(
MediaRecorder.AudioSource.MIC,
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize
)
}
@JvmStatic
fun readFrame(recorder: AudioRecord, frameSize: Int): PcmFrameData? {
val buffer = ByteArray(frameSize)
val readLen = recorder.read(buffer, 0, frameSize)
if (readLen <= 0) {
return null
}
val base64 = Base64.encodeToString(buffer, 0, readLen, Base64.NO_WRAP)
return PcmFrameData(base64, readLen)
}
}
import AudioRecord from 'android.media.AudioRecord'
import Thread from 'java.lang.Thread'
import Runnable from 'java.lang.Runnable'
import { PcmCaptureNative } from 'uts.sdk.modules.glPcmCapture'
import {
StartPcmCaptureOptions,
StartPcmCaptureSuccess,
PcmFrameResult,
StopPcmCaptureOptions,
StopPcmCaptureSuccess
} from '../interface.uts'
import { PcmCaptureFailImpl } from '../unierror.uts'
let audioRecord : AudioRecord | null = null
let captureThread : Thread | null = null
let isRunning = false
let seqCounter : Int = 0
let frameCallback : ((res : PcmFrameResult) => void) | null = null
let currentSampleRate : Int = 16000
let currentFrameSize : Int = 4096
export function onPcmFrame(callback : (res : PcmFrameResult) => void) : void {
frameCallback = callback
}
export function offPcmFrame() : void {
frameCallback = null
}
function dispatchFrame(frame : PcmFrameResult) : void {
const cb = frameCallback
if (cb == null) {
return
}
const activity = UTSAndroid.getUniActivity()
if (activity != null) {
const uiRunnable = new (class implements Runnable {
override run() : void {
cb(frame)
}
})
activity.runOnUiThread(uiRunnable)
} else {
cb(frame)
}
}
export function startPcmCapture(options : StartPcmCaptureOptions) : void {
if (isRunning) {
const err = new PcmCaptureFailImpl(1400003)
options.fail?.(err)
options.complete?.(err)
return
}
const sampleRateInt = (options.sampleRate ?? 16000).toInt()
const frameSizeInt = (options.frameSize ?? 4096).toInt()
currentSampleRate = sampleRateInt
currentFrameSize = frameSizeInt
const minBufferSize = PcmCaptureNative.getMinBufferSize(sampleRateInt)
if (minBufferSize <= 0) {
const err = new PcmCaptureFailImpl(1400001)
options.fail?.(err)
options.complete?.(err)
return
}
const bufferSizeInt = Math.max(minBufferSize, frameSizeInt * 2).toInt()
try {
const recorder = PcmCaptureNative.createRecorder(sampleRateInt, bufferSizeInt)
if (recorder.getState() != AudioRecord.STATE_INITIALIZED) {
recorder.release()
const err = new PcmCaptureFailImpl(1400002)
options.fail?.(err)
options.complete?.(err)
return
}
audioRecord = recorder
isRunning = true
seqCounter = 0
recorder.startRecording()
const runnable = new (class implements Runnable {
override run() : void {
while (isRunning && audioRecord != null) {
const frameData = PcmCaptureNative.readFrame(audioRecord!, currentFrameSize)
if (frameData != null) {
const frame : PcmFrameResult = {
base64: frameData.base64,
byteLength: frameData.byteLength,
seq: seqCounter,
timestamp: Date.now(),
sampleRate: currentSampleRate,
channels: 1,
bitDepth: 16
}
seqCounter++
dispatchFrame(frame)
} else {
// read 返回 0 或负数时短暂让出 CPU,避免空转
Thread.sleep(10)
}
}
}
})
const thread = new Thread(runnable)
captureThread = thread
thread.start()
const success : StartPcmCaptureSuccess = { errMsg: 'startPcmCapture:ok' }
options.success?.(success)
options.complete?.(success)
} catch (e : Exception) {
isRunning = false
audioRecord = null
const err = new PcmCaptureFailImpl(1400001)
err.errMsg = 'startPcmCapture fail: ' + e.message
options.fail?.(err)
options.complete?.(err)
}
}
export function stopPcmCapture(options ?: StopPcmCaptureOptions) : void {
isRunning = false
const recorder = audioRecord
if (recorder != null) {
try {
recorder.stop()
} catch (e : Exception) {
// 录音过短时 stop 可能抛异常,忽略
}
try {
recorder.release()
} catch (e : Exception) {
// ignore
}
audioRecord = null
}
captureThread = null
seqCounter = 0
const success : StopPcmCaptureSuccess = { errMsg: 'stopPcmCapture:ok' }
options?.success?.(success)
options?.complete?.(success)
}
export type PcmFrameResult = {
base64: string
byteLength: number
seq: number
timestamp: number
sampleRate: number
channels: number
bitDepth: number
}
export type StartPcmCaptureOptions = {
sampleRate?: number
frameSize?: number
success?: (res: { errMsg: string }) => void
fail?: (err: { errCode: number; errMsg: string }) => void
complete?: (res: any) => void
}
export type StopPcmCaptureOptions = {
success?: (res: { errMsg: string }) => void
complete?: (res: any) => void
}
export declare function startPcmCapture(options: StartPcmCaptureOptions): void
export declare function stopPcmCapture(options?: StopPcmCaptureOptions): void
export declare function onPcmFrame(callback: (res: PcmFrameResult) => void): void
export declare function offPcmFrame(): void
export type PcmFrameResult = {
base64 : string
byteLength : number
seq : number
timestamp : number
sampleRate : number
channels : number
bitDepth : number
}
export type StartPcmCaptureSuccess = {
errMsg : string
}
export type StopPcmCaptureSuccess = {
errMsg : string
}
export type PcmCaptureErrorCode = 1400001 | 1400002 | 1400003
export interface PcmCaptureFail extends IUniError {
errCode : PcmCaptureErrorCode
}
export type PcmCaptureFailCallback = (err : PcmCaptureFail) => void
export type StartPcmCaptureSuccessCallback = (res : StartPcmCaptureSuccess) => void
export type StopPcmCaptureSuccessCallback = (res : StopPcmCaptureSuccess) => void
export type PcmCaptureCompleteCallback = (res : any) => void
export type PcmFrameCallback = (res : PcmFrameResult) => void
export type StartPcmCaptureOptions = {
sampleRate ?: number
frameSize ?: number
success ?: StartPcmCaptureSuccessCallback | null
fail ?: PcmCaptureFailCallback | null
complete ?: PcmCaptureCompleteCallback | null
}
export type StopPcmCaptureOptions = {
success ?: StopPcmCaptureSuccessCallback | null
fail ?: PcmCaptureFailCallback | null
complete ?: PcmCaptureCompleteCallback | null
}
export type StartPcmCapture = (options : StartPcmCaptureOptions) => void
export type StopPcmCapture = (options ?: StopPcmCaptureOptions) => void
export type OnPcmFrame = (callback : PcmFrameCallback) => void
export type OffPcmFrame = () => void
import { PcmCaptureErrorCode, PcmCaptureFail } from "./interface.uts"
export const UniErrorSubject = 'gl-pcm-capture'
export const UniErrors : Map<PcmCaptureErrorCode, string> = new Map([
[1400001, 'AudioRecord init or read failed'],
[1400002, 'AudioRecord not initialized'],
[1400003, 'Already capturing'],
])
export class PcmCaptureFailImpl extends UniError implements PcmCaptureFail {
constructor(errCode : PcmCaptureErrorCode) {
super()
this.errSubject = UniErrorSubject
this.errCode = errCode
this.errMsg = UniErrors[errCode] ?? ""
}
}
/*
* @Description: 首页录音 + WebSocket 边录边传 Demo(NativeWsClient)
*/
import AudioStreamService from './AudioStreamService.js'
import { demoLog } from './demoLog.js'
import NativeWsClient from '@/utils/socket/NativeWsClient.js'
import permision from '@/js_sdk/wa-permission/permission.js'
const DEMO_RECORD_MS = 5000
const PCM_START_TIMEOUT_MS = 8000
export default class AudioStreamDemoRunner {
constructor(hooks = {}) {
this._onLog = hooks.onLog || (() => {})
this._onStatus = hooks.onStatus || (() => {})
this._frames = []
this._chunkHandler = null
this._timer = null
this._running = false
this._ws = null
this._prevOnMessage = null
this._ownsWs = false
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
}
get isRunning() {
return this._running
}
async start() {
// #ifndef APP-PLUS
this._log('warn', '仅 App 端支持')
return false
// #endif
// #ifdef APP-PLUS
if (this._running) {
this._log('warn', 'Demo 进行中')
return false
}
if (plus.os.name !== 'Android') {
this._log('warn', '当前 Demo 仅支持 Android PCM')
return false
}
const permitted = await this._ensureRecordPermission()
if (!permitted) {
this._log('error', '无录音权限')
return false
}
this._running = true
this._frames = []
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
this._setStatus('connecting')
this._ws = NativeWsClient.getInstance()
this._prevOnMessage = this._ws.onMessage
this._ws.onMessage = (data) => {
this._log('info', `[WS] 收到 <= ${JSON.stringify(data || {}).slice(0, 240)}`)
this._prevOnMessage && this._prevOnMessage(data)
}
if (!this._ws.isConnected) {
this._log('info', '连接原生 WebSocket(uni.connectSocket)…')
try {
await this._ws.connect()
this._ownsWs = true
} catch (e) {
this._log('error', `WebSocket 连接失败: ${e.message || e}`)
this._cleanup(false)
return false
}
} else {
this._log('info', '复用已有 NativeWs 连接')
}
const stream = AudioStreamService.getInstance()
if (stream.isRunning) {
this._log('warn', 'PCM 采集中(可能接待录音占用麦克风),先停止再试')
stream.stop()
}
this._chunkHandler = (frame) => this._onPcmChunk(frame)
stream.onChunk(this._chunkHandler)
let started = false
try {
started = await Promise.race([
stream.start({ debugLog: true }),
new Promise((_, reject) => {
setTimeout(() => reject(new Error('PCM 启动超时,检查 gl-pcm-capture 插件与麦克风占用')), PCM_START_TIMEOUT_MS)
})
])
} catch (e) {
this._log('error', e.message || String(e))
started = false
}
if (!started) {
this._log('error', 'PCM 采集启动失败(插件未生效或麦克风被占用)')
this._cleanup(false)
return false
}
this._setStatus('recording')
this._log('info', `PCM 已启动,边录边传 ${DEMO_RECORD_MS / 1000}s 后结束`)
this._timer = setTimeout(() => {
this.stopAndUpload()
}, DEMO_RECORD_MS)
return true
// #endif
}
_onPcmChunk(frame) {
this._frames.push({
seq: frame.seq,
base64: frame.base64,
byteLength: frame.byteLength,
timestamp: frame.timestamp
})
if (frame.seq % 8 === 0) {
this._log('info', `采集中 帧#${frame.seq} ${frame.byteLength}B,已缓存 ${this._frames.length} 帧,已发送 ${this._sentCount} 帧`)
}
const ws = this._ws
if (!ws?.isConnected) return
this._sendChain = this._sendChain
.then(() => this._sendPcmFrame(frame))
.catch((e) => {
this._log('warn', `发送帧#${frame.seq} 失败: ${e.message || e}`)
})
}
async _sendPcmFrame(frame) {
const ws = this._ws
if (!ws?.isConnected) return
if (!this._streamStarted) {
const ok = await ws.send({
command: 'audioStreamStart',
data: {
sampleRate: 16000,
channels: 1,
bitDepth: 16,
format: 'pcm',
demo: true
}
})
if (!ok) {
throw new Error('audioStreamStart 发送失败')
}
this._streamStarted = true
this._log('info', '已发送 audioStreamStart,开始上传 PCM 帧')
}
const ok = await ws.send({
command: 'audioStream',
data: {
seq: frame.seq,
chunk: frame.base64,
byteLength: frame.byteLength,
timestamp: frame.timestamp
}
})
if (!ok) {
throw new Error(`audioStream seq=${frame.seq} 发送失败`)
}
this._sentCount++
if (this._sentCount % 10 === 0) {
this._log('info', `实时上传 ${this._sentCount} 帧`)
}
}
async stopAndUpload() {
if (!this._running) return
clearTimeout(this._timer)
this._timer = null
this._setStatus('uploading')
this._log('info', '停止录音…')
const stream = AudioStreamService.getInstance()
if (this._chunkHandler) {
stream.offChunk(this._chunkHandler)
this._chunkHandler = null
}
stream.stop()
await this._sendChain.catch(() => {})
const total = this._frames.length
const bytes = this._frames.reduce((sum, f) => sum + (f.byteLength || 0), 0)
this._log('info', `录音结束:采集 ${total} 帧 / 已发送 ${this._sentCount} 帧,约 ${(bytes / 1024).toFixed(1)} KB`)
const ws = this._ws
if (ws?.isConnected && this._streamStarted) {
try {
await ws.send({
command: 'audioStreamEnd',
data: { total, sent: this._sentCount, bytes }
})
this._log('info', `已发送 audioStreamEnd sent=${this._sentCount}`)
} catch (e) {
this._log('error', `audioStreamEnd 失败: ${e.message || e}`)
}
} else if (total === 0) {
this._log('warn', '未采集到 PCM 数据,未向服务端发送音频')
} else if (!this._streamStarted) {
this._log('warn', '未发送 audioStreamStart,跳过 audioStreamEnd')
}
this._cleanup(true)
}
cancel() {
clearTimeout(this._timer)
this._timer = null
const stream = AudioStreamService.getInstance()
if (this._chunkHandler) {
stream.offChunk(this._chunkHandler)
this._chunkHandler = null
}
stream.stop()
this._cleanup(false)
this._log('warn', 'Demo 已取消')
}
async _ensureRecordPermission() {
// #ifdef APP-PLUS
if (plus.os.name === 'Android') {
const code = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
return code === 1
}
// #endif
return true
}
_cleanup(done) {
this._running = false
this._frames = []
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
if (this._ws) {
this._ws.onMessage = this._prevOnMessage
}
if (this._ownsWs && this._ws) {
this._ws.close().catch(() => {})
NativeWsClient.resetInstance()
}
this._ws = null
this._prevOnMessage = null
this._ownsWs = false
this._setStatus(done ? 'done' : 'idle')
}
_log(level, msg) {
const entry = demoLog(level, msg)
this._onLog(entry)
}
_setStatus(status) {
this._onStatus(status)
}
}
/*
* @Description: PCM 实时流服务(Android UTS 插件封装)
* 用法:
* const stream = AudioStreamService.getInstance()
* stream.onChunk((frame) => { ... })
* stream.start() / stream.stop()
*/
import { DEFAULT_FRAME_SIZE, DEFAULT_SAMPLE_RATE } from './constants.js'
import { normalizePcmFrame } from './pcmUtils.js'
// #ifdef APP-PLUS
import {
startPcmCapture,
stopPcmCapture,
onPcmFrame,
offPcmFrame
} from '@/uni_modules/gl-pcm-capture'
// #endif
class AudioStreamService {
static _instance = null
constructor() {
this._listeners = new Set()
this._running = false
this._frameHandler = null
this._logEveryN = 50
this._frameCount = 0
}
static getInstance() {
if (!AudioStreamService._instance) {
AudioStreamService._instance = new AudioStreamService()
}
return AudioStreamService._instance
}
/**
* 订阅 PCM 帧
* @param {(frame: object) => void} callback frame 含 base64、buffer(ArrayBuffer)、seq 等
* @returns {() => void} 取消订阅
*/
onChunk(callback) {
if (typeof callback !== 'function') {
return () => {}
}
this._listeners.add(callback)
return () => this._listeners.delete(callback)
}
offChunk(callback) {
this._listeners.delete(callback)
}
get isRunning() {
return this._running
}
/**
* @param {object} [options]
* @param {number} [options.sampleRate]
* @param {number} [options.frameSize]
* @param {boolean} [options.debugLog] 是否打印采样日志
*/
start(options = {}) {
// #ifndef APP-PLUS
uni.$logger?.local?.warn('[AudioStream] 仅 App 端支持')
return Promise.resolve(false)
// #endif
// #ifdef APP-PLUS
if (plus.os.name !== 'Android') {
uni.$logger?.local?.warn('[AudioStream] 当前仅实现 Android PCM 采集')
return Promise.resolve(false)
}
if (typeof startPcmCapture !== 'function') {
uni.$logger?.local?.error(
'[AudioStream] gl-pcm-capture 未加载,请使用含 UTS 插件的自定义基座/正式包'
)
return Promise.resolve(false)
}
if (this._running) {
return Promise.resolve(true)
}
const sampleRate = options.sampleRate || DEFAULT_SAMPLE_RATE
const frameSize = options.frameSize || DEFAULT_FRAME_SIZE
const debugLog = options.debugLog !== false
this._frameHandler = (frame) => {
const normalized = normalizePcmFrame(frame)
this._frameCount++
if (debugLog && this._frameCount % this._logEveryN === 1) {
uni.$logger?.local?.info(
`[AudioStream] frame#${normalized.seq} bytes=${normalized.byteLength} ts=${normalized.timestamp}`
)
}
this._listeners.forEach((cb) => {
try {
cb(normalized)
} catch (e) {
uni.$logger?.local?.error(`[AudioStream] listener error: ${e.message}`)
}
})
}
onPcmFrame(this._frameHandler)
return new Promise((resolve) => {
startPcmCapture({
sampleRate,
frameSize,
success: () => {
this._running = true
this._frameCount = 0
uni.$logger?.local?.info('[AudioStream] PCM 采集已启动')
resolve(true)
},
fail: (err) => {
offPcmFrame()
this._frameHandler = null
uni.$logger?.local?.error(`[AudioStream] 启动失败: ${JSON.stringify(err)}`)
resolve(false)
}
})
})
// #endif
}
stop() {
// #ifdef APP-PLUS
if (plus.os.name === 'Android') {
stopPcmCapture()
offPcmFrame()
}
// #endif
this._running = false
this._frameHandler = null
this._frameCount = 0
uni.$logger?.local?.info('[AudioStream] PCM 采集已停止')
}
}
export default AudioStreamService
/** 接待录音时是否同步启动 PCM 流采集(Android) */
export const ENABLE_PCM_STREAM = true
/** 默认采样率,与接待录音一致 */
export const DEFAULT_SAMPLE_RATE = 16000
/** 每帧字节数,约 128ms @ 16kHz mono 16bit */
export const DEFAULT_FRAME_SIZE = 4096
import FloatLogBus from '@/utils/logger/FloatLogBus.js'
const DEMO_TAG = '[AudioDemo]'
export function demoLog(level, msg) {
const text = `${DEMO_TAG} ${msg}`
const logger = uni.$logger?.local
// 只走 logger;若已 install FloatLogBus,logger 监听器会同步到悬浮窗,避免重复打两条
if (logger?.[level]) {
logger[level](text)
} else {
console.log(text)
try {
if (!FloatLogBus.isInstalled()) {
FloatLogBus.install()
}
FloatLogBus.push(level, text)
} catch (_) {
/* ignore */
}
}
return { level, text, time: Date.now() }
}
import AudioStreamService from './AudioStreamService.js'
import AudioStreamDemoRunner from './AudioStreamDemoRunner.js'
import { ENABLE_PCM_STREAM, DEFAULT_SAMPLE_RATE, DEFAULT_FRAME_SIZE } from './constants.js'
import { base64ToArrayBuffer, normalizePcmFrame } from './pcmUtils.js'
import { demoLog } from './demoLog.js'
export {
AudioStreamService,
AudioStreamDemoRunner,
ENABLE_PCM_STREAM,
DEFAULT_SAMPLE_RATE,
DEFAULT_FRAME_SIZE,
base64ToArrayBuffer,
normalizePcmFrame,
demoLog
}
export default AudioStreamService
/**
* base64 PCM → ArrayBuffer
* @param {string} base64
* @returns {ArrayBuffer}
*/
export function base64ToArrayBuffer(base64) {
if (typeof uni !== 'undefined' && typeof uni.base64ToArrayBuffer === 'function') {
return uni.base64ToArrayBuffer(base64)
}
const binary = atob(base64)
const len = binary.length
const bytes = new Uint8Array(len)
for (let i = 0; i < len; i++) {
bytes[i] = binary.charCodeAt(i)
}
return bytes.buffer
}
/**
* 将插件帧数据标准化,附带 ArrayBuffer
* @param {object} frame
* @returns {object}
*/
export function normalizePcmFrame(frame) {
return {
...frame,
buffer: base64ToArrayBuffer(frame.base64)
}
}
...@@ -11,6 +11,7 @@ import { AudioManager, RecordDto, helpler, StrategyFactory, TimeoutService } fro ...@@ -11,6 +11,7 @@ import { AudioManager, RecordDto, helpler, StrategyFactory, TimeoutService } fro
import { storageApi } from '@/utils/cache' import { storageApi } from '@/utils/cache'
import permision from '@/js_sdk/wa-permission/permission.js' import permision from '@/js_sdk/wa-permission/permission.js'
import store from '@/store' import store from '@/store'
import AudioStreamService, { ENABLE_PCM_STREAM } from '@/utils/audioStream'
class RecordService { class RecordService {
static instance = null static instance = null
...@@ -99,6 +100,7 @@ class RecordService { ...@@ -99,6 +100,7 @@ class RecordService {
} }
this.audioManager.start() this.audioManager.start()
this.timeoutService.start() this.timeoutService.start()
await this.startPcmStream()
return true // 返回 true 表示成功启动 return true // 返回 true 表示成功启动
} catch (e) { } catch (e) {
uni.$logger.local.error(`【录音服务RecordService】 == startAudio 异常: ${e.message}`) uni.$logger.local.error(`【录音服务RecordService】 == startAudio 异常: ${e.message}`)
...@@ -200,10 +202,26 @@ class RecordService { ...@@ -200,10 +202,26 @@ class RecordService {
this.stopAudioRecord() this.stopAudioRecord()
} }
stopAudioRecord() { stopAudioRecord() {
this.stopPcmStream()
this.audioManager?.stop() this.audioManager?.stop()
this.timeoutService?.stop() this.timeoutService?.stop()
} }
/** 获取 PCM 流服务,业务侧通过 onChunk 监听实时音频帧 */
getAudioStreamService() {
return AudioStreamService.getInstance()
}
async startPcmStream() {
if (!ENABLE_PCM_STREAM) return
await AudioStreamService.getInstance().start()
}
stopPcmStream() {
if (!ENABLE_PCM_STREAM) return
AudioStreamService.getInstance().stop()
}
handler(params, fn, delay = 0) { handler(params, fn, delay = 0) {
if (this.isReceptioning()) { if (this.isReceptioning()) {
// if (delay > 0) { // if (delay > 0) {
......
/*
* 原生 WebSocket 客户端(SocketTask)
* 协议对齐 venus uniapp-x-tape/ws/Ws.uts
* API 对齐 https://uniapp.dcloud.net.cn/api/request/websocket.html
*/
import config from '@/config.js'
import { serializeIfObject } from '@/utils/utils.js'
import { loginDevice } from './wsAuth.js'
import {
buildAuthenticatedWsUrl,
getNativeWsBase,
pickLoginWsUrl
} from './wsConfig.js'
import { normalizeWsPayload } from './wsMessage.js'
import { createSocketTask } from './connectSocketTask.js'
const DEFAULT_TYPE = 'private'
function formatSocketErr(err) {
if (!err) return 'unknown'
if (typeof err === 'string') return err
if (err.errMsg) return err.errMsg
if (err.message) return err.message
const raw = serializeIfObject(err)
return raw === '{}' ? 'WebSocket 连接失败(请确认 utils/socket/wsConfig.js 中 NATIVE_WS_BASE)' : raw
}
class NativeWsClient {
constructor() {
this.wsAddress = getNativeWsBase() || config.SOCKET_SERVER
this.token = ''
this.deviceId = ''
this.onMessage = null
this.socketTask = null
this._connected = false
this._manualClose = false
this._reconnectTimer = null
this._reconnectCount = 0
this._isReconnecting = false
}
get isConnected() {
return this._connected && this.socketTask != null
}
async connect() {
this._manualClose = false
try {
const loginRes = await loginDevice()
const code = loginRes?.code
if (code != 200 && code != 0) {
throw new Error(`登录失败 code=${code}`)
}
const data = loginRes.data || {}
this.deviceId = data.id
this.token = data.token
if (!this.deviceId || !this.token) {
throw new Error('登录返回缺少 id 或 token')
}
const wsFromLogin = pickLoginWsUrl(data)
if (wsFromLogin) {
this.wsAddress = wsFromLogin
}
await this._createSocket()
} catch (e) {
this._log('error', `connect 失败: ${e.message}`)
this._scheduleReconnect()
throw e
}
}
send(data, type = DEFAULT_TYPE) {
if (!this.isConnected) {
this._log('warn', '未连接,send 忽略')
return Promise.resolve(false)
}
const packet =
typeof data === 'string'
? data
: JSON.stringify({
...data,
device_id: this.deviceId,
type: data.type || type
})
return new Promise((resolve) => {
this.socketTask.send({
data: packet,
success: () => resolve(true),
fail: (err) => {
this._log('warn', `send 失败: ${serializeIfObject(err)}`)
resolve(false)
}
})
})
}
async close(code = 1000, reason = 'manual close', manual = true) {
this._manualClose = manual
this._clearReconnectTimer()
this._connected = false
const task = this.socketTask
this.socketTask = null
if (!task) return
await new Promise((resolve) => {
task.close({ code, reason, complete: () => resolve() })
})
}
async waitUntilConnected(timeoutMs = 15000) {
if (this.isConnected) return true
const start = Date.now()
while (Date.now() - start < timeoutMs) {
if (this.isConnected) return true
await new Promise((r) => setTimeout(r, 200))
}
return false
}
async _createSocket() {
await this.close(1000, 'reconnect', false).catch(() => {})
this._manualClose = false
const url = buildAuthenticatedWsUrl(this.wsAddress, this.token, this.deviceId)
await this._connectSocketByUrl(url)
}
_connectSocketByUrl(targetUrl) {
this._log(
'info',
`连接地址 ${targetUrl}(login=${config.HTTP_SERVER})`
)
return new Promise((resolve, reject) => {
let opened = false
let settled = false
const timer = setTimeout(() => {
if (settled) return
settled = true
reject(new Error(`连接超时: ${targetUrl}`))
}, 8000)
const finishOpen = () => {
if (settled) return
opened = true
settled = true
clearTimeout(timer)
this._reconnectCount = 0
this._isReconnecting = false
this._connected = true
this._log('warn', '连接成功')
resolve()
}
const failEarly = (err) => {
if (settled) return
settled = true
clearTimeout(timer)
reject(new Error(err?.message || serializeIfObject(err)))
}
let socketTask
try {
socketTask = createSocketTask({
url: targetUrl,
fail: (err) => failEarly(err)
})
} catch (e) {
failEarly(e)
return
}
this.socketTask = socketTask
socketTask.onOpen(() => finishOpen())
socketTask.onMessage((event) => this._handleMessage(event?.data))
socketTask.onError((err) => {
this._log('error', `异常 ${formatSocketErr(err)}`)
if (!opened && !settled) {
failEarly(new Error(`onError: ${formatSocketErr(err)}`))
} else if (opened && !this._manualClose) {
this._scheduleReconnect()
}
})
socketTask.onClose((res) => {
this._connected = false
this.socketTask = null
this._log('warn', `断开 ${serializeIfObject(res)}`)
if (!opened && !settled) {
const closeHint = res?.code === 1006 || !res?.code
? '(握手失败,常见原因:路径 404 或服务端仅支持 socket.io)'
: ''
failEarly(new Error(`onClose before open: ${serializeIfObject(res)}${closeHint}`))
return
}
if (!this._manualClose) {
this._scheduleReconnect()
}
})
})
}
_handleMessage(raw) {
const data = normalizeWsPayload(raw)
this._log('info', `收到 <= ${JSON.stringify(data).slice(0, 240)}`)
if (data.errorCode && data.errorCode == 907) {
this._log('warn', 'Token 过期,准备重连')
this._scheduleReconnect(true)
return
}
this.onMessage && this.onMessage(data)
}
_scheduleReconnect(force = false) {
if (this._manualClose) return
if (this._isReconnecting && !force) return
this._isReconnecting = true
this._clearReconnectTimer()
this._reconnectCount += 1
const delay = Math.min(30000, this._reconnectCount * 2000)
this._log('warn', `${delay}ms 后第 ${this._reconnectCount} 次重连`)
this._reconnectTimer = setTimeout(() => {
this._reconnectTimer = null
this.connect().catch(() => {})
}, delay)
}
_clearReconnectTimer() {
if (this._reconnectTimer != null) {
clearTimeout(this._reconnectTimer)
this._reconnectTimer = null
}
}
_log(level, msg) {
const text = `[NativeWs] ${msg}`
const logger = uni.$logger?.local
if (logger?.[level]) {
logger[level](text)
} else if (level === 'error') {
console.error(text)
} else if (level === 'warn') {
console.warn(text)
} else {
console.log(text)
}
}
}
let _instance = null
NativeWsClient.getInstance = function getInstance() {
if (!_instance) {
_instance = new NativeWsClient()
}
return _instance
}
NativeWsClient.resetInstance = function resetInstance() {
if (_instance) {
_instance.close().catch(() => {})
_instance = null
}
}
export default NativeWsClient
/*
* socket.io 客户端封装(与 ws/Ws.js 同协议,供 Demo / 业务推流使用)
* 注意:项目服务端是 socket.io,不能用 uni.connectSocket 直连
*/
import io from '@/uni_modules/hyoga-uni-socket_io/uni-socket.io.js'
import config from '@/config.js'
import { WsTyps } from '@/utils/common'
import { serializeIfObject } from '@/utils/utils.js'
import { loginDevice } from './wsAuth.js'
class SocketIoClient {
constructor(options = {}) {
this._tag = options.logTag || 'SocketIo'
this._ws = null
this._deviceId = null
this._token = null
this._onMessage = null
this._connected = false
}
get isConnected() {
return this._connected && this._ws != null
}
get deviceId() {
return this._deviceId
}
onMessage(handler) {
this._onMessage = typeof handler === 'function' ? handler : null
}
/**
* 登录并连接 socket.io(与 Ws.js 相同 path / auth)
*/
async connect() {
if (this.isConnected) {
return true
}
const { code, data } = await loginDevice()
if (code != 200) {
throw new Error(`WS 登录失败 code=${code}`)
}
this._deviceId = data.id
this._token = data.token
this._log('info', `登录成功 deviceId=${this._deviceId}`)
return new Promise((resolve, reject) => {
const socket = io(config.SOCKET_SERVER, {
path: '/websocket/',
auth: { token: this._token, deviceId: this._deviceId },
transports: ['websocket'],
timeout: 5000
})
const timer = setTimeout(() => {
cleanup()
reject(new Error('socket.io 连接超时'))
}, 8000)
const onConnect = () => {
cleanup()
this._ws = socket
this._connected = true
this._log('info', 'socket.io 已连接')
this._bindMessage()
resolve(true)
}
const onError = (err) => {
cleanup()
this._log('error', `socket.io 错误 ${serializeIfObject(err)}`)
reject(err || new Error('socket.io error'))
}
const onDisconnect = () => {
this._connected = false
this._log('warn', 'socket.io 已断开')
}
const cleanup = () => {
clearTimeout(timer)
socket.off(WsTyps.Connected, onConnect)
socket.off(WsTyps.Eroor, onError)
}
socket.on(WsTyps.Connected, onConnect)
socket.on(WsTyps.Eroor, onError)
socket.on(WsTyps.Disconnected, onDisconnect)
this._log('info', `连接 socket.io -> ${config.SOCKET_SERVER}/websocket/`)
})
}
_bindMessage() {
if (!this._ws || !this._onMessage) return
this._ws.on(WsTyps.MessageTypes.Private, (data) => {
this._onMessage(data)
})
}
/**
* 发送消息(默认 private 频道,自动带 device_id)
* @param {object} data
*/
send(data, type = WsTyps.MessageTypes.Private) {
if (!this.isConnected) {
return Promise.reject(new Error('socket.io 未连接'))
}
const payload = { device_id: this._deviceId, ...data }
this._log('debug', `发送 => ${serializeIfObject(data).slice(0, 200)}`)
this._ws.emit(type, payload)
return Promise.resolve({ errMsg: 'emit:ok' })
}
disconnect() {
this._connected = false
if (this._ws) {
try {
this._ws.disconnect()
} catch (_) {
/* ignore */
}
this._ws = null
}
this._onMessage = null
this._log('info', 'socket.io 已关闭')
}
_log(level, msg) {
const text = `[${this._tag}] ${msg}`
uni.$logger?.local?.[level]?.(text) || console.log(text)
}
}
export default SocketIoClient
/*
* uni.connectSocket 官方说明:
* https://uniapp.dcloud.net.cn/api/request/websocket.html
*
* - 至少传入 success / fail / complete 之一 → 同步返回 SocketTask
* - 不传上述回调 → 返回封装后的 Promise<SocketTask>
*
* 统一使用 SocketTask(onOpen / onMessage / send / close),
* 不使用已废弃的全局 uni.onSocketOpen / uni.sendSocketMessage 等。
*/
export function isSocketTask(task) {
return task != null && typeof task.onOpen === 'function'
}
/**
* 文档推荐写法:传入 complete,同步拿到 SocketTask
* @param {{ url: string, header?: object, protocols?: string[], fail?: Function }} options
* @returns {object} SocketTask
*/
export function createSocketTask(options) {
const { url, header, protocols, fail } = options
if (!url) {
throw new Error('connectSocket 缺少 url')
}
const socketTask = uni.connectSocket({
url,
header: header || {},
protocols: protocols || [],
fail,
complete: () => {}
})
if (!isSocketTask(socketTask)) {
throw new Error('connectSocket 未返回 SocketTask,需传入 success / fail / complete 之一')
}
return socketTask
}
/**
* 兼容 Promise 封装:不传 success/fail/complete 时 await
* @param {{ url: string, header?: object, protocols?: string[] }} options
* @returns {Promise<object>} SocketTask
*/
export async function connectSocketTask(options) {
const { url, header, protocols } = options
if (!url) {
throw new Error('connectSocket 缺少 url')
}
const result = uni.connectSocket({
url,
header: header || {},
protocols: protocols || []
})
if (isSocketTask(result)) {
return result
}
if (result != null && typeof result.then === 'function') {
const task = await result
if (!isSocketTask(task)) {
throw new Error('connectSocket Promise 未解析为 SocketTask')
}
return task
}
return createSocketTask(options)
}
/** WebSocket 连接状态 */
export const SocketState = {
IDLE: 'idle',
CONNECTING: 'connecting',
OPEN: 'open',
CLOSING: 'closing',
CLOSED: 'closed'
}
export const DEFAULT_OPTIONS = {
/** 断线后是否自动重连 */
reconnect: true,
/** 重连间隔(ms) */
reconnectInterval: 3000,
/** 最大重连次数,-1 表示不限 */
reconnectMaxRetries: -1,
/** 未连接时是否缓存 send 队列 */
enableSendQueue: true,
/** send 队列上限 */
sendQueueMax: 100,
/** 收到文本消息时尝试 JSON.parse */
autoParseJson: true,
/** 日志标签 */
logTag: 'SocketClient'
}
import SocketClient from './SocketClient.js'
import NativeWsClient from './NativeWsClient.js'
import { createSocketTask, connectSocketTask, isSocketTask } from './connectSocketTask.js'
import { SocketState, DEFAULT_OPTIONS } from './constants.js'
import {
WS_NATIVE_PATH,
NATIVE_WS_BASE,
setNativeWsBase,
getNativeWsBase,
normalizeWsUrl,
buildAuthenticatedWsUrl,
pickLoginWsUrl
} from './wsConfig.js'
import { normalizeWsPayload } from './wsMessage.js'
import { loginDevice } from './wsAuth.js'
export {
SocketClient,
NativeWsClient,
createSocketTask,
connectSocketTask,
isSocketTask,
SocketState,
DEFAULT_OPTIONS,
WS_NATIVE_PATH,
NATIVE_WS_BASE,
setNativeWsBase,
getNativeWsBase,
normalizeWsUrl,
buildAuthenticatedWsUrl,
pickLoginWsUrl,
normalizeWsPayload,
loginDevice
}
export default SocketClient
/*
* 设备 WS 登录:POST {HTTP_SERVER}/login,body { sn: deviceId }
* 对齐 venus uniapp-x-tape/ws/Ws.uts login()
*
* 使用方:
* - utils/socket/NativeWsClient(原生 SocketTask / 音频 Demo)
* 不使用方:
* - 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))
}
}
}
/*
* 原生 WebSocket 地址(对齐 uniapp-x-tape/ws/Ws.uts)
* 连接格式: ws://host:port/path?token=xxx&deviceId=xxx
*
* WebSocket 与 HTTP 共用同一套服务,地址由服务端提供后填到 NATIVE_WS_BASE。
* 不修改 config.js / env.js。
*/
import config from '@/config.js'
/** SOCKET_SERVER 仅为域名时自动拼接的路径 */
export const WS_NATIVE_PATH = '/ws-native'
/**
* 原生 WS 完整 base(不含 ?token=),服务端提供后填写,例如:
* ws://host:8081/ws-native
*/
export let NATIVE_WS_BASE = 'wss://echo.websocket.org'
export function setNativeWsBase(url) {
NATIVE_WS_BASE = (url || '').trim()
}
export function getNativeWsBase() {
return NATIVE_WS_BASE
}
/**
* @param {string} url
* @returns {string}
*/
export function normalizeWsUrl(url) {
if (!url) return ''
const trimmed = url.trim()
if (/^wss?:\/\//i.test(trimmed)) {
return trimmed.replace(/\/+$/, '')
}
if (trimmed.startsWith('https://')) {
return `wss://${trimmed.slice(8)}`.replace(/\/+$/, '')
}
if (trimmed.startsWith('http://')) {
return `ws://${trimmed.slice(7)}`.replace(/\/+$/, '')
}
return trimmed
}
/**
* 从登录 data 中取服务端下发的 ws 地址(若有)
* @param {object} data
*/
export function pickLoginWsUrl(data) {
if (!data) return ''
return (
data.wsUrl ||
data.ws_url ||
data.socketUrl ||
data.socket_url ||
data.wsAddress ||
data.ws_address ||
''
)
}
/**
* 拼带鉴权 query 的完整 ws 地址
* @param {string} base SOCKET_SERVER 或登录返回的 wsUrl
* @param {string} token
* @param {string|number} deviceId
*/
export function buildAuthenticatedWsUrl(base, token, deviceId) {
const configured = NATIVE_WS_BASE.trim()
let root = configured ? normalizeWsUrl(configured) : normalizeWsUrl(base)
if (!configured) {
const path = WS_NATIVE_PATH.startsWith('/') ? WS_NATIVE_PATH : `/${WS_NATIVE_PATH}`
const hasPath = /^wss?:\/\/[^/]+\/.+/.test(root)
if (!hasPath) {
root = `${root.replace(/\/+$/, '')}${path}`
}
}
const encodedToken = encodeURIComponent(token)
const encodedDeviceId = encodeURIComponent(String(deviceId))
return `${root}?token=${encodedToken}&deviceId=${encodedDeviceId}`
}
/*
* 原生 WebSocket 消息解析(对齐 uniapp-x-tape/ws/Ws.uts normalizePayload)
*/
/**
* @param {string|ArrayBuffer|object} raw
* @returns {object}
*/
export function normalizeWsPayload(raw) {
if (raw == null) {
return { command: 'message', data: null }
}
let parsed = null
if (typeof raw === 'string') {
try {
parsed = JSON.parse(raw.trim())
} catch {
return { command: 'message', raw }
}
} else if (raw instanceof ArrayBuffer) {
try {
const text = uni.arrayBufferToBase64
? decodeArrayBuffer(raw)
: String(raw)
parsed = JSON.parse(text)
} catch {
return { command: 'message', raw: '[ArrayBuffer]' }
}
} else if (typeof raw === 'object') {
parsed = raw
} else {
return { command: 'message', raw: String(raw) }
}
// { event: "private", data: { command: "xxx" } }
if (parsed.event != null && parsed.data != null) {
return typeof parsed.data === 'object' ? parsed.data : { data: parsed.data }
}
// { code: 200, data: { event, data: { command } } }
if (parsed.code != null && parsed.data != null) {
const outer = parsed.data
if (outer && outer.data != null) {
return typeof outer.data === 'object' ? outer.data : { data: outer.data }
}
return typeof outer === 'object' ? outer : { data: outer }
}
return parsed
}
function decodeArrayBuffer(buffer) {
if (typeof TextDecoder !== 'undefined') {
return new TextDecoder('utf-8').decode(buffer)
}
const bytes = new Uint8Array(buffer)
let s = ''
for (let i = 0; i < bytes.length; i++) {
s += String.fromCharCode(bytes[i])
}
return s
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!