Files
ttstd_family_care_miniapp/utils/sse.ts
T
tongtong 9030938c84 feat(miniapp): 补齐设备功能页面与统一 UI 规范
- 新增系统设置、壁纸、图标包、设备管理、通讯录、通话、短信、相册、文件、应用、告警、信息、首页布局、账号安全、绑定手机号、法律条款等页面
- utils/api.ts 补齐设备操作、策略、壁纸、图标包等 /api/v1/client/** 接口,新增多文件上传
- 新增 utils/sse.ts 与 utils/wx-session.ts
- 「更多/进入」指示统一改为图片箭头,首卡统一 .hero-card 高度,页面首卡贴顶
- AGENTS.md 补充功能对接状态与小程序 UI 约定
2026-11-28 18:19:19 +08:00

205 lines
5.7 KiB
TypeScript

import { BASE_URL } from './config'
import { getAccessToken } from './token'
/** 与后端 SseEventConstants.DEVICE_ONLINE_STATUS 保持一致 */
const DEVICE_ONLINE_STATUS_EVENT = 'device-online-status'
export interface DeviceOnlineStatus {
serialno: string
online: number
lastHeartbeatTime?: string
ip?: string
screenState?: number | null
}
interface SsePacket {
event: string
data: string
}
/** miniprogram-api-typings 尚未声明 enableChunked,这里补最小类型 */
interface ChunkedRequestOptions {
url: string
method: 'GET'
header: Record<string, string>
responseType: 'arraybuffer'
enableChunked: boolean
enableHttp2: boolean
timeout: number
success: () => void
fail: () => void
}
interface ChunkedRequestTask {
onChunkReceived: (callback: (result: { data: ArrayBuffer }) => void) => void
abort: () => void
}
type ChunkedRequest = (options: ChunkedRequestOptions) => ChunkedRequestTask
const chunkedRequest = wx.request as unknown as ChunkedRequest
/** 流式 UTF-8 解码:chunk 可能在多字节字符中间截断 */
class Utf8StreamDecoder {
private pending: number[] = []
decode(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer)
let result = ''
const append = (codePoint: number): void => {
if (codePoint <= 0xffff) {
result += String.fromCharCode(codePoint)
return
}
const value = codePoint - 0x10000
result += String.fromCharCode(0xd800 + (value >> 10), 0xdc00 + (value & 0x3ff))
}
for (let index = 0; index < bytes.length; index += 1) {
const byte = bytes[index]
if (this.pending.length === 0) {
if (byte < 0x80) {
append(byte)
} else if (byte >= 0xc2 && byte <= 0xf4) {
this.pending.push(byte)
} else {
append(0xfffd)
}
continue
}
const first = this.pending[0]
const expected = first < 0xe0 ? 2 : first < 0xf0 ? 3 : 4
this.pending.push(byte)
if (this.pending.length < expected) continue
const [b0, b1, b2, b3] = this.pending
this.pending = []
let valid = (b1 & 0xc0) === 0x80
let codePoint = 0
if (expected === 2) {
codePoint = ((b0 & 0x1f) << 6) | (b1 & 0x3f)
} else {
valid = valid && (b2 & 0xc0) === 0x80
if (expected === 3) {
codePoint = ((b0 & 0x0f) << 12) | ((b1 & 0x3f) << 6) | (b2 & 0x3f)
valid = valid && codePoint >= 0x800 && !(codePoint >= 0xd800 && codePoint <= 0xdfff)
} else {
valid = valid && (b3 & 0xc0) === 0x80
codePoint = ((b0 & 0x07) << 18) | ((b1 & 0x3f) << 12) | ((b2 & 0x3f) << 6) | (b3 & 0x3f)
valid = valid && codePoint >= 0x10000 && codePoint <= 0x10ffff
}
}
append(valid ? codePoint : 0xfffd)
}
return result
}
}
/** 家属端设备在线状态 SSE 客户端 */
export class DeviceStatusSseClient {
private task: ChunkedRequestTask | null = null
private decoder = new Utf8StreamDecoder()
private buffer = ''
private retry = 0
private stopped = true
private reconnectTimer: number | null = null
constructor(private readonly onStatus: (status: DeviceOnlineStatus) => void) {}
start(): void {
if (!this.stopped) return
this.stopped = false
this.retry = 0
this.connect()
}
stop(): void {
this.stopped = true
if (this.reconnectTimer !== null) {
clearTimeout(this.reconnectTimer)
this.reconnectTimer = null
}
this.task?.abort()
this.task = null
this.buffer = ''
}
private connect(): void {
if (this.stopped) return
const token = getAccessToken()
if (!token) return
this.decoder = new Utf8StreamDecoder()
this.buffer = ''
const task = chunkedRequest({
url: `${BASE_URL}/v1/client/sn/online/stream`,
method: 'GET',
header: {
Authorization: `Bearer ${token}`,
Accept: 'text/event-stream'
},
responseType: 'arraybuffer',
enableChunked: true,
enableHttp2: false,
timeout: 60000,
success: () => this.onDisconnected(),
fail: () => this.onDisconnected()
})
this.task = task
task.onChunkReceived(({ data }) => {
this.buffer += this.decoder.decode(data)
this.parseEvents().forEach((packet) => this.handlePacket(packet))
})
}
private parseEvents(): SsePacket[] {
const normalized = this.buffer.replace(/\r\n/g, '\n')
const blocks = normalized.split('\n\n')
this.buffer = blocks.pop() || ''
return blocks
.map((block) => {
let event = ''
const dataLines: string[] = []
block.split('\n').forEach((line) => {
if (line.startsWith('event:')) {
event = line.slice(6).trim()
} else if (line.startsWith('data:')) {
dataLines.push(line.slice(5).replace(/^ /, ''))
}
})
return { event, data: dataLines.join('\n') }
})
.filter((packet) => !!packet.event || !!packet.data)
}
private handlePacket(packet: SsePacket): void {
if (packet.event === 'ping') {
this.retry = 0
return
}
if (packet.event !== DEVICE_ONLINE_STATUS_EVENT || !packet.data) return
try {
const status = JSON.parse(packet.data) as DeviceOnlineStatus
if (status && status.serialno) this.onStatus(status)
} catch {
// 忽略单条格式异常事件,不影响后续推送
}
}
private onDisconnected(): void {
if (this.stopped) return
this.task = null
this.retry += 1
const delay = Math.min(30000, 1000 * Math.pow(2, Math.min(this.retry, 5)))
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null
this.connect()
}, delay) as unknown as number
}
}