fix:蓝牙bug解决
This commit is contained in:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user