feat:客服
This commit is contained in:
58
src/utils/message-push-cache.ts
Normal file
58
src/utils/message-push-cache.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { ref } from 'vue'
|
||||
import type { AppMessageVo, MessagePushPayload } from '@/types/message'
|
||||
import { buildMessageFromPush, normalizeMessageId } from '@/utils/message-push'
|
||||
|
||||
const cachedPushes = new Map<string, AppMessageVo>()
|
||||
export const pushCacheCount = ref(0)
|
||||
|
||||
function syncCacheCount() {
|
||||
pushCacheCount.value = cachedPushes.size
|
||||
}
|
||||
|
||||
function resolveCacheId(payload: MessagePushPayload, message: AppMessageVo): string {
|
||||
const messageId = normalizeMessageId(message)
|
||||
if (messageId) return messageId
|
||||
if (payload.alertId != null && payload.alertId !== '') return String(payload.alertId)
|
||||
const stamp = payload.timestamp || Date.now()
|
||||
const title = payload.title || payload.content || 'push'
|
||||
return `${title}-${stamp}`
|
||||
}
|
||||
|
||||
export function rememberPushPayload(payload: MessagePushPayload): AppMessageVo | null {
|
||||
if (!payload.title && !payload.content && payload.messageId == null && payload.alertId == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
const message = buildMessageFromPush(payload)
|
||||
const id = resolveCacheId(payload, message)
|
||||
message.messageId = id
|
||||
cachedPushes.set(id, message)
|
||||
syncCacheCount()
|
||||
return message
|
||||
}
|
||||
|
||||
export function mergeCachedMessages(rows: AppMessageVo[]): AppMessageVo[] {
|
||||
const map = new Map<string, AppMessageVo>()
|
||||
for (const item of rows) {
|
||||
const id = normalizeMessageId(item)
|
||||
if (id) map.set(id, item)
|
||||
}
|
||||
for (const [id, item] of cachedPushes) {
|
||||
if (!map.has(id)) map.set(id, item)
|
||||
}
|
||||
return Array.from(map.values())
|
||||
}
|
||||
|
||||
export function forgetCachedMessage(messageId: string) {
|
||||
cachedPushes.delete(messageId)
|
||||
syncCacheCount()
|
||||
}
|
||||
|
||||
export function clearPushCache() {
|
||||
cachedPushes.clear()
|
||||
syncCacheCount()
|
||||
}
|
||||
|
||||
export function getCachedPushCount(): number {
|
||||
return pushCacheCount.value
|
||||
}
|
||||
114
src/utils/message-push.ts
Normal file
114
src/utils/message-push.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import type { AppMessageVo, MessagePushPayload } from '@/types/message'
|
||||
|
||||
export function normalizeMessageId(message: AppMessageVo): string {
|
||||
const raw = message.messageId
|
||||
if (raw === undefined || raw === null || raw === '') return ''
|
||||
return String(raw)
|
||||
}
|
||||
|
||||
export function buildMessageFromPush(payload: MessagePushPayload): AppMessageVo {
|
||||
return {
|
||||
messageId: payload.messageId,
|
||||
alertId: payload.alertId,
|
||||
alertType: payload.alertType,
|
||||
title: payload.title,
|
||||
content: payload.content,
|
||||
deviceId: payload.deviceId,
|
||||
timestamp: payload.timestamp,
|
||||
readFlag: '0',
|
||||
}
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
|
||||
return value as Record<string, unknown>
|
||||
}
|
||||
|
||||
function pickString(obj: Record<string, unknown>, keys: string[]): string | undefined {
|
||||
for (const key of keys) {
|
||||
const value = obj[key]
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
return String(value)
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function pickId(obj: Record<string, unknown>, keys: string[]): string | number | undefined {
|
||||
for (const key of keys) {
|
||||
const value = obj[key]
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
return typeof value === 'number' ? value : String(value)
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function normalizeMessagePushPayload(
|
||||
source: Record<string, unknown>,
|
||||
): MessagePushPayload {
|
||||
return {
|
||||
messageId: pickId(source, ['messageId', 'id', 'msgId']),
|
||||
alertId: pickId(source, ['alertId', 'alert_id']),
|
||||
alertType: pickString(source, ['alertType', 'alert_type', 'type']),
|
||||
title: pickString(source, ['title', 'msgTitle', 'subject']),
|
||||
content: pickString(source, ['content', 'msgContent', 'body', 'message']),
|
||||
deviceId: pickId(source, ['deviceId', 'device_id']),
|
||||
timestamp: pickString(source, ['timestamp', 'createTime', 'time']),
|
||||
}
|
||||
}
|
||||
|
||||
export function parseMessagePushPayload(raw: string): MessagePushPayload | null {
|
||||
if (!raw || raw === 'ping' || raw === 'pong') return null
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Record<string, unknown>
|
||||
const type = String(parsed.type ?? '').toLowerCase()
|
||||
|
||||
if (type === 'message' || type === 'push' || type === 'notify') {
|
||||
const nested = asRecord(parsed.data) ?? asRecord(parsed.message) ?? asRecord(parsed.msg)
|
||||
if (nested) return normalizeMessagePushPayload(nested)
|
||||
}
|
||||
|
||||
const nested = asRecord(parsed.data) ?? asRecord(parsed.message) ?? asRecord(parsed.msg)
|
||||
if (nested) {
|
||||
const payload = normalizeMessagePushPayload(nested)
|
||||
if (payload.title || payload.content || payload.messageId) return payload
|
||||
}
|
||||
|
||||
const direct = normalizeMessagePushPayload(parsed)
|
||||
if (direct.title || direct.content || direct.messageId || direct.alertId) {
|
||||
return direct
|
||||
}
|
||||
|
||||
if (import.meta.env.DEV) {
|
||||
console.log('[Message WS] unknown payload', parsed)
|
||||
}
|
||||
return null
|
||||
} catch {
|
||||
if (import.meta.env.DEV) {
|
||||
console.log('[Message WS] invalid json', raw)
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function decodeSocketMessageData(data: unknown): string {
|
||||
if (typeof data === 'string') return data
|
||||
if (data instanceof ArrayBuffer) {
|
||||
return new TextDecoder('utf-8').decode(data)
|
||||
}
|
||||
if (ArrayBuffer.isView(data)) {
|
||||
return new TextDecoder('utf-8').decode(data.buffer)
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
export function getMessagePushToastText(payload: MessagePushPayload): string | null {
|
||||
const title = payload.title?.trim()
|
||||
if (title) return title
|
||||
const content = payload.content?.trim()
|
||||
if (content) return content.length > 30 ? `${content.slice(0, 30)}...` : content
|
||||
if (payload.messageId || payload.alertId) return '您有新消息'
|
||||
return null
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
import {
|
||||
decodeSocketMessageData,
|
||||
getMessagePushToastText,
|
||||
parseMessagePushPayload,
|
||||
} from '@/utils/message-push'
|
||||
import type { MessagePushPayload } from '@/types/message'
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 25000
|
||||
@@ -9,6 +14,8 @@ let heartbeatTimer: ReturnType<typeof setInterval> | null = null
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let connecting = false
|
||||
let manualClosed = false
|
||||
let socketOpened = false
|
||||
let disconnectHandled = false
|
||||
|
||||
const listeners = new Set<(payload: MessagePushPayload) => void>()
|
||||
|
||||
@@ -35,11 +42,15 @@ function stopHeartbeat() {
|
||||
heartbeatTimer = null
|
||||
}
|
||||
|
||||
function sendPing() {
|
||||
if (!socketOpened || !socketTask) return
|
||||
socketTask.send({ data: 'ping' })
|
||||
}
|
||||
|
||||
function startHeartbeat() {
|
||||
stopHeartbeat()
|
||||
heartbeatTimer = setInterval(() => {
|
||||
socketTask?.send({ data: 'ping' })
|
||||
}, HEARTBEAT_INTERVAL_MS)
|
||||
sendPing()
|
||||
heartbeatTimer = setInterval(sendPing, HEARTBEAT_INTERVAL_MS)
|
||||
}
|
||||
|
||||
function clearReconnectTimer() {
|
||||
@@ -58,20 +69,45 @@ function scheduleReconnect() {
|
||||
function cleanupSocketTask() {
|
||||
stopHeartbeat()
|
||||
socketTask = null
|
||||
socketOpened = false
|
||||
connecting = false
|
||||
disconnectHandled = false
|
||||
}
|
||||
|
||||
function handleDisconnect(reason: string) {
|
||||
if (disconnectHandled) return
|
||||
disconnectHandled = true
|
||||
if (import.meta.env.DEV) {
|
||||
console.log(`[Message WS] ${reason}`)
|
||||
}
|
||||
cleanupSocketTask()
|
||||
if (!manualClosed) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
function handleSocketMessage(raw: string) {
|
||||
if (!raw || raw === 'ping' || raw === 'pong') return
|
||||
try {
|
||||
const data = JSON.parse(raw) as MessagePushPayload
|
||||
listeners.forEach((listener) => listener(data))
|
||||
if (data.title) {
|
||||
uni.showToast({ title: data.title, icon: 'none' })
|
||||
}
|
||||
} catch {
|
||||
// ignore invalid payload
|
||||
const payload = parseMessagePushPayload(raw)
|
||||
if (!payload) return
|
||||
|
||||
if (import.meta.env.DEV) {
|
||||
console.log('[Message WS] push', payload)
|
||||
}
|
||||
|
||||
listeners.forEach((listener) => listener(payload))
|
||||
|
||||
const toastText = getMessagePushToastText(payload)
|
||||
if (toastText) {
|
||||
uni.showToast({ title: toastText, icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
export function isMessageSocketConnected(): boolean {
|
||||
return socketOpened && !!socketTask
|
||||
}
|
||||
|
||||
export function isMessageSocketConnecting(): boolean {
|
||||
return connecting || (!!socketTask && !socketOpened)
|
||||
}
|
||||
|
||||
export function onMessagePush(listener: (payload: MessagePushPayload) => void) {
|
||||
@@ -81,38 +117,47 @@ export function onMessagePush(listener: (payload: MessagePushPayload) => void) {
|
||||
|
||||
export function connectMessageSocket() {
|
||||
const token = getStoredToken()
|
||||
if (!token || connecting || socketTask) return
|
||||
if (!token || manualClosed) return
|
||||
if (socketOpened && socketTask) return
|
||||
// 握手进行中:不要 close,否则 DevTools 会报 "closed before connection is established"
|
||||
if (isMessageSocketConnecting()) return
|
||||
|
||||
manualClosed = false
|
||||
connecting = true
|
||||
disconnectHandled = false
|
||||
clearReconnectTimer()
|
||||
|
||||
const task = uni.connectSocket({
|
||||
url: resolveMessageWsUrl(token),
|
||||
complete: () => {
|
||||
connecting = false
|
||||
fail: (err) => {
|
||||
if (import.meta.env.DEV) {
|
||||
console.log('[Message WS] connect fail', err)
|
||||
}
|
||||
handleDisconnect('connect fail')
|
||||
},
|
||||
})
|
||||
|
||||
socketTask = task
|
||||
|
||||
task.onOpen(() => {
|
||||
socketOpened = true
|
||||
connecting = false
|
||||
if (import.meta.env.DEV) {
|
||||
console.log('[Message WS] connected')
|
||||
}
|
||||
startHeartbeat()
|
||||
})
|
||||
|
||||
task.onMessage((res) => {
|
||||
const raw = typeof res.data === 'string' ? res.data : ''
|
||||
handleSocketMessage(raw)
|
||||
handleSocketMessage(decodeSocketMessageData(res.data))
|
||||
})
|
||||
|
||||
task.onClose(() => {
|
||||
cleanupSocketTask()
|
||||
scheduleReconnect()
|
||||
handleDisconnect('closed')
|
||||
})
|
||||
|
||||
task.onError(() => {
|
||||
cleanupSocketTask()
|
||||
scheduleReconnect()
|
||||
handleDisconnect('error')
|
||||
})
|
||||
}
|
||||
|
||||
@@ -120,9 +165,15 @@ export function disconnectMessageSocket() {
|
||||
manualClosed = true
|
||||
clearReconnectTimer()
|
||||
stopHeartbeat()
|
||||
disconnectHandled = true
|
||||
if (socketTask) {
|
||||
socketTask.close({})
|
||||
try {
|
||||
socketTask.close({})
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
socketTask = null
|
||||
socketOpened = false
|
||||
connecting = false
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import iconRunModeInfo from '@/static/组 15227@2x.png'
|
||||
import iconHomeSelector from '@/static/图标 4.png'
|
||||
import iconHomeArrow from '@/static/组 9.png'
|
||||
import iconHomeSelected from '@/static/完成@2x.png'
|
||||
import iconNotify from '@/static/组 27.png'
|
||||
import iconNotify from '@/static/通知 (1).png'
|
||||
import iconDeviceEmpty from '@/static/图标 8.png'
|
||||
import iconDeviceNameEdit from '@/static/图标 9.png'
|
||||
import iconBindComplete from '@/static/组 41@2x.png'
|
||||
@@ -57,7 +57,7 @@ export const staticAssets = {
|
||||
iconHomeArrow,
|
||||
/** 完成@2x.png — 「我的家」下拉选中图标 */
|
||||
iconHomeSelected,
|
||||
/** 组 27.png — 设备页右上角通知 */
|
||||
/** 通知 (1).png — 设备页右上角通知 */
|
||||
iconNotify,
|
||||
/** 图标 8.png — 设备空状态中心图标 */
|
||||
iconDeviceEmpty,
|
||||
|
||||
@@ -100,6 +100,11 @@ export function splitZ2NotifyRecords(raw: string): string[] {
|
||||
return [text]
|
||||
}
|
||||
|
||||
// 实机单包 Q 应答(含 M= 与 B=)整条解析,避免误拆成碎片
|
||||
if (text.startsWith('Q;') && /;M=/i.test(text)) {
|
||||
return [text]
|
||||
}
|
||||
|
||||
// 仅标准多包应答(Q; 开头或独立 FL=/FILTER= 行)才拆分
|
||||
const isMultiRecord = text.startsWith('Q;')
|
||||
|| /(?:^|;)FL=|(?:^|;)FILTER=/.test(text)
|
||||
@@ -196,10 +201,9 @@ function parseBatteryValue(value: string): number | undefined {
|
||||
const raw = Number(matched[1])
|
||||
if (!Number.isFinite(raw)) return undefined
|
||||
if (raw <= 100) return clampPercent(raw)
|
||||
// 实机可能上报 731 表示 73.1%
|
||||
const scaled = Math.round(raw / 10)
|
||||
if (scaled <= 100) return clampPercent(scaled)
|
||||
return clampPercent(raw % 100)
|
||||
// 实机可能上报 731 表示 73.1%,800 表示 80.0%
|
||||
if (raw <= 1000) return clampPercent(Math.round(raw / 10))
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 解析单行 Notify,如 `Q;M=L;W=C;A=G` 或 `B=34;P=B` */
|
||||
@@ -269,11 +273,21 @@ export function mergeZ2DeviceState(
|
||||
|
||||
export function parseZ2NotifyPayload(lines: string[]): Z2DeviceState {
|
||||
let state: Z2DeviceState = {}
|
||||
let batteryFromMainLine: number | undefined
|
||||
|
||||
for (const line of lines) {
|
||||
for (const record of splitZ2NotifyRecords(line)) {
|
||||
state = mergeZ2DeviceState(state, parseZ2NotifyLine(record))
|
||||
const patch = parseZ2NotifyLine(record)
|
||||
if (/M=/i.test(record) && patch.battery != null) {
|
||||
batteryFromMainLine = patch.battery
|
||||
}
|
||||
state = mergeZ2DeviceState(state, patch)
|
||||
}
|
||||
}
|
||||
|
||||
if (batteryFromMainLine != null) {
|
||||
state.battery = batteryFromMainLine
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
|
||||
@@ -291,9 +291,12 @@ function writeBleAscii(
|
||||
|
||||
function appendNotifyText(buffer: string, chunk: string): string {
|
||||
if (!chunk) return buffer
|
||||
if (!buffer) return chunk
|
||||
const needsSeparator = !/[;\r\n]$/.test(buffer) && !/^(B=\d|T=\d|FL=|FILTER=|Q;)/.test(chunk)
|
||||
return needsSeparator ? `${buffer}${chunk}` : `${buffer}${chunk}`
|
||||
const next = chunk.trim()
|
||||
if (!next) return buffer
|
||||
if (!buffer) return next
|
||||
if (/[;\r\n]$/.test(buffer)) return `${buffer}${next}`
|
||||
// 分包粘连时补分隔符,避免 B=8 + 0... 被拼成 B=80
|
||||
return `${buffer};${next}`
|
||||
}
|
||||
|
||||
function resolveNotifyRecords(buffer: string): string[] {
|
||||
@@ -307,7 +310,7 @@ async function collectNotifyLines(
|
||||
options: { maxWaitMs?: number; idleMs?: number } = {},
|
||||
): Promise<string[]> {
|
||||
const maxWaitMs = options.maxWaitMs ?? 6000
|
||||
const idleMs = options.idleMgs ?? 400
|
||||
const idleMs = options.idleMs ?? 400
|
||||
let buffer = ''
|
||||
let settled = false
|
||||
|
||||
|
||||
Reference in New Issue
Block a user