feat:蓝牙绑定和在线客服

This commit is contained in:
李伊帆
2026-10-13 16:23:43 +08:00
parent d4b02745e1
commit e22ebd6bef
128 changed files with 10429 additions and 385 deletions

View File

@@ -0,0 +1,111 @@
import {
findDeviceInBleScan,
isBluetoothApiSupported,
rssiToSignalLevel,
scanBluetoothDevices,
} from '@/utils/bluetooth'
import { sameId } from '@/utils/device-id'
import { updateDeviceRuntime } from './detail/device-detail.api'
import type { DeviceListItem } from './device.types'
let syncing = false
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 applyPresence(
device: DeviceListItem,
present: boolean,
): DeviceListItem {
const nextStatus = present ? '1' : '2'
const nextBluetooth = present ? '1' : '0'
return {
...device,
status: nextStatus,
bluetoothConnected: nextBluetooth,
isOnline: present,
}
}
/** 通过 BLE 扫描刷新设备在线状态(status: 1在线 / 2离线) */
export async function refreshDevicePresence(
devices: DeviceListItem[],
): Promise<DeviceListItem[]> {
if (!isBluetoothApiSupported()) return devices
const targets = devices.filter((item) => item.deviceId && (item.mac || item.name))
if (!targets.length) {
logPresence('skip: no mac/name on devices')
return devices
}
if (syncing) return devices
syncing = true
try {
const scanned = await scanBluetoothDevices({ timeoutMs: 5000 })
logPresence('scan result', {
count: scanned.length,
names: scanned.map((item) => item.name || item.localName || item.deviceId),
})
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 = findDeviceInBleScan(
{ mac: device.mac, name: device.name },
scanned,
{ strictName: true },
)
const present = !!found
logPresence('device presence', {
name: device.name,
mac: device.mac,
present,
foundId: found?.deviceId,
})
return applyPresence(device, present)
})
void Promise.allSettled(
nextDevices
.filter((device) => device.deviceId && targets.some((item) => sameId(item.deviceId, device.deviceId)))
.map(async (device) => {
const found = findDeviceInBleScan(
{ mac: device.mac, name: device.name },
scanned,
{ strictName: true },
)
const present = !!found
try {
await updateDeviceRuntime({
deviceId: device.deviceId!,
status: present ? '1' : '2',
bluetoothConnected: present ? '1' : '0',
signalLevel: present ? rssiToSignalLevel(found?.RSSI) : '0',
})
} catch (err) {
logPresence('updateRuntime failed', err)
}
}),
)
return nextDevices
} catch (err) {
logPresence('scan failed', err)
return devices
} finally {
syncing = false
}
}