Files
czzj-app/src/pages/device/device-presence.ts
2026-10-28 10:36:39 +08:00

174 lines
4.8 KiB
TypeScript

import { buildBleDeviceName } from '@/utils/ble-device-name'
import {
findDeviceInBleScan,
isBluetoothApiSupported,
scanBluetoothDevices,
} from '@/utils/bluetooth'
import { sameId } from '@/utils/device-id'
import {
markPresenceOfflineReportedToCloud,
recordPresenceHit,
recordPresenceMiss,
shouldMarkDeviceOffline,
shouldReportPresenceOfflineToCloud,
} from './device-presence-state'
import { updateDeviceRuntime } from './detail/device-detail.api'
import type { DeviceListItem } from './device.types'
let syncing = false
const PRESENCE_SCAN_MS = 8000
const PRESENCE_DEBUG = import.meta.env.DEV
|| import.meta.env.VITE_BLE_DEBUG === 'true'
function logPresence(message: string, payload?: unknown) {
if (!PRESENCE_DEBUG) return
if (payload !== undefined) {
console.log(`[Device Presence] ${message}`, payload)
return
}
console.log(`[Device Presence] ${message}`)
}
function wasDeviceOnlineInCloud(device: DeviceListItem): boolean {
return device.status === '1' && device.bluetoothConnected === '1'
}
function applyPresence(
device: DeviceListItem,
blePresent: boolean,
): DeviceListItem {
if (!device.deviceId) return device
if (blePresent) {
recordPresenceHit(device.deviceId)
return {
...device,
status: '1',
bluetoothConnected: '1',
isOnline: true,
}
}
recordPresenceMiss(device.deviceId)
if (!shouldMarkDeviceOffline(device.deviceId, device.isOnline)) {
return device
}
return {
...device,
status: '2',
bluetoothConnected: '0',
isOnline: false,
}
}
async function reportPresenceOnlineToCloud(device: DeviceListItem) {
if (!device.deviceId) return
if (device.status === '1' && device.bluetoothConnected === '1') return
try {
await updateDeviceRuntime({
deviceId: device.deviceId,
status: '1',
bluetoothConnected: '1',
})
} catch (err) {
logPresence('online updateRuntime failed', err)
}
}
async function reportPresenceOfflineToCloud(device: DeviceListItem) {
if (!device.deviceId) return
if (!shouldReportPresenceOfflineToCloud(device.deviceId)) return
try {
await updateDeviceRuntime({
deviceId: device.deviceId,
status: '2',
bluetoothConnected: '0',
signalLevel: '0',
})
markPresenceOfflineReportedToCloud(device.deviceId)
logPresence('reported offline to cloud', { deviceId: device.deviceId })
} catch (err) {
logPresence('offline updateRuntime failed', err)
}
}
function shouldSyncOfflineToCloud(before: DeviceListItem, after: DeviceListItem): boolean {
if (!after.deviceId) return false
if (after.status !== '2' || after.bluetoothConnected !== '0') return false
if (!after.isOnline && before.isOnline) return true
if (wasDeviceOnlineInCloud(before) && !wasDeviceOnlineInCloud(after)) return true
return false
}
/** 通过 BLE 扫描刷新设备在线状态(仅 MAC 精确匹配,不用缓存广播) */
export async function refreshDevicePresence(
devices: DeviceListItem[],
): Promise<DeviceListItem[]> {
if (!isBluetoothApiSupported()) return devices
const targets = devices.filter((item) => item.deviceId && item.mac)
if (!targets.length) {
logPresence('skip: no mac on devices')
return devices
}
if (syncing) return devices
syncing = true
try {
const scanned = await scanBluetoothDevices({ timeoutMs: PRESENCE_SCAN_MS })
logPresence('scan result', {
count: scanned.length,
names: scanned.map((item) => item.name || item.localName || item.deviceId),
})
const offlineReports: DeviceListItem[] = []
const nextDevices = devices.map((device) => {
if (!device.deviceId) return device
const isTarget = targets.some((item) => sameId(item.deviceId, device.deviceId))
if (!isTarget) return device
const found = device.mac
? findDeviceInBleScan({ mac: device.mac }, scanned, { strictName: true })
: null
const present = !!found
logPresence('device presence', {
name: device.name,
mac: device.mac,
present,
foundId: found?.deviceId,
bleName: device.mac ? buildBleDeviceName(device.mac) : '',
})
const next = applyPresence(device, present)
if (shouldSyncOfflineToCloud(device, next)) {
offlineReports.push(next)
}
return next
})
void Promise.allSettled(
targets.map(async (device) => {
const found = device.mac
? findDeviceInBleScan({ mac: device.mac }, scanned, { strictName: true })
: null
if (found) {
await reportPresenceOnlineToCloud(device)
}
}),
)
void Promise.allSettled(offlineReports.map((device) => reportPresenceOfflineToCloud(device)))
return nextDevices
} catch (err) {
logPresence('scan failed', err)
return devices
} finally {
syncing = false
}
}