蓝牙设备配网

更新时间:2026-01-15 07:29:06LLM 副本以 Markdown 格式查看下载 PDF

鸿蒙系统下,蓝牙设备目前仅支持两种蓝牙类型的配网方案:

蓝牙类型 说明 设备应用示例
蓝牙单点 蓝牙设备与手机一对一连接单点设备(蓝牙或低功耗蓝牙) 体脂秤、手环、温控器、电动牙刷、门锁等
双模设备 一些多协议设备也会使用到蓝牙技术,例如同时具备 Wi-Fi 能力和蓝牙能力的 双模设备 蓝牙 Mesh 网关、IPC 设备、新版多协议 Wi-Fi 设备等

功能描述

蓝牙模块支持 设备配网 功能,可实现设备扫描发现与配网操作。

申请蓝牙权限

需要申请蓝牙权限 ohos.permission.ACCESS_BLUETOOTH。关于配置和申请权限的具体操作,请参考 声明权限向用户申请授权

蓝牙类设备配网 API 使用示例

具体 API 说明,请参考 设备配网

扫描蓝牙设备

实现扫描结果监听器

  scanListener: TSmartScannerListener = {
    onDeviceFound: (scanResult: TSmartScannerResult): void => {
      // 实现相关逻辑
    }
  };

构造扫描实例

// 使用扫描监听器创建扫描实例
this.scanner = new TSmartScannerBuilder(this.scanListener);
// 设置扫描超时时间和扫描方式(蓝牙扫描模式)
this.scanner.setScanTimeout(120000).addScanMode(TSmartScanMode.SCAN_MODE_BLE);

开始扫描

this.scanner.startScan();

停止扫描

this.scanner.stopScan();

扫描结果

根据 实现扫描结果监听器TSmartScannerResult 返回的扫描结果,来决定进行蓝牙配网或者双模配网,具体参数说明如下:

名称 类型 是否必填 说明
uniqueId string 设备唯一标记
productId string 产品 ID
deviceType TSmartDeviceType 设备类型,具体请参考表格下方的说明
name string 设备名称,通过网络请求获取,请求失败时会默认为 New Device
icon string 设备图标的 URL,通过网络请求获取,请求失败时默认空字符串
scannedBleDevice Device 当设备类型是蓝牙或双模设备时有值

TSmartDeviceType

export enum TSmartDeviceType {
  BLE,              // 蓝牙设备
  WIFI_BLE,         // 双模设备
  WIRED             // 有线设备
}

配网

实现配网监听器中的方法

activatorListener: ITSmartActivatorListener = {
    onActiveSetpAndError: (step: TSmartActivatorStep, error?: Error, device?: TSmartDeviceModel) => {
      // 实现相关逻辑
    },

    onActiveSuccess: (deviceModel: TSmartDeviceModel) => {
      // 处理配网成功的逻辑,例如更新 UI,跳转到下一个页面
    },
};

创建配网实例

  • 如果是单点设备(scanResult.deviceType= TSmartDeviceType.BLE),蓝牙单点配网实例的创建方式:

    const activatorBuilder = TSmartActivator.buildBleActivatorBuilder(homeId, 120000,listener)
    this.activator = TSmartActivator.createActivator(activatorBuilder);
    // 添加待配网的设备
    this.activator.appendDevice(scanResult.scannedBleDevice)
    
  • 如果是双模设备(scanResult.deviceType = TSmartDeviceType.WIFI_BLE),双模配网实例的创建方式:

    const activatorBuilder = TSmartActivator.buildBleWifiActivatorBuilder(
                    homeId,
                    this.ssid,
                    this.password,
                    120000,
                    listener,
                  )
    this.activator = TSmartActivator.createActivator(activatorBuilder);
    // 添加待配网的设备
    this.activator.appendDevice(scanResult.scannedBleDevice)
    

调用开始配网接口

this.activator.startActive()

调用停止配网接口

this.activator.stopActive()