Files
czzj-app/src/utils/ble-device-id-cache.ts
2026-10-29 10:09:43 +08:00

52 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
}