468 lines
13 KiB
TypeScript
468 lines
13 KiB
TypeScript
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,
|
||
isBleDeviceConnected,
|
||
isBluetoothApiSupported,
|
||
rssiToSignalLevel,
|
||
scanForBleDeviceByMac,
|
||
subscribeBleConnectionStateChange,
|
||
} from '@/utils/bluetooth'
|
||
import { mapZ2StateToRuntimePatch } from '@/utils/z2-ble-protocol'
|
||
import { clearZ2BleHandleCache, sendZ2BleCommand } from '@/utils/z2-ble'
|
||
import { updateDeviceRuntime } from './device-detail.api'
|
||
import { readRuntimeFromBle, type BleRuntimePatch } from './device-bluetooth-read'
|
||
import type { UpdateDeviceRuntimeBody } from './device-detail.types'
|
||
|
||
const SYNC_INTERVAL_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
|
||
getMac: () => string | undefined
|
||
getDeviceName?: () => string
|
||
getRuntimePatch: () => Partial<UpdateDeviceRuntimeBody>
|
||
onBluetoothConnectedChange: (connected: boolean) => void
|
||
onSyncTextChange: (text: string) => void
|
||
onSynced?: () => void | Promise<void>
|
||
onBleRuntimeRead?: (patch: BleRuntimePatch) => void
|
||
}
|
||
|
||
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
|
||
context.onBluetoothConnectedChange(false)
|
||
try {
|
||
await updateDeviceRuntime({
|
||
deviceId,
|
||
status: '2',
|
||
bluetoothConnected: '0',
|
||
signalLevel: '0',
|
||
})
|
||
} catch {
|
||
// 上报失败时保留本地状态
|
||
}
|
||
}
|
||
|
||
function reportBleLinkLostLocal() {
|
||
context.onBluetoothConnectedChange(false)
|
||
}
|
||
|
||
function clearDisconnectTimer() {
|
||
if (disconnectTimer) {
|
||
clearTimeout(disconnectTimer)
|
||
disconnectTimer = undefined
|
||
}
|
||
}
|
||
|
||
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
|
||
}
|
||
|
||
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(
|
||
targetBleId: string,
|
||
foundDevice: UniApp.BluetoothDeviceInfo | null,
|
||
): Promise<boolean> {
|
||
const deviceId = context.getDeviceId()
|
||
if (!deviceId) return false
|
||
|
||
setSyncText('正在同步设备数据…')
|
||
const blePayload = await readRuntimeFromBle(targetBleId)
|
||
const hasBleData = Object.keys(blePayload).length > 0
|
||
if (!hasBleData) {
|
||
throw new Error('设备无响应,请确认已开机并靠近手机')
|
||
}
|
||
|
||
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,
|
||
...bleRuntimeBody,
|
||
status: '1',
|
||
bluetoothConnected: '1',
|
||
signalLevel,
|
||
})
|
||
setSyncText('刚刚更新 · 数据实时同步中')
|
||
await context.onSynced?.()
|
||
} catch (apiErr) {
|
||
setSyncText(`蓝牙已连接 · 云端同步失败:${getErrorMessage(apiErr, '请检查网络')}`)
|
||
}
|
||
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()
|
||
if (!deviceId) return false
|
||
|
||
if (!isBluetoothApiSupported()) {
|
||
setSyncText('当前环境不支持蓝牙同步')
|
||
return false
|
||
}
|
||
|
||
if (!mac) {
|
||
setSyncText('缺少设备 MAC,无法蓝牙同步')
|
||
return false
|
||
}
|
||
|
||
if (syncing.value) return false
|
||
syncing.value = true
|
||
connecting.value = !hadSuccessfulSync
|
||
|
||
let targetBleId = bleDeviceId.value || recallBleDeviceId(mac)
|
||
|
||
try {
|
||
if (connecting.value) {
|
||
setSyncText('正在搜索并连接设备…')
|
||
}
|
||
await ensureBluetoothReady()
|
||
|
||
// 周期同步 / 回前台:链路还在就只读数据,避免反复建连闪断
|
||
const quiet = await syncIfAlreadyConnected(mac)
|
||
if (quiet != null) return quiet
|
||
|
||
const foundDevice = await resolveBleTarget(mac)
|
||
if (!foundDevice) {
|
||
setSyncText('未找到设备,请确认已开机并靠近手机')
|
||
if (!tearingDown) {
|
||
if (hadSuccessfulSync) {
|
||
hadSuccessfulSync = false
|
||
void reportBleDisconnected()
|
||
} else {
|
||
reportBleLinkLostLocal()
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
targetBleId = foundDevice.deviceId
|
||
persistBleId(mac, targetBleId)
|
||
|
||
const alreadyLinked = await isBleDeviceConnected(targetBleId)
|
||
if (!alreadyLinked) {
|
||
if (!hadSuccessfulSync) {
|
||
connecting.value = true
|
||
setSyncText('正在连接蓝牙…')
|
||
}
|
||
linking = true
|
||
try {
|
||
await ensureBleConnection(targetBleId)
|
||
} finally {
|
||
linking = false
|
||
}
|
||
}
|
||
|
||
return await syncBleData(targetBleId, foundDevice)
|
||
} catch (err) {
|
||
const bleName = resolveBleBroadcastName(mac)
|
||
const stillConnected = await getConnectedBleDeviceByMac(mac, {
|
||
name: bleName,
|
||
preferredBleId: targetBleId,
|
||
})
|
||
if (stillConnected) {
|
||
persistBleId(mac, stillConnected.deviceId)
|
||
context.onBluetoothConnectedChange(true)
|
||
try {
|
||
return await syncBleData(stillConnected.deviceId, stillConnected)
|
||
} catch (retryErr) {
|
||
setSyncText(getBluetoothErrorMessage(retryErr))
|
||
return true
|
||
}
|
||
}
|
||
|
||
setSyncText(getBluetoothErrorMessage(err))
|
||
if (!tearingDown) {
|
||
clearZ2BleHandleCache(targetBleId)
|
||
if (hadSuccessfulSync) {
|
||
hadSuccessfulSync = false
|
||
void reportBleDisconnected()
|
||
} else {
|
||
reportBleLinkLostLocal()
|
||
}
|
||
}
|
||
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()
|
||
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 {
|
||
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
|
||
}
|
||
}
|
||
}
|
||
|
||
function startSyncLoop() {
|
||
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 || !active) return
|
||
if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return
|
||
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)
|
||
}
|
||
|
||
async function stopSync() {
|
||
tearingDown = true
|
||
active = false
|
||
hadSuccessfulSync = false
|
||
connecting.value = false
|
||
linking = false
|
||
clearDisconnectTimer()
|
||
if (syncTimer) {
|
||
clearInterval(syncTimer)
|
||
syncTimer = undefined
|
||
}
|
||
unsubscribeConnection?.()
|
||
unsubscribeConnection = undefined
|
||
|
||
const currentBleId = bleDeviceId.value
|
||
bleDeviceId.value = undefined
|
||
|
||
if (currentBleId) {
|
||
clearZ2BleHandleCache(currentBleId)
|
||
await closeBleConnection(currentBleId).catch(() => {})
|
||
}
|
||
tearingDown = false
|
||
}
|
||
|
||
onShow(() => {
|
||
try {
|
||
uni.hideLoading()
|
||
} catch {
|
||
// ignore
|
||
}
|
||
if (!active || tearingDown) return
|
||
void connectAndSync()
|
||
})
|
||
|
||
onUnload(() => {
|
||
void stopSync()
|
||
})
|
||
|
||
return {
|
||
syncing,
|
||
connecting,
|
||
startSyncLoop,
|
||
stopSync,
|
||
connectAndSync,
|
||
sendBleCommand,
|
||
}
|
||
}
|