feat:蓝牙绑定和在线客服
This commit is contained in:
@@ -162,6 +162,34 @@ export function rssiToSignalLevel(rssi?: number): string {
|
||||
return '0'
|
||||
}
|
||||
|
||||
export function isBleAlreadyConnectedError(err: unknown): boolean {
|
||||
if (err instanceof BluetoothError) {
|
||||
if (err.errCode === 10010) return true
|
||||
const msg = err.message.toLowerCase()
|
||||
return msg.includes('already connect') || msg.includes('已连接')
|
||||
}
|
||||
|
||||
const fail = err as UniFail
|
||||
if (fail?.errCode === 10010) return true
|
||||
const msg = String(fail?.errMsg || '').toLowerCase()
|
||||
return msg.includes('already connect') || msg.includes('已连接')
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
/** 建立 BLE 连接;若设备已连接则视为成功 */
|
||||
export async function ensureBleConnection(bleDeviceId: string): Promise<void> {
|
||||
try {
|
||||
await createBleConnection(bleDeviceId)
|
||||
} catch (err) {
|
||||
if (!isBleAlreadyConnectedError(err)) throw err
|
||||
}
|
||||
// Android / 微信小程序连接后 GATT 表需短暂就绪
|
||||
await delay(400)
|
||||
}
|
||||
|
||||
export function createBleConnection(bleDeviceId: string): Promise<void> {
|
||||
if (typeof uni.createBLEConnection !== 'function') {
|
||||
return Promise.reject(new BluetoothError('当前环境不支持蓝牙连接'))
|
||||
@@ -202,14 +230,28 @@ export function subscribeBleConnectionStateChange(
|
||||
}
|
||||
}
|
||||
|
||||
/** 扫描并匹配指定 MAC 的 BLE 设备 */
|
||||
function deviceMatchesName(
|
||||
device: UniApp.BluetoothDeviceInfo,
|
||||
name: string,
|
||||
): boolean {
|
||||
const target = name.trim().toLowerCase()
|
||||
if (!target) return false
|
||||
const candidates = [device.name, device.localName]
|
||||
.filter(Boolean)
|
||||
.map((item) => String(item).trim().toLowerCase())
|
||||
return candidates.some((item) => item === target || item.includes(target) || target.includes(item))
|
||||
}
|
||||
|
||||
/** 扫描并匹配 MAC 或广播名的 BLE 设备(iOS 需依赖名称) */
|
||||
export async function scanForBleDeviceByMac(
|
||||
mac: string,
|
||||
options: { timeoutMs?: number } = {},
|
||||
options: { timeoutMs?: number; name?: string } = {},
|
||||
): Promise<UniApp.BluetoothDeviceInfo | null> {
|
||||
const timeoutMs = options.timeoutMs ?? 15000
|
||||
const normalizedMac = normalizeMacAddress(mac)
|
||||
if (!normalizedMac) return null
|
||||
const targetName = options.name?.trim()
|
||||
|
||||
if (!normalizedMac && !targetName) return null
|
||||
|
||||
await ensureBluetoothReady()
|
||||
|
||||
@@ -217,7 +259,11 @@ export async function scanForBleDeviceByMac(
|
||||
|
||||
const pickMatch = (devices: UniApp.BluetoothDeviceInfo[]) => {
|
||||
for (const device of devices) {
|
||||
if (deviceMatchesMac(device, normalizedMac)) {
|
||||
if (normalizedMac && deviceMatchesMac(device, normalizedMac)) {
|
||||
matched = device
|
||||
return true
|
||||
}
|
||||
if (targetName && deviceMatchesName(device, targetName)) {
|
||||
matched = device
|
||||
return true
|
||||
}
|
||||
@@ -253,6 +299,78 @@ export async function scanForBleDeviceByMac(
|
||||
return matched
|
||||
}
|
||||
|
||||
function deviceMatchesNameStrict(
|
||||
device: UniApp.BluetoothDeviceInfo,
|
||||
name: string,
|
||||
): boolean {
|
||||
const target = name.trim().toLowerCase()
|
||||
if (!target) return false
|
||||
const candidates = [device.name, device.localName]
|
||||
.filter(Boolean)
|
||||
.map((item) => String(item).trim().toLowerCase())
|
||||
return candidates.some((item) => item === target)
|
||||
}
|
||||
|
||||
/** 短时扫描附近全部 BLE 设备(默认仅收集本次扫描窗口内发现的设备,避免系统缓存误判在线) */
|
||||
export async function scanBluetoothDevices(
|
||||
options: { timeoutMs?: number; includeCached?: boolean } = {},
|
||||
): Promise<UniApp.BluetoothDeviceInfo[]> {
|
||||
const timeoutMs = options.timeoutMs ?? 5000
|
||||
const collected = new Map<string, UniApp.BluetoothDeviceInfo>()
|
||||
|
||||
const merge = (devices: UniApp.BluetoothDeviceInfo[]) => {
|
||||
for (const device of devices) {
|
||||
collected.set(device.deviceId, device)
|
||||
}
|
||||
}
|
||||
|
||||
await ensureBluetoothReady()
|
||||
await stopBluetoothDiscovery().catch(() => {})
|
||||
|
||||
if (options.includeCached) {
|
||||
merge(await getDiscoveredBluetoothDevices())
|
||||
}
|
||||
|
||||
const unsubscribe = subscribeBluetoothDevicesFound(merge)
|
||||
try {
|
||||
await startBluetoothDiscovery()
|
||||
await delay(timeoutMs)
|
||||
} finally {
|
||||
unsubscribe()
|
||||
await stopBluetoothDiscovery().catch(() => {})
|
||||
}
|
||||
|
||||
return [...collected.values()]
|
||||
}
|
||||
|
||||
/** 在扫描结果中匹配设备(有 MAC 时仅按 MAC 匹配) */
|
||||
export function findDeviceInBleScan(
|
||||
target: { mac?: string; name?: string },
|
||||
scanned: UniApp.BluetoothDeviceInfo[],
|
||||
options: { strictName?: boolean } = { strictName: true },
|
||||
): UniApp.BluetoothDeviceInfo | null {
|
||||
const normalizedMac = target.mac ? normalizeMacAddress(target.mac) : undefined
|
||||
const targetName = target.name?.trim()
|
||||
|
||||
if (normalizedMac) {
|
||||
for (const device of scanned) {
|
||||
if (deviceMatchesMac(device, normalizedMac)) return device
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
if (!targetName) return null
|
||||
|
||||
for (const device of scanned) {
|
||||
if (options.strictName) {
|
||||
if (deviceMatchesNameStrict(device, targetName)) return device
|
||||
} else if (deviceMatchesName(device, targetName)) {
|
||||
return device
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function getBluetoothErrorMessage(err: unknown): string {
|
||||
if (err instanceof BluetoothError) return err.message
|
||||
|
||||
@@ -275,6 +393,9 @@ export function getBluetoothErrorMessage(err: unknown): string {
|
||||
case 10007:
|
||||
return '当前特征值不支持此操作'
|
||||
case 10008:
|
||||
if (msg && /no descriptor/i.test(msg)) {
|
||||
return '蓝牙通知特征值不可用,请确认设备 Notify 已配置'
|
||||
}
|
||||
return '蓝牙操作失败,请重试'
|
||||
case 10009:
|
||||
return '本机不支持低功耗蓝牙'
|
||||
|
||||
Reference in New Issue
Block a user