From 03839624edffdcd41f0ad9c4c25db62d96041737 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=BC=8A=E5=B8=86?= <15818603+Osborn-lyf@user.noreply.gitee.com> Date: Fri, 16 Oct 2026 08:53:45 +0800 Subject: [PATCH] =?UTF-8?q?feat=EF=BC=9A=E5=AE=A2=E6=9C=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package-lock.json | 16 + package.json | 1 + src/App.vue | 10 +- src/api/auth.ts | 8 + src/hooks/use-message-inbox.ts | 52 ++- src/manifest.json | 4 + src/pages/change-password/index.vue | 10 + .../change-password/use-change-password.ts | 17 +- .../device/components/device-header/index.vue | 26 +- .../detail/use-device-bluetooth-sync.ts | 39 +- src/pages/device/device-presence.ts | 43 +-- src/pages/device/use-device.ts | 2 + src/pages/forgot-password/index.vue | 6 +- .../forgot-password/use-forgot-password.ts | 33 +- .../edit/components/region-picker/index.vue | 180 ++++++++++ .../components/region-picker/region-data.ts | 61 ++++ src/pages/mine/edit/index.vue | 50 +-- src/pages/mine/edit/use-edit-profile.ts | 25 +- src/pages/mine/index.vue | 32 -- src/pages/mine/mine.scss | 97 +---- src/pages/mine/notify/index.vue | 1 + src/pages/mine/notify/notify.scss | 9 +- src/pages/mine/notify/notify.utils.ts | 13 +- src/pages/mine/notify/use-notify.ts | 50 ++- src/pages/mine/privacy/use-privacy.ts | 16 +- .../phone/use-set-password-phone.ts | 89 +---- .../mine/set-password/use-set-password.ts | 67 +--- .../verify/use-set-password-verify.ts | 9 +- src/pages/mine/support/index.vue | 83 +++-- src/pages/mine/support/support.scss | 41 ++- src/pages/mine/support/support.types.ts | 4 +- src/pages/mine/support/support.utils.ts | 65 +++- src/pages/mine/support/use-support-voice.ts | 336 ++++++++++++++++++ src/pages/mine/support/use-support.ts | 3 +- src/pages/mine/use-mine.ts | 54 +-- src/static/通知 (1).png | Bin 0 -> 6153 bytes src/utils/message-push-cache.ts | 58 +++ src/utils/message-push.ts | 114 ++++++ src/utils/message-socket.ts | 95 +++-- src/utils/static-assets.ts | 4 +- src/utils/z2-ble-protocol.ts | 24 +- src/utils/z2-ble.ts | 11 +- 42 files changed, 1375 insertions(+), 483 deletions(-) create mode 100644 src/pages/mine/edit/components/region-picker/index.vue create mode 100644 src/pages/mine/edit/components/region-picker/region-data.ts create mode 100644 src/pages/mine/support/use-support-voice.ts create mode 100644 src/static/通知 (1).png create mode 100644 src/utils/message-push-cache.ts create mode 100644 src/utils/message-push.ts diff --git a/package-lock.json b/package-lock.json index ed5eb19..0a16b22 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24,6 +24,7 @@ "@dcloudio/uni-mp-weixin": "3.0.0-5020420260813003", "@dcloudio/uni-mp-xhs": "3.0.0-5020420260813003", "@dcloudio/uni-quickapp-webview": "3.0.0-5020420260813003", + "element-china-area-data": "^6.1.0", "vue": "^3.4.21", "vue-i18n": "^9.1.9" }, @@ -6856,6 +6857,12 @@ "node": ">=10" } }, + "node_modules/china-division": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/china-division/-/china-division-2.7.0.tgz", + "integrity": "sha512-4uUPAT+1WfqDh5jytq7omdCmHNk3j+k76zEG/2IqaGcYB90c2SwcixttcypdsZ3T/9tN1TTpBDoeZn+Yw/qBEA==", + "license": "MIT" + }, "node_modules/chokidar": { "version": "3.6.0", "resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-3.6.0.tgz", @@ -7413,6 +7420,15 @@ "integrity": "sha512-vUNKPrUzw8ByEMOxloq0a71iD/mPuPxVkbDm3G5YhnxTzOw/I6qAg2MUS0cYj/c267lWmw26yW4Vv7foxTxPLg==", "license": "ISC" }, + "node_modules/element-china-area-data": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/element-china-area-data/-/element-china-area-data-6.1.0.tgz", + "integrity": "sha512-IkpcjwQv2A/2AxFiSoaISZ+oMw1rZCPUSOg5sOCwT5jKc96TaawmKZeY81xfxXsO0QbKxU5LLc6AirhG52hUmg==", + "license": "MIT", + "dependencies": { + "china-division": "^2.7.0" + } + }, "node_modules/emittery": { "version": "0.8.1", "resolved": "https://registry.npmmirror.com/emittery/-/emittery-0.8.1.tgz", diff --git a/package.json b/package.json index 2871fdc..6edc36d 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,7 @@ "@dcloudio/uni-mp-weixin": "3.0.0-5020420260813003", "@dcloudio/uni-mp-xhs": "3.0.0-5020420260813003", "@dcloudio/uni-quickapp-webview": "3.0.0-5020420260813003", + "element-china-area-data": "^6.1.0", "vue": "^3.4.21", "vue-i18n": "^9.1.9" }, diff --git a/src/App.vue b/src/App.vue index 7e1ae94..7992e57 100644 --- a/src/App.vue +++ b/src/App.vue @@ -1,6 +1,11 @@ diff --git a/src/api/auth.ts b/src/api/auth.ts index 3bf25aa..c654a69 100644 --- a/src/api/auth.ts +++ b/src/api/auth.ts @@ -31,3 +31,11 @@ export function logout() { method: 'POST', }) } + +/** POST /app/auth/cancelAccount — 注销账号 */ +export function cancelAccount() { + return request({ + url: '/app/auth/cancelAccount', + method: 'POST', + }) +} diff --git a/src/hooks/use-message-inbox.ts b/src/hooks/use-message-inbox.ts index 431878a..4b0dfd4 100644 --- a/src/hooks/use-message-inbox.ts +++ b/src/hooks/use-message-inbox.ts @@ -1,14 +1,30 @@ -import { ref } from 'vue' +import { computed, ref } from 'vue' import { fetchUnreadMessageCount } from '@/api/message' -import { connectMessageSocket, disconnectMessageSocket, onMessagePush } from '@/utils/message-socket' +import { + connectMessageSocket, + disconnectMessageSocket, + isMessageSocketConnected, + isMessageSocketConnecting, + onMessagePush, +} from '@/utils/message-socket' +import { + clearPushCache, + getCachedPushCount, + pushCacheCount, + rememberPushPayload, +} from '@/utils/message-push-cache' export const unreadMessageCount = ref(0) +export const hasUnreadMessages = computed( + () => unreadMessageCount.value > 0 || pushCacheCount.value > 0, +) let inboxInitialized = false let refreshingUnread = false let lastUnreadRefreshAt = 0 +let pendingPushUnread = 0 -const UNREAD_REFRESH_MIN_GAP_MS = 5000 +const UNREAD_REFRESH_MIN_GAP_MS = 15000 export async function refreshUnreadMessageCount(force = false): Promise { const now = Date.now() @@ -19,30 +35,48 @@ export async function refreshUnreadMessageCount(force = false): Promise refreshingUnread = true try { const count = await fetchUnreadMessageCount() - unreadMessageCount.value = typeof count === 'number' ? count : Number(count) || 0 + const serverCount = typeof count === 'number' ? count : Number(count) || 0 + const cached = getCachedPushCount() + if (serverCount > 0) { + pendingPushUnread = 0 + unreadMessageCount.value = serverCount + } else { + pendingPushUnread = cached + unreadMessageCount.value = Math.max(serverCount, cached) + } lastUnreadRefreshAt = Date.now() } catch { - unreadMessageCount.value = 0 + unreadMessageCount.value = pendingPushUnread } finally { refreshingUnread = false } return unreadMessageCount.value } +function handleIncomingPush(payload: Parameters[0]) { + if (!rememberPushPayload(payload)) return + pendingPushUnread = getCachedPushCount() + unreadMessageCount.value = Math.max(unreadMessageCount.value, pendingPushUnread) +} + export function setupMessageInbox() { - connectMessageSocket() if (!inboxInitialized) { inboxInitialized = true - onMessagePush(() => { - void refreshUnreadMessageCount() + onMessagePush((payload) => { + handleIncomingPush(payload) }) void refreshUnreadMessageCount(true) - return + } + + if (!isMessageSocketConnected() && !isMessageSocketConnecting()) { + connectMessageSocket() } } export function teardownMessageInbox() { disconnectMessageSocket() + clearPushCache() unreadMessageCount.value = 0 + pendingPushUnread = 0 inboxInitialized = false } diff --git a/src/manifest.json b/src/manifest.json index 36cb0f4..fe2b659 100644 --- a/src/manifest.json +++ b/src/manifest.json @@ -39,6 +39,7 @@ "", "", "", + "", "", "", "", @@ -69,6 +70,9 @@ }, "scope.userLocation" : { "desc" : "你的位置信息将用于在地图上选择家庭位置" + }, + "scope.record" : { + "desc" : "你的麦克风将用于在线客服语音输入" } }, "requiredPrivateInfos" : [ diff --git a/src/pages/change-password/index.vue b/src/pages/change-password/index.vue index 99b1cda..44aa38c 100644 --- a/src/pages/change-password/index.vue +++ b/src/pages/change-password/index.vue @@ -7,6 +7,8 @@ + 8-20位字符,须包含字母、数字、符号中的至少2种。 + @@ -38,6 +40,14 @@ const { password, confirmPassword, submit } = useChangePassword() margin-bottom: 48rpx; } +.auth-form-page__hint { + display: block; + margin-top: 16rpx; + font-size: 24rpx; + color: $color-text-secondary; + line-height: 1.5; +} + .auth-form-page__btn { margin-top: 16rpx; } diff --git a/src/pages/change-password/use-change-password.ts b/src/pages/change-password/use-change-password.ts index 2b34937..28633ee 100644 --- a/src/pages/change-password/use-change-password.ts +++ b/src/pages/change-password/use-change-password.ts @@ -1,18 +1,20 @@ import { onLoad } from '@dcloudio/uni-app' import { ref } from 'vue' import { getErrorMessage } from '@/utils/api-error' -import { isValidPassword } from '@/utils/validate' +import { isValidStrongPassword } from '@/utils/validate' import { resetPasswordByToken } from './change-password.api' export function useChangePassword() { const password = ref('') const confirmPassword = ref('') const resetToken = ref('') + const fromPrivacy = ref(false) const loading = ref(false) onLoad((query) => { const raw = (query?.resetToken as string) || '' resetToken.value = raw ? decodeURIComponent(raw) : '' + fromPrivacy.value = query?.from === 'privacy' if (!resetToken.value) { uni.showToast({ title: '请先完成验证码校验', icon: 'none' }) setTimeout(() => uni.navigateBack(), 1500) @@ -24,8 +26,11 @@ export function useChangePassword() { uni.showToast({ title: '重置令牌无效', icon: 'none' }) return } - if (!isValidPassword(password.value)) { - uni.showToast({ title: '密码至少 6 位', icon: 'none' }) + if (!isValidStrongPassword(password.value)) { + uni.showToast({ + title: '密码需8-20位,且包含字母、数字、符号中至少2种', + icon: 'none', + }) return } if (password.value !== confirmPassword.value) { @@ -40,8 +45,12 @@ export function useChangePassword() { newPassword: password.value, confirmPassword: confirmPassword.value, }) - uni.showToast({ title: '修改成功', icon: 'success' }) + uni.showToast({ title: '密码修改成功', icon: 'success' }) setTimeout(() => { + if (fromPrivacy.value) { + uni.navigateBack({ delta: 2 }) + return + } uni.reLaunch({ url: '/pages/login/index' }) }, 800) } catch (err) { diff --git a/src/pages/device/components/device-header/index.vue b/src/pages/device/components/device-header/index.vue index 5fc6c9c..0f22abf 100644 --- a/src/pages/device/components/device-header/index.vue +++ b/src/pages/device/components/device-header/index.vue @@ -49,6 +49,7 @@ :src="staticAssets.iconNotify" mode="aspectFit" /> + @@ -72,6 +73,7 @@ diff --git a/src/pages/mine/edit/components/region-picker/region-data.ts b/src/pages/mine/edit/components/region-picker/region-data.ts new file mode 100644 index 0000000..8bc5db9 --- /dev/null +++ b/src/pages/mine/edit/components/region-picker/region-data.ts @@ -0,0 +1,61 @@ +import { regionData } from 'element-china-area-data' + +export interface RegionNode { + label: string + children?: RegionNode[] +} + +export const CHINA_REGION_TREE: RegionNode[] = regionData.map((province) => ({ + label: province.label, + children: province.children?.map((city) => ({ + label: city.label, + children: city.children?.map((district) => ({ + label: district.label, + })), + })), +})) + +export function getProvinceList(tree: RegionNode[] = CHINA_REGION_TREE): string[] { + return tree.map((item) => item.label) +} + +export function getCityList(provinceIndex: number, tree: RegionNode[] = CHINA_REGION_TREE): string[] { + return tree[provinceIndex]?.children?.map((item) => item.label) ?? [] +} + +export function getDistrictList( + provinceIndex: number, + cityIndex: number, + tree: RegionNode[] = CHINA_REGION_TREE, +): string[] { + return tree[provinceIndex]?.children?.[cityIndex]?.children?.map((item) => item.label) ?? [] +} + +export function findRegionIndexes( + province: string, + city: string, + district: string, + tree: RegionNode[] = CHINA_REGION_TREE, +): [number, number, number] { + const provinceIndex = Math.max( + 0, + tree.findIndex((item) => item.label === province), + ) + const cities = tree[provinceIndex]?.children ?? [] + const cityIndex = Math.max(0, cities.findIndex((item) => item.label === city)) + const districts = cities[cityIndex]?.children ?? [] + const districtIndex = Math.max(0, districts.findIndex((item) => item.label === district)) + return [provinceIndex, cityIndex, districtIndex] +} + +export function getRegionByIndexes( + indexes: [number, number, number], + tree: RegionNode[] = CHINA_REGION_TREE, +): { province: string; city: string; district: string } { + const [provinceIndex, cityIndex, districtIndex] = indexes + const province = tree[provinceIndex]?.label ?? '' + const city = tree[provinceIndex]?.children?.[cityIndex]?.label ?? '' + const district = + tree[provinceIndex]?.children?.[cityIndex]?.children?.[districtIndex]?.label ?? '' + return { province, city, district } +} diff --git a/src/pages/mine/edit/index.vue b/src/pages/mine/edit/index.vue index 0b9c23e..2b3678c 100644 --- a/src/pages/mine/edit/index.vue +++ b/src/pages/mine/edit/index.vue @@ -84,26 +84,24 @@ - - - 所在地 - - - {{ locationText }} - - - + + 所在地 + + + {{ locationText }} + + - + @@ -144,6 +142,14 @@ :value="form.nickName" @confirm="onConfirmNickname" /> + + @@ -151,6 +157,7 @@ import { staticAssets } from '@/utils/static-assets' import AvatarActionSheet from './components/avatar-action-sheet/index.vue' import NicknameDialog from './components/nickname-dialog/index.vue' +import RegionPicker from './components/region-picker/index.vue' import { useEditProfile } from './use-edit-profile' const today = new Date().toISOString().slice(0, 10) @@ -162,7 +169,7 @@ const { maskedPhone, genderText, locationText, - regionValue, + regionPickerVisible, avatarSheetVisible, nicknameDialogVisible, onOpenAvatarSheet, @@ -173,7 +180,8 @@ const { onConfirmNickname, onPickGender, onBirthdayChange, - onRegionChange, + onOpenRegionPicker, + onConfirmRegion, onChangePhone, onSave, } = useEditProfile() diff --git a/src/pages/mine/edit/use-edit-profile.ts b/src/pages/mine/edit/use-edit-profile.ts index 0d9a527..e1e9cdf 100644 --- a/src/pages/mine/edit/use-edit-profile.ts +++ b/src/pages/mine/edit/use-edit-profile.ts @@ -49,18 +49,13 @@ export function useEditProfile() { const form = ref(createEmptyForm()) const avatarSheetVisible = ref(false) const nicknameDialogVisible = ref(false) + const regionPickerVisible = ref(false) const maskedPhone = computed(() => maskPhone(form.value.phonenumber)) const genderText = computed(() => GENDER_LABELS[form.value.gender] || '未知') const locationText = computed(() => formatLocation(form.value.province, form.value.city, form.value.district), ) - const regionValue = computed(() => { - const { province, city, district } = form.value - if (province && city && district) return [province, city, district] - return [] - }) - async function loadProfile() { if (loading.value) return loading.value = true @@ -158,11 +153,14 @@ export function useEditProfile() { form.value.birthday = e.detail.value } - function onRegionChange(e: { detail: { value: string[] } }) { - const [province, city, district] = e.detail.value - form.value.province = province || '' - form.value.city = city || '' - form.value.district = district || '' + function onOpenRegionPicker() { + regionPickerVisible.value = true + } + + function onConfirmRegion(value: { province: string; city: string; district: string }) { + form.value.province = value.province + form.value.city = value.city + form.value.district = value.district } function onChangePhone() { @@ -214,7 +212,7 @@ export function useEditProfile() { maskedPhone, genderText, locationText, - regionValue, + regionPickerVisible, avatarSheetVisible, nicknameDialogVisible, onOpenAvatarSheet, @@ -225,7 +223,8 @@ export function useEditProfile() { onConfirmNickname, onPickGender, onBirthdayChange, - onRegionChange, + onOpenRegionPicker, + onConfirmRegion, onChangePhone, onSave, } diff --git a/src/pages/mine/index.vue b/src/pages/mine/index.vue index 825116b..4a8ce5b 100644 --- a/src/pages/mine/index.vue +++ b/src/pages/mine/index.vue @@ -27,35 +27,6 @@ - - - {{ item.value }} - {{ item.label }} - - - - - - - - - {{ action.label }} - - - @@ -270,6 +287,7 @@ import { computed, nextTick, ref, watch } from 'vue' import { staticAssets } from '@/utils/static-assets' import { useSupport } from './use-support' +import { useSupportVoice } from './use-support-voice' import type { DiagnosisItem } from './support.types' const { @@ -290,8 +308,29 @@ const { onSend, } = useSupport() +const { + inputMode, + voiceHolding, + voiceRecognizing, + toggleInputMode, + onVoiceTouchStart, + onVoiceTouchEnd, + onVoiceTouchCancel, +} = useSupportVoice({ + onRecognized: (text) => { + inputValue.value = text + onSend() + }, +}) + const humanAvatarText = computed(() => headerInfo.value.avatarText || '服') +const voiceButtonText = computed(() => { + if (voiceRecognizing.value && !voiceHolding.value) return '识别中...' + if (voiceHolding.value) return '松手 发送' + return '按住 说话' +}) + const scrollIntoView = ref('chat-bottom') watch( diff --git a/src/pages/mine/support/support.scss b/src/pages/mine/support/support.scss index f6d6cda..802bbfb 100644 --- a/src/pages/mine/support/support.scss +++ b/src/pages/mine/support/support.scss @@ -209,7 +209,7 @@ $support-danger: #f04438; } &--user { - border-radius: 16rpx; + border-radius: 50%; background: #d0d5dd; color: #fff; } @@ -259,13 +259,6 @@ $support-danger: #f04438; } } -.support-page__bubble-time { - margin-top: 8rpx; - font-size: 22rpx; - color: $support-text-secondary; - line-height: 1.2; -} - .support-page__quick { display: flex; flex-wrap: wrap; @@ -637,6 +630,34 @@ $support-danger: #f04438; height: 56rpx; } +.support-page__keyboard-icon { + font-size: 40rpx; + line-height: 1; + color: $support-text-muted; +} + +.support-page__voice-btn { + flex: 1; + height: 72rpx; + border-radius: 36rpx; + background: #f5f6f8; + display: flex; + align-items: center; + justify-content: center; + user-select: none; + + &--holding, + &--recognizing { + background: rgba(30, 198, 113, 0.12); + } +} + +.support-page__voice-btn-text { + font-size: 28rpx; + color: $support-text; + line-height: 1; +} + .support-page__input-wrap { flex: 1; height: 72rpx; @@ -687,7 +708,9 @@ $support-danger: #f04438; } .support-page__secure { - margin-top: 12rpx; + display: block; + margin: 0 0 16rpx; + padding: 0 16rpx; text-align: center; font-size: 22rpx; color: $support-text-secondary; diff --git a/src/pages/mine/support/support.types.ts b/src/pages/mine/support/support.types.ts index cbaab06..c4f9b40 100644 --- a/src/pages/mine/support/support.types.ts +++ b/src/pages/mine/support/support.types.ts @@ -128,7 +128,7 @@ export type SupportMessage = type: 'text' role: ChatRole content: string - time?: string + createTime?: string } | { id: string @@ -165,7 +165,7 @@ export type SupportMessage = type: 'image' role: 'user' src: string - time?: string + createTime?: string } export interface SupportHeaderInfo { diff --git a/src/pages/mine/support/support.utils.ts b/src/pages/mine/support/support.utils.ts index 2c48a0d..302020a 100644 --- a/src/pages/mine/support/support.utils.ts +++ b/src/pages/mine/support/support.utils.ts @@ -91,11 +91,62 @@ export function getQueueEstimate(session: CsSessionVo): string { return session.estimateWaitTime?.trim() || '正在为您分配人工客服' } -function formatMessageTime(value?: string): string | undefined { - if (!value) return undefined +const TIME_DIVIDER_GAP_MS = 5 * 60 * 1000 + +function parseMessageTimestamp(value?: string): number | null { + if (!value) return null const date = new Date(value) - if (Number.isNaN(date.getTime())) return undefined - return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}` + const ts = date.getTime() + return Number.isNaN(ts) ? null : ts +} + +function formatTimeDividerText(value: string): string { + const date = new Date(value) + if (Number.isNaN(date.getTime())) return '' + const hm = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}` + const now = new Date() + if (date.toDateString() === now.toDateString()) return hm + + const yesterday = new Date(now) + yesterday.setDate(now.getDate() - 1) + if (date.toDateString() === yesterday.toDateString()) return `昨天 ${hm}` + + return `${date.getMonth() + 1}月${date.getDate()}日 ${hm}` +} + +function getMessageCreateTime(item: SupportMessage): string | undefined { + if (item.type === 'text' || item.type === 'image') return item.createTime + return undefined +} + +export function injectTimeDividers(messages: SupportMessage[]): SupportMessage[] { + const result: SupportMessage[] = [] + let lastTimestamp = 0 + + for (const item of messages) { + const createTime = getMessageCreateTime(item) + const timestamp = parseMessageTimestamp(createTime) + const shouldInsertDivider = timestamp !== null + && (lastTimestamp === 0 || timestamp - lastTimestamp >= TIME_DIVIDER_GAP_MS) + + if (shouldInsertDivider && createTime) { + const text = formatTimeDividerText(createTime) + if (text) { + result.push({ + id: `time-${timestamp}`, + type: 'time', + text, + }) + } + lastTimestamp = timestamp + } else if (timestamp !== null) { + lastTimestamp = timestamp + } + + result.push(item) + } + + return result } function resolveSenderRole(senderType?: string | number): ChatRole | null { @@ -183,7 +234,7 @@ function mapStructuredMessage(message: CsMessageVo, payload: Record void +} + +interface SpeechRecognitionInstance { + lang: string + continuous: boolean + interimResults: boolean + start: () => void + stop: () => void + abort: () => void + onresult: ((event: { results: Array> }) => void) | null + onerror: ((event: { error?: string }) => void) | null + onend: (() => void) | null +} + +const MAX_VOICE_DURATION_MS = 60000 + +export function useSupportVoice(options: UseSupportVoiceOptions) { + const inputMode = ref('text') + const voiceHolding = ref(false) + const voiceRecognizing = ref(false) + + let touchCanceled = false + let recordStopTimer: ReturnType | null = null + let h5Recognition: SpeechRecognitionInstance | null = null + + // #ifdef MP-WEIXIN + let mpRecoManager: { + start: (opts: { duration: number; lang: string }) => void + stop: () => void + onStop?: (res: { result?: string }) => void + onError?: () => void + } | null = null + + try { + const plugin = requirePlugin('WechatSI') as { + getRecordRecognitionManager: () => NonNullable + } + mpRecoManager = plugin.getRecordRecognitionManager() + mpRecoManager.onStop = (res) => { + voiceRecognizing.value = false + const text = res.result?.trim() + if (text) { + options.onRecognized(text) + return + } + uni.showToast({ title: '未识别到语音内容', icon: 'none' }) + } + mpRecoManager.onError = () => { + voiceRecognizing.value = false + uni.showToast({ title: '语音识别失败', icon: 'none' }) + } + } catch { + mpRecoManager = null + } + // #endif + + function clearRecordStopTimer() { + if (recordStopTimer) clearTimeout(recordStopTimer) + recordStopTimer = null + } + + function resetVoiceState() { + voiceHolding.value = false + voiceRecognizing.value = false + touchCanceled = false + clearRecordStopTimer() + } + + function isVoiceSupported(): boolean { + // #ifdef H5 + const win = window as Window & { + SpeechRecognition?: new () => SpeechRecognitionInstance + webkitSpeechRecognition?: new () => SpeechRecognitionInstance + } + return !!(win.SpeechRecognition || win.webkitSpeechRecognition) + // #endif + + // #ifdef APP-PLUS + return typeof plus !== 'undefined' && !!plus.speech + // #endif + + // #ifdef MP-WEIXIN + return !!mpRecoManager + // #endif + + return false + } + + function ensureRecordPermission(): Promise { + return new Promise((resolve) => { + uni.getSetting({ + success: (res) => { + if (res.authSetting['scope.record']) { + resolve(true) + return + } + uni.authorize({ + scope: 'scope.record', + success: () => resolve(true), + fail: () => { + uni.showModal({ + title: '需要麦克风权限', + content: '请在设置中开启麦克风权限后使用语音输入', + confirmText: '去设置', + success: (modalRes) => { + if (modalRes.confirm) { + uni.openSetting({}) + } + }, + }) + resolve(false) + }, + }) + }, + fail: () => resolve(false), + }) + }) + } + + function cleanupH5Recognition() { + if (!h5Recognition) return + try { + h5Recognition.abort() + } catch { + // ignore + } + h5Recognition.onresult = null + h5Recognition.onerror = null + h5Recognition.onend = null + h5Recognition = null + } + + async function startH5Voice() { + const win = window as Window & { + SpeechRecognition?: new () => SpeechRecognitionInstance + webkitSpeechRecognition?: new () => SpeechRecognitionInstance + } + const Ctor = win.SpeechRecognition || win.webkitSpeechRecognition + if (!Ctor) { + uni.showToast({ title: '当前浏览器不支持语音输入', icon: 'none' }) + resetVoiceState() + return + } + + cleanupH5Recognition() + const recognition = new Ctor() + h5Recognition = recognition + recognition.lang = 'zh-CN' + recognition.continuous = false + recognition.interimResults = false + voiceRecognizing.value = true + + recognition.onresult = (event) => { + const text = event.results[0]?.[0]?.transcript?.trim() + if (text) options.onRecognized(text) + } + recognition.onerror = (event) => { + if (event.error !== 'aborted') { + uni.showToast({ title: '语音识别失败', icon: 'none' }) + } + } + recognition.onend = () => { + voiceRecognizing.value = false + h5Recognition = null + } + + try { + recognition.start() + } catch { + voiceRecognizing.value = false + h5Recognition = null + uni.showToast({ title: '无法启动语音识别', icon: 'none' }) + } + } + + function stopH5Voice() { + if (!h5Recognition) return + try { + h5Recognition.stop() + } catch { + h5Recognition.abort() + } + } + + function startAppVoice() { + if (!plus.speech) { + uni.showToast({ title: '当前环境不支持语音输入', icon: 'none' }) + return + } + voiceRecognizing.value = true + plus.speech.startRecognize( + { + engine: 'baidu', + lang: 'zh-cn', + punctuation: false, + timeout: 10000, + }, + (text) => { + voiceRecognizing.value = false + const result = String(text || '').trim() + if (result) { + options.onRecognized(result) + return + } + uni.showToast({ title: '未识别到语音内容', icon: 'none' }) + }, + () => { + voiceRecognizing.value = false + uni.showToast({ title: '语音识别失败', icon: 'none' }) + }, + ) + } + + async function startMpVoice() { + if (!mpRecoManager) { + uni.showToast({ title: '未配置同声传译插件,暂无法使用语音输入', icon: 'none' }) + resetVoiceState() + return + } + const granted = await ensureRecordPermission() + if (!granted) { + resetVoiceState() + return + } + voiceRecognizing.value = true + mpRecoManager.start({ duration: MAX_VOICE_DURATION_MS, lang: 'zh_CN' }) + } + + function stopMpVoice() { + mpRecoManager?.stop() + } + + function cancelVoiceCapture() { + // #ifdef H5 + cleanupH5Recognition() + // #endif + + // #ifdef APP-PLUS + if (voiceRecognizing.value) { + plus.speech.stopRecognize() + } + // #endif + + // #ifdef MP-WEIXIN + mpRecoManager?.stop() + // #endif + + voiceRecognizing.value = false + } + + function toggleInputMode() { + if (inputMode.value === 'text') { + if (!isVoiceSupported()) { + uni.showToast({ title: '当前环境不支持语音输入', icon: 'none' }) + return + } + inputMode.value = 'voice' + return + } + cancelVoiceCapture() + resetVoiceState() + inputMode.value = 'text' + } + + async function onVoiceTouchStart() { + if (voiceRecognizing.value) return + touchCanceled = false + voiceHolding.value = true + + // #ifdef H5 + await startH5Voice() + // #endif + + // #ifdef MP-WEIXIN + await startMpVoice() + // #endif + + clearRecordStopTimer() + recordStopTimer = setTimeout(() => { + if (voiceHolding.value) { + onVoiceTouchEnd() + } + }, MAX_VOICE_DURATION_MS) + } + + function onVoiceTouchEnd() { + if (!voiceHolding.value) return + voiceHolding.value = false + clearRecordStopTimer() + + if (touchCanceled) { + cancelVoiceCapture() + return + } + + // #ifdef H5 + stopH5Voice() + // #endif + + // #ifdef APP-PLUS + startAppVoice() + // #endif + + // #ifdef MP-WEIXIN + stopMpVoice() + // #endif + } + + function onVoiceTouchCancel() { + touchCanceled = true + voiceHolding.value = false + clearRecordStopTimer() + cancelVoiceCapture() + } + + onBeforeUnmount(() => { + cancelVoiceCapture() + clearRecordStopTimer() + }) + + return { + inputMode, + voiceHolding, + voiceRecognizing, + toggleInputMode, + onVoiceTouchStart, + onVoiceTouchEnd, + onVoiceTouchCancel, + } +} diff --git a/src/pages/mine/support/use-support.ts b/src/pages/mine/support/use-support.ts index afb5040..f9c837c 100644 --- a/src/pages/mine/support/use-support.ts +++ b/src/pages/mine/support/use-support.ts @@ -39,6 +39,7 @@ import { getMaxSeq, getQueueEstimate, getQueuePosition, + injectTimeDividers, mapCsMessage, mergeSupportMessages, normalizeSessionId, @@ -124,7 +125,7 @@ export function useSupport() { estimateText: queueEstimate.value, }) } - return list + return injectTimeDividers(list) }) function clearQueueTimer() { diff --git a/src/pages/mine/use-mine.ts b/src/pages/mine/use-mine.ts index a8e32e2..f59c121 100644 --- a/src/pages/mine/use-mine.ts +++ b/src/pages/mine/use-mine.ts @@ -1,29 +1,14 @@ import { onShow } from '@dcloudio/uni-app' import { computed, ref } from 'vue' import { getErrorMessage } from '@/utils/api-error' -import { staticAssets } from '@/utils/static-assets' import { fetchMineOverview } from './mine.api' -import type { MineMenuItem, MineQuickAction } from './mine.types' - -const APP_VERSION = 'v3.2.0' - -const QUICK_ACTIONS: MineQuickAction[] = [ - { id: 'notify', label: '消息通知', icon: staticAssets.iconMineNotify }, - { id: 'order', label: '我的订单', icon: staticAssets.iconMineOrder }, - { id: 'coupon', label: '优惠券', icon: staticAssets.iconMineCoupon }, - { id: 'address', label: '收货地址', icon: staticAssets.iconMineAddress }, -] +import type { MineMenuItem } from './mine.types' const MENU_ITEMS: MineMenuItem[] = [ { id: 'devices', title: '我的设备' }, - { id: 'members', title: '家庭成员' }, - { id: 'scene', title: '场景与自动化' }, - { id: 'service', title: '售后服务' }, { id: 'support', title: '在线客服' }, - { id: 'feedback', title: '帮助与反馈' }, - { id: 'settings', title: '通用设置' }, + { id: 'storage', title: '储存空间' }, { id: 'privacy', title: '隐私与安全' }, - { id: 'about', title: '关于我们', value: APP_VERSION }, ] export function useMine() { @@ -32,32 +17,13 @@ export function useMine() { const phone = ref('') const avatarUrl = ref('') const deviceCount = ref(0) - const memberCount = ref(0) - const warrantyCount = ref(0) - const sceneCount = ref(0) - const statusBarHeight = ref(0) - const stats = computed(() => [ - { label: '我的设备', value: deviceCount.value }, - { label: '家庭成员', value: memberCount.value }, - { label: '保修中', value: warrantyCount.value }, - ]) - const menuList = computed(() => MENU_ITEMS.map((item) => { if (item.id === 'devices') { return { ...item, value: `已绑定 ${deviceCount.value} 台` } } - if (item.id === 'members') { - return { ...item, value: `${memberCount.value} 位成员` } - } - if (item.id === 'scene') { - return { ...item, value: `${sceneCount.value} 个场景` } - } - if (item.id === 'service') { - return { ...item, value: '报修 / 退换' } - } return item }), ) @@ -82,14 +48,6 @@ export function useMine() { uni.navigateTo({ url: '/pages/mine/edit/index' }) } - function onQuickAction(action: MineQuickAction) { - if (action.id === 'notify') { - uni.navigateTo({ url: '/pages/mine/notify/index' }) - return - } - uni.showToast({ title: `${action.label}功能开发中`, icon: 'none' }) - } - function onMenuTap(item: MineMenuItem) { if (item.id === 'devices') { uni.reLaunch({ url: '/pages/device/index' }) @@ -99,16 +57,13 @@ export function useMine() { uni.navigateTo({ url: '/pages/mine/support/index' }) return } - if (item.id === 'settings') { + if (item.id === 'storage') { uni.navigateTo({ url: '/pages/mine/storage/index' }) return } if (item.id === 'privacy') { uni.navigateTo({ url: '/pages/mine/privacy/index' }) - return } - if (item.id === 'about') return - uni.showToast({ title: `${item.title}功能开发中`, icon: 'none' }) } onShow(() => { @@ -122,11 +77,8 @@ export function useMine() { nickName, phone, avatarUrl, - stats, - quickActions: QUICK_ACTIONS, menuList, onEditNickname, - onQuickAction, onMenuTap, } } diff --git a/src/static/通知 (1).png b/src/static/通知 (1).png new file mode 100644 index 0000000000000000000000000000000000000000..aa6a7303241e36b2167a775acd41c9294b6658fd GIT binary patch literal 6153 zcmaKQbyQT}_x22oFh~uIgi=F|fP6rZ&KVe_dngfx6a=NaV?dBjX%VHRQ%R9Vq(efH z?ruch>-X>9djGih?z7i(_SyHWb)J3p6RD-4NPhd?Z4d}VuB?R70lvNe9w-s;E;B68 z0fAs3WeghY1>QCxcVnDzZ}rp{K?($Z50-0}=AhSr3Jk}0D{~dA`%s99)M_o;dhS>l zvx5uxW=uYXJLy=du+rOeN`C1c?RT%Lqb@?povVY#guoe2P;e48<6j-P+<9>nH&|7& z;jC=g(z5J>zvDBHXC8Z5p2DT+zI#n)O?#Q5vR9VDydgn|he!gsc!75bOd+5k80K*> z;vog#aBfd92?5640Dyu(hT1C2)cOqqMg_qmsJN5ycgX;ZnbR9nb^z45Bv)5gXLPXo z&E{Ul=-T~zV`U_gH3ANW^_-c4n)_Qg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) + +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() + 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 +} diff --git a/src/utils/message-push.ts b/src/utils/message-push.ts new file mode 100644 index 0000000..3930bc3 --- /dev/null +++ b/src/utils/message-push.ts @@ -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 | null { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null + return value as Record +} + +function pickString(obj: Record, 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, 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, +): 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 + 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 +} diff --git a/src/utils/message-socket.ts b/src/utils/message-socket.ts index ee4f977..874e204 100644 --- a/src/utils/message-socket.ts +++ b/src/utils/message-socket.ts @@ -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 | null = null let reconnectTimer: ReturnType | 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 } diff --git a/src/utils/static-assets.ts b/src/utils/static-assets.ts index cec7f53..5b53fce 100644 --- a/src/utils/static-assets.ts +++ b/src/utils/static-assets.ts @@ -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, diff --git a/src/utils/z2-ble-protocol.ts b/src/utils/z2-ble-protocol.ts index 917c3f0..5b3cd25 100644 --- a/src/utils/z2-ble-protocol.ts +++ b/src/utils/z2-ble-protocol.ts @@ -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 } diff --git a/src/utils/z2-ble.ts b/src/utils/z2-ble.ts index 31e8c80..814e8d8 100644 --- a/src/utils/z2-ble.ts +++ b/src/utils/z2-ble.ts @@ -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 { const maxWaitMs = options.maxWaitMs ?? 6000 - const idleMs = options.idleMgs ?? 400 + const idleMs = options.idleMs ?? 400 let buffer = '' let settled = false