Bluetooth ============= 1. **简介** -------------- AIOT-3568A设有蓝牙模块,可以直接搜索,也可接天线用于信号增幅。 蓝牙模块以及如何连接天线如下: |image1| 2. **HDC相关指令** -------------- 3. **标准API使用方法** -------------- .. note:: 本模块提供了对蓝牙操作和管理的方,首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + **蓝牙标准接口** **@ohos.bluetooth.ble (蓝牙ble模块)** + **API使用说明** 使用蓝牙相关API开发时候,需要先了解熟悉第一个open Harmony工程的创建,相关文档 :doc:`Hello World应用以及部署<../../Quick-Start/OpenHarmony/04-应用以及部署>` 在使用一个API时,需要注意以下几点: + API权限说明 + API的参数与返回值 + API调用错误的时候,参考API错误码和通用错误码 + API示例的正确使用 如下图所示,即为标准API文档 |btIndex| + **官方标准开发文档** `蓝牙官方标准API开发文档 `_ 4. **社区Demo** -------------- + **简介** 为了帮助开发者更快速的使用板子开发和学习,我们在gitee上提供了一个蓝牙相关的使用示例,每一个项目都是独立的DevEco Studio工程,开发者可以将工程导入到DevEco Studio中即可,通过浏览代码、编译工程、安装和运行应用示例来了解应用示例中涉及API的使用方法。 `gitee蓝牙示例 `_ .. tip:: 在导入社区Demo工程的时候,需要开发者需要注意本地的开发环境是否与项目的一致,即本地SDK是否与项目SDK一致。 + **导入模块** 在使用蓝牙标准API的时候,最重要的一步是导入蓝牙的模块,才能使用蓝牙相应的API接口。通常模块导入是在文件头导入 导入模块如下: **import blueToothManager from '@ohos.bluetooth.ble'** + **API 介绍** 社区Demo的实现引用以下API,实现如何打开蓝牙、蓝牙扫描,以及蓝牙的连接的基本实现。 .. note:: 以下介绍均以为简单介绍API的系统能力以及对应函数 请结合 `gitee蓝牙示例 `_ 和 `蓝牙官方标准API开发文档 `_ 去熟悉开发 + **ble.createGattServer(创建GattServer实例)** + createGattServer(): GattServer + **ble.createGattClientDevice(创建一个可使用的GattClientDevice实例)** + createGattClientDevice(deviceId: string): GattClientDevice + **ble.getConnectedBLEDevices(获取和当前设备连接的BLE设备)** + getConnectedBLEDevices(): Array + 需要权限:ohos.permission.ACCESS_BLUETOOTH + **ble.startBLEScan(发起BLE扫描流程)** + startBLEScan(filters: Array, options?: ScanOptions): void + 需要权限:ohos.permission.ACCESS_BLUETOOTH + **ble.stopBLEScan(停止BLE扫描流程)** + stopBLEScan(): void + 需要权限:ohos.permission.ACCESS_BLUETOOTH + **ble.startAdvertising(开始发送BLE广播)** + startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void + 需要权限:ohos.permission.ACCESS_BLUETOOTH + **ble.stopAdvertising(开始发送BLE广播)** + stopAdvertising(): void + 需要权限:ohos.permission.ACCESS_BLUETOOTH + **Demo主要实现源码** + BT.ets .. code-block:: TypeScript :linenos: import ble from "@ohos.bluetooth.ble" import { BusinessError } from '@ohos.base' // import access from '@ohos.bluetooth.access'; const minRssi = -100 @Entry @Component struct Index { @State message: string = 'Hello BLE' @State availableDevices: Array = []; addData(data:ble.ScanResult):void { let bFind = false this.availableDevices.forEach(element => { if (!bFind && element.deviceId == data.deviceId) { console.info('BLE scan update ' + data.deviceId + ' rssi:' + element.rssi +' ==> '+ data.rssi) element.rssi = data.rssi bFind = true } }) if (!bFind) { console.info('BLE scan add ' + data.deviceId + ' count:' + this.availableDevices.length) this.availableDevices.push(data) this.message='BLE count:' + this.availableDevices.length } } dataToString(data:ArrayBuffer) :String { let str = '' let v = new Uint8Array(data); v.forEach(element => { let s = '' s = element.toString(16) if (s.length == 1) { s = '0'+s } str+=s+' ' }); return str } openBle():void { try { ble.on("BLEDeviceFind", (data:Array) => { // console.info('BLE scan device find result = '+ JSON.stringify(data)); let i = 0 data.forEach(element => { console.info('BLE scan device[' + i + '] deviceId = '+ element["deviceId"] + ' name = ' + element["deviceName"] + ' rssi = ' + element["rssi"] + ' data['+element["data"].byteLength+'] = ' + this.dataToString(element["data"])) if (element.rssi > minRssi && element.deviceName != '' ) { this.addData(element) } i++ }); }); ble.startBLEScan( null, { interval: 500, dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER, matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE, } ); } catch (err) { console.error("ble errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); } } // onAccessEvent(data: access.BluetoothState):void { // console.info('bluetooth state = '+ JSON.stringify(data)); // if (data == access.BluetoothState.STATE_ON) { // this.openBle() // } // } build() { Row() { Column() { Text(this.message) .fontSize(30) .fontWeight(FontWeight.Bold) // 添加按钮,开启ble扫描 Button() { Text('ble start') .fontSize(30) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .margin({ top: 20 }) .backgroundColor('#0D9FFB') .width('30%') .height('10%') // 跳转按钮绑定onClick事件,点击时跳转到第二页 .onClick(() => { console.info("onClick") try { this.openBle() // } } catch (err) { console.error('ble errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } }) // 添加按钮,停止ble扫描 Button() { Text('ble stop') .fontSize(30) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .margin({ top: 20 }) .backgroundColor('#0D9FFB') .width('30%') .height('10%') .onClick(() => { this.availableDevices = [] this.message = 'Hello BLE' // AppStorage.setOrCreate('bluetoothAvailableDevices', this.availableDevices); try { ble.off('BLEDeviceFind') ble.stopBLEScan(); } catch (err) { console.error("ble errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); } }) List({ space: "4vp", initialIndex: 0 }) { ForEach(this.availableDevices, (item: ble.ScanResult, index: number) => { ListItemGroup() { ListItem() { Text('['+index.toString(10) +"]" + item.deviceId) .textAlign(TextAlign.Center) .fontSize(30) .backgroundColor(Color.Yellow) .width('100%') } ListItem() { Text(' name:' + item.deviceName) .textAlign(TextAlign.Start) .fontSize(30) .backgroundColor(Color.Orange) .width('100%') } ListItem() { Text(' rssi:' + item.rssi.toString(10)) .textAlign(TextAlign.Start) .fontSize(30) .backgroundColor(Color.Orange) .width('100%') } ListItem() { Text(' connectable:' + item.connectable) .textAlign(TextAlign.Start) .fontSize(30) .backgroundColor(Color.Orange) .width('100%') } ListItem() { Text(' data:' + this.dataToString(item.data)) .textAlign(TextAlign.Start) .fontSize(30) .backgroundColor(Color.Orange) .width('100%') } } }) } .layoutWeight(10) .backgroundColor(0xDCDCDC) .height('50%') .width('60%') .margin({ top: 20 }) } .width('100%') } .height('100%') } } 5. **代码编译** -------------- .. tip:: 代码编译详细流程可见,:doc:`Hello World应用以及部署<../../Quick-Start/OpenHarmony/04-应用以及部署>` 中的第二部分(构建第一个页面部分内容) 6. **代码运行效果** -------------- 用以上标准API接口实现蓝牙 Demo,如下图所示: |BT| .. |BT| image:: media1/BT.png :width: 5.75in :height: 3.92708in .. |image1| image:: media1/wifiImage.png :width: 5.75in :height: 3.92708in .. |btIndex| image:: media1/btIndex.png :width: 5.75in :height: 3.92708in