fix:蓝牙bug解决
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
<template>
|
||||
<view
|
||||
v-if="visible"
|
||||
class="ble-reconnect-loading"
|
||||
:style="{ top: `${topOffsetPx}px` }"
|
||||
@tap.stop.prevent
|
||||
@touchmove.stop.prevent
|
||||
>
|
||||
<view class="ble-reconnect-loading__center" @tap.stop.prevent>
|
||||
<view class="ble-reconnect-loading__spinner" aria-hidden="true">
|
||||
<view class="ble-reconnect-loading__ring" />
|
||||
<view class="ble-reconnect-loading__core" />
|
||||
</view>
|
||||
<text class="ble-reconnect-loading__title">{{ title }}</text>
|
||||
<text class="ble-reconnect-loading__desc">{{ desc }}</text>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
visible?: boolean
|
||||
title?: string
|
||||
desc?: string
|
||||
/** 顶部留白(状态栏+导航),保证返回可点 */
|
||||
topOffsetPx?: number
|
||||
}>(),
|
||||
{
|
||||
visible: false,
|
||||
title: '设备连接中',
|
||||
desc: '正在重新连接蓝牙,请靠近设备并稍候',
|
||||
topOffsetPx: 88,
|
||||
},
|
||||
)
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.ble-reconnect-loading {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
background: rgba(16, 24, 40, 0.28);
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__center {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 420rpx;
|
||||
padding: 48rpx 36rpx 44rpx;
|
||||
border-radius: 28rpx;
|
||||
background: #fff;
|
||||
box-shadow: 0 16rpx 48rpx rgba(16, 24, 40, 0.16);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__spinner {
|
||||
position: relative;
|
||||
width: 96rpx;
|
||||
height: 96rpx;
|
||||
margin-bottom: 28rpx;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__ring {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 50%;
|
||||
border: 6rpx solid #e8f8ef;
|
||||
border-top-color: #21c25e;
|
||||
animation: ble-reconnect-spin 0.9s linear infinite;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__core {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: 18rpx;
|
||||
height: 18rpx;
|
||||
margin: -9rpx 0 0 -9rpx;
|
||||
border-radius: 50%;
|
||||
background: #21c25e;
|
||||
opacity: 0.85;
|
||||
animation: ble-reconnect-pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__title {
|
||||
font-size: 32rpx;
|
||||
font-weight: 600;
|
||||
color: #1a1a1a;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.ble-reconnect-loading__desc {
|
||||
margin-top: 12rpx;
|
||||
font-size: 24rpx;
|
||||
color: #667085;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@keyframes ble-reconnect-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes ble-reconnect-pulse {
|
||||
0%,
|
||||
100% {
|
||||
transform: scale(0.85);
|
||||
opacity: 0.55;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,8 +1,9 @@
|
||||
import {
|
||||
mapZ2StateToRuntimePatch,
|
||||
Z2_BLE_CMD,
|
||||
type Z2AirQuality,
|
||||
} from '@/utils/z2-ble-protocol'
|
||||
import { queryZ2BleState } from '@/utils/z2-ble'
|
||||
import { queryZ2BleState, sendZ2BleCommand } from '@/utils/z2-ble'
|
||||
import type { UpdateDeviceRuntimeBody } from './device-detail.types'
|
||||
|
||||
export type BleRuntimePatch = Partial<UpdateDeviceRuntimeBody> & {
|
||||
@@ -11,12 +12,61 @@ export type BleRuntimePatch = Partial<UpdateDeviceRuntimeBody> & {
|
||||
airQuality?: Z2AirQuality
|
||||
}
|
||||
|
||||
/** 通过 Z2 BLE 协议查询设备运行数据 */
|
||||
function toUpdateRuntimeBody(patch: BleRuntimePatch): Partial<UpdateDeviceRuntimeBody> {
|
||||
const {
|
||||
runMode,
|
||||
fanLevel,
|
||||
tvoc,
|
||||
powerMode,
|
||||
deviceBattery,
|
||||
filterLife,
|
||||
charging,
|
||||
status,
|
||||
bluetoothConnected,
|
||||
signalLevel,
|
||||
} = patch
|
||||
return {
|
||||
...(runMode != null ? { runMode } : {}),
|
||||
...(fanLevel != null ? { fanLevel } : {}),
|
||||
...(tvoc != null ? { tvoc } : {}),
|
||||
...(powerMode != null ? { powerMode } : {}),
|
||||
...(deviceBattery != null ? { deviceBattery } : {}),
|
||||
...(filterLife != null ? { filterLife } : {}),
|
||||
...(charging != null ? { charging } : {}),
|
||||
...(status != null ? { status } : {}),
|
||||
...(bluetoothConnected != null ? { bluetoothConnected } : {}),
|
||||
...(signalLevel != null ? { signalLevel } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** 通过 Z2 BLE 协议查询设备运行数据(Q 全量 + I 滤芯,滤芯始终单独查) */
|
||||
export async function readRuntimeFromBle(
|
||||
bleDeviceId: string,
|
||||
): Promise<BleRuntimePatch> {
|
||||
if (typeof uni.readBLECharacteristicValue !== 'function') return {}
|
||||
|
||||
const state = await queryZ2BleState(bleDeviceId)
|
||||
return mapZ2StateToRuntimePatch(state)
|
||||
let patch = mapZ2StateToRuntimePatch(state)
|
||||
|
||||
// 滤芯衰减靠嵌入式维护,Q 里经常没有;每次同步都发 I,避免一直显示云端旧百分比
|
||||
try {
|
||||
const filterState = await sendZ2BleCommand(bleDeviceId, Z2_BLE_CMD.QUERY_FILTER, {
|
||||
timeoutMs: 4000,
|
||||
})
|
||||
const filterPatch = mapZ2StateToRuntimePatch(filterState)
|
||||
if (filterPatch.filterLife != null) {
|
||||
patch = { ...patch, filterLife: filterPatch.filterLife }
|
||||
} else if (import.meta.env.DEV || import.meta.env.VITE_BLE_DEBUG === 'true') {
|
||||
console.log('[Z2 BLE] filter query returned no filterLife', filterState)
|
||||
}
|
||||
} catch (err) {
|
||||
if (import.meta.env.DEV || import.meta.env.VITE_BLE_DEBUG === 'true') {
|
||||
console.log('[Z2 BLE] filter query failed', err)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...toUpdateRuntimeBody(patch),
|
||||
...(patch.airQuality != null ? { airQuality: patch.airQuality } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,11 +97,26 @@
|
||||
}
|
||||
}
|
||||
|
||||
.device-detail-hero__status-spinner {
|
||||
width: 20rpx;
|
||||
height: 20rpx;
|
||||
border-radius: 50%;
|
||||
border: 3rpx solid rgba(255, 255, 255, 0.35);
|
||||
border-top-color: #fff;
|
||||
animation: device-detail-status-spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
.device-detail-hero__status-text {
|
||||
font-size: 24rpx;
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
}
|
||||
|
||||
@keyframes device-detail-status-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.device-detail-hero__metric-row {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
|
||||
@@ -22,6 +22,12 @@
|
||||
|
||||
<view class="device-detail-hero__status">
|
||||
<view
|
||||
v-if="showReconnectLoading"
|
||||
class="device-detail-hero__status-spinner"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<view
|
||||
v-else
|
||||
class="device-detail-hero__status-dot"
|
||||
:class="{ 'device-detail-hero__status-dot--offline': !isOnline }"
|
||||
/>
|
||||
@@ -151,6 +157,14 @@
|
||||
@confirm="onConfirmFilterReplace"
|
||||
/>
|
||||
<run-mode-explain-dialog v-model:visible="runModeExplainVisible" />
|
||||
|
||||
<!-- 页面居中加载,挡住下方操作区;顶栏返回仍可点 -->
|
||||
<ble-reconnect-loading
|
||||
:visible="showReconnectLoading"
|
||||
:title="reconnectLoadingTitle"
|
||||
:desc="reconnectLoadingDesc"
|
||||
:top-offset-px="statusBarHeight + 44"
|
||||
/>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
@@ -158,6 +172,7 @@
|
||||
import { ref } from 'vue'
|
||||
import { usePageScrollHeight } from '@/hooks/use-page-scroll-height'
|
||||
import { staticAssets } from '@/utils/static-assets'
|
||||
import BleReconnectLoading from './components/ble-reconnect-loading/index.vue'
|
||||
import FilterReplaceDialog from './components/filter-replace-dialog/index.vue'
|
||||
import RunModeExplainDialog from './components/run-mode-explain-dialog/index.vue'
|
||||
import { useDeviceDetail } from './use-device-detail'
|
||||
@@ -168,14 +183,13 @@ const { scrollStyle: detailScrollStyle } = usePageScrollHeight({
|
||||
})
|
||||
const runModeExplainVisible = ref(false)
|
||||
|
||||
function onOpenRunModeExplain() {
|
||||
runModeExplainVisible.value = true
|
||||
}
|
||||
|
||||
const {
|
||||
deviceName,
|
||||
connectionText,
|
||||
isOnline,
|
||||
showReconnectLoading,
|
||||
reconnectLoadingTitle,
|
||||
reconnectLoadingDesc,
|
||||
tvocDisplay,
|
||||
tvocLevel,
|
||||
syncText,
|
||||
@@ -199,6 +213,11 @@ const {
|
||||
onConfirmFilterReplace,
|
||||
} = useDeviceDetail()
|
||||
|
||||
function onOpenRunModeExplain() {
|
||||
if (showReconnectLoading.value) return
|
||||
runModeExplainVisible.value = true
|
||||
}
|
||||
|
||||
function onBack() {
|
||||
const pages = getCurrentPages()
|
||||
if (pages.length > 1) {
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { onShow, onUnload } from '@dcloudio/uni-app'
|
||||
import { ref } from 'vue'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { buildBleDeviceName } from '@/utils/ble-device-name'
|
||||
import { recallBleDeviceId, rememberBleDeviceId } from '@/utils/ble-device-id-cache'
|
||||
import {
|
||||
closeBleConnection,
|
||||
ensureBleConnection,
|
||||
ensureBluetoothReady,
|
||||
getBluetoothErrorMessage,
|
||||
getConnectedBleDeviceByMac,
|
||||
getDiscoveredBluetoothDevices,
|
||||
isBleDeviceConnected,
|
||||
isBluetoothApiSupported,
|
||||
rssiToSignalLevel,
|
||||
scanForBleDeviceByMac,
|
||||
@@ -20,7 +22,10 @@ import { readRuntimeFromBle, type BleRuntimePatch } from './device-bluetooth-rea
|
||||
import type { UpdateDeviceRuntimeBody } from './device-detail.types'
|
||||
|
||||
const SYNC_INTERVAL_MS = 15000
|
||||
const SCAN_TIMEOUT_MS = 15000
|
||||
const QUICK_SCAN_MS = 5000
|
||||
const RETRY_SCAN_MS = 10000
|
||||
/** 断连事件防抖:避免 create/notify 过程中的瞬时断连触发重连循环 */
|
||||
const DISCONNECT_CONFIRM_MS = 700
|
||||
|
||||
export interface DeviceBluetoothSyncContext {
|
||||
getDeviceId: () => string | number
|
||||
@@ -35,17 +40,34 @@ export interface DeviceBluetoothSyncContext {
|
||||
|
||||
export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
const syncing = ref(false)
|
||||
const connecting = ref(false)
|
||||
const bleDeviceId = ref<string>()
|
||||
let syncTimer: ReturnType<typeof setInterval> | undefined
|
||||
let disconnectTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let unsubscribeConnection: (() => void) | undefined
|
||||
let active = false
|
||||
let tearingDown = false
|
||||
let hadSuccessfulSync = false
|
||||
/** 正在主动建连,忽略期间的断连回调 */
|
||||
let linking = false
|
||||
|
||||
function setSyncText(text: string) {
|
||||
context.onSyncTextChange(text)
|
||||
}
|
||||
|
||||
function resolveBleBroadcastName(mac: string): string | undefined {
|
||||
try {
|
||||
return buildBleDeviceName(mac)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function persistBleId(mac: string, id: string) {
|
||||
bleDeviceId.value = id
|
||||
rememberBleDeviceId(mac, id)
|
||||
}
|
||||
|
||||
async function reportBleDisconnected() {
|
||||
const deviceId = context.getDeviceId()
|
||||
if (!deviceId) return
|
||||
@@ -66,25 +88,70 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
context.onBluetoothConnectedChange(false)
|
||||
}
|
||||
|
||||
async function resolveBleTarget(
|
||||
mac: string,
|
||||
preferredBleId?: string,
|
||||
): Promise<UniApp.BluetoothDeviceInfo | null> {
|
||||
const connected = await getConnectedBleDeviceByMac(mac)
|
||||
if (connected) return connected
|
||||
function clearDisconnectTimer() {
|
||||
if (disconnectTimer) {
|
||||
clearTimeout(disconnectTimer)
|
||||
disconnectTimer = undefined
|
||||
}
|
||||
}
|
||||
|
||||
if (preferredBleId) {
|
||||
const discovered = await getDiscoveredBluetoothDevices()
|
||||
const cached = discovered.find((item) => item.deviceId === preferredBleId)
|
||||
if (cached) return cached
|
||||
async function resolveBleTarget(mac: string): Promise<UniApp.BluetoothDeviceInfo | null> {
|
||||
const bleName = resolveBleBroadcastName(mac)
|
||||
const preferredBleId = bleDeviceId.value || recallBleDeviceId(mac)
|
||||
|
||||
const connected = await getConnectedBleDeviceByMac(mac, {
|
||||
name: bleName,
|
||||
preferredBleId,
|
||||
})
|
||||
if (connected) {
|
||||
persistBleId(mac, connected.deviceId)
|
||||
return connected
|
||||
}
|
||||
|
||||
const deviceName = context.getDeviceName?.()
|
||||
return scanForBleDeviceByMac(mac, {
|
||||
timeoutMs: SCAN_TIMEOUT_MS,
|
||||
name: deviceName,
|
||||
skipCached: !preferredBleId && !hadSuccessfulSync,
|
||||
if (preferredBleId) {
|
||||
try {
|
||||
linking = true
|
||||
await ensureBleConnection(preferredBleId, { settleMs: 200 })
|
||||
const after = await getConnectedBleDeviceByMac(mac, {
|
||||
name: bleName,
|
||||
preferredBleId,
|
||||
})
|
||||
if (after) {
|
||||
persistBleId(mac, after.deviceId)
|
||||
return after
|
||||
}
|
||||
if (await isBleDeviceConnected(preferredBleId)) {
|
||||
persistBleId(mac, preferredBleId)
|
||||
return {
|
||||
deviceId: preferredBleId,
|
||||
name: bleName,
|
||||
localName: bleName,
|
||||
} as UniApp.BluetoothDeviceInfo
|
||||
}
|
||||
} catch {
|
||||
if (bleDeviceId.value === preferredBleId) bleDeviceId.value = undefined
|
||||
} finally {
|
||||
linking = false
|
||||
}
|
||||
}
|
||||
|
||||
const foundQuick = await scanForBleDeviceByMac(mac, {
|
||||
timeoutMs: QUICK_SCAN_MS,
|
||||
name: bleName,
|
||||
skipCached: false,
|
||||
})
|
||||
if (foundQuick) {
|
||||
persistBleId(mac, foundQuick.deviceId)
|
||||
return foundQuick
|
||||
}
|
||||
|
||||
const foundRetry = await scanForBleDeviceByMac(mac, {
|
||||
timeoutMs: RETRY_SCAN_MS,
|
||||
name: bleName,
|
||||
skipCached: true,
|
||||
})
|
||||
if (foundRetry) persistBleId(mac, foundRetry.deviceId)
|
||||
return foundRetry
|
||||
}
|
||||
|
||||
async function syncBleData(
|
||||
@@ -103,16 +170,21 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
|
||||
hadSuccessfulSync = true
|
||||
context.onBluetoothConnectedChange(true)
|
||||
// 先更新本地 UI(含滤芯),再上报云端
|
||||
context.onBleRuntimeRead?.(blePayload)
|
||||
|
||||
const runtimePatch = context.getRuntimePatch()
|
||||
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
|
||||
const {
|
||||
airQuality: _airQuality,
|
||||
...bleRuntimeBody
|
||||
} = blePayload
|
||||
|
||||
try {
|
||||
await updateDeviceRuntime({
|
||||
deviceId,
|
||||
...runtimePatch,
|
||||
...blePayload,
|
||||
...bleRuntimeBody,
|
||||
status: '1',
|
||||
bluetoothConnected: '1',
|
||||
signalLevel,
|
||||
@@ -125,6 +197,33 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
return true
|
||||
}
|
||||
|
||||
/** 已连上时只拉数据,绝不重新 createBLEConnection */
|
||||
async function syncIfAlreadyConnected(mac: string): Promise<boolean | null> {
|
||||
const bleName = resolveBleBroadcastName(mac)
|
||||
const preferredBleId = bleDeviceId.value || recallBleDeviceId(mac)
|
||||
const connected = await getConnectedBleDeviceByMac(mac, {
|
||||
name: bleName,
|
||||
preferredBleId,
|
||||
})
|
||||
if (!connected) {
|
||||
if (preferredBleId && await isBleDeviceConnected(preferredBleId)) {
|
||||
persistBleId(mac, preferredBleId)
|
||||
try {
|
||||
return await syncBleData(preferredBleId, null)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
persistBleId(mac, connected.deviceId)
|
||||
try {
|
||||
return await syncBleData(connected.deviceId, connected)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function connectAndSync(): Promise<boolean> {
|
||||
const deviceId = context.getDeviceId()
|
||||
const mac = context.getMac()
|
||||
@@ -142,14 +241,21 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
|
||||
if (syncing.value) return false
|
||||
syncing.value = true
|
||||
connecting.value = !hadSuccessfulSync
|
||||
|
||||
let targetBleId = bleDeviceId.value
|
||||
let foundDevice: UniApp.BluetoothDeviceInfo | null = null
|
||||
let targetBleId = bleDeviceId.value || recallBleDeviceId(mac)
|
||||
|
||||
try {
|
||||
if (connecting.value) {
|
||||
setSyncText('正在搜索并连接设备…')
|
||||
}
|
||||
await ensureBluetoothReady()
|
||||
|
||||
foundDevice = await resolveBleTarget(mac, targetBleId)
|
||||
// 周期同步 / 回前台:链路还在就只读数据,避免反复建连闪断
|
||||
const quiet = await syncIfAlreadyConnected(mac)
|
||||
if (quiet != null) return quiet
|
||||
|
||||
const foundDevice = await resolveBleTarget(mac)
|
||||
if (!foundDevice) {
|
||||
setSyncText('未找到设备,请确认已开机并靠近手机')
|
||||
if (!tearingDown) {
|
||||
@@ -164,18 +270,31 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
}
|
||||
|
||||
targetBleId = foundDevice.deviceId
|
||||
bleDeviceId.value = targetBleId
|
||||
persistBleId(mac, targetBleId)
|
||||
|
||||
if (!hadSuccessfulSync) {
|
||||
setSyncText('正在连接蓝牙…')
|
||||
const alreadyLinked = await isBleDeviceConnected(targetBleId)
|
||||
if (!alreadyLinked) {
|
||||
if (!hadSuccessfulSync) {
|
||||
connecting.value = true
|
||||
setSyncText('正在连接蓝牙…')
|
||||
}
|
||||
linking = true
|
||||
try {
|
||||
await ensureBleConnection(targetBleId)
|
||||
} finally {
|
||||
linking = false
|
||||
}
|
||||
}
|
||||
await ensureBleConnection(targetBleId)
|
||||
|
||||
return await syncBleData(targetBleId, foundDevice)
|
||||
} catch (err) {
|
||||
const stillConnected = await getConnectedBleDeviceByMac(mac)
|
||||
const bleName = resolveBleBroadcastName(mac)
|
||||
const stillConnected = await getConnectedBleDeviceByMac(mac, {
|
||||
name: bleName,
|
||||
preferredBleId: targetBleId,
|
||||
})
|
||||
if (stillConnected) {
|
||||
bleDeviceId.value = stillConnected.deviceId
|
||||
persistBleId(mac, stillConnected.deviceId)
|
||||
context.onBluetoothConnectedChange(true)
|
||||
try {
|
||||
return await syncBleData(stillConnected.deviceId, stillConnected)
|
||||
@@ -187,7 +306,6 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
|
||||
setSyncText(getBluetoothErrorMessage(err))
|
||||
if (!tearingDown) {
|
||||
bleDeviceId.value = undefined
|
||||
clearZ2BleHandleCache(targetBleId)
|
||||
if (hadSuccessfulSync) {
|
||||
hadSuccessfulSync = false
|
||||
@@ -199,9 +317,35 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
return false
|
||||
} finally {
|
||||
syncing.value = false
|
||||
connecting.value = active && !hadSuccessfulSync && !tearingDown
|
||||
}
|
||||
}
|
||||
|
||||
async function handleConfirmedDisconnect(disconnectedId: string) {
|
||||
if (tearingDown || !active) return
|
||||
const mac = context.getMac()
|
||||
if (mac) {
|
||||
const stillConnected = await getConnectedBleDeviceByMac(mac, {
|
||||
name: resolveBleBroadcastName(mac),
|
||||
preferredBleId: bleDeviceId.value || disconnectedId,
|
||||
})
|
||||
if (stillConnected) {
|
||||
persistBleId(mac, stillConnected.deviceId)
|
||||
return
|
||||
}
|
||||
if (await isBleDeviceConnected(disconnectedId)) return
|
||||
}
|
||||
|
||||
hadSuccessfulSync = false
|
||||
reportBleLinkLostLocal()
|
||||
connecting.value = true
|
||||
setSyncText('蓝牙已断开,正在尝试重连…')
|
||||
if (bleDeviceId.value === disconnectedId) bleDeviceId.value = undefined
|
||||
clearZ2BleHandleCache(disconnectedId)
|
||||
void reportBleDisconnected()
|
||||
if (!syncing.value) void connectAndSync()
|
||||
}
|
||||
|
||||
async function sendBleCommand(command: string): Promise<boolean> {
|
||||
if (!bleDeviceId.value) {
|
||||
const ok = await connectAndSync()
|
||||
@@ -215,7 +359,18 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
const ok = await connectAndSync()
|
||||
if (!ok || !bleDeviceId.value) return false
|
||||
try {
|
||||
const state = await sendZ2BleCommand(bleDeviceId.value, command)
|
||||
const runtimePatch = mapZ2StateToRuntimePatch(state)
|
||||
if (Object.keys(runtimePatch).length) {
|
||||
context.onBleRuntimeRead?.(runtimePatch)
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,37 +378,42 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
if (active) return
|
||||
|
||||
if (!isBluetoothApiSupported()) {
|
||||
connecting.value = false
|
||||
setSyncText('云端数据已加载 · 实时同步请使用 App 或微信小程序')
|
||||
return
|
||||
}
|
||||
|
||||
active = true
|
||||
connecting.value = true
|
||||
setSyncText('正在搜索并连接设备…')
|
||||
|
||||
const mac = context.getMac()
|
||||
if (mac) {
|
||||
const cached = recallBleDeviceId(mac)
|
||||
if (cached) bleDeviceId.value = cached
|
||||
}
|
||||
|
||||
unsubscribeConnection = subscribeBleConnectionStateChange((res) => {
|
||||
if (tearingDown) return
|
||||
if (tearingDown || !active) return
|
||||
if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return
|
||||
if (!res.connected) {
|
||||
void (async () => {
|
||||
const mac = context.getMac()
|
||||
if (mac) {
|
||||
const stillConnected = await getConnectedBleDeviceByMac(mac)
|
||||
if (stillConnected) {
|
||||
bleDeviceId.value = stillConnected.deviceId
|
||||
return
|
||||
}
|
||||
}
|
||||
bleDeviceId.value = undefined
|
||||
clearZ2BleHandleCache(res.deviceId)
|
||||
void reportBleDisconnected()
|
||||
setSyncText('蓝牙已断开,正在尝试重连…')
|
||||
void connectAndSync()
|
||||
})()
|
||||
if (res.connected) {
|
||||
clearDisconnectTimer()
|
||||
return
|
||||
}
|
||||
// 主动建连 / 同步中的瞬时断连忽略,等结束后再判定
|
||||
if (linking || syncing.value) return
|
||||
|
||||
clearDisconnectTimer()
|
||||
disconnectTimer = setTimeout(() => {
|
||||
disconnectTimer = undefined
|
||||
void handleConfirmedDisconnect(res.deviceId)
|
||||
}, DISCONNECT_CONFIRM_MS)
|
||||
})
|
||||
|
||||
void connectAndSync()
|
||||
|
||||
syncTimer = setInterval(() => {
|
||||
if (syncing.value || tearingDown || linking) return
|
||||
void connectAndSync()
|
||||
}, SYNC_INTERVAL_MS)
|
||||
}
|
||||
@@ -262,6 +422,9 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
tearingDown = true
|
||||
active = false
|
||||
hadSuccessfulSync = false
|
||||
connecting.value = false
|
||||
linking = false
|
||||
clearDisconnectTimer()
|
||||
if (syncTimer) {
|
||||
clearInterval(syncTimer)
|
||||
syncTimer = undefined
|
||||
@@ -280,6 +443,11 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
}
|
||||
|
||||
onShow(() => {
|
||||
try {
|
||||
uni.hideLoading()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
if (!active || tearingDown) return
|
||||
void connectAndSync()
|
||||
})
|
||||
@@ -290,6 +458,7 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
|
||||
return {
|
||||
syncing,
|
||||
connecting,
|
||||
startSyncLoop,
|
||||
stopSync,
|
||||
connectAndSync,
|
||||
|
||||
@@ -6,7 +6,7 @@ import { getErrorMessage } from '@/utils/api-error'
|
||||
import { parseDeviceId, parseId, sameId } from '@/utils/device-id'
|
||||
import { fetchProductOptions } from '@/pages/add-device/complete/complete.api'
|
||||
import { fetchAllDeviceList } from '../device.api'
|
||||
import { findPatchedDeviceName } from '../device-list-patch'
|
||||
import { findPatchedDeviceLocation, findPatchedDeviceName } from '../device-list-patch'
|
||||
import { fetchDeviceRuntime, updateDeviceRuntime } from './device-detail.api'
|
||||
import type { AppDeviceRuntimeVo, DeviceDetailRouteQuery, FanLevel, RunMode } from './device-detail.types'
|
||||
import {
|
||||
@@ -50,6 +50,8 @@ export function useDeviceDetail() {
|
||||
const bluetoothConnected = ref(false)
|
||||
const charging = ref(false)
|
||||
const loading = ref(false)
|
||||
/** 进入详情后、首轮蓝牙连接开始前也展示加载态 */
|
||||
const awaitingBleStart = ref(true)
|
||||
const isOnline = computed(() => bluetoothConnected.value)
|
||||
|
||||
const runMode = ref<RunMode>('0')
|
||||
@@ -64,6 +66,8 @@ export function useDeviceDetail() {
|
||||
const filterReplaceDialogVisible = ref(false)
|
||||
const batteryLevel = ref<number | null>(null)
|
||||
let pendingBatteryReading: number | null = null
|
||||
/** 本页已从蓝牙读到滤芯后,避免云端旧值盖住实时衰减 */
|
||||
let filterLifeFromBle = false
|
||||
const syncText = ref('数据实时同步中')
|
||||
|
||||
const tvocDisplay = computed(() => formatTvocValue(tvoc.value ?? undefined))
|
||||
@@ -75,13 +79,6 @@ export function useDeviceDetail() {
|
||||
const batteryDisplay = computed(() =>
|
||||
batteryLevel.value != null ? `${batteryLevel.value}%` : '--',
|
||||
)
|
||||
const connectionText = computed(() =>
|
||||
formatConnectionText({
|
||||
status: deviceStatus.value,
|
||||
bluetoothConnected: bluetoothConnected.value ? '1' : '0',
|
||||
locationName: locationName.value,
|
||||
}),
|
||||
)
|
||||
const showFanLevelControl = computed(() => isAutoRunMode(runMode.value))
|
||||
const fanLevelOptions = computed(() =>
|
||||
showFanLevelControl.value ? AUTO_FAN_LEVEL_OPTIONS : [],
|
||||
@@ -135,6 +132,7 @@ export function useDeviceDetail() {
|
||||
if (patch.powerMode != null) powerMode.value = patch.powerMode
|
||||
if (patch.filterLife != null) {
|
||||
filterLife.value = patch.filterLife
|
||||
filterLifeFromBle = true
|
||||
updateFilterRemainText()
|
||||
}
|
||||
if (patch.deviceBattery != null) applyBatteryLevel(patch.deviceBattery, true)
|
||||
@@ -148,8 +146,13 @@ export function useDeviceDetail() {
|
||||
fanLevel.value = view.fanLevel
|
||||
if (view.tvoc != null) tvoc.value = view.tvoc
|
||||
powerMode.value = view.powerMode
|
||||
filterLife.value = view.filterLife
|
||||
filterRemainText.value = view.filterRemainText
|
||||
// 蓝牙已读到实时滤芯时,不以云端缓存覆盖(否则 15 分钟衰减看不到)
|
||||
if (!filterLifeFromBle) {
|
||||
filterLife.value = view.filterLife
|
||||
filterRemainText.value = view.filterRemainText
|
||||
} else {
|
||||
updateFilterRemainText()
|
||||
}
|
||||
filterReplaced.value = view.filterReplaced
|
||||
if (data.deviceBattery != null) applyBatteryLevel(data.deviceBattery, false)
|
||||
if (!bluetoothConnected.value && data.status !== undefined) {
|
||||
@@ -162,6 +165,11 @@ export function useDeviceDetail() {
|
||||
const bleConnectedLocally = bluetoothConnected.value
|
||||
const patchedName = findPatchedDeviceName(deviceId.value)
|
||||
if (patchedName) deviceName.value = patchedName
|
||||
const patchedLocation = findPatchedDeviceLocation(deviceId.value)
|
||||
if (patchedLocation) {
|
||||
locationId.value = patchedLocation.locationId
|
||||
locationName.value = patchedLocation.locationName
|
||||
}
|
||||
try {
|
||||
const list = await fetchAllDeviceList()
|
||||
const device = list?.find((item) => String(item.deviceId) === deviceId.value)
|
||||
@@ -169,22 +177,34 @@ export function useDeviceDetail() {
|
||||
if (device.deviceId != null) deviceId.value = String(device.deviceId)
|
||||
if (device.deviceNo) deviceNo.value = device.deviceNo
|
||||
if (device.mac) deviceMac.value = device.mac
|
||||
if (device.name) deviceName.value = device.name
|
||||
const parsedLocationId = parseId(device.locationId)
|
||||
if (parsedLocationId) locationId.value = parsedLocationId
|
||||
// 本地刚改名优先,避免 onShow 刷新用接口旧名称盖回去
|
||||
if (patchedName && device.name !== patchedName) {
|
||||
deviceName.value = patchedName
|
||||
} else if (device.name) {
|
||||
deviceName.value = device.name
|
||||
}
|
||||
const parsedHomeId = parseId(device.homeId)
|
||||
if (parsedHomeId) homeId.value = parsedHomeId
|
||||
if (parsedHomeId && parsedLocationId) {
|
||||
const locations = await fetchRoomList(parsedHomeId)
|
||||
const matched = locations.find((item) => sameId(item.locationId, parsedLocationId))
|
||||
if (matched) locationName.value = matched.name
|
||||
if (patchedLocation) {
|
||||
// 本地刚切换的房间优先,避免接口短暂延迟把展示盖回旧房间
|
||||
} else {
|
||||
const parsedLocationId = parseId(device.locationId)
|
||||
if (parsedLocationId) locationId.value = parsedLocationId
|
||||
if (parsedHomeId && parsedLocationId) {
|
||||
const locations = await fetchRoomList(parsedHomeId)
|
||||
const matched = locations.find((item) => sameId(item.locationId, parsedLocationId))
|
||||
if (matched) locationName.value = matched.name
|
||||
}
|
||||
}
|
||||
charging.value = device.charging === '1'
|
||||
// 详情页连接态以本地 BLE 为准:云端不能把状态打成「已连接」,
|
||||
// 否则会提前关掉重连加载遮罩(列表/接口常有脏在线态)
|
||||
if (!bleConnectedLocally) {
|
||||
bluetoothConnected.value = isBluetoothConnected(device.bluetoothConnected)
|
||||
deviceStatus.value = bluetoothConnected.value
|
||||
? '1'
|
||||
: (device.status === '0' ? '0' : '2')
|
||||
const apiConnected = isBluetoothConnected(device.bluetoothConnected)
|
||||
if (!apiConnected) {
|
||||
bluetoothConnected.value = false
|
||||
deviceStatus.value = device.status === '0' ? '0' : '2'
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 列表刷新失败时保留路由参数状态
|
||||
@@ -255,17 +275,20 @@ export function useDeviceDetail() {
|
||||
}
|
||||
|
||||
function onSelectRunMode(mode: RunMode) {
|
||||
if (showReconnectLoading.value) return
|
||||
if (runMode.value === mode) return
|
||||
void patchRuntime({ runMode: mode })
|
||||
}
|
||||
|
||||
function onSelectFanLevel(level: FanLevel) {
|
||||
if (showReconnectLoading.value) return
|
||||
if (!isAutoRunMode(runMode.value)) return
|
||||
if (fanLevel.value === level) return
|
||||
void patchRuntime({ fanLevel: level })
|
||||
}
|
||||
|
||||
function onSettings() {
|
||||
if (showReconnectLoading.value) return
|
||||
if (!deviceId.value) {
|
||||
uni.showToast({ title: '设备信息不完整', icon: 'none' })
|
||||
return
|
||||
@@ -284,6 +307,7 @@ export function useDeviceDetail() {
|
||||
}
|
||||
|
||||
function onFilterReplace() {
|
||||
if (showReconnectLoading.value) return
|
||||
if (filterReplaced.value) return
|
||||
filterReplaceDialogVisible.value = true
|
||||
}
|
||||
@@ -300,11 +324,16 @@ export function useDeviceDetail() {
|
||||
}
|
||||
filterReplaced.value = true
|
||||
filterLife.value = 100
|
||||
filterLifeFromBle = true
|
||||
updateFilterRemainText()
|
||||
uni.showToast({ title: '操作成功', icon: 'success' })
|
||||
}
|
||||
|
||||
const { startSyncLoop, sendBleCommand } = useDeviceBluetoothSync({
|
||||
const {
|
||||
connecting: bleConnecting,
|
||||
startSyncLoop,
|
||||
sendBleCommand,
|
||||
} = useDeviceBluetoothSync({
|
||||
getDeviceId: () => deviceId.value,
|
||||
getMac: () => deviceMac.value,
|
||||
getDeviceName: () => deviceName.value,
|
||||
@@ -330,6 +359,33 @@ export function useDeviceDetail() {
|
||||
},
|
||||
})
|
||||
|
||||
/** 仅离线进入或断线重连时展示;在线进入 / 改名返回不闪遮罩 */
|
||||
const showReconnectLoading = computed(
|
||||
() => !bluetoothConnected.value && (awaitingBleStart.value || bleConnecting.value),
|
||||
)
|
||||
|
||||
const reconnectLoadingTitle = computed(() => {
|
||||
if (/重连/.test(syncText.value)) return '设备重连中'
|
||||
return '设备连接中'
|
||||
})
|
||||
|
||||
const reconnectLoadingDesc = computed(() => {
|
||||
const text = syncText.value.trim()
|
||||
if (text && /连接|搜索|同步|重连/.test(text)) return text
|
||||
return '正在重新连接蓝牙,请靠近设备并稍候'
|
||||
})
|
||||
|
||||
const connectionText = computed(() => {
|
||||
if (showReconnectLoading.value) {
|
||||
return reconnectLoadingTitle.value
|
||||
}
|
||||
return formatConnectionText({
|
||||
status: deviceStatus.value,
|
||||
bluetoothConnected: bluetoothConnected.value ? '1' : '0',
|
||||
locationName: locationName.value,
|
||||
})
|
||||
})
|
||||
|
||||
onLoad((query?: DeviceDetailRouteQuery) => {
|
||||
deviceId.value = parseDeviceId(query?.deviceId)
|
||||
if (query?.deviceNo) {
|
||||
@@ -346,12 +402,19 @@ export function useDeviceDetail() {
|
||||
if (parsedHomeId) homeId.value = parsedHomeId
|
||||
if (query?.model) productModel.value = decodeURIComponent(String(query.model))
|
||||
if (query?.mac) deviceMac.value = decodeURIComponent(String(query.mac))
|
||||
bluetoothConnected.value = false
|
||||
deviceStatus.value = '2'
|
||||
// 以列表带入的在线态为准:在线进入不闪重连遮罩;离线进入才展示连接中
|
||||
const enteredOnline = isBluetoothConnected(query?.bluetoothConnected)
|
||||
|| query?.status === '1'
|
||||
bluetoothConnected.value = enteredOnline
|
||||
deviceStatus.value = enteredOnline ? '1' : (query?.status === '0' ? '0' : '2')
|
||||
awaitingBleStart.value = !enteredOnline
|
||||
charging.value = query?.charging === '1'
|
||||
void loadRuntime().then(() => {
|
||||
startSyncLoop()
|
||||
})
|
||||
void loadRuntime()
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
startSyncLoop()
|
||||
awaitingBleStart.value = false
|
||||
})
|
||||
})
|
||||
|
||||
usePageShowRefresh(() => refreshDeviceMeta(), { skipInitialShow: true })
|
||||
@@ -360,6 +423,9 @@ export function useDeviceDetail() {
|
||||
deviceName,
|
||||
connectionText,
|
||||
isOnline,
|
||||
showReconnectLoading,
|
||||
reconnectLoadingTitle,
|
||||
reconnectLoadingDesc,
|
||||
tvocDisplay,
|
||||
tvocLevel,
|
||||
syncText,
|
||||
|
||||
Reference in New Issue
Block a user