52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
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
|
||
}
|