fix:最新

This commit is contained in:
李伊帆
2026-10-23 10:26:54 +08:00
parent e4276b0853
commit 28531c8120
104 changed files with 3248 additions and 722 deletions

View File

@@ -1,4 +1,4 @@
import { onUnload } from '@dcloudio/uni-app'
import { onShow, onUnload } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error'
import {
@@ -6,6 +6,7 @@ import {
ensureBleConnection,
ensureBluetoothReady,
getBluetoothErrorMessage,
getConnectedBleDeviceByMac,
getDiscoveredBluetoothDevices,
isBluetoothApiSupported,
rssiToSignalLevel,
@@ -38,27 +39,14 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
let syncTimer: ReturnType<typeof setInterval> | undefined
let unsubscribeConnection: (() => void) | undefined
let active = false
let tearingDown = false
let hadSuccessfulSync = false
function setSyncText(text: string) {
context.onSyncTextChange(text)
}
async function reportBleDisconnected() {
const deviceId = context.getDeviceId()
if (!deviceId) return
context.onBluetoothConnectedChange(false)
try {
await updateDeviceRuntime({
deviceId,
bluetoothConnected: '0',
signalLevel: '0',
})
} catch {
// 上报失败时保留本地状态
}
}
async function reportDeviceOffline() {
const deviceId = context.getDeviceId()
if (!deviceId) return
context.onBluetoothConnectedChange(false)
@@ -74,6 +62,69 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
}
}
function reportBleLinkLostLocal() {
context.onBluetoothConnectedChange(false)
}
async function resolveBleTarget(
mac: string,
preferredBleId?: string,
): Promise<UniApp.BluetoothDeviceInfo | null> {
const connected = await getConnectedBleDeviceByMac(mac)
if (connected) return connected
if (preferredBleId) {
const discovered = await getDiscoveredBluetoothDevices()
const cached = discovered.find((item) => item.deviceId === preferredBleId)
if (cached) return cached
}
const deviceName = context.getDeviceName?.()
return scanForBleDeviceByMac(mac, {
timeoutMs: SCAN_TIMEOUT_MS,
name: deviceName,
skipCached: !preferredBleId && !hadSuccessfulSync,
})
}
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)
context.onBleRuntimeRead?.(blePayload)
const runtimePatch = context.getRuntimePatch()
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
try {
await updateDeviceRuntime({
deviceId,
...runtimePatch,
...blePayload,
status: '1',
bluetoothConnected: '1',
signalLevel,
})
setSyncText('刚刚更新 · 数据实时同步中')
await context.onSynced?.()
} catch (apiErr) {
setSyncText(`蓝牙已连接 · 云端同步失败:${getErrorMessage(apiErr, '请检查网络')}`)
}
return true
}
async function connectAndSync(): Promise<boolean> {
const deviceId = context.getDeviceId()
const mac = context.getMac()
@@ -92,78 +143,48 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (syncing.value) return false
syncing.value = true
let connected = false
let targetBleId = bleDeviceId.value
let foundDevice: UniApp.BluetoothDeviceInfo | null = null
try {
setSyncText('正在连接蓝牙…')
await ensureBluetoothReady()
let foundDevice: UniApp.BluetoothDeviceInfo | null = null
if (!targetBleId) {
const deviceName = context.getDeviceName?.()
foundDevice = await scanForBleDeviceByMac(mac ?? '', {
timeoutMs: SCAN_TIMEOUT_MS,
name: deviceName,
})
if (!foundDevice) {
setSyncText('未找到设备,请确认已开机并靠近手机')
await reportDeviceOffline()
return false
foundDevice = await resolveBleTarget(mac, targetBleId)
if (!foundDevice) {
setSyncText('未找到设备,请确认已开机并靠近手机')
if (!tearingDown) {
reportBleLinkLostLocal()
}
targetBleId = foundDevice.deviceId
bleDeviceId.value = targetBleId
} else {
const discovered = await getDiscoveredBluetoothDevices()
foundDevice = discovered.find((item) => item.deviceId === targetBleId) ?? null
return false
}
targetBleId = foundDevice.deviceId
bleDeviceId.value = targetBleId
if (!hadSuccessfulSync) {
setSyncText('正在连接蓝牙…')
}
await ensureBleConnection(targetBleId)
connected = true
context.onBluetoothConnectedChange(true)
setSyncText('正在同步设备数据…')
const blePayload = await readRuntimeFromBle(targetBleId)
if (Object.keys(blePayload).length) {
context.onBleRuntimeRead?.(blePayload)
}
const runtimePatch = context.getRuntimePatch()
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
const hasBleData = Object.keys(blePayload).length > 0
try {
await updateDeviceRuntime({
deviceId,
...runtimePatch,
...blePayload,
status: '1',
bluetoothConnected: '1',
signalLevel,
})
if (!hasBleData) {
setSyncText('蓝牙已连接,等待设备上报数据…')
} else {
setSyncText('刚刚更新 · 数据实时同步中')
}
await context.onSynced?.()
} catch (apiErr) {
if (hasBleData) {
setSyncText('蓝牙已连接 · 本地数据已更新,云端同步失败')
} else {
setSyncText(
`蓝牙已连接 · 云端同步失败:${getErrorMessage(apiErr, '请检查网络')}`,
)
}
}
return true
return await syncBleData(targetBleId, foundDevice)
} catch (err) {
const stillConnected = await getConnectedBleDeviceByMac(mac)
if (stillConnected) {
bleDeviceId.value = stillConnected.deviceId
context.onBluetoothConnectedChange(true)
try {
return await syncBleData(stillConnected.deviceId, stillConnected)
} catch (retryErr) {
setSyncText(getBluetoothErrorMessage(retryErr))
return true
}
}
setSyncText(getBluetoothErrorMessage(err))
if (!connected) {
if (!tearingDown) {
bleDeviceId.value = undefined
clearZ2BleHandleCache(targetBleId)
await reportDeviceOffline()
reportBleLinkLostLocal()
}
return false
} finally {
@@ -199,11 +220,24 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
active = true
unsubscribeConnection = subscribeBleConnectionStateChange((res) => {
if (tearingDown) return
if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return
if (!res.connected) {
bleDeviceId.value = undefined
void reportBleDisconnected()
setSyncText('蓝牙已断开,正在尝试重连…')
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()
})()
}
})
@@ -215,7 +249,9 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
}
async function stopSync() {
tearingDown = true
active = false
hadSuccessfulSync = false
if (syncTimer) {
clearInterval(syncTimer)
syncTimer = undefined
@@ -229,10 +265,15 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (currentBleId) {
clearZ2BleHandleCache(currentBleId)
await closeBleConnection(currentBleId).catch(() => {})
await reportBleDisconnected()
}
tearingDown = false
}
onShow(() => {
if (!active || tearingDown) return
void connectAndSync()
})
onUnload(() => {
void stopSync()
})