feat:绑定设备和设备详情
This commit is contained in:
185
src/pages/device/detail/use-device-bluetooth-sync.ts
Normal file
185
src/pages/device/detail/use-device-bluetooth-sync.ts
Normal file
@@ -0,0 +1,185 @@
|
||||
import { onUnload } from '@dcloudio/uni-app'
|
||||
import { ref } from 'vue'
|
||||
import {
|
||||
BluetoothError,
|
||||
closeBleConnection,
|
||||
createBleConnection,
|
||||
ensureBluetoothReady,
|
||||
getBluetoothErrorMessage,
|
||||
getDiscoveredBluetoothDevices,
|
||||
isBluetoothApiSupported,
|
||||
rssiToSignalLevel,
|
||||
scanForBleDeviceByMac,
|
||||
subscribeBleConnectionStateChange,
|
||||
} from '@/utils/bluetooth'
|
||||
import { updateDeviceRuntime } from './device-detail.api'
|
||||
import { readRuntimeFromBle } from './device-bluetooth-read'
|
||||
import type { UpdateDeviceRuntimeBody } from './device-detail.types'
|
||||
|
||||
const SYNC_INTERVAL_MS = 15000
|
||||
const SCAN_TIMEOUT_MS = 15000
|
||||
|
||||
export interface DeviceBluetoothSyncContext {
|
||||
getDeviceId: () => number
|
||||
getMac: () => string | undefined
|
||||
getRuntimePatch: () => Partial<UpdateDeviceRuntimeBody>
|
||||
onBluetoothConnectedChange: (connected: boolean) => void
|
||||
onSyncTextChange: (text: string) => void
|
||||
onSynced?: () => void | Promise<void>
|
||||
}
|
||||
|
||||
export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
const syncing = ref(false)
|
||||
const bleDeviceId = ref<string>()
|
||||
let syncTimer: ReturnType<typeof setInterval> | undefined
|
||||
let unsubscribeConnection: (() => void) | undefined
|
||||
let active = false
|
||||
|
||||
function setSyncText(text: string) {
|
||||
context.onSyncTextChange(text)
|
||||
}
|
||||
|
||||
async function reportDisconnected() {
|
||||
const deviceId = context.getDeviceId()
|
||||
if (!deviceId) return
|
||||
context.onBluetoothConnectedChange(false)
|
||||
try {
|
||||
await updateDeviceRuntime({
|
||||
deviceId,
|
||||
bluetoothConnected: '0',
|
||||
signalLevel: '0',
|
||||
})
|
||||
} catch {
|
||||
// 上报失败时保留本地状态
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
try {
|
||||
setSyncText('正在连接蓝牙…')
|
||||
await ensureBluetoothReady()
|
||||
|
||||
let targetBleId = bleDeviceId.value
|
||||
let foundDevice: UniApp.BluetoothDeviceInfo | null = null
|
||||
|
||||
if (!targetBleId) {
|
||||
foundDevice = await scanForBleDeviceByMac(mac, { timeoutMs: SCAN_TIMEOUT_MS })
|
||||
if (!foundDevice) {
|
||||
setSyncText('未找到设备,请确认已开机并靠近手机')
|
||||
await reportDisconnected()
|
||||
return false
|
||||
}
|
||||
targetBleId = foundDevice.deviceId
|
||||
bleDeviceId.value = targetBleId
|
||||
} else {
|
||||
const discovered = await getDiscoveredBluetoothDevices()
|
||||
foundDevice = discovered.find((item) => item.deviceId === targetBleId) ?? null
|
||||
}
|
||||
|
||||
try {
|
||||
await createBleConnection(targetBleId)
|
||||
} catch (err) {
|
||||
const btErr = err as BluetoothError
|
||||
if (btErr.errCode !== 10010) throw err
|
||||
}
|
||||
|
||||
if (!targetBleId) {
|
||||
setSyncText('蓝牙连接异常,请重试')
|
||||
await reportDisconnected()
|
||||
return false
|
||||
}
|
||||
|
||||
context.onBluetoothConnectedChange(true)
|
||||
|
||||
const blePayload = await readRuntimeFromBle(targetBleId)
|
||||
const runtimePatch = context.getRuntimePatch()
|
||||
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
|
||||
|
||||
await updateDeviceRuntime({
|
||||
deviceId,
|
||||
...runtimePatch,
|
||||
...blePayload,
|
||||
status: '1',
|
||||
bluetoothConnected: '1',
|
||||
signalLevel,
|
||||
})
|
||||
|
||||
setSyncText('刚刚更新 · 数据实时同步中')
|
||||
await context.onSynced?.()
|
||||
return true
|
||||
} catch (err) {
|
||||
setSyncText(getBluetoothErrorMessage(err))
|
||||
bleDeviceId.value = undefined
|
||||
await reportDisconnected()
|
||||
return false
|
||||
} finally {
|
||||
syncing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function startSyncLoop() {
|
||||
if (active) return
|
||||
active = true
|
||||
|
||||
unsubscribeConnection = subscribeBleConnectionStateChange((res) => {
|
||||
if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return
|
||||
if (!res.connected) {
|
||||
bleDeviceId.value = undefined
|
||||
void reportDisconnected()
|
||||
setSyncText('蓝牙已断开,正在尝试重连…')
|
||||
}
|
||||
})
|
||||
|
||||
void connectAndSync()
|
||||
|
||||
syncTimer = setInterval(() => {
|
||||
void connectAndSync()
|
||||
}, SYNC_INTERVAL_MS)
|
||||
}
|
||||
|
||||
async function stopSync() {
|
||||
active = false
|
||||
if (syncTimer) {
|
||||
clearInterval(syncTimer)
|
||||
syncTimer = undefined
|
||||
}
|
||||
unsubscribeConnection?.()
|
||||
unsubscribeConnection = undefined
|
||||
|
||||
const currentBleId = bleDeviceId.value
|
||||
bleDeviceId.value = undefined
|
||||
|
||||
if (currentBleId) {
|
||||
await closeBleConnection(currentBleId).catch(() => {})
|
||||
await reportDisconnected()
|
||||
}
|
||||
}
|
||||
|
||||
onUnload(() => {
|
||||
void stopSync()
|
||||
})
|
||||
|
||||
return {
|
||||
syncing,
|
||||
startSyncLoop,
|
||||
stopSync,
|
||||
connectAndSync,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user