Files
czzj-app/src/pages/device/device-presence-state.ts
2026-10-29 10:09:43 +08:00

68 lines
2.0 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.
const missCounts = new Map<string, number>()
const lastSeenAt = new Map<string, number>()
/** 已向云端上报离线的设备,避免轮询重复写库 */
const cloudOfflineReported = new Set<string>()
/**
* 扫描未命中次数达到该值后判定离线。
* 关机后广播立刻消失,1 次完整扫描未命中即可标离线(不再做长宽限)。
*/
const OFFLINE_AFTER_MISSES = 1
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())
cloudOfflineReported.delete(key)
}
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 {
const key = deviceKey(deviceId)
const misses = missCounts.get(key) ?? 0
return misses >= OFFLINE_AFTER_MISSES
}
export function resetPresenceState(deviceId?: string | number) {
if (deviceId == null) {
missCounts.clear()
lastSeenAt.clear()
cloudOfflineReported.clear()
return
}
const key = deviceKey(deviceId)
missCounts.delete(key)
lastSeenAt.delete(key)
cloudOfflineReported.delete(key)
}
export function shouldReportPresenceOfflineToCloud(deviceId: string | number): boolean {
const key = deviceKey(deviceId)
if (!key) return false
return !cloudOfflineReported.has(key)
}
export function markPresenceOfflineReportedToCloud(deviceId: string | number) {
const key = deviceKey(deviceId)
if (!key) return
cloudOfflineReported.add(key)
}
export function getLastPresenceSeenAt(deviceId: string | number): number {
return lastSeenAt.get(deviceKey(deviceId)) ?? 0
}