feat:蓝牙绑定和在线客服

This commit is contained in:
李伊帆
2026-10-13 16:23:43 +08:00
parent d4b02745e1
commit e22ebd6bef
128 changed files with 10429 additions and 385 deletions

View File

@@ -1,9 +1,8 @@
import { onUnload } from '@dcloudio/uni-app'
import { ref } from 'vue'
import {
BluetoothError,
closeBleConnection,
createBleConnection,
ensureBleConnection,
ensureBluetoothReady,
getBluetoothErrorMessage,
getDiscoveredBluetoothDevices,
@@ -12,20 +11,24 @@ import {
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 } from './device-bluetooth-read'
import { readRuntimeFromBle, type BleRuntimePatch } 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
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) {
@@ -39,7 +42,7 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
context.onSyncTextChange(text)
}
async function reportDisconnected() {
async function reportBleDisconnected() {
const deviceId = context.getDeviceId()
if (!deviceId) return
context.onBluetoothConnectedChange(false)
@@ -54,6 +57,22 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
}
}
async function reportDeviceOffline() {
const deviceId = context.getDeviceId()
if (!deviceId) return
context.onBluetoothConnectedChange(false)
try {
await updateDeviceRuntime({
deviceId,
status: '2',
bluetoothConnected: '0',
signalLevel: '0',
})
} catch {
// 上报失败时保留本地状态
}
}
async function connectAndSync(): Promise<boolean> {
const deviceId = context.getDeviceId()
const mac = context.getMac()
@@ -72,18 +91,24 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (syncing.value) return false
syncing.value = true
let connected = false
let targetBleId = bleDeviceId.value
try {
setSyncText('正在连接蓝牙…')
await ensureBluetoothReady()
let targetBleId = bleDeviceId.value
let foundDevice: UniApp.BluetoothDeviceInfo | null = null
if (!targetBleId) {
foundDevice = await scanForBleDeviceByMac(mac, { timeoutMs: SCAN_TIMEOUT_MS })
const deviceName = context.getDeviceName?.()
foundDevice = await scanForBleDeviceByMac(mac ?? '', {
timeoutMs: SCAN_TIMEOUT_MS,
name: deviceName,
})
if (!foundDevice) {
setSyncText('未找到设备,请确认已开机并靠近手机')
await reportDisconnected()
await reportDeviceOffline()
return false
}
targetBleId = foundDevice.deviceId
@@ -93,22 +118,16 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
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
}
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)
@@ -121,28 +140,58 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
signalLevel,
})
setSyncText('刚刚更新 · 数据实时同步中')
if (!Object.keys(blePayload).length) {
setSyncText('蓝牙已连接,等待设备上报数据…')
} else {
setSyncText('刚刚更新 · 数据实时同步中')
}
await context.onSynced?.()
return true
} catch (err) {
setSyncText(getBluetoothErrorMessage(err))
bleDeviceId.value = undefined
await reportDisconnected()
if (!connected) {
bleDeviceId.value = undefined
clearZ2BleHandleCache(targetBleId)
await reportDeviceOffline()
}
return false
} finally {
syncing.value = false
}
}
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 {
return false
}
}
function startSyncLoop() {
if (active) return
if (!isBluetoothApiSupported()) {
setSyncText('云端数据已加载 · 实时同步请使用 App 或微信小程序')
return
}
active = true
unsubscribeConnection = subscribeBleConnectionStateChange((res) => {
if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return
if (!res.connected) {
bleDeviceId.value = undefined
void reportDisconnected()
void reportBleDisconnected()
setSyncText('蓝牙已断开,正在尝试重连…')
}
})
@@ -167,8 +216,9 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
bleDeviceId.value = undefined
if (currentBleId) {
clearZ2BleHandleCache(currentBleId)
await closeBleConnection(currentBleId).catch(() => {})
await reportDisconnected()
await reportBleDisconnected()
}
}
@@ -181,5 +231,6 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
startSyncLoop,
stopSync,
connectAndSync,
sendBleCommand,
}
}