Files
czzj-app/src/utils/bluetooth.ts
2026-10-29 10:09:43 +08:00

624 lines
19 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.
export class BluetoothError extends Error {
errCode?: number
constructor(message: string, errCode?: number) {
super(message)
this.name = 'BluetoothError'
this.errCode = errCode
}
}
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)
}
export function isBluetoothApiSupported(): boolean {
return (
typeof uni.openBluetoothAdapter === 'function'
&& typeof uni.startBluetoothDevicesDiscovery === 'function'
&& typeof uni.onBluetoothDeviceFound === 'function'
)
}
function openAdapter(): Promise<void> {
return new Promise((resolve, reject) => {
uni.openBluetoothAdapter({
success: () => resolve(),
fail: (err) => reject(toBluetoothError(err, '蓝牙初始化失败')),
})
})
}
function getAdapterState(): Promise<UniApp.GetBluetoothAdapterStateSuccess> {
return new Promise((resolve, reject) => {
uni.getBluetoothAdapterState({
success: (res) => resolve(res),
fail: (err) => reject(toBluetoothError(err, '获取蓝牙状态失败')),
})
})
}
/** 初始化蓝牙适配器并确认可用 */
export async function ensureBluetoothReady(): Promise<void> {
if (!isBluetoothApiSupported()) {
throw new BluetoothError('当前环境不支持蓝牙,请使用 App 或微信小程序')
}
try {
await openAdapter()
} catch (err) {
const btErr = err as BluetoothError
if (btErr.errCode !== 10001) {
try {
const state = await getAdapterState()
if (state.available) return
} catch {
// fall through
}
}
throw err
}
const state = await getAdapterState()
if (!state.available) {
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)
}
}
export function startBluetoothDiscovery(): Promise<void> {
if (typeof uni.startBluetoothDevicesDiscovery !== 'function') {
return Promise.reject(new BluetoothError('当前环境不支持蓝牙扫描'))
}
return new Promise((resolve, reject) => {
uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
success: () => resolve(),
fail: (err) => reject(toBluetoothError(err, '开始扫描失败')),
})
})
}
export function stopBluetoothDiscovery(): Promise<void> {
if (typeof uni.stopBluetoothDevicesDiscovery !== 'function') {
return Promise.resolve()
}
return new Promise((resolve, reject) => {
uni.stopBluetoothDevicesDiscovery({
success: () => resolve(),
fail: (err) => reject(toBluetoothError(err, '停止扫描失败')),
})
})
}
export function getDiscoveredBluetoothDevices(): Promise<UniApp.BluetoothDeviceInfo[]> {
if (typeof uni.getBluetoothDevices !== 'function') {
return Promise.resolve([])
}
return new Promise((resolve, reject) => {
uni.getBluetoothDevices({
success: (res) => resolve(res.devices ?? []),
fail: (err) => reject(toBluetoothError(err, '获取已发现设备失败')),
})
})
}
export function subscribeBluetoothDevicesFound(
onFound: (devices: UniApp.BluetoothDeviceInfo[]) => void,
): () => void {
if (typeof uni.onBluetoothDeviceFound !== 'function') {
return () => {}
}
const handler = (res: UniApp.OnBluetoothDeviceFoundCallbackResult) => {
if (res.devices?.length) onFound(res.devices)
}
uni.onBluetoothDeviceFound(handler)
return () => {
if (typeof uni.offBluetoothDeviceFound !== 'function') return
uni.offBluetoothDeviceFound(handler)
}
}
const MAC_PATTERN = /^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/
/** 规范化为大写 MAC(AA:BB:CC:DD:EE:FF) */
export function normalizeMacAddress(value: string): string | undefined {
const trimmed = value.trim()
if (MAC_PATTERN.test(trimmed)) return trimmed.toUpperCase()
const compact = trimmed.replace(/[^0-9A-Fa-f]/g, '').toUpperCase()
if (compact.length !== 12) return undefined
return compact.replace(/(.{2})(?=.)/g, '$1:')
}
/** 去掉分隔符的大写 MAC */
export function compactMacAddress(value: string): string {
return value.replace(/[^0-9A-Fa-f]/g, '').toUpperCase()
}
export function deviceMatchesMac(
device: UniApp.BluetoothDeviceInfo,
mac: string,
): boolean {
const target = compactMacAddress(mac)
if (!target) return false
const deviceMac = normalizeMacAddress(device.deviceId)
if (deviceMac && compactMacAddress(deviceMac) === target) return true
const compactId = compactMacAddress(device.deviceId)
return compactId === target
}
/** RSSI → signalLevel:0离线 1弱 2一般 3强 */
export function rssiToSignalLevel(rssi?: number): string {
if (rssi == null) return '0'
if (rssi >= -55) return '3'
if (rssi >= -70) return '2'
if (rssi >= -85) return '1'
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))
}
/** 指定 deviceId 是否已在系统已连接列表中 */
export async function isBleDeviceConnected(bleDeviceId: string): Promise<boolean> {
if (!bleDeviceId || typeof uni.getConnectedBluetoothDevices !== 'function') return false
try {
const res = await new Promise<UniApp.GetConnectedBluetoothDevicesSuccess>((resolve, reject) => {
uni.getConnectedBluetoothDevices({
success: resolve,
fail: reject,
})
})
return (res.devices ?? []).some((item) => item.deviceId === bleDeviceId)
} catch {
return false
}
}
/**
* 建立 BLE 连接;已连接则直接返回,避免重复 createBLEConnection
*(部分机型对已连接设备再 create 会闪断,导致连上又断开的循环)
*/
export async function ensureBleConnection(
bleDeviceId: string,
options: { settleMs?: number } = {},
): Promise<void> {
if (await isBleDeviceConnected(bleDeviceId)) return
try {
await createBleConnection(bleDeviceId)
} catch (err) {
if (!isBleAlreadyConnectedError(err)) throw err
return
}
// Android / 微信小程序连接后 GATT 表需短暂就绪
const settleMs = options.settleMs ?? 280
if (settleMs > 0) await delay(settleMs)
}
export function createBleConnection(bleDeviceId: string): Promise<void> {
if (typeof uni.createBLEConnection !== 'function') {
return Promise.reject(new BluetoothError('当前环境不支持蓝牙连接'))
}
return new Promise((resolve, reject) => {
uni.createBLEConnection({
deviceId: bleDeviceId,
timeout: 10000,
success: () => resolve(),
fail: (err) => reject(toBluetoothError(err, '连接设备失败')),
})
})
}
export function closeBleConnection(bleDeviceId: string): Promise<void> {
if (typeof uni.closeBLEConnection !== 'function') {
return Promise.resolve()
}
return new Promise((resolve, reject) => {
uni.closeBLEConnection({
deviceId: bleDeviceId,
success: () => resolve(),
fail: (err) => reject(toBluetoothError(err, '断开连接失败')),
})
})
}
/** 断开当前已连接的全部 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 / 广播名 / 已知 deviceId 查找 */
export async function getConnectedBleDeviceByMac(
mac: string,
options: { name?: string; preferredBleId?: string } = {},
): Promise<UniApp.BluetoothDeviceInfo | null> {
if (typeof uni.getConnectedBluetoothDevices !== 'function') return null
const normalizedMac = normalizeMacAddress(mac)
const targetName = options.name?.trim()
const preferredBleId = options.preferredBleId?.trim()
if (!normalizedMac && !targetName && !preferredBleId) 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 (preferredBleId && device.deviceId === preferredBleId) return device
if (normalizedMac && deviceMatchesMac(device, normalizedMac)) return device
// iOS deviceId 非 MAC,需靠标准广播名识别
if (targetName && deviceMatchesName(device, targetName)) return device
}
} catch {
// ignore
}
return null
}
export function subscribeBleConnectionStateChange(
onChange: (res: { deviceId: string; connected: boolean }) => void,
): () => void {
if (typeof uni.onBLEConnectionStateChange !== 'function') {
return () => {}
}
uni.onBLEConnectionStateChange(onChange)
return () => {
if (typeof uni.offBLEConnectionStateChange !== 'function') return
uni.offBLEConnectionStateChange(onChange)
}
}
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; 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
await ensureBluetoothReady()
let matched: UniApp.BluetoothDeviceInfo | null = null
const pickMatch = (devices: UniApp.BluetoothDeviceInfo[]) => {
for (const device of devices) {
if (normalizedMac && deviceMatchesMac(device, normalizedMac)) {
matched = device
return true
}
// 有 MAC 时也按广播名匹配(iOS deviceId 是 UUID)
if (targetName && deviceMatchesNameStrict(device, targetName)) {
matched = device
return true
}
if (targetName && deviceMatchesName(device, targetName)) {
matched = device
return true
}
}
return false
}
if (!skipCached) {
const existing = await getDiscoveredBluetoothDevices()
if (pickMatch(existing)) {
return matched
}
}
const unsubscribe = subscribeBluetoothDevicesFound((devices) => {
pickMatch(devices)
})
try {
await startBluetoothDiscovery()
} catch (err) {
unsubscribe()
throw err
}
const startedAt = Date.now()
while (!matched && Date.now() - startedAt < timeoutMs) {
await new Promise((resolve) => setTimeout(resolve, 300))
const cached = await getDiscoveredBluetoothDevices()
if (pickMatch(cached)) break
}
unsubscribe()
await stopBluetoothDiscovery().catch(() => {})
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;iOS 无 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
}
}
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
}
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) {
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:
return '请先打开手机蓝牙后再试'
case 10002:
return '没有找到指定设备'
case 10003:
return '连接失败,请靠近设备后重试'
case 10004:
return '没有找到指定服务'
case 10005:
return '没有找到指定特征值'
case 10006:
return '当前连接已断开'
case 10007:
return '当前特征值不支持此操作'
case 10008:
if (msg && /no descriptor/i.test(msg)) {
return '蓝牙通知特征值不可用,请确认设备 Notify 已配置'
}
return '蓝牙操作失败,请重试'
case 10009:
return '本机不支持低功耗蓝牙'
case 10010:
return '设备已连接'
case 10011:
return '配对设备需要配对码'
case 10012:
return '连接超时,请重试'
case 10013:
return '设备标识无效'
default:
return mapBluetoothErrMsg(msg) || '蓝牙不可用,请检查权限与系统设置'
}
}