import { NativeModules } from 'react-native'; import { delay } from './delay'; import type { IScanDeviceRes } from './interface/iDevice'; const { BluetoothManager: OC } = NativeModules; /** * 蓝牙设备管理 */ export class BluetoothManager { public static async _isBluetoothEnabled() { return (await OC.isBluetoothEnabled()) === 'true'; } /** * 检查蓝牙服务是否启用 */ public static async isBluetoothEnabled() { if (!(await this._isBluetoothEnabled())) { await delay(500); return await this._isBluetoothEnabled(); } return true; } /** * 启用蓝牙服务。 只有 android 有用, ios 直接返回 null */ public static async enableBluetooth() { const r = await OC.enableBluetooth(); if (r && r.length > 0) { try { return r.map((n: any) => JSON.parse(n)); } catch { return []; } } } /** * 关闭蓝牙服务。 只有 android 有用, ios 不可用 */ public static async disableBluetooth() { return await OC.disableBluetooth(); } /** * 扫描蓝牙设备。 */ public static async scanDevices() { const { found, paired } = await OC.scanDevices(); return { found: JSON.parse(found) || [], paired: JSON.parse(paired) || [], } as IScanDeviceRes; } /** * 连接蓝牙设备 * @param address 蓝牙设备地址 */ public static async connect(address: string) { return await OC.connect(address); } /** * 断开蓝牙设备 * @param address 蓝牙设备地址 */ public static async disconnect(address: string) { return await OC.disconnect(address); } }