fix:蓝牙bug解决
This commit is contained in:
51
src/utils/ble-device-id-cache.ts
Normal file
51
src/utils/ble-device-id-cache.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { compactMacAddress } from '@/utils/bluetooth'
|
||||
|
||||
const STORAGE_KEY = 'czzj_ble_device_id_by_mac'
|
||||
const memory = new Map<string, string>()
|
||||
|
||||
function macKey(mac: string): string {
|
||||
return compactMacAddress(mac)
|
||||
}
|
||||
|
||||
function readStorage(): Record<string, string> {
|
||||
try {
|
||||
const raw = uni.getStorageSync(STORAGE_KEY)
|
||||
if (raw && typeof raw === 'object') return raw as Record<string, string>
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
function writeStorage(map: Record<string, string>) {
|
||||
try {
|
||||
uni.setStorageSync(STORAGE_KEY, map)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
/** 记住 MAC → 系统 ble deviceId(尤其 iOS UUID),加速二次重连 */
|
||||
export function rememberBleDeviceId(mac: string, bleDeviceId: string) {
|
||||
const key = macKey(mac)
|
||||
const id = bleDeviceId.trim()
|
||||
if (!key || key.length !== 12 || !id) return
|
||||
memory.set(key, id)
|
||||
const stored = readStorage()
|
||||
if (stored[key] === id) return
|
||||
stored[key] = id
|
||||
writeStorage(stored)
|
||||
}
|
||||
|
||||
export function recallBleDeviceId(mac: string): string | undefined {
|
||||
const key = macKey(mac)
|
||||
if (!key) return undefined
|
||||
const fromMem = memory.get(key)
|
||||
if (fromMem) return fromMem
|
||||
const fromStore = readStorage()[key]
|
||||
if (fromStore) {
|
||||
memory.set(key, fromStore)
|
||||
return fromStore
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
Reference in New Issue
Block a user