fix:最新
This commit is contained in:
52
src/pages/device/device-presence-state.ts
Normal file
52
src/pages/device/device-presence-state.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
const missCounts = new Map<string, number>()
|
||||
const lastSeenAt = new Map<string, number>()
|
||||
|
||||
/** 连续扫描未命中次数达到该值后才判定离线 */
|
||||
const OFFLINE_AFTER_MISSES = 2
|
||||
/** 最近一次 BLE 命中后的宽限期(避免切换页面时瞬时扫不到) */
|
||||
const ONLINE_GRACE_MS = 45_000
|
||||
|
||||
function deviceKey(deviceId: string | number | undefined): string {
|
||||
return deviceId != null ? String(deviceId) : ''
|
||||
}
|
||||
|
||||
export function recordPresenceHit(deviceId: string | number) {
|
||||
const key = deviceKey(deviceId)
|
||||
if (!key) return
|
||||
missCounts.set(key, 0)
|
||||
lastSeenAt.set(key, Date.now())
|
||||
}
|
||||
|
||||
export function recordPresenceMiss(deviceId: string | number) {
|
||||
const key = deviceKey(deviceId)
|
||||
if (!key) return
|
||||
missCounts.set(key, (missCounts.get(key) ?? 0) + 1)
|
||||
}
|
||||
|
||||
/** 是否应将设备展示为离线(需连续未命中且超出宽限期) */
|
||||
export function shouldMarkDeviceOffline(
|
||||
deviceId: string | number,
|
||||
wasOnline = false,
|
||||
): boolean {
|
||||
if (!wasOnline) return true
|
||||
|
||||
const key = deviceKey(deviceId)
|
||||
const misses = missCounts.get(key) ?? 0
|
||||
if (misses < OFFLINE_AFTER_MISSES) return false
|
||||
|
||||
const lastSeen = lastSeenAt.get(key) ?? 0
|
||||
if (lastSeen && Date.now() - lastSeen < ONLINE_GRACE_MS) return false
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
export function resetPresenceState(deviceId?: string | number) {
|
||||
if (deviceId == null) {
|
||||
missCounts.clear()
|
||||
lastSeenAt.clear()
|
||||
return
|
||||
}
|
||||
const key = deviceKey(deviceId)
|
||||
missCounts.delete(key)
|
||||
lastSeenAt.delete(key)
|
||||
}
|
||||
Reference in New Issue
Block a user