fix:最新
This commit is contained in:
@@ -10,6 +10,8 @@ export class BluetoothError extends Error {
|
||||
|
||||
type UniFail = UniApp.GeneralCallbackResult
|
||||
|
||||
export const BLUETOOTH_DISABLED_MESSAGE = '请先打开手机蓝牙后再试'
|
||||
|
||||
function toBluetoothError(err: UniFail, fallback: string): BluetoothError {
|
||||
const msg = err.errMsg || fallback
|
||||
return new BluetoothError(getBluetoothErrorMessage({ errCode: err.errCode, errMsg: msg }), err.errCode)
|
||||
@@ -64,7 +66,70 @@ export async function ensureBluetoothReady(): Promise<void> {
|
||||
|
||||
const state = await getAdapterState()
|
||||
if (!state.available) {
|
||||
throw new BluetoothError('本机不支持蓝牙', 10009)
|
||||
throw new BluetoothError(BLUETOOTH_DISABLED_MESSAGE, 10001)
|
||||
}
|
||||
}
|
||||
|
||||
export function isBluetoothDisabledError(err: unknown): boolean {
|
||||
if (err instanceof BluetoothError && err.errCode === 10001) return true
|
||||
const code = (err as UniFail)?.errCode
|
||||
if (code === 10001) return true
|
||||
const message = err instanceof BluetoothError
|
||||
? err.message
|
||||
: String((err as UniFail)?.errMsg || (err instanceof Error ? err.message : ''))
|
||||
const lower = message.toLowerCase()
|
||||
return (
|
||||
message === BLUETOOTH_DISABLED_MESSAGE
|
||||
|| /请先打开手机蓝牙/.test(message)
|
||||
|| /bluetooth adapter not available|adapter not available|not init|not open|bluetooth.*off/i.test(lower)
|
||||
)
|
||||
}
|
||||
|
||||
export function openSystemBluetoothSetting(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof uni.openSystemBluetoothSetting !== 'function') {
|
||||
reject(new BluetoothError('当前环境无法打开系统蓝牙设置'))
|
||||
return
|
||||
}
|
||||
uni.openSystemBluetoothSetting({
|
||||
success: () => resolve(),
|
||||
fail: (err) => reject(toBluetoothError(err, '无法打开蓝牙设置')),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export function promptEnableBluetooth(content?: string) {
|
||||
uni.showModal({
|
||||
title: '请开启蓝牙',
|
||||
content: content || '添加设备需要使用手机蓝牙,请先在系统设置中打开蓝牙',
|
||||
confirmText: '去开启',
|
||||
cancelText: '取消',
|
||||
success: (res) => {
|
||||
if (!res.confirm) return
|
||||
void openSystemBluetoothSetting().catch(() => {
|
||||
uni.showToast({ title: BLUETOOTH_DISABLED_MESSAGE, icon: 'none' })
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function isBluetoothPermissionError(err: unknown): boolean {
|
||||
const message = getBluetoothErrorMessage(err)
|
||||
return /定位权限|蓝牙相关权限|permission/i.test(message)
|
||||
}
|
||||
|
||||
/** 确认蓝牙已开启且可扫描(添加设备流程入口使用) */
|
||||
export async function assertBluetoothEnabledForScan(): Promise<void> {
|
||||
try {
|
||||
await ensureBluetoothReady()
|
||||
await startBluetoothDiscovery()
|
||||
await stopBluetoothDiscovery()
|
||||
} catch (err) {
|
||||
if (isBluetoothDisabledError(err) || isBluetoothPermissionError(err)) {
|
||||
throw err
|
||||
}
|
||||
// 部分机型蓝牙未开时 openAdapter 仍成功,扫描失败会落到通用错误
|
||||
throw new BluetoothError(BLUETOOTH_DISABLED_MESSAGE, 10001)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,6 +282,53 @@ export function closeBleConnection(bleDeviceId: string): Promise<void> {
|
||||
})
|
||||
}
|
||||
|
||||
/** 断开当前已连接的全部 BLE 设备,避免重连时 operate timeout */
|
||||
export async function closeAllBleConnections(): Promise<void> {
|
||||
if (typeof uni.getConnectedBluetoothDevices !== 'function') return
|
||||
try {
|
||||
const res = await new Promise<UniApp.GetConnectedBluetoothDevicesSuccess>((resolve, reject) => {
|
||||
uni.getConnectedBluetoothDevices({
|
||||
success: resolve,
|
||||
fail: reject,
|
||||
})
|
||||
})
|
||||
for (const device of res.devices ?? []) {
|
||||
await closeBleConnection(device.deviceId).catch(() => {})
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export async function releaseBleDevice(bleDeviceId?: string): Promise<void> {
|
||||
if (!bleDeviceId) return
|
||||
await closeBleConnection(bleDeviceId).catch(() => {})
|
||||
}
|
||||
|
||||
/** 从系统已连接 BLE 列表中按 MAC 查找(GATT 已连接时扫描往往找不到设备) */
|
||||
export async function getConnectedBleDeviceByMac(
|
||||
mac: string,
|
||||
): Promise<UniApp.BluetoothDeviceInfo | null> {
|
||||
if (typeof uni.getConnectedBluetoothDevices !== 'function') return null
|
||||
const normalizedMac = normalizeMacAddress(mac)
|
||||
if (!normalizedMac) return null
|
||||
|
||||
try {
|
||||
const res = await new Promise<UniApp.GetConnectedBluetoothDevicesSuccess>((resolve, reject) => {
|
||||
uni.getConnectedBluetoothDevices({
|
||||
success: resolve,
|
||||
fail: reject,
|
||||
})
|
||||
})
|
||||
for (const device of res.devices ?? []) {
|
||||
if (deviceMatchesMac(device, normalizedMac)) return device
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function subscribeBleConnectionStateChange(
|
||||
onChange: (res: { deviceId: string; connected: boolean }) => void,
|
||||
): () => void {
|
||||
@@ -245,11 +357,12 @@ function deviceMatchesName(
|
||||
/** 扫描并匹配 MAC 或广播名的 BLE 设备(iOS 需依赖名称) */
|
||||
export async function scanForBleDeviceByMac(
|
||||
mac: string,
|
||||
options: { timeoutMs?: number; name?: string } = {},
|
||||
options: { timeoutMs?: number; name?: string; skipCached?: boolean } = {},
|
||||
): Promise<UniApp.BluetoothDeviceInfo | null> {
|
||||
const timeoutMs = options.timeoutMs ?? 15000
|
||||
const normalizedMac = normalizeMacAddress(mac)
|
||||
const targetName = options.name?.trim()
|
||||
const skipCached = options.skipCached ?? false
|
||||
|
||||
if (!normalizedMac && !targetName) return null
|
||||
|
||||
@@ -263,7 +376,7 @@ export async function scanForBleDeviceByMac(
|
||||
matched = device
|
||||
return true
|
||||
}
|
||||
if (targetName && deviceMatchesName(device, targetName)) {
|
||||
if (!normalizedMac && targetName && deviceMatchesName(device, targetName)) {
|
||||
matched = device
|
||||
return true
|
||||
}
|
||||
@@ -271,9 +384,11 @@ export async function scanForBleDeviceByMac(
|
||||
return false
|
||||
}
|
||||
|
||||
const existing = await getDiscoveredBluetoothDevices()
|
||||
if (pickMatch(existing)) {
|
||||
return matched
|
||||
if (!skipCached) {
|
||||
const existing = await getDiscoveredBluetoothDevices()
|
||||
if (pickMatch(existing)) {
|
||||
return matched
|
||||
}
|
||||
}
|
||||
|
||||
const unsubscribe = subscribeBluetoothDevicesFound((devices) => {
|
||||
@@ -371,11 +486,70 @@ export function findDeviceInBleScan(
|
||||
return null
|
||||
}
|
||||
|
||||
function mapBluetoothErrMsg(msg?: string): string | null {
|
||||
if (!msg) return null
|
||||
const lower = msg.toLowerCase()
|
||||
|
||||
if (
|
||||
lower.includes('operate time out')
|
||||
|| lower.includes('operation timeout')
|
||||
|| lower.includes('timed out')
|
||||
|| lower.includes('time out')
|
||||
) {
|
||||
return '蓝牙连接超时,请确认设备已开机并靠近手机后重试'
|
||||
}
|
||||
|
||||
if (lower.includes('createbleconnection')) {
|
||||
return '蓝牙连接失败,请确认设备已开机并靠近手机后重试'
|
||||
}
|
||||
|
||||
if (lower.includes('already connect') || lower.includes('already connected')) {
|
||||
return '设备已连接'
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes('bluetooth adapter not available')
|
||||
|| lower.includes('adapter not available')
|
||||
|| lower.includes('not init')
|
||||
|| lower.includes('not open')
|
||||
) {
|
||||
return '请先打开手机蓝牙后再试'
|
||||
}
|
||||
|
||||
if (lower.includes('no device') || lower.includes('device not found')) {
|
||||
return '没有找到指定设备,请确认已开机并靠近手机'
|
||||
}
|
||||
|
||||
if (lower.includes('connection fail') || lower.includes('connect fail')) {
|
||||
return '蓝牙连接失败,请靠近设备后重试'
|
||||
}
|
||||
|
||||
if (lower.includes('location') && lower.includes('permission')) {
|
||||
return '请开启定位权限后再使用蓝牙功能'
|
||||
}
|
||||
|
||||
if (lower.includes('permission')) {
|
||||
return '请授予蓝牙相关权限后重试'
|
||||
}
|
||||
|
||||
if (/:fail\b/i.test(msg) && /[a-z]/i.test(msg)) {
|
||||
return '蓝牙操作失败,请重试'
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function getBluetoothErrorMessage(err: unknown): string {
|
||||
if (err instanceof BluetoothError) return err.message
|
||||
if (err instanceof BluetoothError) {
|
||||
const mapped = mapBluetoothErrMsg(err.message)
|
||||
if (mapped) return mapped
|
||||
return err.message
|
||||
}
|
||||
|
||||
const code = (err as UniFail)?.errCode
|
||||
const msg = (err as UniFail)?.errMsg
|
||||
const mapped = mapBluetoothErrMsg(msg)
|
||||
if (mapped) return mapped
|
||||
|
||||
switch (code) {
|
||||
case 10001:
|
||||
@@ -408,6 +582,6 @@ export function getBluetoothErrorMessage(err: unknown): string {
|
||||
case 10013:
|
||||
return '设备标识无效'
|
||||
default:
|
||||
return msg || '蓝牙不可用,请检查权限与系统设置'
|
||||
return mapBluetoothErrMsg(msg) || '蓝牙不可用,请检查权限与系统设置'
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user