1# @ohos.bluetooth.ble (蓝牙ble模块) 2 3<!--Kit: Connectivity Kit--> 4<!--Subsystem: Communication--> 5<!--Owner: @enjoy_sunshine--> 6<!--Designer: @chengguohong; @tangjia15--> 7<!--Tester: @wangfeng517--> 8<!--Adviser: @zhang_yixin13--> 9 10本模块提供了基于低功耗蓝牙(Bluetooth Low Energy,[BLE](../../connectivity/terminology.md#ble))技术的蓝牙能力,支持发起BLE扫描、发送BLE广播报文、以及基于通用属性协议(Generic Attribute Profile,[GATT](../../connectivity/terminology.md#gatt))的连接和传输数据。 11 12> **说明:** 13> - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 14> - 接口中涉及的[UUID](../../connectivity/terminology.md#uuid)服务,可以通过工具函数[util.generateRandomUUID](../apis-arkts/js-apis-util.md#utilgeneraterandomuuid9)生成。 15 16 17 18## 导入模块 19 20```js 21import { ble } from '@kit.ConnectivityKit'; 22``` 23 24 25## ProfileConnectionState<sup>10+</sup> 26 27type ProfileConnectionState = constant.ProfileConnectionState 28 29蓝牙设备的Profile协议连接状态。 30 31**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 32 33**系统能力**:SystemCapability.Communication.Bluetooth.Core 34 35| 类型 | 说明 | 36| ------------------- | ------------------- | 37| [constant.ProfileConnectionState](js-apis-bluetooth-constant.md#profileconnectionstate) | 蓝牙设备的profile连接状态。 | 38 39 40## ble.createGattServer 41 42createGattServer(): GattServer 43 44创建[GattServer](#gattserver)实例,表示GATT连接中的server端。 45- 通过该实例可以操作server端的行为,如添加服务[addService](#addservice)、通知特征值变化[notifyCharacteristicChanged](#notifycharacteristicchanged)等。 46 47**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 48 49**系统能力**:SystemCapability.Communication.Bluetooth.Core 50 51**返回值:** 52 53| 类型 | 说明 | 54| ----------------------------- | ---------- | 55| [GattServer](#gattserver) | 返回一个Gatt服务的实例。 | 56 57**示例:** 58 59```js 60let gattServer: ble.GattServer = ble.createGattServer(); 61console.info('gatt success'); 62``` 63 64 65## ble.createGattClientDevice 66 67createGattClientDevice(deviceId: string): GattClientDevice 68 69创建[GattClientDevice](#gattclientdevice)实例,表示GATT连接中的client端。 70- 通过该实例可以操作client端行为,如调用[connect](#connect)向对端设备发起连接,调用[getServices](#getservices)获取对端设备支持的所有服务能力。 71- 创建该实例所需要的设备地址表示server端设备。可以通过[ble.startBLEScan](#blestartblescan)或[BleScanner](#blescanner15)的[startScan](#startscan15)接口获取server端设备地址,且需保证server端设备的BLE广播是可连接的。 72 73**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 74 75**系统能力**:SystemCapability.Communication.Bluetooth.Core 76 77**参数:** 78 79| 参数名 | 类型 | 必填 | 说明 | 80| -------- | ------ | ---- | ------------------------------------ | 81| deviceId | string | 是 | 对端设备地址, 例如:"XX:XX:XX:XX:XX:XX"。 | 82 83**返回值:** 84 85| 类型 | 说明 | 86| ------------------------------------- | ------------------------------------ | 87| [GattClientDevice](#gattclientdevice) | client端类,使用client端方法之前需要创建该类的实例进行操作。 | 88 89**错误码**: 90 91以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 92 93| 错误码ID | 错误信息 | 94| -------- | ---------------------------- | 95|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 96|801 | Capability not supported. | 97 98**示例:** 99 100```js 101import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 102try { 103 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 104} catch (err) { 105 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 106} 107``` 108 109 110## ble.getConnectedBLEDevices 111 112getConnectedBLEDevices(): Array<string> 113 114获取和本机设备已连接GATT的BLE设备集合。 115- 建议给server端使用,client端使用返回的设备地址集合为空。 116 117**需要权限**:ohos.permission.ACCESS_BLUETOOTH 118 119**系统能力**:SystemCapability.Communication.Bluetooth.Core 120 121**返回值:** 122 123| 类型 | 说明 | 124| ------------------- | ------------------- | 125| Array<string> | 返回和本机设备已建立GATT连接的BLE设备地址集合。<br>基于信息安全考虑,此处获取的设备地址为虚拟MAC地址。<br>- 若和该设备地址配对成功后,该地址不会变更。<br>- 取消配对该设备或蓝牙关闭后,若重新获取,该虚拟地址会变更。<br>- 若要持久化保存该地址,可使用[access.addPersistentDeviceId](js-apis-bluetooth-access.md#accessaddpersistentdeviceid16)方法 | 126 127**错误码**: 128 129以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 130 131| 错误码ID | 错误信息 | 132| -------- | ---------------------------- | 133|201 | Permission denied. | 134|801 | Capability not supported. | 135|2900001 | Service stopped. | 136|2900003 | Bluetooth disabled. | 137|2900099 | Operation failed. | 138 139**示例:** 140 141```js 142import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 143try { 144 let result: Array<string> = ble.getConnectedBLEDevices(); 145} catch (err) { 146 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 147} 148``` 149 150 151## ble.startBLEScan 152 153startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void 154 155发起BLE扫描流程。 156- 扫描结果会通过[ble.on('BLEDeviceFind')](#bleonbledevicefind)的回调函数获取到。只能扫描BLE设备,调用[ble.stopBLEScan](#blestopblescan)可以停止该方法开启的扫描流程。 157- 该接口只支持单路扫描,即应用同时只能调用一次,下一次调用前,需要先调用[ble.stopBLEScan](#blestopblescan)停止上一次的扫描流程。 158- 若需要使用多路扫描,可使用[BleScanner](#blescanner15)。 159 160**需要权限**:ohos.permission.ACCESS_BLUETOOTH 161 162**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 163 164**系统能力**:SystemCapability.Communication.Bluetooth.Core 165 166**参数:** 167 168| 参数名 | 类型 | 必填 | 说明 | 169| ------- | -------------------------------------- | ---- | ----------------------------------- | 170| filters | Array<[ScanFilter](#scanfilter)> | 是 | 表示扫描结果过滤策略集合,符合过滤条件的设备发现会保留。<br>-若该参数设置为null,将扫描所有可发现的周边BLE设备,但是不建议使用此方式,可能扫描到非预期设备,并增加功耗。 | 171| options | [ScanOptions](#scanoptions) | 否 | 表示扫描的参数配置。 | 172 173**错误码**: 174 175以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 176 177| 错误码ID | 错误信息 | 178| -------- | ---------------------------- | 179|201 | Permission denied. | 180|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 181|801 | Capability not supported. | 182|2900001 | Service stopped. | 183|2900003 | Bluetooth disabled. | 184|2900099 | Operation failed. | 185 186**示例:** 187 188```js 189import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 190function onReceiveEvent(data: Array<ble.ScanResult>) { 191 console.info('BLE scan device find result = '+ JSON.stringify(data)); 192} 193try { 194 ble.on("BLEDeviceFind", onReceiveEvent); 195 let scanFilter: ble.ScanFilter = { 196 deviceId:"XX:XX:XX:XX:XX:XX", 197 name:"test", 198 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb" 199 }; 200 let scanOptions: ble.ScanOptions = { 201 interval: 500, 202 dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER, 203 matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE 204 } 205 ble.startBLEScan([scanFilter],scanOptions); 206} catch (err) { 207 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 208} 209``` 210 211 212## ble.stopBLEScan 213 214stopBLEScan(): void 215 216停止BLE扫描流程。 217- 停止的BLE扫描由[ble.startBLEScan](#blestartblescan)触发。 218- 当应用不再需要扫描BLE设备时,需主动调用该方法停止扫描。 219- 调用此接口后将不再收到扫描结果上报,重新开启BLE扫描即可再次扫到BLE设备。 220 221**需要权限**:ohos.permission.ACCESS_BLUETOOTH 222 223**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 224 225**系统能力**:SystemCapability.Communication.Bluetooth.Core 226 227**错误码**: 228 229以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 230 231| 错误码ID | 错误信息 | 232| -------- | ---------------------------- | 233|201 | Permission denied. | 234|801 | Capability not supported. | 235|2900001 | Service stopped. | 236|2900003 | Bluetooth disabled. | 237|2900099 | Operation failed. | 238 239**示例:** 240 241```js 242import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 243try { 244 ble.stopBLEScan(); 245} catch (err) { 246 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 247} 248``` 249 250 251## ble.startAdvertising 252 253startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void 254 255开始发送BLE广播报文。 256- 当应用不再需要发送BLE广播报文时,需主动调用[ble.stopAdvertising](#blestopadvertising)停止发送。 257- 同步接口,不要和API version 11的[ble.stopAdvertising](#blestopadvertising11)搭配使用。 258 259 260**需要权限**:ohos.permission.ACCESS_BLUETOOTH 261 262**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 263 264**系统能力**:SystemCapability.Communication.Bluetooth.Core 265 266**参数:** 267 268| 参数名 | 类型 | 必填 | 说明 | 269| ----------- | ------------------------------------- | ---- | -------------- | 270| setting | [AdvertiseSetting](#advertisesetting) | 是 | BLE广播的相关参数。 | 271| advData | [AdvertiseData](#advertisedata) | 是 | BLE广播报文内容。 | 272| advResponse | [AdvertiseData](#advertisedata) | 否 | BLE扫描回复广播报文。 | 273 274**错误码**: 275 276以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 277 278| 错误码ID | 错误信息 | 279| -------- | ---------------------------- | 280|201 | Permission denied. | 281|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 282|801 | Capability not supported. | 283|2900001 | Service stopped. | 284|2900003 | Bluetooth disabled. | 285|2900010 | The number of advertising resources reaches the upper limit. | 286|2900099 | Operation failed. | 287|2902054 | The length of the advertising data exceeds the upper limit. | 288 289**示例:** 290 291```js 292import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 293let manufactureValueBuffer = new Uint8Array(4); 294manufactureValueBuffer[0] = 1; 295manufactureValueBuffer[1] = 2; 296manufactureValueBuffer[2] = 3; 297manufactureValueBuffer[3] = 4; 298 299let serviceValueBuffer = new Uint8Array(4); 300serviceValueBuffer[0] = 4; 301serviceValueBuffer[1] = 6; 302serviceValueBuffer[2] = 7; 303serviceValueBuffer[3] = 8; 304console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); 305console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); 306try { 307 let setting: ble.AdvertiseSetting = { 308 interval:150, 309 txPower:0, 310 connectable:true 311 }; 312 let manufactureDataUnit: ble.ManufactureData = { 313 manufactureId:4567, 314 manufactureValue:manufactureValueBuffer.buffer 315 }; 316 let serviceDataUnit: ble.ServiceData = { 317 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", 318 serviceValue:serviceValueBuffer.buffer 319 }; 320 let advData: ble.AdvertiseData = { 321 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 322 manufactureData:[manufactureDataUnit], 323 serviceData:[serviceDataUnit] 324 }; 325 let advResponse: ble.AdvertiseData = { 326 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 327 manufactureData:[manufactureDataUnit], 328 serviceData:[serviceDataUnit] 329 }; 330 ble.startAdvertising(setting, advData ,advResponse); 331} catch (err) { 332 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 333} 334``` 335 336 337## ble.stopAdvertising 338 339stopAdvertising(): void 340 341停止发送BLE广播报文。 342- 停止的BLE广播是由[ble.startAdvertising](#blestartadvertising)触发的。 343- 不可以和API version 11的[ble.startAdvertising](#blestartadvertising11)搭配使用。 344- 当应用不再需要发送BLE广播报文时,需主动调用该方法停止发送。 345 346**需要权限**:ohos.permission.ACCESS_BLUETOOTH 347 348**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 349 350**系统能力**:SystemCapability.Communication.Bluetooth.Core 351 352**错误码**: 353 354以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 355 356| 错误码ID | 错误信息 | 357| -------- | ---------------------------- | 358|201 | Permission denied. | 359|801 | Capability not supported. | 360|2900001 | Service stopped. | 361|2900003 | Bluetooth disabled. | 362|2900099 | Operation failed. | 363 364**示例:** 365 366```js 367import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 368try { 369 ble.stopAdvertising(); 370} catch (err) { 371 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 372} 373``` 374 375 376## ble.startAdvertising<sup>11+</sup> 377 378startAdvertising(advertisingParams: AdvertisingParams, callback: AsyncCallback<number>): void 379 380首次启动发送BLE广播报文。使用Callback异步回调。 381- 启动成功后,蓝牙子系统会分配相关资源,并使用Callback异步返回该广播的标识。 382- 若携带了发送广播持续时间,则一定时间后,广播会停止发送,但分配的广播资源还存在,可以通过[ble.enableAdvertising](#bleenableadvertising11)重新启动发送该广播。 383- 从API version 15开始,应用可多次调用,支持发起多路广播,每一路广播通过不同的ID标识管理。 384- 当应用不再需要该广播时,需调用API version 11开始支持的[ble.stopAdvertising](#blestopadvertising11)完全停止该广播,不要与API version 10开始支持的[ble.stopAdvertising](#blestopadvertising)混用。 385 386**需要权限**:ohos.permission.ACCESS_BLUETOOTH 387 388**系统能力**:SystemCapability.Communication.Bluetooth.Core 389 390**参数:** 391 392| 参数名 | 类型 | 必填 | 说明 | 393| ------------------- | --------------------------------------- | ----- | ------------------------------- | 394| advertisingParams | [AdvertisingParams](#advertisingparams11) | 是 | 启动BLE广播的相关参数。 | 395| callback | AsyncCallback<number> | 是 | 广播ID标识,通过注册回调函数获取。 | 396 397**错误码**: 398 399以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 400 401| 错误码ID | 错误信息 | 402| -------- | -------------------------------------- | 403|201 | Permission denied. | 404|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 405|801 | Capability not supported. | 406|2900001 | Service stopped. | 407|2900003 | Bluetooth disabled. | 408|2900010 | The number of advertising resources reaches the upper limit. | 409|2900099 | Operation failed. | 410|2902054 | The length of the advertising data exceeds the upper limit. | 411 412**示例:** 413 414```js 415import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 416let manufactureValueBuffer = new Uint8Array(4); 417manufactureValueBuffer[0] = 1; 418manufactureValueBuffer[1] = 2; 419manufactureValueBuffer[2] = 3; 420manufactureValueBuffer[3] = 4; 421 422let serviceValueBuffer = new Uint8Array(4); 423serviceValueBuffer[0] = 4; 424serviceValueBuffer[1] = 6; 425serviceValueBuffer[2] = 7; 426serviceValueBuffer[3] = 8; 427console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); 428console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); 429try { 430 let setting: ble.AdvertiseSetting = { 431 interval:150, 432 txPower:0, 433 connectable:true, 434 }; 435 let manufactureDataUnit: ble.ManufactureData = { 436 manufactureId:4567, 437 manufactureValue:manufactureValueBuffer.buffer 438 }; 439 let serviceDataUnit: ble.ServiceData = { 440 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", 441 serviceValue:serviceValueBuffer.buffer 442 }; 443 let advData: ble.AdvertiseData = { 444 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 445 manufactureData:[manufactureDataUnit], 446 serviceData:[serviceDataUnit] 447 }; 448 let advResponse: ble.AdvertiseData = { 449 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 450 manufactureData:[manufactureDataUnit], 451 serviceData:[serviceDataUnit] 452 }; 453 let advertisingParams: ble.AdvertisingParams = { 454 advertisingSettings: setting, 455 advertisingData: advData, 456 advertisingResponse: advResponse, 457 duration: 0 458 } 459 let advHandle = 0xFF; 460 ble.startAdvertising(advertisingParams, (err, outAdvHandle) => { 461 if (err) { 462 return; 463 } else { 464 advHandle = outAdvHandle; 465 console.info("advHandle: " + advHandle); 466 } 467 }); 468} catch (err) { 469 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 470} 471``` 472 473 474## ble.startAdvertising<sup>11+</sup> 475 476startAdvertising(advertisingParams: AdvertisingParams): Promise<number> 477 478首次启动发送BLE广播报文。使用Promise异步回调。 479- 启动成功后,蓝牙子系统会分配相关资源,并使用Promise异步返回该广播的标识。 480- 若携带了发送广播持续时间,则一定时间后,广播会停止发送,但分配的广播资源还存在,可以通过[ble.enableAdvertising](#bleenableadvertising11)重新启动发送该广播。 481- 从API version 15开始,应用可多次调用,支持发起多路广播,每一路广播通过不同的ID标识管理。 482- 当应用不再需要该广播时,需调用API version 11开始支持的[ble.stopAdvertising](#blestopadvertising11-1)完全停止该广播,不要与API version 10开始支持的[ble.stopAdvertising](#blestopadvertising)混用。 483 484**需要权限**:ohos.permission.ACCESS_BLUETOOTH 485 486**系统能力**:SystemCapability.Communication.Bluetooth.Core 487 488**参数:** 489 490| 参数名 | 类型 | 必填 | 说明 | 491| ------------------- | -------------------------------------- | ----- | ----------------------- | 492| advertisingParams | [AdvertisingParams](#advertisingparams11) | 是 | 启动BLE广播的相关参数。 | 493 494**返回值:** 495 496| 类型 | 说明 | 497| -------------------------- | ------------------------------- | 498| Promise<number> | 广播ID标识,通过promise形式获取。 | 499 500**错误码**: 501 502以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 503 504| 错误码ID | 错误信息 | 505| -------- | -------------------------------------- | 506|201 | Permission denied. | 507|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 508|801 | Capability not supported. | 509|2900001 | Service stopped. | 510|2900003 | Bluetooth disabled. | 511|2900010 | The number of advertising resources reaches the upper limit. | 512|2900099 | Operation failed. | 513|2902054 | The length of the advertising data exceeds the upper limit. | 514 515**示例:** 516 517```js 518import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 519let manufactureValueBuffer = new Uint8Array(4); 520manufactureValueBuffer[0] = 1; 521manufactureValueBuffer[1] = 2; 522manufactureValueBuffer[2] = 3; 523manufactureValueBuffer[3] = 4; 524 525let serviceValueBuffer = new Uint8Array(4); 526serviceValueBuffer[0] = 4; 527serviceValueBuffer[1] = 6; 528serviceValueBuffer[2] = 7; 529serviceValueBuffer[3] = 8; 530console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); 531console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); 532try { 533 let setting: ble.AdvertiseSetting = { 534 interval:150, 535 txPower:0, 536 connectable:true 537 }; 538 let manufactureDataUnit: ble.ManufactureData = { 539 manufactureId:4567, 540 manufactureValue:manufactureValueBuffer.buffer 541 }; 542 let serviceDataUnit: ble.ServiceData = { 543 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", 544 serviceValue:serviceValueBuffer.buffer 545 }; 546 let advData: ble.AdvertiseData = { 547 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 548 manufactureData:[manufactureDataUnit], 549 serviceData:[serviceDataUnit] 550 }; 551 let advResponse: ble.AdvertiseData = { 552 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 553 manufactureData:[manufactureDataUnit], 554 serviceData:[serviceDataUnit] 555 }; 556 let advertisingParams: ble.AdvertisingParams = { 557 advertisingSettings: setting, 558 advertisingData: advData, 559 advertisingResponse: advResponse, 560 duration: 0 561 } 562 let advHandle = 0xFF; 563 ble.startAdvertising(advertisingParams) 564 .then(outAdvHandle => { 565 advHandle = outAdvHandle; 566 }); 567} catch (err) { 568 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 569} 570``` 571 572 573## ble.enableAdvertising<sup>11+</sup> 574 575enableAdvertising(advertisingEnableParams: AdvertisingEnableParams, callback: AsyncCallback<void>): void 576 577重新启动指定标识的BLE广播。使用Callback异步回调。 578- [AdvertisingEnableParams](#advertisingenableparams11)中advertisingId对应的广播资源已在[ble.startAdvertising](#blestartadvertising11)首次启动广播时分配。 579- 若[ble.startAdvertising](#blestartadvertising11)首次启动广播时指定了广播持续时间,超时后广播自动停止,调用此接口可重新启动同一路BLE广播。 580- 通过[ble.disableAdvertising](#bledisableadvertising11)停止的广播,调用此接口可重新启动同一路BLE广播。 581- 通过[ble.on('advertisingStateChange')](#bleonadvertisingstatechange11)回调获取重新启动广播结果。 582 583**需要权限**:ohos.permission.ACCESS_BLUETOOTH 584 585**系统能力**:SystemCapability.Communication.Bluetooth.Core 586 587**参数:** 588 589| 参数名 | 类型 | 必填 | 说明 | 590| ------------------------- | --------------------------------------------------- | ----- | ------------------------------- | 591| advertisingEnableParams | [AdvertisingEnableParams](#advertisingenableparams11) | 是 | 临时启动BLE广播的相关参数。 | 592| callback | AsyncCallback<void> | 是 | 回调函数。 | 593 594**错误码**: 595 596以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 597 598| 错误码ID | 错误信息 | 599| ------- | -------------------------------------- | 600|201 | Permission denied. | 601|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 602|801 | Capability not supported. | 603|2900001 | Service stopped. | 604|2900003 | Bluetooth disabled. | 605|2900099 | Operation failed. | 606|2902055 | Invalid advertising id. | 607 608**示例:** 609 610```js 611import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 612let manufactureValueBuffer = new Uint8Array(4); 613manufactureValueBuffer[0] = 1; 614manufactureValueBuffer[1] = 2; 615manufactureValueBuffer[2] = 3; 616manufactureValueBuffer[3] = 4; 617 618let serviceValueBuffer = new Uint8Array(4); 619serviceValueBuffer[0] = 4; 620serviceValueBuffer[1] = 6; 621serviceValueBuffer[2] = 7; 622serviceValueBuffer[3] = 8; 623console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); 624console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); 625try { 626 let setting: ble.AdvertiseSetting = { 627 interval:150, 628 txPower:0, 629 connectable:true 630 }; 631 let manufactureDataUnit: ble.ManufactureData = { 632 manufactureId:4567, 633 manufactureValue:manufactureValueBuffer.buffer 634 }; 635 let serviceDataUnit: ble.ServiceData = { 636 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", 637 serviceValue:serviceValueBuffer.buffer 638 }; 639 let advData: ble.AdvertiseData = { 640 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 641 manufactureData:[manufactureDataUnit], 642 serviceData:[serviceDataUnit] 643 }; 644 let advResponse: ble.AdvertiseData = { 645 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 646 manufactureData:[manufactureDataUnit], 647 serviceData:[serviceDataUnit] 648 }; 649 let advertisingParams: ble.AdvertisingParams = { 650 advertisingSettings: setting, 651 advertisingData: advData, 652 advertisingResponse: advResponse, 653 duration: 300 654 } 655 let advHandle = 0xFF; 656 ble.startAdvertising(advertisingParams, (err, outAdvHandle) => { 657 if (err) { 658 return; 659 } else { 660 advHandle = outAdvHandle; 661 console.info("advHandle: " + advHandle); 662 } 663 }); 664 665 let advertisingEnableParams: ble.AdvertisingEnableParams = { 666 advertisingId: advHandle, 667 duration: 0 668 } 669 670 // after 3s, advertising disabled, then enable the advertising 671 ble.enableAdvertising(advertisingEnableParams, (err) => { 672 if (err) { 673 return; 674 } 675 }); 676} catch (err) { 677 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 678} 679``` 680 681 682## ble.enableAdvertising<sup>11+</sup> 683 684enableAdvertising(advertisingEnableParams: AdvertisingEnableParams): Promise<void> 685 686重新启动指定标识的BLE广播。使用Promise异步回调。 687- [AdvertisingEnableParams](#advertisingenableparams11)中advertisingId对应的广播资源已在[ble.startAdvertising](#blestartadvertising11)首次启动广播时分配。 688- 若[ble.startAdvertising](#blestartadvertising11)首次启动广播时指定了广播持续时间,超时后广播自动停止,调用此接口可重新启动同一路BLE广播。 689- 通过[ble.disableAdvertising](#bledisableadvertising11)停止的广播,调用此接口可重新启动同一路BLE广播。 690- 通过[ble.on('advertisingStateChange')](#bleonadvertisingstatechange11)回调获取启动广播结果。 691 692**需要权限**:ohos.permission.ACCESS_BLUETOOTH 693 694**系统能力**:SystemCapability.Communication.Bluetooth.Core 695 696**参数:** 697 698| 参数名 | 类型 | 必填 | 说明 | 699| ------------------------- | --------------------------------------------------- | ----- | ------------------------------- | 700| advertisingEnableParams | [AdvertisingEnableParams](#advertisingenableparams11) | 是 | 临时启动BLE广播的相关参数。 | 701 702**返回值:** 703 704| 类型 | 说明 | 705| -------------------------- | ------------ | 706| Promise<void> | 回调函数。 | 707 708**错误码**: 709 710以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 711 712| 错误码ID | 错误信息 | 713| ------- | -------------------------------------- | 714|201 | Permission denied. | 715|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 716|801 | Capability not supported. | 717|2900001 | Service stopped. | 718|2900003 | Bluetooth disabled. | 719|2900099 | Operation failed. | 720|2902055 | Invalid advertising id. | 721 722**示例:** 723 724```js 725import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 726let manufactureValueBuffer = new Uint8Array(4); 727manufactureValueBuffer[0] = 1; 728manufactureValueBuffer[1] = 2; 729manufactureValueBuffer[2] = 3; 730manufactureValueBuffer[3] = 4; 731 732let serviceValueBuffer = new Uint8Array(4); 733serviceValueBuffer[0] = 4; 734serviceValueBuffer[1] = 6; 735serviceValueBuffer[2] = 7; 736serviceValueBuffer[3] = 8; 737console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); 738console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); 739try { 740 let setting: ble.AdvertiseSetting = { 741 interval:150, 742 txPower:0, 743 connectable:true 744 }; 745 let manufactureDataUnit: ble.ManufactureData = { 746 manufactureId:4567, 747 manufactureValue:manufactureValueBuffer.buffer 748 }; 749 let serviceDataUnit: ble.ServiceData = { 750 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", 751 serviceValue:serviceValueBuffer.buffer 752 }; 753 let advData: ble.AdvertiseData = { 754 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 755 manufactureData:[manufactureDataUnit], 756 serviceData:[serviceDataUnit] 757 }; 758 let advResponse: ble.AdvertiseData = { 759 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 760 manufactureData:[manufactureDataUnit], 761 serviceData:[serviceDataUnit] 762 }; 763 let advertisingParams: ble.AdvertisingParams = { 764 advertisingSettings: setting, 765 advertisingData: advData, 766 advertisingResponse: advResponse, 767 duration: 300 768 } 769 let advHandle = 0xFF; 770 ble.startAdvertising(advertisingParams, (err, outAdvHandle) => { 771 if (err) { 772 return; 773 } else { 774 advHandle = outAdvHandle; 775 console.info("advHandle: " + advHandle); 776 } 777 }); 778 779 let advertisingEnableParams: ble.AdvertisingEnableParams = { 780 advertisingId: advHandle, 781 duration: 0 782 } 783 784 // after 3s, advertising disabled, then enable the advertising 785 ble.enableAdvertising(advertisingEnableParams) 786 .then(() => { 787 console.info("enable success"); 788 }); 789} catch (err) { 790 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 791} 792``` 793 794 795## ble.disableAdvertising<sup>11+</sup> 796 797disableAdvertising(advertisingDisableParams: AdvertisingDisableParams, callback: AsyncCallback<void>): void 798 799停止指定标识的BLE广播。使用Callback异步回调。 800- 停止BLE广播,但不释放已申请的广播资源,调用[ble.enableAdvertising](#bleenableadvertising11)可重新启动此方法停止的广播。 801- [AdvertisingDisableParams](#advertisingdisableparams11)中advertisingId对应的广播资源已在[ble.startAdvertising](#blestartadvertising11)首次启动广播时分配。 802- 通过[ble.on('advertisingStateChange')](#bleonadvertisingstatechange11)回调获取停止广播结果。 803 804**需要权限**:ohos.permission.ACCESS_BLUETOOTH 805 806**系统能力**:SystemCapability.Communication.Bluetooth.Core 807 808**参数:** 809 810| 参数名 | 类型 | 必填 | 说明 | 811| ------------------------- | ----------------------------------------------------- | ----- | ------------------------------- | 812| advertisingDisableParams | [AdvertisingDisableParams](#advertisingdisableparams11) | 是 | 临时关闭BLE广播的相关参数。 | 813| callback | AsyncCallback<void> | 是 | 回调函数。 | 814 815**错误码**: 816 817以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 818 819| 错误码ID | 错误信息 | 820| ------- | -------------------------------------- | 821|201 | Permission denied. | 822|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 823|801 | Capability not supported. | 824|2900001 | Service stopped. | 825|2900003 | Bluetooth disabled. | 826|2900099 | Operation failed. | 827|2902055 | Invalid advertising id. | 828 829**示例:** 830 831```js 832import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 833let manufactureValueBuffer = new Uint8Array(4); 834manufactureValueBuffer[0] = 1; 835manufactureValueBuffer[1] = 2; 836manufactureValueBuffer[2] = 3; 837manufactureValueBuffer[3] = 4; 838 839let serviceValueBuffer = new Uint8Array(4); 840serviceValueBuffer[0] = 4; 841serviceValueBuffer[1] = 6; 842serviceValueBuffer[2] = 7; 843serviceValueBuffer[3] = 8; 844console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); 845console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); 846try { 847 let setting: ble.AdvertiseSetting = { 848 interval:150, 849 txPower:0, 850 connectable:true 851 }; 852 let manufactureDataUnit: ble.ManufactureData = { 853 manufactureId:4567, 854 manufactureValue:manufactureValueBuffer.buffer 855 }; 856 let serviceDataUnit: ble.ServiceData = { 857 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", 858 serviceValue:serviceValueBuffer.buffer 859 }; 860 let advData: ble.AdvertiseData = { 861 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 862 manufactureData:[manufactureDataUnit], 863 serviceData:[serviceDataUnit] 864 }; 865 let advResponse: ble.AdvertiseData = { 866 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 867 manufactureData:[manufactureDataUnit], 868 serviceData:[serviceDataUnit] 869 }; 870 let advertisingParams: ble.AdvertisingParams = { 871 advertisingSettings: setting, 872 advertisingData: advData, 873 advertisingResponse: advResponse, 874 duration: 0 875 } 876 let advHandle = 0xFF; 877 ble.startAdvertising(advertisingParams, (err, outAdvHandle) => { 878 if (err) { 879 return; 880 } else { 881 advHandle = outAdvHandle; 882 console.info("advHandle: " + advHandle); 883 } 884 }); 885 886 let advertisingDisableParams: ble.AdvertisingDisableParams = { 887 advertisingId: advHandle 888 } 889 ble.disableAdvertising(advertisingDisableParams, (err) => { 890 if (err) { 891 return; 892 } 893 }); 894} catch (err) { 895 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 896} 897``` 898 899 900## ble.disableAdvertising<sup>11+</sup> 901 902disableAdvertising(advertisingDisableParams: AdvertisingDisableParams): Promise<void> 903 904停止指定标识的BLE广播。使用Promise异步回调。 905- 停止BLE广播,但不释放已申请的广播资源,调用[ble.enableAdvertising](#bleenableadvertising11)可重新启动此方法停止的广播。 906- [AdvertisingDisableParams](#advertisingdisableparams11)中advertisingId对应的广播资源已在[ble.startAdvertising](#blestartadvertising11)首次启动广播时分配。 907- 通过[ble.on('advertisingStateChange')](#bleonadvertisingstatechange11)回调获取停止广播结果。 908 909**需要权限**:ohos.permission.ACCESS_BLUETOOTH 910 911**系统能力**:SystemCapability.Communication.Bluetooth.Core 912 913**参数:** 914 915| 参数名 | 类型 | 必填 | 说明 | 916| ------------------------- | ----------------------------------------------------- | ----- | ------------------------------- | 917| advertisingDisableParams | [AdvertisingDisableParams](#advertisingdisableparams11) | 是 | 临时关闭BLE广播的相关参数。 | 918 919**返回值:** 920 921| 类型 | 说明 | 922| -------------------------- | ------------ | 923| Promise<void> | 回调函数。 | 924 925**错误码**: 926 927以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 928 929| 错误码ID | 错误信息 | 930| ------- | -------------------------------------- | 931|201 | Permission denied. | 932|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 933|801 | Capability not supported. | 934|2900001 | Service stopped. | 935|2900003 | Bluetooth disabled. | 936|2900099 | Operation failed. | 937|2902055 | Invalid advertising id. | 938 939**示例:** 940 941```js 942import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 943let manufactureValueBuffer = new Uint8Array(4); 944manufactureValueBuffer[0] = 1; 945manufactureValueBuffer[1] = 2; 946manufactureValueBuffer[2] = 3; 947manufactureValueBuffer[3] = 4; 948 949let serviceValueBuffer = new Uint8Array(4); 950serviceValueBuffer[0] = 4; 951serviceValueBuffer[1] = 6; 952serviceValueBuffer[2] = 7; 953serviceValueBuffer[3] = 8; 954console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); 955console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); 956try { 957 let setting: ble.AdvertiseSetting = { 958 interval:150, 959 txPower:0, 960 connectable:true 961 }; 962 let manufactureDataUnit: ble.ManufactureData = { 963 manufactureId:4567, 964 manufactureValue:manufactureValueBuffer.buffer 965 }; 966 let serviceDataUnit: ble.ServiceData = { 967 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", 968 serviceValue:serviceValueBuffer.buffer 969 }; 970 let advData: ble.AdvertiseData = { 971 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 972 manufactureData:[manufactureDataUnit], 973 serviceData:[serviceDataUnit] 974 }; 975 let advResponse: ble.AdvertiseData = { 976 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 977 manufactureData:[manufactureDataUnit], 978 serviceData:[serviceDataUnit] 979 }; 980 let advertisingParams: ble.AdvertisingParams = { 981 advertisingSettings: setting, 982 advertisingData: advData, 983 advertisingResponse: advResponse, 984 duration: 0 985 } 986 let advHandle = 0xFF; 987 ble.startAdvertising(advertisingParams, (err, outAdvHandle) => { 988 if (err) { 989 return; 990 } else { 991 advHandle = outAdvHandle; 992 console.info("advHandle: " + advHandle); 993 } 994 }); 995 996 let advertisingDisableParams: ble.AdvertisingDisableParams = { 997 advertisingId: advHandle 998 } 999 ble.disableAdvertising(advertisingDisableParams) 1000 .then(() => { 1001 console.info("enable success"); 1002 }); 1003} catch (err) { 1004 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1005} 1006``` 1007 1008## ble.stopAdvertising<sup>11+</sup> 1009 1010stopAdvertising(advertisingId: number, callback: AsyncCallback<void>): void 1011 1012完全停止发送BLE广播。使用Callback异步回调。 1013- 与API version 11开始支持的[ble.startAdvertising](#blestartadvertising11)搭配使用,会释放已经申请的广播资源。 1014- [ble.startAdvertising](#blestartadvertising11)首次启动广播时分配的广播标识也将失效。 1015- 不可以和API version 10开始支持的[ble.startAdvertising](#blestartadvertising)接口搭配使用。 1016- 通过[ble.on('advertisingStateChange')](#bleonadvertisingstatechange11)回调获取完全停止广播结果。 1017 1018**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1019 1020**系统能力**:SystemCapability.Communication.Bluetooth.Core 1021 1022**参数:** 1023 1024| 参数名 | 类型 | 必填 | 说明 | 1025| ------------------------- | ---------------------------- | ----- | --------------------------- | 1026| advertisingId | number | 是 | 需要停止的广播ID标识。 | 1027| callback | AsyncCallback<void> | 是 | 回调函数。 | 1028 1029**错误码**: 1030 1031以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1032 1033| 错误码ID | 错误信息 | 1034| -------- | ---------------------------- | 1035|201 | Permission denied. | 1036|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 1037|801 | Capability not supported. | 1038|2900001 | Service stopped. | 1039|2900003 | Bluetooth disabled. | 1040|2900099 | Operation failed. | 1041|2902055 | Invalid advertising id. | 1042 1043**示例:** 1044 1045```js 1046import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1047let manufactureValueBuffer = new Uint8Array(4); 1048manufactureValueBuffer[0] = 1; 1049manufactureValueBuffer[1] = 2; 1050manufactureValueBuffer[2] = 3; 1051manufactureValueBuffer[3] = 4; 1052 1053let serviceValueBuffer = new Uint8Array(4); 1054serviceValueBuffer[0] = 4; 1055serviceValueBuffer[1] = 6; 1056serviceValueBuffer[2] = 7; 1057serviceValueBuffer[3] = 8; 1058console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); 1059console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); 1060try { 1061 let setting: ble.AdvertiseSetting = { 1062 interval:150, 1063 txPower:0, 1064 connectable:true 1065 }; 1066 let manufactureDataUnit: ble.ManufactureData = { 1067 manufactureId:4567, 1068 manufactureValue:manufactureValueBuffer.buffer 1069 }; 1070 let serviceDataUnit: ble.ServiceData = { 1071 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", 1072 serviceValue:serviceValueBuffer.buffer 1073 }; 1074 let advData: ble.AdvertiseData = { 1075 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 1076 manufactureData:[manufactureDataUnit], 1077 serviceData:[serviceDataUnit] 1078 }; 1079 let advResponse: ble.AdvertiseData = { 1080 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 1081 manufactureData:[manufactureDataUnit], 1082 serviceData:[serviceDataUnit] 1083 }; 1084 let advertisingParams: ble.AdvertisingParams = { 1085 advertisingSettings: setting, 1086 advertisingData: advData, 1087 advertisingResponse: advResponse, 1088 duration: 0 1089 } 1090 let advHandle = 0xFF; 1091 ble.startAdvertising(advertisingParams, (err, outAdvHandle) => { 1092 if (err) { 1093 return; 1094 } else { 1095 advHandle = outAdvHandle; 1096 console.info("advHandle: " + advHandle); 1097 } 1098 }); 1099 1100 ble.stopAdvertising(advHandle, (err) => { 1101 if (err) { 1102 return; 1103 } 1104 }); 1105} catch (err) { 1106 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1107} 1108``` 1109 1110 1111## ble.stopAdvertising<sup>11+</sup> 1112 1113stopAdvertising(advertisingId: number): Promise<void> 1114 1115完全停止发送BLE广播。使用Promise异步回调。 1116- 与API version 11开始支持的[ble.startAdvertising](#blestartadvertising11)搭配使用,会释放已经申请的广播资源。 1117- [ble.startAdvertising](#blestartadvertising11)首次启动广播时分配的广播标识也将失效。 1118- 不可以和API version 10开始支持的[ble.startAdvertising](#blestartadvertising)接口搭配使用。 1119- 通过[ble.on('advertisingStateChange')](#bleonadvertisingstatechange11)回调获取完全停止广播结果。 1120 1121**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1122 1123**系统能力**:SystemCapability.Communication.Bluetooth.Core 1124 1125**参数:** 1126 1127| 参数名 | 类型 | 必填 | 说明 | 1128| ------------------------- | ---------------------------- | ----- | --------------------------- | 1129| advertisingId | number | 是 | 需要停止的广播ID标识。 | 1130 1131**返回值:** 1132 1133| 类型 | 说明 | 1134| -------------------------- | ------------ | 1135| Promise<void> | 回调函数。 | 1136 1137**错误码**: 1138 1139以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1140 1141| 错误码ID | 错误信息 | 1142| -------- | ---------------------------- | 1143|201 | Permission denied. | 1144|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 1145|801 | Capability not supported. | 1146|2900001 | Service stopped. | 1147|2900003 | Bluetooth disabled. | 1148|2900099 | Operation failed. | 1149|2902055 | Invalid advertising id. | 1150 1151**示例:** 1152 1153```js 1154import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1155let manufactureValueBuffer = new Uint8Array(4); 1156manufactureValueBuffer[0] = 1; 1157manufactureValueBuffer[1] = 2; 1158manufactureValueBuffer[2] = 3; 1159manufactureValueBuffer[3] = 4; 1160 1161let serviceValueBuffer = new Uint8Array(4); 1162serviceValueBuffer[0] = 4; 1163serviceValueBuffer[1] = 6; 1164serviceValueBuffer[2] = 7; 1165serviceValueBuffer[3] = 8; 1166console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); 1167console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); 1168try { 1169 let setting: ble.AdvertiseSetting = { 1170 interval:150, 1171 txPower:0, 1172 connectable:true 1173 }; 1174 let manufactureDataUnit: ble.ManufactureData = { 1175 manufactureId:4567, 1176 manufactureValue:manufactureValueBuffer.buffer 1177 }; 1178 let serviceDataUnit: ble.ServiceData = { 1179 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", 1180 serviceValue:serviceValueBuffer.buffer 1181 }; 1182 let advData: ble.AdvertiseData = { 1183 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 1184 manufactureData:[manufactureDataUnit], 1185 serviceData:[serviceDataUnit] 1186 }; 1187 let advResponse: ble.AdvertiseData = { 1188 serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], 1189 manufactureData:[manufactureDataUnit], 1190 serviceData:[serviceDataUnit] 1191 }; 1192 let advertisingParams: ble.AdvertisingParams = { 1193 advertisingSettings: setting, 1194 advertisingData: advData, 1195 advertisingResponse: advResponse, 1196 duration: 0 1197 } 1198 let advHandle = 0xFF; 1199 ble.startAdvertising(advertisingParams, (err, outAdvHandle) => { 1200 if (err) { 1201 return; 1202 } else { 1203 advHandle = outAdvHandle; 1204 console.info("advHandle: " + advHandle); 1205 } 1206 }); 1207 1208 ble.stopAdvertising(advHandle) 1209 .then(() => { 1210 console.info("enable success"); 1211 }); 1212} catch (err) { 1213 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1214} 1215``` 1216 1217 1218## ble.on('advertisingStateChange')<sup>11+</sup> 1219 1220on(type: 'advertisingStateChange', callback: Callback<AdvertisingStateChangeInfo>): void 1221 1222订阅BLE广播状态。使用Callback异步回调。 1223 1224**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1225 1226**系统能力**:SystemCapability.Communication.Bluetooth.Core 1227 1228**参数:** 1229 1230| 参数名 | 类型 | 必填 | 说明 | 1231| -------- | ------------------------------------------------------------------------- | ----- | ---------------------------------------------------------- | 1232| type | string | 是 | 事件回调类型,支持的事件为'advertisingStateChange',表示广播状态事件。<br>当调用[ble.startAdvertising](#blestartadvertising11)、[ble.stopAdvertising](#blestopadvertising11)、[ble.enableAdvertising](#bleenableadvertising11)、[ble.disableAdvertising](#bledisableadvertising11),广播状态改变时,均会触发该事件。 | 1233| callback | Callback<[AdvertisingStateChangeInfo](#advertisingstatechangeinfo11)> | 是 | 指定订阅的回调函数,会携带广播状态信息。 | 1234 1235**错误码**: 1236 1237以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1238 1239| 错误码ID | 错误信息 | 1240| -------- | ---------------------------- | 1241|201 | Permission denied. | 1242|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1243|801 | Capability not supported. | 1244|2900099 | Operation failed. | 1245 1246**示例:** 1247 1248```js 1249import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1250function onReceiveEvent(data: ble.AdvertisingStateChangeInfo) { 1251 console.info('bluetooth advertising state = ' + JSON.stringify(data)); 1252} 1253try { 1254 ble.on('advertisingStateChange', onReceiveEvent); 1255} catch (err) { 1256 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1257} 1258``` 1259 1260 1261## ble.off('advertisingStateChange')<sup>11+</sup> 1262 1263off(type: 'advertisingStateChange', callback?: Callback<AdvertisingStateChangeInfo>): void 1264 1265取消订阅BLE广播状态。广播停止或启动将不再收到通知。 1266 1267**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1268 1269**系统能力**:SystemCapability.Communication.Bluetooth.Core 1270 1271**参数:** 1272 1273| 参数名 | 类型 | 必填 | 说明 | 1274| -------- | ------------------------------------------------------------------------- | ----- | ---------------------------------------------------------- | 1275| type | string | 是 | 事件回调类型,支持的事件为'advertisingStateChange',表示广播状态事件。 | 1276| callback | Callback<[AdvertisingStateChangeInfo](#advertisingstatechangeinfo11)> | 否 | 指定取消订阅的回调函数通知。<br>若传参,则需与[ble.on('advertisingStateChange')](#bleonadvertisingstatechange11)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 1277 1278**错误码**: 1279 1280以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1281 1282| 错误码ID | 错误信息 | 1283| -------- | ---------------------------- | 1284|201 | Permission denied. | 1285|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1286|801 | Capability not supported. | 1287|2900099 | Operation failed. | 1288 1289**示例:** 1290 1291```js 1292import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1293function onReceiveEvent(data: ble.AdvertisingStateChangeInfo) { 1294 console.info('bluetooth advertising state = ' + JSON.stringify(data)); 1295} 1296try { 1297 ble.on('advertisingStateChange', onReceiveEvent); 1298 ble.off('advertisingStateChange', onReceiveEvent); 1299} catch (err) { 1300 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1301} 1302``` 1303 1304 1305## ble.on('BLEDeviceFind') 1306 1307on(type: 'BLEDeviceFind', callback: Callback<Array<ScanResult>>): void 1308 1309订阅BLE设备扫描结果上报事件。使用Callback异步回调。 1310 1311**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1312 1313**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1314 1315**系统能力**:SystemCapability.Communication.Bluetooth.Core 1316 1317**参数:** 1318 1319| 参数名 | 类型 | 必填 | 说明 | 1320| -------- | ---------------------------------------- | ---- | ----------------------------------- | 1321| type | string | 是 | 事件回调类型,支持的事件为'BLEDeviceFind',表示BLE设备扫描结果上报事件。<br>当调用[ble.startBLEScan](#blestartblescan) 后,开始BLE扫描,若扫描到BLE设备,触发该事件。 | 1322| callback | Callback<Array<[ScanResult](#scanresult)>> | 是 | 指定订阅的回调函数,会携带扫描结果的集合。 | 1323 1324**错误码**: 1325 1326以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1327 1328| 错误码ID | 错误信息 | 1329| -------- | ---------------------------- | 1330|201 | Permission denied. | 1331|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1332|801 | Capability not supported. | 1333|2900099 | Operation failed. | 1334 1335**示例:** 1336 1337```js 1338import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1339function onReceiveEvent(data: Array<ble.ScanResult>) { 1340 console.info('bluetooth device find = '+ JSON.stringify(data)); 1341} 1342try { 1343 ble.on('BLEDeviceFind', onReceiveEvent); 1344} catch (err) { 1345 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1346} 1347``` 1348 1349 1350## ble.off('BLEDeviceFind') 1351 1352off(type: 'BLEDeviceFind', callback?: Callback<Array<ScanResult>>): void 1353 1354取消订阅BLE设备扫描结果上报事件。 1355- 若不再需要扫描BLE设备,调用[ble.stopBLEScan](#blestopblescan)方法后,需要调用此方法取消订阅。 1356 1357**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1358 1359**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1360 1361**系统能力**:SystemCapability.Communication.Bluetooth.Core 1362 1363**参数:** 1364 1365| 参数名 | 类型 | 必填 | 说明 | 1366| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 1367| type | string | 是 | 事件回调类型,支持的事件为'BLEDeviceFind',表示BLE设备扫描结果上报事件。 | 1368| callback | Callback<Array<[ScanResult](#scanresult)>> | 否 | 指定取消订阅的回调函数通知。<br>若传参,则需与[ble.on('BLEDeviceFind')](#bleonbledevicefind)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 1369 1370**错误码**: 1371 1372以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1373 1374 1375| 错误码ID | 错误信息 | 1376| -------- | ---------------------------- | 1377|201 | Permission denied. | 1378|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1379|801 | Capability not supported. | 1380|2900099 | Operation failed. | 1381 1382**示例:** 1383 1384```js 1385import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1386function onReceiveEvent(data: Array<ble.ScanResult>) { 1387 console.info('bluetooth device find = '+ JSON.stringify(data)); 1388} 1389try { 1390 ble.on('BLEDeviceFind', onReceiveEvent); 1391 ble.off('BLEDeviceFind', onReceiveEvent); 1392} catch (err) { 1393 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1394} 1395``` 1396 1397 1398## GattServer 1399 1400GATT通信中的服务端类。 1401- 通过[ble.createGattServer](#blecreategattserver)方法可以构造server实例。 1402- 通过该实例可以操作server端的行为,如添加服务[addService](#addservice)、通知特征值变化[notifyCharacteristicChanged](#notifycharacteristicchanged)等。 1403 1404 1405### addService 1406 1407addService(service: GattService): void 1408 1409server端添加服务。该操作会在蓝牙子系统中注册该服务,表示server端支持的能力。 1410 1411**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1412 1413**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1414 1415**系统能力**:SystemCapability.Communication.Bluetooth.Core 1416 1417**参数:** 1418 1419| 参数名 | 类型 | 必填 | 说明 | 1420| ------- | --------------------------- | ---- | ------------------------ | 1421| service | [GattService](#gattservice) | 是 | server端的service数据。表示支持的特定功能。<br>例如:00001800-0000-1000-8000-00805f9b34fb表示通用访问服务;00001801-0000-1000-8000-00805f9b34fb表示通用属性服务等。 | 1422 1423**错误码**: 1424 1425以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1426 1427| 错误码ID | 错误信息 | 1428| -------- | ---------------------------- | 1429|201 | Permission denied. | 1430|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1431|801 | Capability not supported. | 1432|2900001 | Service stopped. | 1433|2900003 | Bluetooth disabled. | 1434|2900099 | Operation failed. | 1435 1436**示例:** 1437 1438```js 1439import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1440// 创建descriptors。 1441let descriptors: Array<ble.BLEDescriptor> = []; 1442let arrayBuffer = new ArrayBuffer(2); 1443let descV = new Uint8Array(arrayBuffer); 1444descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 1445let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 1446 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 1447 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; 1448descriptors[0] = descriptor; 1449 1450// 创建characteristics。 1451let characteristics: Array<ble.BLECharacteristic> = []; 1452let arrayBufferC = new ArrayBuffer(8); 1453let cccV = new Uint8Array(arrayBufferC); 1454cccV[0] = 1; 1455let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 1456 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; 1457characteristics[0] = characteristic; 1458 1459// 创建gattService。 1460let gattService: ble.GattService = {serviceUuid:'00001810-0000-1000-8000-00805F9B34FB', isPrimary: true, characteristics:characteristics, includeServices:[]}; 1461 1462try { 1463 let gattServer: ble.GattServer = ble.createGattServer(); 1464 gattServer.addService(gattService); 1465} catch (err) { 1466 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1467} 1468``` 1469 1470 1471### removeService 1472 1473removeService(serviceUuid: string): void 1474 1475删除server端已添加的服务。 1476- 该服务曾通过[addService](#addservice)添加。 1477 1478**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1479 1480**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1481 1482**系统能力**:SystemCapability.Communication.Bluetooth.Core 1483 1484**参数:** 1485 1486| 参数名 | 类型 | 必填 | 说明 | 1487| ----------- | ------ | ---- | ---------------------------------------- | 1488| serviceUuid | string | 是 | 即将删除的服务的UUID。例如:00001810-0000-1000-8000-00805F9B34FB。 | 1489 1490**错误码**: 1491 1492以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1493 1494| 错误码ID | 错误信息 | 1495| -------- | ---------------------------- | 1496|201 | Permission denied. | 1497|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1498|801 | Capability not supported. | 1499|2900001 | Service stopped. | 1500|2900003 | Bluetooth disabled. | 1501|2900004 | Profile not supported. | 1502|2900099 | Operation failed. | 1503 1504**示例:** 1505 1506```js 1507import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1508let server: ble.GattServer = ble.createGattServer(); 1509try { 1510 // 调用removeService接口前需要完成server端和client端的配对及连接。 1511 server.removeService('00001810-0000-1000-8000-00805F9B34FB'); 1512} catch (err) { 1513 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1514} 1515``` 1516 1517 1518### close 1519 1520close(): void 1521 1522销毁server端实例。销毁后,通过[ble.createGattServer](#blecreategattserver)创建的实例将不可用。 1523 1524**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1525 1526**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1527 1528**系统能力**:SystemCapability.Communication.Bluetooth.Core 1529 1530**错误码**: 1531 1532以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1533 1534| 错误码ID | 错误信息 | 1535| -------- | ---------------------------- | 1536|201 | Permission denied. | 1537|801 | Capability not supported. | 1538|2900001 | Service stopped. | 1539|2900003 | Bluetooth disabled. | 1540|2900099 | Operation failed. | 1541 1542**示例:** 1543 1544```js 1545import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1546let server: ble.GattServer = ble.createGattServer(); 1547try { 1548 server.close(); 1549} catch (err) { 1550 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1551} 1552``` 1553 1554 1555### notifyCharacteristicChanged 1556 1557notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic, callback: AsyncCallback<void>): void 1558 1559server端发送特征值变化通知或者指示给client端。使用Callback异步回调。 1560 1561- 建议该特征值的Client Characteristic Configuration描述符(UUID:00002902-0000-1000-8000-00805f9b34fb)notification(通知)或indication(指示)能力已被使能。 1562- 蓝牙标准协议规定Client Characteristic Configuration描述符的数据内容长度为2字节,bit0和bit1分别表示notification(通知)和indication(指示)能力是否使能,例如bit0 = 1表示notification enabled。 1563- 该特征值数据内容变化时调用。 1564- [notifyCharacteristic](#notifycharacteristic)入参的characteristicValue数据长度默认限制为(MTU-3)字节,MTU大小可从订阅的回调[on('BLEMtuChange')](#onblemtuchange)获取。 1565 1566**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1567 1568**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1569 1570**系统能力**:SystemCapability.Communication.Bluetooth.Core 1571 1572**参数:** 1573 1574| 参数名 | 类型 | 必填 | 说明 | 1575| -------------------- | ---------------------------------------- | ---- | --------------------------------------- | 1576| deviceId | string | 是 | 接收通知的client设备地址。例如:“XX:XX:XX:XX:XX:XX”。 | 1577| notifyCharacteristic | [NotifyCharacteristic](#notifycharacteristic) | 是 | 通知给client的特征值数据对象。 | 1578| callback | AsyncCallback<void> | 是 | 回调函数。当通知成功,err为undefined,否则为错误对象。 | 1579 1580**错误码**: 1581 1582以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1583 1584| 错误码ID | 错误信息 | 1585| -------- | ---------------------------- | 1586|201 | Permission denied. | 1587|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1588|801 | Capability not supported. | 1589|2900001 | Service stopped. | 1590|2900003 | Bluetooth disabled. | 1591|2900099 | Operation failed. | 1592 1593**示例:** 1594 1595```js 1596import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1597let arrayBufferC = new ArrayBuffer(8); 1598let notifyCharacter: ble.NotifyCharacteristic = { 1599 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 1600 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 1601 characteristicValue: arrayBufferC, 1602 confirm: true 1603}; 1604try { 1605 let gattServer: ble.GattServer = ble.createGattServer(); 1606 gattServer.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacter, (err: BusinessError) => { 1607 if (err) { 1608 console.error('notifyCharacteristicChanged callback failed'); 1609 } else { 1610 console.info('notifyCharacteristicChanged callback successful'); 1611 } 1612 }); 1613} catch (err) { 1614 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1615} 1616``` 1617 1618 1619### notifyCharacteristicChanged 1620 1621notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): Promise<void> 1622 1623server端发送特征值变化通知或者指示给对端设备。使用Promise异步回调。 1624 1625- 建议该特征值的Client Characteristic Configuration描述符notification(通知)或indication(指示)能力已被使能。 1626- 蓝牙标准协议规定Client Characteristic Configuration描述符的数据内容长度为2字节,bit0和bit1分别表示notification(通知)和indication(指示)能力是否使能,例如bit0 = 1表示notification enabled。 1627- 该特征值数据内容变化时调用。 1628 1629**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1630 1631**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1632 1633**系统能力**:SystemCapability.Communication.Bluetooth.Core 1634 1635**参数:** 1636 1637| 参数名 | 类型 | 必填 | 说明 | 1638| -------------------- | ---------------------------------------- | ---- | --------------------------------------- | 1639| deviceId | string | 是 | 接收通知的client设备地址。例如:“XX:XX:XX:XX:XX:XX”。 | 1640| notifyCharacteristic | [NotifyCharacteristic](#notifycharacteristic) | 是 | 通知给client的特征值数据对象。 | 1641 1642**返回值:** 1643 1644| 类型 | 说明 | 1645| ------------------- | ------------- | 1646| Promise<void> | Promise对象。无返回结果的Promise对象。 | 1647 1648**错误码**: 1649 1650以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1651 1652| 错误码ID | 错误信息 | 1653| -------- | ---------------------------- | 1654|201 | Permission denied. | 1655|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1656|801 | Capability not supported. | 1657|2900001 | Service stopped. | 1658|2900003 | Bluetooth disabled. | 1659|2900099 | Operation failed. | 1660 1661**示例:** 1662 1663```js 1664import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1665let arrayBufferC = new ArrayBuffer(8); 1666let notifyCharacter: ble.NotifyCharacteristic = { 1667 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 1668 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 1669 characteristicValue: arrayBufferC, 1670 confirm: true 1671}; 1672try { 1673 let gattServer: ble.GattServer = ble.createGattServer(); 1674 gattServer.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacter).then(() => { 1675 console.info('notifyCharacteristicChanged promise successful'); 1676 }); 1677} catch (err) { 1678 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1679} 1680``` 1681 1682 1683### sendResponse 1684 1685sendResponse(serverResponse: ServerResponse): void 1686 1687server端收到client的请求操作后,需要调用此接口回复client,否则可能导致链路异常,超时后断连。 1688 1689client请求是指通过下述接口订阅回调收到的请求消息: 1690 1691- [on('characteristicRead')](#oncharacteristicread) 1692- [on('characteristicWrite')](#oncharacteristicwrite),需根据[CharacteristicWriteRequest](#characteristicwriterequest)中的needRsp决定是否需要回复。 1693- [on('descriptorRead')](#ondescriptorread) 1694- [on('descriptorWrite')](#ondescriptorwrite),需根据[DescriptorWriteRequest](#descriptorwriterequest)中的needRsp决定是否需要回复。 1695 1696**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1697 1698**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1699 1700**系统能力**:SystemCapability.Communication.Bluetooth.Core 1701 1702**参数:** 1703 1704| 参数名 | 类型 | 必填 | 说明 | 1705| -------------- | --------------------------------- | ---- | --------------- | 1706| serverResponse | [ServerResponse](#serverresponse) | 是 | server端回复client的响应数据。 | 1707 1708**错误码**: 1709 1710以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1711 1712| 错误码ID | 错误信息 | 1713| -------- | ---------------------------- | 1714|201 | Permission denied. | 1715|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1716|801 | Capability not supported. | 1717|2900001 | Service stopped. | 1718|2900003 | Bluetooth disabled. | 1719|2900099 | Operation failed. | 1720 1721**示例:** 1722 1723```js 1724import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1725/* send response */ 1726let arrayBufferCCC = new ArrayBuffer(8); 1727let cccValue = new Uint8Array(arrayBufferCCC); 1728cccValue[0] = 1; 1729let serverResponse: ble.ServerResponse = { 1730 deviceId: 'XX:XX:XX:XX:XX:XX', 1731 transId: 0, 1732 status: 0, 1733 offset: 0, 1734 value: arrayBufferCCC 1735}; 1736try { 1737 let gattServer: ble.GattServer = ble.createGattServer(); 1738 gattServer.sendResponse(serverResponse); 1739} catch (err) { 1740 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1741} 1742``` 1743 1744 1745### on('characteristicRead') 1746 1747on(type: 'characteristicRead', callback: Callback<CharacteristicReadRequest>): void 1748 1749server端订阅client的特征值读请求事件,server端收到该事件后需要调用[sendResponse](#sendresponse)接口回复client。使用Callback异步回调。 1750 1751**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1752 1753**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1754 1755**系统能力**:SystemCapability.Communication.Bluetooth.Core 1756 1757**参数:** 1758 1759| 参数名 | 类型 | 必填 | 说明 | 1760| -------- | ---------------------------------------- | ---- | ------------------------------------- | 1761| type | string | 是 | 事件回调类型,支持的事件为'characteristicRead',表示特征值读请求事件。<br>当收到client端设备的读取特征值请求时,触发该事件。 | 1762| callback | Callback<[CharacteristicReadRequest](#characteristicreadrequest)> | 是 | 指定订阅的回调函数,会携带client端发送的读请求数据。 | 1763 1764**错误码**: 1765 1766以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 1767 1768| 错误码ID | 错误信息 | 1769| -------- | ---------------------------- | 1770|201 | Permission denied. | 1771|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1772|801 | Capability not supported. | 1773 1774**示例:** 1775 1776```js 1777import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1778let arrayBufferCCC = new ArrayBuffer(8); 1779let cccValue = new Uint8Array(arrayBufferCCC); 1780cccValue[0] = 1; 1781let gattServer: ble.GattServer = ble.createGattServer(); 1782function ReadCharacteristicReq(characteristicReadRequest: ble.CharacteristicReadRequest) { 1783 let deviceId: string = characteristicReadRequest.deviceId; 1784 let transId: number = characteristicReadRequest.transId; 1785 let offset: number = characteristicReadRequest.offset; 1786 let characteristicUuid: string = characteristicReadRequest.characteristicUuid; 1787 1788 let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; 1789 1790 try { 1791 gattServer.sendResponse(serverResponse); 1792 } catch (err) { 1793 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1794 } 1795} 1796gattServer.on('characteristicRead', ReadCharacteristicReq); 1797``` 1798 1799 1800### off('characteristicRead') 1801 1802off(type: 'characteristicRead', callback?: Callback<CharacteristicReadRequest>): void 1803 1804server端取消订阅client的特征值读请求事件。 1805 1806**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1807 1808**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1809 1810**系统能力**:SystemCapability.Communication.Bluetooth.Core 1811 1812**参数:** 1813 1814| 参数名 | 类型 | 必填 | 说明 | 1815| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 1816| type | string | 是 | 事件回调类型,支持的事件为'characteristicRead',表示特征值读请求事件。 | 1817| callback | Callback<[CharacteristicReadRequest](#characteristicreadrequest)> | 否 | 指定取消订阅的回调函数通知。<br>若传参,则需与[on('characteristicRead')](#oncharacteristicread)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 1818 1819**错误码**: 1820 1821以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 1822 1823| 错误码ID | 错误信息 | 1824| -------- | ---------------------------- | 1825|201 | Permission denied. | 1826|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1827|801 | Capability not supported. | 1828 1829**示例:** 1830 1831```js 1832import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1833try { 1834 let gattServer: ble.GattServer = ble.createGattServer(); 1835 gattServer.off('characteristicRead'); 1836} catch (err) { 1837 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 1838} 1839``` 1840 1841 1842### on('characteristicWrite') 1843 1844on(type: 'characteristicWrite', callback: Callback<CharacteristicWriteRequest>): void 1845 1846server端订阅client的特征值写请求事件,server端收到该事件后需要根据[CharacteristicWriteRequest](#characteristicwriterequest)中的needRsp决定是否调用[sendResponse](#sendresponse)接口回复client。 1847 1848**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1849 1850**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1851 1852**系统能力**:SystemCapability.Communication.Bluetooth.Core 1853 1854**参数:** 1855 1856| 参数名 | 类型 | 必填 | 说明 | 1857| -------- | ---------------------------------------- | ---- | -------------------------------------- | 1858| type | string | 是 | 事件回调类型,支持的事件为'characteristicWrite',表示特征值写请求事件。<br>当收到client端设备的写特征值请求时,触发该事件。 | 1859| callback | Callback<[CharacteristicWriteRequest](#characteristicwriterequest)> | 是 | 指定订阅的回调函数,会携带client端发送的写请求数据。 | 1860 1861**错误码**: 1862 1863以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 1864 1865| 错误码ID | 错误信息 | 1866| -------- | ---------------------------- | 1867|201 | Permission denied. | 1868|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1869|801 | Capability not supported. | 1870 1871**示例:** 1872 1873```js 1874import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1875let arrayBufferCCC = new ArrayBuffer(8); 1876let cccValue = new Uint8Array(arrayBufferCCC); 1877let gattServer: ble.GattServer = ble.createGattServer(); 1878function WriteCharacteristicReq(characteristicWriteRequest: ble.CharacteristicWriteRequest) { 1879 let deviceId: string = characteristicWriteRequest.deviceId; 1880 let transId: number = characteristicWriteRequest.transId; 1881 let offset: number = characteristicWriteRequest.offset; 1882 let isPrepared: boolean = characteristicWriteRequest.isPrepared; 1883 let needRsp: boolean = characteristicWriteRequest.needRsp; 1884 let value: Uint8Array = new Uint8Array(characteristicWriteRequest.value); 1885 let characteristicUuid: string = characteristicWriteRequest.characteristicUuid; 1886 1887 cccValue[0] = value[0]; 1888 let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; 1889 1890 try { 1891 gattServer.sendResponse(serverResponse); 1892 } catch (err) { 1893 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1894 } 1895} 1896gattServer.on('characteristicWrite', WriteCharacteristicReq); 1897``` 1898 1899 1900### off('characteristicWrite') 1901 1902off(type: 'characteristicWrite', callback?: Callback<CharacteristicWriteRequest>): void 1903 1904server端取消订阅client的特征值写请求事件。 1905 1906**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1907 1908**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1909 1910**系统能力**:SystemCapability.Communication.Bluetooth.Core 1911 1912**参数:** 1913 1914| 参数名 | 类型 | 必填 | 说明 | 1915| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 1916| type | string | 是 | 事件回调类型,支持的事件为'characteristicWrite',表示特征值写请求事件。 | 1917| callback | Callback<[CharacteristicWriteRequest](#characteristicwriterequest)> | 否 | 指定取消订阅的回调函数通知。<br>若传参,则需与[on('characteristicWrite')](#oncharacteristicwrite)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 1918 1919**错误码**: 1920 1921以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 1922 1923| 错误码ID | 错误信息 | 1924| -------- | ---------------------------- | 1925|201 | Permission denied. | 1926|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1927|801 | Capability not supported. | 1928 1929**示例:** 1930 1931```js 1932import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1933try { 1934 let gattServer: ble.GattServer = ble.createGattServer(); 1935 gattServer.off('characteristicWrite'); 1936} catch (err) { 1937 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 1938} 1939``` 1940 1941 1942### on('descriptorRead') 1943 1944on(type: 'descriptorRead', callback: Callback<DescriptorReadRequest>): void 1945 1946server端订阅client的描述符读请求事件,server端收到该事件后需要调用[sendResponse](#sendresponse)接口回复client。 1947 1948**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1949 1950**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1951 1952**系统能力**:SystemCapability.Communication.Bluetooth.Core 1953 1954**参数:** 1955 1956| 参数名 | 类型 | 必填 | 说明 | 1957| -------- | ---------------------------------------- | ---- | --------------------------------- | 1958| type | string | 是 | 事件回调类型,支持的事件为'descriptorRead',表示描述符读请求事件。<br>当收到client端设备的读取描述符请求时,触发该事件。 | 1959| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | 是 | 指定订阅的回调函数,会携带client端发送的读请求数据。 | 1960 1961**错误码**: 1962 1963以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 1964 1965| 错误码ID | 错误信息 | 1966| -------- | ---------------------------- | 1967|201 | Permission denied. | 1968|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1969|801 | Capability not supported. | 1970 1971**示例:** 1972 1973```js 1974import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1975let arrayBufferDesc = new ArrayBuffer(8); 1976let descValue = new Uint8Array(arrayBufferDesc); 1977descValue[0] = 1; 1978let gattServer: ble.GattServer = ble.createGattServer(); 1979function ReadDescriptorReq(descriptorReadRequest: ble.DescriptorReadRequest) { 1980 let deviceId: string = descriptorReadRequest.deviceId; 1981 let transId: number = descriptorReadRequest.transId; 1982 let offset: number = descriptorReadRequest.offset; 1983 let descriptorUuid: string = descriptorReadRequest.descriptorUuid; 1984 1985 let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; 1986 1987 try { 1988 gattServer.sendResponse(serverResponse); 1989 } catch (err) { 1990 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1991 } 1992} 1993gattServer.on('descriptorRead', ReadDescriptorReq); 1994``` 1995 1996 1997### off('descriptorRead') 1998 1999off(type: 'descriptorRead', callback?: Callback<DescriptorReadRequest>): void 2000 2001server端取消订阅client的描述符读请求事件。 2002 2003**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2004 2005**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2006 2007**系统能力**:SystemCapability.Communication.Bluetooth.Core 2008 2009**参数:** 2010 2011| 参数名 | 类型 | 必填 | 说明 | 2012| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2013| type | string | 是 | 事件回调类型,支持的事件为'descriptorRead',表示描述符读请求事件。 | 2014| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | 否 | 指定取消订阅的回调函数通知。<br>若传参,则需与[on('descriptorRead')](#ondescriptorread)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 2015 2016**错误码**: 2017 2018以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 2019 2020| 错误码ID | 错误信息 | 2021| -------- | ---------------------------- | 2022|201 | Permission denied. | 2023|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2024|801 | Capability not supported. | 2025 2026**示例:** 2027 2028```js 2029import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2030try { 2031 let gattServer: ble.GattServer = ble.createGattServer(); 2032 gattServer.off('descriptorRead'); 2033} catch (err) { 2034 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 2035} 2036``` 2037 2038 2039### on('descriptorWrite') 2040 2041on(type: 'descriptorWrite', callback: Callback<DescriptorWriteRequest>): void 2042 2043server端订阅client的描述符写请求事件,server端收到该事件后需要根据[DescriptorWriteRequest](#descriptorwriterequest)里的needRsp决定是否调用[sendResponse](#sendresponse)接口回复client。 2044 2045**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2046 2047**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2048 2049**系统能力**:SystemCapability.Communication.Bluetooth.Core 2050 2051**参数:** 2052 2053| 参数名 | 类型 | 必填 | 说明 | 2054| -------- | ---------------------------------------- | ---- | ---------------------------------- | 2055| type | string | 是 | 事件回调类型,支持的事件为'descriptorWrite',表示描述符写请求事件。<br>当收到client端设备的写描述符请求时,触发该事件。 | 2056| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | 是 | 指定订阅的回调函数,会携带client端发送的写请求数据。 | 2057 2058**错误码**: 2059 2060以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 2061 2062| 错误码ID | 错误信息 | 2063| -------- | ---------------------------- | 2064|201 | Permission denied. | 2065|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2066|801 | Capability not supported. | 2067 2068**示例:** 2069 2070```js 2071import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2072let arrayBufferDesc = new ArrayBuffer(8); 2073let descValue = new Uint8Array(arrayBufferDesc); 2074let gattServer: ble.GattServer = ble.createGattServer(); 2075function WriteDescriptorReq(descriptorWriteRequest: ble.DescriptorWriteRequest) { 2076 let deviceId: string = descriptorWriteRequest.deviceId; 2077 let transId: number = descriptorWriteRequest.transId; 2078 let offset: number = descriptorWriteRequest.offset; 2079 let isPrepared: boolean = descriptorWriteRequest.isPrepared; 2080 let needRsp: boolean = descriptorWriteRequest.needRsp; 2081 let value: Uint8Array = new Uint8Array(descriptorWriteRequest.value); 2082 let descriptorUuid: string = descriptorWriteRequest.descriptorUuid; 2083 2084 descValue[0] = value[0]; 2085 let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; 2086 2087 try { 2088 gattServer.sendResponse(serverResponse); 2089 } catch (err) { 2090 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2091 } 2092} 2093gattServer.on('descriptorWrite', WriteDescriptorReq); 2094``` 2095 2096 2097### off('descriptorWrite') 2098 2099off(type: 'descriptorWrite', callback?: Callback<DescriptorWriteRequest>): void 2100 2101server端取消订阅client的描述符写请求事件。 2102 2103**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2104 2105**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2106 2107**系统能力**:SystemCapability.Communication.Bluetooth.Core 2108 2109**参数:** 2110 2111| 参数名 | 类型 | 必填 | 说明 | 2112| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2113| type | string | 是 | 事件回调类型,支持的事件为'descriptorWrite',表示描述符写请求事件。 | 2114| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | 否 | 指定取消订阅的回调函数通知。<br>若传参,则需与[on('descriptorWrite')](#ondescriptorwrite)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 2115 2116**错误码**: 2117 2118以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 2119 2120| 错误码ID | 错误信息 | 2121| -------- | ---------------------------- | 2122|201 | Permission denied. | 2123|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2124|801 | Capability not supported. | 2125 2126**示例:** 2127 2128```js 2129import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2130try { 2131let gattServer: ble.GattServer = ble.createGattServer(); 2132gattServer.off('descriptorWrite'); 2133} catch (err) { 2134 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 2135} 2136``` 2137 2138 2139### on('connectionStateChange') 2140 2141on(type: 'connectionStateChange', callback: Callback<BLEConnectionChangeState>): void 2142 2143server端订阅GATT profile协议的连接状态变化事件。使用Callback异步回调。 2144 2145**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2146 2147**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2148 2149**系统能力**:SystemCapability.Communication.Bluetooth.Core 2150 2151**参数:** 2152 2153| 参数名 | 类型 | 必填 | 说明 | 2154| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2155| type | string | 是 | 事件回调类型,支持的事件为'connectionStateChange',表示GATT profile连接状态发生变化的事件。<br>当client和server端之间的连接状态发生变化时,触发该事件。<br>例如:收到连接请求或者断连请求时,可能引起连接状态生变化。 | 2156| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | 是 | 指定订阅的回调函数,会携带连接状态。 | 2157 2158**错误码**: 2159 2160以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 2161 2162| 错误码ID | 错误信息 | 2163| -------- | ---------------------------- | 2164|201 | Permission denied. | 2165|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2166|801 | Capability not supported. | 2167 2168**示例:** 2169 2170```js 2171import { constant } from '@kit.ConnectivityKit'; 2172import { BusinessError } from '@kit.BasicServicesKit'; 2173let connected = (bleConnectionChangeState: ble.BLEConnectionChangeState) => { 2174 let deviceId: string = bleConnectionChangeState.deviceId; 2175 let status: constant.ProfileConnectionState = bleConnectionChangeState.state; 2176} 2177try { 2178 let gattServer: ble.GattServer = ble.createGattServer(); 2179 gattServer.on('connectionStateChange', connected); 2180} catch (err) { 2181 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 2182} 2183``` 2184 2185 2186### off('connectionStateChange') 2187 2188off(type: 'connectionStateChange', callback?: Callback<BLEConnectionChangeState>): void 2189 2190server端取消订阅GATT profile协议的连接状态变化事件。 2191 2192**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2193 2194**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2195 2196**系统能力**:SystemCapability.Communication.Bluetooth.Core 2197 2198**参数:** 2199 2200| 参数名 | 类型 | 必填 | 说明 | 2201| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2202| type | string | 是 | 事件回调类型,支持的事件为'connectionStateChange',表示GATT profile连接状态发生变化的事件。 | 2203| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | 否 | 指定取消订阅的回调函数通知。<br>若传参,则需与[on('connectionStateChange')](#onconnectionstatechange)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 2204 2205**错误码**: 2206 2207以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 2208 2209| 错误码ID | 错误信息 | 2210| -------- | ---------------------------- | 2211|201 | Permission denied. | 2212|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2213|801 | Capability not supported. | 2214 2215**示例:** 2216 2217```js 2218import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2219try { 2220 let gattServer: ble.GattServer = ble.createGattServer(); 2221 gattServer.off('connectionStateChange'); 2222} catch (err) { 2223 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 2224} 2225``` 2226 2227 2228### on('BLEMtuChange') 2229 2230on(type: 'BLEMtuChange', callback: Callback<number>): void 2231 2232server端订阅MTU(最大传输单元)大小变更事件。使用Callback异步回调。 2233 2234**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2235 2236**系统能力**:SystemCapability.Communication.Bluetooth.Core 2237 2238**参数:** 2239 2240| 参数名 | 类型 | 必填 | 说明 | 2241| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2242| type | string | 是 | 事件回调类型,支持的事件为'BLEMtuChange',表示MTU状态变化事件。<br>当收到了client端发起了MTU协商请求时,触发该事件。 | 2243| callback | Callback<number> | 是 | 指定订阅的回调函数,会携带协商后的MTU大小。单位:Byte。 | 2244 2245**错误码**: 2246 2247以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 2248 2249| 错误码ID | 错误信息 | 2250| -------- | ---------------------------- | 2251|201 | Permission denied. | 2252|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2253|801 | Capability not supported. | 2254 2255**示例:** 2256 2257```js 2258import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2259try { 2260 let gattServer: ble.GattServer = ble.createGattServer(); 2261 gattServer.on('BLEMtuChange', (mtu: number) => { 2262 console.info('BLEMtuChange, mtu: ' + mtu); 2263 }); 2264} catch (err) { 2265 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2266} 2267``` 2268 2269 2270### off('BLEMtuChange') 2271 2272off(type: 'BLEMtuChange', callback?: Callback<number>): void 2273 2274server端取消订阅MTU(最大传输单元)大小变更事件。 2275 2276**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2277 2278**系统能力**:SystemCapability.Communication.Bluetooth.Core 2279 2280**参数:** 2281 2282| 参数名 | 类型 | 必填 | 说明 | 2283| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2284| type | string | 是 | 事件回调类型,支持的事件为"BLEMtuChange",表示MTU状态变化事件。 | 2285| callback | Callback<number> | 否 | 指定取消订阅的回调函数通知。<br>若传参,则需与[on('BLEMtuChange')](#onblemtuchange)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 2286 2287**错误码**: 2288 2289以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 2290 2291| 错误码ID | 错误信息 | 2292| -------- | ---------------------------- | 2293|201 | Permission denied. | 2294|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2295|801 | Capability not supported. | 2296 2297**示例:** 2298 2299```js 2300import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2301try { 2302 let gattServer: ble.GattServer = ble.createGattServer(); 2303 gattServer.off('BLEMtuChange'); 2304} catch (err) { 2305 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2306} 2307``` 2308 2309 2310## GattClientDevice 2311 2312GATT客户端类,提供了和服务端进行连接和数据传输等操作方法。 2313 2314- 使用该类的方法前,需通过[createGattClientDevice](#blecreategattclientdevice)方法构造该类的实例。 2315- 通过创建不同的该类实例,可以管理多路GATT连接。 2316 2317### connect 2318 2319connect(): void 2320 2321client端主动发起和server蓝牙设备的GATT协议连接。 2322 2323- 远端设备地址已通过[createGattClientDevice](#blecreategattclientdevice)方法中的deviceId参数指定。 2324- client可通过订阅[on('BLEConnectionStateChange')](#onbleconnectionstatechange)事件来感知连接是否成功。 2325 2326**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2327 2328**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2329 2330**系统能力**:SystemCapability.Communication.Bluetooth.Core 2331 2332**错误码**: 2333 2334以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2335 2336| 错误码ID | 错误信息 | 2337| -------- | ---------------------------- | 2338|201 | Permission denied. | 2339|801 | Capability not supported. | 2340|2900001 | Service stopped. | 2341|2900003 | Bluetooth disabled. | 2342|2900099 | Operation failed. | 2343 2344**示例:** 2345 2346```js 2347import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2348try { 2349 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2350 device.connect(); 2351} catch (err) { 2352 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2353} 2354``` 2355 2356 2357### disconnect 2358 2359disconnect(): void 2360 2361client断开与远端蓝牙低功耗设备的连接。 2362 2363- client可通过订阅[on('BLEConnectionStateChange')](#onbleconnectionstatechange)事件来感知连接是否成功。 2364 2365**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2366 2367**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2368 2369**系统能力**:SystemCapability.Communication.Bluetooth.Core 2370 2371**错误码**: 2372 2373以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2374 2375| 错误码ID | 错误信息 | 2376| -------- | ---------------------------- | 2377|201 | Permission denied. | 2378|801 | Capability not supported. | 2379|2900001 | Service stopped. | 2380|2900003 | Bluetooth disabled. | 2381|2900099 | Operation failed. | 2382 2383**示例:** 2384 2385```js 2386import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2387try { 2388 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2389 device.disconnect(); 2390} catch (err) { 2391 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2392} 2393``` 2394 2395 2396### close 2397 2398close(): void 2399 2400销毁client端实例。销毁后,通过[GattClientDevice](#gattclientdevice)创建的实例将不可用。 2401 2402**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2403 2404**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2405 2406**系统能力**:SystemCapability.Communication.Bluetooth.Core 2407 2408**错误码**: 2409 2410以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2411 2412| 错误码ID | 错误信息 | 2413| -------- | ---------------------------- | 2414|201 | Permission denied. | 2415|801 | Capability not supported. | 2416|2900001 | Service stopped. | 2417|2900003 | Bluetooth disabled. | 2418|2900099 | Operation failed. | 2419 2420**示例:** 2421 2422```js 2423import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2424try { 2425 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2426 device.close(); 2427} catch (err) { 2428 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2429} 2430``` 2431 2432 2433### getDeviceName 2434 2435getDeviceName(callback: AsyncCallback<string>): void 2436 2437client获取server端设备名称。使用Callback异步回调。 2438 2439**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2440 2441**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2442 2443**系统能力**:SystemCapability.Communication.Bluetooth.Core 2444 2445**参数:** 2446 2447| 参数名 | 类型 | 必填 | 说明 | 2448| -------- | --------------------------- | ---- | ------------------------------- | 2449| callback | AsyncCallback<string> | 是 | 回调函数。当读取成功,err为undefined,data为server端设备名称。 | 2450 2451**错误码**: 2452 2453以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2454 2455| 错误码ID | 错误信息 | 2456| -------- | ---------------------------- | 2457|201 | Permission denied. | 2458|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 2459|801 | Capability not supported. | 2460|2900001 | Service stopped. | 2461|2900099 | Operation failed. | 2462 2463**示例:** 2464 2465```js 2466import { ble, constant } from '@kit.ConnectivityKit'; 2467import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2468let gattClient: ble.GattClientDevice = ble.createGattClientDevice("11:22:33:44:55:66"); 2469function ConnectStateChanged(state: ble.BLEConnectionChangeState) { 2470 console.info('bluetooth connect state changed'); 2471 let connectState: ble.ProfileConnectionState = state.state; 2472 if (connectState == constant.ProfileConnectionState.STATE_CONNECTED) { 2473 gattClient.getDeviceName((err: BusinessError, data: string)=> { 2474 console.info('device name err ' + JSON.stringify(err)); 2475 console.info('device name' + JSON.stringify(data)); 2476 }) 2477 } 2478} 2479// callback 2480try { 2481 gattClient.connect(); 2482} catch (err) { 2483 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2484} 2485``` 2486 2487 2488### getDeviceName 2489 2490getDeviceName(): Promise<string> 2491 2492client获取远端蓝牙低功耗设备的名称。使用Promise异步回调。 2493 2494**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2495 2496**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2497 2498**系统能力**:SystemCapability.Communication.Bluetooth.Core 2499 2500**返回值:** 2501 2502| 类型 | 说明 | 2503| --------------------- | ---------------------------------- | 2504| Promise<string> | Promise对象,携带server端设备名称。 | 2505 2506**错误码**: 2507 2508以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2509 2510| 错误码ID | 错误信息 | 2511| -------- | ---------------------------- | 2512|201 | Permission denied. | 2513|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 2514|801 | Capability not supported. | 2515|2900001 | Service stopped. | 2516|2900099 | Operation failed. | 2517 2518**示例:** 2519 2520```js 2521import { ble, constant } from '@kit.ConnectivityKit'; 2522import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2523let gattClient: ble.GattClientDevice = ble.createGattClientDevice("11:22:33:44:55:66"); 2524gattClient.on('BLEConnectionStateChange', ConnectStateChanged); 2525function ConnectStateChanged(state: ble.BLEConnectionChangeState) { 2526 console.info('bluetooth connect state changed'); 2527 let connectState: ble.ProfileConnectionState = state.state; 2528 if (connectState == constant.ProfileConnectionState.STATE_CONNECTED) { 2529 gattClient.getDeviceName().then((data: string) => { 2530 console.info('device name' + JSON.stringify(data)); 2531 }) 2532 } 2533} 2534// promise 2535try { 2536 gattClient.connect(); 2537} catch (err) { 2538 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2539} 2540``` 2541 2542 2543### getServices 2544 2545getServices(callback: AsyncCallback<Array<GattService>>): void 2546 2547client获取server端支持的所有服务能力,即服务发现流程。使用Callback异步回调。 2548 2549应用调用该方法后,才能调用其他读写特征值、描述符等其他方法,且需确保server支持的服务能力中包含需要操作的特征值或描述符。包含接口如下所示: 2550 2551- [readCharacteristicValue](#readcharacteristicvalue) 2552- [readDescriptorValue](#readdescriptorvalue) 2553- [writeCharacteristicValue](#writecharacteristicvalue) 2554- [writeDescriptorValue](#writedescriptorvalue) 2555- [setCharacteristicChangeNotification](#setcharacteristicchangenotification) 2556- [setCharacteristicChangeIndication](#setcharacteristicchangeindication) 2557 2558**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2559 2560**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2561 2562**系统能力**:SystemCapability.Communication.Bluetooth.Core 2563 2564**参数:** 2565 2566| 参数名 | 类型 | 必填 | 说明 | 2567| -------- | ---------------------------------------- | ---- | ------------------------ | 2568| callback | AsyncCallback<Array<[GattService](#gattservice)>> | 是 | 回调函数。当读取成功,err为undefined,data为server端的服务列表。 | 2569 2570**错误码**: 2571 2572以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2573 2574| 错误码ID | 错误信息 | 2575| -------- | ---------------------------- | 2576|201 | Permission denied. | 2577|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 2578|801 | Capability not supported. | 2579|2900001 | Service stopped. | 2580|2900099 | Operation failed. | 2581 2582**示例:** 2583 2584```js 2585import { ble, constant } from '@kit.ConnectivityKit'; 2586import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2587// callback 模式。 2588let getServices = (code: BusinessError, gattServices: Array<ble.GattService>) => { 2589 if (code && code.code != 0) { 2590 console.info('bluetooth code is ' + code.code); 2591 return; 2592 } 2593 let services: Array<ble.GattService> = gattServices; 2594 console.info('bluetooth services size is ', services.length); 2595 for (let i = 0; i < services.length; i++) { 2596 console.info('bluetooth serviceUuid is ' + services[i].serviceUuid); 2597 } 2598} 2599let device: ble.GattClientDevice = ble.createGattClientDevice("11:22:33:44:55:66"); 2600function ConnectStateChanged(state: ble.BLEConnectionChangeState) { 2601 console.info('bluetooth connect state changed'); 2602 let connectState: ble.ProfileConnectionState = state.state; 2603 if (connectState == constant.ProfileConnectionState.STATE_CONNECTED) { 2604 device.getServices(getServices); 2605 } 2606} 2607 2608try { 2609 device.connect(); 2610} catch (err) { 2611 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2612} 2613``` 2614 2615 2616### getServices 2617 2618getServices(): Promise<Array<GattService>> 2619 2620client端获取蓝牙低功耗设备的所有服务,即服务发现。使用Promise异步回调。 2621 2622**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2623 2624**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2625 2626**系统能力**:SystemCapability.Communication.Bluetooth.Core 2627 2628**返回值:** 2629 2630| 类型 | 说明 | 2631| ---------------------------------------- | --------------------------- | 2632| Promise<Array<[GattService](#gattservice)>> | Promise对象,返回获取到的server端服务列表。 | 2633 2634**错误码**: 2635 2636以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2637 2638| 错误码ID | 错误信息 | 2639| -------- | ---------------------------- | 2640|201 | Permission denied. | 2641|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2642|801 | Capability not supported. | 2643|2900001 | Service stopped. | 2644|2900099 | Operation failed. | 2645 2646**示例:** 2647 2648```js 2649import { ble, constant } from '@kit.ConnectivityKit'; 2650import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2651// Promise 模式。 2652let device: ble.GattClientDevice = ble.createGattClientDevice("11:22:33:44:55:66"); 2653function ConnectStateChanged(state: ble.BLEConnectionChangeState) { 2654 console.info('bluetooth connect state changed'); 2655 let connectState: ble.ProfileConnectionState = state.state; 2656 if (connectState == constant.ProfileConnectionState.STATE_CONNECTED) { 2657 device.getServices().then((result: Array<ble.GattService>) => { 2658 console.info('getServices successfully:' + JSON.stringify(result)); 2659 }); 2660 } 2661} 2662try { 2663 device.connect(); 2664} catch (err) { 2665 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2666} 2667``` 2668 2669 2670### readCharacteristicValue 2671 2672readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void 2673 2674client端从指定的server端特征值读取数据。使用Callback异步回调。<br> 2675- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且包含指定的入参特征值UUID;否则会读取失败。<br> 2676- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。<br> 2677- 读取特征值过程中,需确保[BLECharacteristic](#blecharacteristic)入参特征值的serviceUuid、characteristicUuid准确。characteristicValue表示的数据内容长度可由用户任意指定,不会影响实际读取到的特征值数据内容。 2678 2679**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2680 2681**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2682 2683**系统能力**:SystemCapability.Communication.Bluetooth.Core 2684 2685**参数:** 2686 2687| 参数名 | 类型 | 必填 | 说明 | 2688| -------------- | ---------------------------------------- | ---- | ----------------------- | 2689| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 需要读取的特征值。 | 2690| callback | AsyncCallback<[BLECharacteristic](#blecharacteristic)> | 是 | 回调函数。当读取成功,err为undefined,data为获取到的特征值对象,包含读取到的数据内容;否则为错误对象。 | 2691 2692**错误码**: 2693 2694以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2695 2696| 错误码ID | 错误信息 | 2697| -------- | ---------------------------- | 2698|201 | Permission denied. | 2699|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2700|801 | Capability not supported. | 2701|2900001 | Service stopped. | 2702|2900011 | The operation is busy. The last operation is not complete. | 2703|2900099 | Operation failed. | 2704|2901000 | Read forbidden. | 2705|2901003 | The connection is not established. | 2706|2901004 | The connection is congested. | 2707|2901005 | The connection is not encrypted. | 2708|2901006 | The connection is not authenticated. | 2709|2901007 | The connection is not authorized. | 2710 2711**示例:** 2712 2713```js 2714import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2715function readCcc(code: BusinessError, BLECharacteristic: ble.BLECharacteristic) { 2716 if (code.code != 0) { 2717 return; 2718 } 2719 console.info('bluetooth characteristic uuid: ' + BLECharacteristic.characteristicUuid); 2720 let value = new Uint8Array(BLECharacteristic.characteristicValue); 2721 console.info('bluetooth characteristic value: ' + value[0]); 2722} 2723 2724let descriptors: Array<ble.BLEDescriptor> = []; 2725let bufferDesc = new ArrayBuffer(2); 2726let descV = new Uint8Array(bufferDesc); 2727descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 2728let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2729characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2730descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; 2731descriptors[0] = descriptor; 2732 2733let bufferCCC = new ArrayBuffer(8); 2734let cccV = new Uint8Array(bufferCCC); 2735cccV[0] = 1; 2736let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2737characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2738characteristicValue: bufferCCC, descriptors:descriptors}; 2739 2740try { 2741 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2742 device.readCharacteristicValue(characteristic, readCcc); 2743} catch (err) { 2744 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2745} 2746``` 2747 2748 2749### readCharacteristicValue 2750 2751readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic> 2752 2753client端从指定的server端特征值读取数据。使用Promise异步回调。<br> 2754- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且包含指定的入参特征值UUID;否则会读取失败。<br> 2755- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。<br> 2756- 读取特征值过程中,需确保[BLECharacteristic](#blecharacteristic)入参特征值的serviceUuid、characteristicUuid准确。characteristicValue表示的数据内容长度可由用户任意指定,不会影响实际读取到的特征值数据内容。 2757 2758**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2759 2760**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2761 2762**系统能力**:SystemCapability.Communication.Bluetooth.Core 2763 2764**参数:** 2765 2766| 参数名 | 类型 | 必填 | 说明 | 2767| -------------- | --------------------------------------- | ---- | -------- | 2768| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 需要读取的特征值。 | 2769 2770**返回值:** 2771 2772| 类型 | 说明 | 2773| ---------------------------------------- | -------------------------- | 2774| Promise<[BLECharacteristic](#blecharacteristic)> | Promise对象,返回获取到的特征值对象,包含读取到的数据内容。 | 2775 2776**错误码**: 2777 2778以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2779 2780| 错误码ID | 错误信息 | 2781| -------- | ---------------------------- | 2782|201 | Permission denied. | 2783|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2784|801 | Capability not supported. | 2785|2900001 | Service stopped. | 2786|2900011 | The operation is busy. The last operation is not complete. | 2787|2900099 | Operation failed. | 2788|2901000 | Read forbidden. | 2789|2901003 | The connection is not established. | 2790|2901004 | The connection is congested. | 2791|2901005 | The connection is not encrypted. | 2792|2901006 | The connection is not authenticated. | 2793|2901007 | The connection is not authorized. | 2794 2795**示例:** 2796 2797```js 2798import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2799let descriptors: Array<ble.BLEDescriptor> = []; 2800let bufferDesc = new ArrayBuffer(2); 2801let descV = new Uint8Array(bufferDesc); 2802descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 2803let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2804characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2805descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; 2806descriptors[0] = descriptor; 2807 2808let bufferCCC = new ArrayBuffer(8); 2809let cccV = new Uint8Array(bufferCCC); 2810cccV[0] = 1; 2811let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2812characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2813characteristicValue: bufferCCC, descriptors:descriptors}; 2814 2815try { 2816 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2817 device.readCharacteristicValue(characteristic); 2818} catch (err) { 2819 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2820} 2821``` 2822 2823 2824### readDescriptorValue 2825 2826readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void 2827 2828client端从指定的server端描述符读取数据。使用Callback异步回调。<br> 2829- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且包含指定的入参描述符UUID;否则会读取失败。<br> 2830- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。 2831- 读取描述符过程中,需确保[BLEDescriptor](#bledescriptor)入参描述符的serviceUuid、characteristicUuid、descriptorUuid准确。descriptorValue表示的数据内容长度可由用户任意指定,不会影响实际读取到的描述符数据内容。 2832 2833**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2834 2835**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2836 2837**系统能力**:SystemCapability.Communication.Bluetooth.Core 2838 2839**参数:** 2840 2841| 参数名 | 类型 | 必填 | 说明 | 2842| ---------- | ---------------------------------------- | ---- | ----------------------- | 2843| descriptor | [BLEDescriptor](#bledescriptor) | 是 | 需要读取的描述符。 | 2844| callback | AsyncCallback<[BLEDescriptor](#bledescriptor)> | 是 | 回调函数。当读取成功,err为undefined,data为获取到的描述符对象,包含读取到的数据内容;否则为错误对象。 | 2845 2846**错误码**: 2847 2848以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2849 2850| 错误码ID | 错误信息 | 2851| -------- | ---------------------------- | 2852|201 | Permission denied. | 2853|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2854|801 | Capability not supported. | 2855|2900001 | Service stopped. | 2856|2900011 | The operation is busy. The last operation is not complete. | 2857|2900099 | Operation failed. | 2858|2901000 | Read forbidden. | 2859|2901003 | The connection is not established. | 2860|2901004 | The connection is congested. | 2861|2901005 | The connection is not encrypted. | 2862|2901006 | The connection is not authenticated. | 2863|2901007 | The connection is not authorized. | 2864 2865**示例:** 2866 2867```js 2868import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2869function readDesc(code: BusinessError, BLEDescriptor: ble.BLEDescriptor) { 2870 if (code.code != 0) { 2871 return; 2872 } 2873 console.info('bluetooth descriptor uuid: ' + BLEDescriptor.descriptorUuid); 2874 let value = new Uint8Array(BLEDescriptor.descriptorValue); 2875 console.info('bluetooth descriptor value: ' + value[0]); 2876} 2877 2878let bufferDesc = new ArrayBuffer(2); 2879let descV = new Uint8Array(bufferDesc); 2880descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 2881let descriptor: ble.BLEDescriptor = { 2882 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2883 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2884 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', 2885 descriptorValue: bufferDesc 2886}; 2887try { 2888 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2889 device.readDescriptorValue(descriptor, readDesc); 2890} catch (err) { 2891 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2892} 2893``` 2894 2895 2896### readDescriptorValue 2897 2898readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor> 2899 2900client端从指定的server端描述符读取数据。使用Promise异步回调。<br> 2901- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且包含指定的入参描述符UUID;否则会读取失败。<br> 2902- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。<br> 2903- 读取描述符过程中,需确保[BLEDescriptor](#bledescriptor)入参描述符的serviceUuid、characteristicUuid、descriptorUuid准确。descriptorValue表示的数据内容长度可由用户任意指定,不会影响实际读取到的描述符数据内容。 2904 2905**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2906 2907**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2908 2909**系统能力**:SystemCapability.Communication.Bluetooth.Core 2910 2911**参数:** 2912 2913| 参数名 | 类型 | 必填 | 说明 | 2914| ---------- | ------------------------------- | ---- | -------- | 2915| descriptor | [BLEDescriptor](#bledescriptor) | 是 | 需要读取的描述符。 | 2916 2917**返回值:** 2918 2919| 类型 | 说明 | 2920| ---------------------------------------- | -------------------------- | 2921| Promise<[BLEDescriptor](#bledescriptor)> | Promise对象,返回获取到的描述符对象,包含读取到的数据内容。 | 2922 2923**错误码**: 2924 2925以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2926 2927| 错误码ID | 错误信息 | 2928| -------- | ---------------------------- | 2929|201 | Permission denied. | 2930|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2931|801 | Capability not supported. | 2932|2900001 | Service stopped. | 2933|2900011 | The operation is busy. The last operation is not complete. | 2934|2900099 | Operation failed. | 2935|2901000 | Read forbidden. | 2936|2901003 | The connection is not established. | 2937|2901004 | The connection is congested. | 2938|2901005 | The connection is not encrypted. | 2939|2901006 | The connection is not authenticated. | 2940|2901007 | The connection is not authorized. | 2941 2942**示例:** 2943 2944```js 2945import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2946let bufferDesc = new ArrayBuffer(2); 2947let descV = new Uint8Array(bufferDesc); 2948descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 2949let descriptor: ble.BLEDescriptor = { 2950 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2951 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2952 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', 2953 descriptorValue: bufferDesc 2954}; 2955try { 2956 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2957 device.readDescriptorValue(descriptor); 2958} catch (err) { 2959 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2960} 2961``` 2962 2963 2964### writeCharacteristicValue 2965 2966writeCharacteristicValue(characteristic: BLECharacteristic, writeType: GattWriteType, callback: AsyncCallback<void>): void 2967 2968client端向指定的server端特征值写入数据。使用Callback异步回调。<br> 2969- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且包含指定的入参特征值UUID;否则会写入失败。<br> 2970- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。<br> 2971- 应用单次可写入的特征值数据长度默认限制为(MTU-3)字节,MTU大小可由[setBLEMtuSize](#setblemtusize)接口指定。 2972 2973**需要权限**:ohos.permission.ACCESS_BLUETOOTH 2974 2975**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 2976 2977**系统能力**:SystemCapability.Communication.Bluetooth.Core 2978 2979**参数:** 2980 2981| 参数名 | 类型 | 必填 | 说明 | 2982| -------------- | --------------------------------------- | ---- | ------------------- | 2983| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 需要写入的特征值,包含写入的数据内容。 | 2984| writeType | [GattWriteType](#gattwritetype) | 是 | 写入特征值的方式。 | 2985| callback | AsyncCallback<void> | 是 | 回调函数。当写入成功,err为undefined,否则为错误对象。 | 2986 2987**错误码**: 2988 2989以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 2990 2991| 错误码ID | 错误信息 | 2992| -------- | ---------------------------- | 2993|201 | Permission denied. | 2994|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2995|801 | Capability not supported. | 2996|2900001 | Service stopped. | 2997|2900011 | The operation is busy. The last operation is not complete. | 2998|2900099 | Operation failed. | 2999|2901001 | Write forbidden. | 3000|2901003 | The connection is not established. | 3001|2901004 | The connection is congested. | 3002|2901005 | The connection is not encrypted. | 3003|2901006 | The connection is not authenticated. | 3004|2901007 | The connection is not authorized. | 3005 3006**示例:** 3007 3008```js 3009import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3010let descriptors: Array<ble.BLEDescriptor> = []; 3011let bufferDesc = new ArrayBuffer(2); 3012let descV = new Uint8Array(bufferDesc); 3013descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 3014let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3015 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3016 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; 3017descriptors[0] = descriptor; 3018 3019let bufferCCC = new ArrayBuffer(8); 3020let cccV = new Uint8Array(bufferCCC); 3021cccV[0] = 1; 3022let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3023 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3024 characteristicValue: bufferCCC, descriptors:descriptors}; 3025function writeCharacteristicValueCallBack(code: BusinessError) { 3026 if (code != null) { 3027 return; 3028 } 3029 console.info('bluetooth writeCharacteristicValue success'); 3030} 3031try { 3032 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3033 device.writeCharacteristicValue(characteristic, ble.GattWriteType.WRITE, writeCharacteristicValueCallBack); 3034} catch (err) { 3035 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3036} 3037``` 3038 3039 3040### writeCharacteristicValue 3041 3042writeCharacteristicValue(characteristic: BLECharacteristic, writeType: GattWriteType): Promise<void> 3043 3044client端向指定的server端特征值写入数据。使用Promise异步回调。<br> 3045- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且包含指定的入参特征值UUID;否则会写入失败。<br> 3046- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。<br> 3047- 应用单次可写入的特征值数据长度默认限制为(MTU-3)字节,MTU大小可由[setBLEMtuSize](#setblemtusize)接口指定。 3048 3049**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3050 3051**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3052 3053**系统能力**:SystemCapability.Communication.Bluetooth.Core 3054 3055**参数:** 3056 3057| 参数名 | 类型 | 必填 | 说明 | 3058| -------------- | --------------------------------------- | ---- | ------------------- | 3059| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 需要写入的特征值,包含写入的数据内容。 | 3060| writeType | [GattWriteType](#gattwritetype) | 是 | 写入特征值的方式。 | 3061 3062**返回值:** 3063 3064| 类型 | 说明 | 3065| ---------------------------------------- | -------------------------- | 3066| Promise<void> | Promise对象。无返回结果的Promise对象。 | 3067 3068**错误码**: 3069 3070以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 3071 3072| 错误码ID | 错误信息 | 3073| -------- | ---------------------------- | 3074|201 | Permission denied. | 3075|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3076|801 | Capability not supported. | 3077|2900001 | Service stopped. | 3078|2900011 | The operation is busy. The last operation is not complete. | 3079|2900099 | Operation failed. | 3080|2901001 | Write forbidden. | 3081|2901003 | The connection is not established. | 3082|2901004 | The connection is congested. | 3083|2901005 | The connection is not encrypted. | 3084|2901006 | The connection is not authenticated. | 3085|2901007 | The connection is not authorized. | 3086 3087**示例:** 3088 3089```js 3090import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3091let descriptors: Array<ble.BLEDescriptor> = []; 3092let bufferDesc = new ArrayBuffer(2); 3093let descV = new Uint8Array(bufferDesc); 3094descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 3095let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3096 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3097 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; 3098descriptors[0] = descriptor; 3099 3100let bufferCCC = new ArrayBuffer(8); 3101let cccV = new Uint8Array(bufferCCC); 3102cccV[0] = 1; 3103let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3104 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3105 characteristicValue: bufferCCC, descriptors:descriptors}; 3106try { 3107 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3108 device.writeCharacteristicValue(characteristic, ble.GattWriteType.WRITE); 3109} catch (err) { 3110 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3111} 3112``` 3113 3114 3115### writeDescriptorValue 3116 3117writeDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<void>): void 3118 3119client端向指定的server端描述符写入数据。使用Callback异步回调。<br> 3120- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且包含指定的入参描述符UUID;否则会写入失败。<br> 3121- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。<br> 3122- 应用单次可写入的描述符数据长度默认限制为(MTU-3)字节,MTU大小可由[setBLEMtuSize](#setblemtusize)接口指定。<br> 3123- Client Characteristic Configuration描述符(UUID:00002902-0000-1000-8000-00805f9b34fb)和 Server Characteristic Configuration描述符(UUID:00002903-0000-1000-8000-00805f9b34fb)较为特殊,蓝牙标准协议规定内容长度为2字节,写入内容长度应设置为2字节。 3124 3125**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3126 3127**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3128 3129**系统能力**:SystemCapability.Communication.Bluetooth.Core 3130 3131**参数:** 3132 3133| 参数名 | 类型 | 必填 | 说明 | 3134| ---------- | ------------------------------- | ---- | ------------------ | 3135| descriptor | [BLEDescriptor](#bledescriptor) | 是 | 需要写入的描述符,包含写入的数据内容。 | 3136| callback | AsyncCallback<void> | 是 | 回调函数。当写入成功,err为undefined,否则为错误对象。 | 3137 3138**错误码**: 3139 3140以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 3141 3142| 错误码ID | 错误信息 | 3143| -------- | ---------------------------- | 3144|201 | Permission denied. | 3145|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3146|801 | Capability not supported. | 3147|2900001 | Service stopped. | 3148|2900011 | The operation is busy. The last operation is not complete. | 3149|2900099 | Operation failed. | 3150|2901001 | Write forbidden. | 3151|2901003 | The connection is not established. | 3152|2901004 | The connection is congested. | 3153|2901005 | The connection is not encrypted. | 3154|2901006 | The connection is not authenticated. | 3155|2901007 | The connection is not authorized. | 3156 3157**示例:** 3158 3159```js 3160import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3161let bufferDesc = new ArrayBuffer(2); 3162let descV = new Uint8Array(bufferDesc); 3163descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 3164let descriptor: ble.BLEDescriptor = { 3165 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3166 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3167 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', 3168 descriptorValue: bufferDesc 3169}; 3170try { 3171 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3172 device.writeDescriptorValue(descriptor, (err: BusinessError) => { 3173 if (err) { 3174 console.error('writeDescriptorValue callback failed'); 3175 } else { 3176 console.info('writeDescriptorValue callback successful'); 3177 } 3178 }); 3179} catch (err) { 3180 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3181} 3182``` 3183 3184 3185### writeDescriptorValue 3186 3187writeDescriptorValue(descriptor: BLEDescriptor): Promise<void> 3188 3189client端向指定的server端描述符写入数据。使用Promise异步回调。<br> 3190- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且包含指定的入参描述符UUID;否则会写入失败。<br> 3191- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。<br> 3192- 应用单次可写入的描述符数据长度默认限制为(MTU-3)字节,MTU大小可由[setBLEMtuSize](#setblemtusize)接口指定。<br> 3193- Client Characteristic Configuration描述符(UUID:00002902-0000-1000-8000-00805f9b34fb)和 Server Characteristic Configuration描述符(UUID:00002903-0000-1000-8000-00805f9b34fb)较为特殊,蓝牙标准协议规定内容长度为2字节,写入内容长度应设置为2字节。 3194 3195**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3196 3197**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3198 3199**系统能力**:SystemCapability.Communication.Bluetooth.Core 3200 3201**参数:** 3202 3203| 参数名 | 类型 | 必填 | 说明 | 3204| ---------- | ------------------------------- | ---- | ------------------ | 3205| descriptor | [BLEDescriptor](#bledescriptor) | 是 | 需要写入的描述符,包含写入的数据内容。 | 3206 3207**返回值:** 3208 3209| 类型 | 说明 | 3210| ---------------------------------------- | -------------------------- | 3211| Promise<void> | Promise对象。无返回结果的Promise对象。 | 3212 3213**错误码**: 3214 3215以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 3216 3217| 错误码ID | 错误信息 | 3218| -------- | ---------------------------- | 3219|201 | Permission denied. | 3220|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3221|801 | Capability not supported. | 3222|2900001 | Service stopped. | 3223|2900011 | The operation is busy. The last operation is not complete. | 3224|2900099 | Operation failed. | 3225|2901001 | Write forbidden. | 3226|2901003 | The connection is not established. | 3227|2901004 | The connection is congested. | 3228|2901005 | The connection is not encrypted. | 3229|2901006 | The connection is not authenticated. | 3230|2901007 | The connection is not authorized. | 3231 3232**示例:** 3233 3234```js 3235import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3236let bufferDesc = new ArrayBuffer(2); 3237let descV = new Uint8Array(bufferDesc); 3238descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 3239let descriptor: ble.BLEDescriptor = { 3240 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3241 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3242 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', 3243 descriptorValue: bufferDesc 3244}; 3245try { 3246 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3247 device.writeDescriptorValue(descriptor).then(() => { 3248 console.info('writeDescriptorValue promise success'); 3249 }); 3250} catch (err) { 3251 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3252} 3253``` 3254 3255 3256### getRssiValue 3257 3258getRssiValue(callback: AsyncCallback<number>): void 3259 3260client端获取GATT连接链路信号强度 (Received Signal Strength Indication, RSSI)。使用Callback异步回调。<br> 3261- 需先调用[connect](#connect)方法,等GATT profile连接成功后才能使用。 3262- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。 3263 3264**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3265 3266**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3267 3268**系统能力**:SystemCapability.Communication.Bluetooth.Core 3269 3270**参数:** 3271 3272| 参数名 | 类型 | 必填 | 说明 | 3273| -------- | --------------------------- | ---- | ------------------------------ | 3274| callback | AsyncCallback<number> | 是 | 回调函数。获取链路信号强度成功,err为undefined,data为获取到的信号强度值,单位:dBm;否则为错误对象。 | 3275 3276**错误码**: 3277 3278以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 3279 3280| 错误码ID | 错误信息 | 3281| -------- | ---------------------------- | 3282|201 | Permission denied. | 3283|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3284|801 | Capability not supported. | 3285|2900011 | The operation is busy. The last operation is not complete. | 3286|2900099 | Operation failed. | 3287|2901003 | The connection is not established. | 3288 3289**示例:** 3290 3291```js 3292import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3293// callback 3294try { 3295 let gattClient: ble.GattClientDevice = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX"); 3296 gattClient.connect(); 3297 let rssi = gattClient.getRssiValue((err: BusinessError, data: number)=> { 3298 console.info('rssi err ' + JSON.stringify(err)); 3299 console.info('rssi value' + JSON.stringify(data)); 3300 }) 3301} catch (err) { 3302 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3303} 3304``` 3305 3306 3307### getRssiValue 3308 3309getRssiValue(): Promise<number> 3310 3311client端获取GATT连接链路信号强度 (Received Signal Strength Indication, RSSI)。使用Promise异步回调。<br> 3312- 需先调用[connect](#connect)方法,等GATT profile连接成功后才能使用。 3313- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。 3314 3315**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3316 3317**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3318 3319**系统能力**:SystemCapability.Communication.Bluetooth.Core 3320 3321**返回值:** 3322 3323| 类型 | 说明 | 3324| --------------------- | --------------------------------- | 3325| Promise<number> | Promise对象。返回链路的信号强度,单位:dBm。 | 3326 3327**错误码**: 3328 3329以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 3330 3331| 错误码ID | 错误信息 | 3332| -------- | ---------------------------- | 3333|201 | Permission denied. | 3334|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 3335|801 | Capability not supported. | 3336|2900011 | The operation is busy. The last operation is not complete. | 3337|2900099 | Operation failed. | 3338|2901003 | The connection is not established. | 3339 3340**示例:** 3341 3342```js 3343import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3344// promise 3345try { 3346 let gattClient: ble.GattClientDevice = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX"); 3347 gattClient.getRssiValue().then((data: number) => { 3348 console.info('rssi' + JSON.stringify(data)); 3349 }) 3350} catch (err) { 3351 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3352} 3353``` 3354 3355 3356### setBLEMtuSize 3357 3358setBLEMtuSize(mtu: number): void 3359 3360client端同server端协商[MTU](../../connectivity/terminology.md#mtu)(最大传输单元)大小。<br> 3361- 需先调用[connect](#connect)方法,等GATT profile连接成功后才能使用。<br> 3362- 通过[on('BLEMtuChange')](#onblemtuchange-1),订阅MTU协商结果。<br> 3363- 如果未协商,MTU大小默认为23字节。 3364 3365**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3366 3367**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3368 3369**系统能力**:SystemCapability.Communication.Bluetooth.Core 3370 3371**参数:** 3372 3373| 参数名 | 类型 | 必填 | 说明 | 3374| ---- | ------ | ---- | -------------- | 3375| mtu | number | 是 | 需要协商的mtu大小,取值范围:[23, 517],单位:Byte。 | 3376 3377**错误码**: 3378 3379以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 3380 3381| 错误码ID | 错误信息 | 3382| -------- | ---------------------------- | 3383|201 | Permission denied. | 3384|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3385|801 | Capability not supported. | 3386|2900001 | Service stopped. | 3387|2900099 | Operation failed. | 3388 3389**示例:** 3390 3391```js 3392import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3393try { 3394 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3395 device.setBLEMtuSize(128); 3396} catch (err) { 3397 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3398} 3399``` 3400 3401 3402### setCharacteristicChangeNotification 3403 3404setCharacteristicChangeNotification(characteristic: BLECharacteristic, enable: boolean, callback: AsyncCallback<void>): void 3405 3406client端启用或者禁用接收server端特征值内容变更通知的能力。使用Callback异步回调。<br> 3407- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且需包含指定的入参特征值UUID。<br> 3408- server端对应的特征值需包含标准协议定义的Client Characteristic Configuration描述符UUID(00002902-0000-1000-8000-00805f9b34fb),server端才能支持发送变更通知。<br> 3409- 若启用该能力,系统蓝牙服务会自动往server端写Client Characteristic Configuration描述符,启用server端的通知能力。<br> 3410- 若禁用该能力,系统蓝牙服务会自动往server端写Client Characteristic Configuration描述符,禁用server端的通知能力。<br> 3411- 通过[on('BLECharacteristicChange')](#onblecharacteristicchange)接收server端特征值内容变更通知。<br> 3412- 若client端收到server端特征值内容变更通知后,无需回复确认。 3413- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。 3414 3415**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3416 3417**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3418 3419**系统能力**:SystemCapability.Communication.Bluetooth.Core 3420 3421**参数:** 3422 3423| 参数名 | 类型 | 必填 | 说明 | 3424| -------------- | --------------------------------------- | ---- | ----------------------------- | 3425| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 需要管理的server端特征值。 | 3426| enable | boolean | 是 | 是否启用接收server端特征值通知的能力。<br>true表示启用,false表示禁用。 | 3427| callback | AsyncCallback<void> | 是 | 回调函数。当调用成功,err为undefined,否则为错误对象。 | 3428 3429**错误码**: 3430 3431以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 3432 3433| 错误码ID | 错误信息 | 3434| -------- | ---------------------------- | 3435|201 | Permission denied. | 3436|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3437|801 | Capability not supported. | 3438|2900001 | Service stopped. | 3439|2900011 | The operation is busy. The last operation is not complete. | 3440|2900099 | Operation failed. | 3441|2901003 | The connection is not established. | 3442 3443**示例:** 3444 3445```js 3446import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3447// 创建descriptors。 3448let descriptors: Array<ble.BLEDescriptor> = []; 3449let arrayBuffer = new ArrayBuffer(2); 3450let descV = new Uint8Array(arrayBuffer); 3451descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 3452let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3453 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3454 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; 3455descriptors[0] = descriptor; 3456let arrayBufferC = new ArrayBuffer(8); 3457let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3458 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; 3459try { 3460 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3461 device.setCharacteristicChangeNotification(characteristic, false, (err: BusinessError) => { 3462 if (err) { 3463 console.error('notifyCharacteristicChanged callback failed'); 3464 } else { 3465 console.info('notifyCharacteristicChanged callback successful'); 3466 } 3467 }); 3468} catch (err) { 3469 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3470} 3471 3472``` 3473 3474 3475### setCharacteristicChangeNotification 3476 3477setCharacteristicChangeNotification(characteristic: BLECharacteristic, enable: boolean): Promise<void> 3478 3479client端启用或者禁用接收server端特征值内容变更通知的能力。使用Promise异步回调。<br> 3480- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且需包含指定的入参特征值UUID。<br> 3481- server端对应的特征值需包含标准协议定义的Client Characteristic Configuration描述符UUID(00002902-0000-1000-8000-00805f9b34fb),server端才能支持发送变更通知。<br> 3482- 若启用该能力,系统蓝牙服务会自动往server端写Client Characteristic Configuration描述符,启用server端的通知能力。<br> 3483- 若禁用该能力,系统蓝牙服务会自动往server端写Client Characteristic Configuration描述符,禁用server端的通知能力。<br> 3484- 通过[on('BLECharacteristicChange')](#onblecharacteristicchange)接收server端特征值内容变更通知。<br> 3485- 若client端收到server端特征值内容变更通知后,无需回复确认。 3486- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。 3487 3488**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3489 3490**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3491 3492**系统能力**:SystemCapability.Communication.Bluetooth.Core 3493 3494**参数:** 3495 3496| 参数名 | 类型 | 必填 | 说明 | 3497| -------------- | --------------------------------------- | ---- | ----------------------------- | 3498| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 需要管理的server端特征值。 | 3499| enable | boolean | 是 | 是否启用接收server端特征值通知的能力。<br>true表示启用,false表示禁用。 | 3500 3501**返回值:** 3502 3503| 类型 | 说明 | 3504| ---------------------------------------- | -------------------------- | 3505| Promise<void> | Promise对象。无返回结果的Promise对象。 | 3506 3507**错误码**: 3508 3509以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 3510 3511| 错误码ID | 错误信息 | 3512| -------- | ---------------------------- | 3513|201 | Permission denied. | 3514|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3515|801 | Capability not supported. | 3516|2900001 | Service stopped. | 3517|2900011 | The operation is busy. The last operation is not complete. | 3518|2900099 | Operation failed. | 3519|2901003 | The connection is not established. | 3520 3521**示例:** 3522 3523```js 3524import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3525// 创建descriptors。 3526let descriptors: Array<ble.BLEDescriptor> = []; 3527let arrayBuffer = new ArrayBuffer(2); 3528let descV = new Uint8Array(arrayBuffer); 3529descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 3530let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3531 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3532 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; 3533descriptors[0] = descriptor; 3534let arrayBufferC = new ArrayBuffer(8); 3535let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3536 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; 3537try { 3538 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3539 device.setCharacteristicChangeNotification(characteristic, false); 3540} catch (err) { 3541 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3542} 3543 3544``` 3545 3546 3547### setCharacteristicChangeIndication 3548 3549setCharacteristicChangeIndication(characteristic: BLECharacteristic, enable: boolean, callback: AsyncCallback<void>): void 3550 3551client端启用或者禁用接收server端特征值内容变更指示的能力。使用Callback异步回调。<br> 3552- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且需包含指定的入参特征值UUID。<br> 3553- server端对应的特征值需包含标准协议定义的Client Characteristic Configuration描述符UUID(00002902-0000-1000-8000-00805f9b34fb),server端才能支持发送变更指示。<br> 3554- 若启用该能力,系统蓝牙服务会自动往server端写Client Characteristic Configuration描述符,启用server端的指示能力。<br> 3555- 若禁用该能力,系统蓝牙服务会自动往server端写Client Characteristic Configuration描述符,禁用server端的指示能力。<br> 3556- 通过[on('BLECharacteristicChange')](#onblecharacteristicchange)接收server端特征值内容变更指示。<br> 3557- 若client端收到server端特征值内容变更指示后,系统蓝牙服务会主动回复确认,应用无需关注。 3558- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。 3559 3560**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3561 3562**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3563 3564**系统能力**:SystemCapability.Communication.Bluetooth.Core 3565 3566**参数:** 3567 3568| 参数名 | 类型 | 必填 | 说明 | 3569| -------------- | --------------------------------------- | ---- | ----------------------------- | 3570| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 需要管理的server端特征值。 | 3571| enable | boolean | 是 | 是否启用接收server端特征值指示的能力。<br>true表示启用,false表示禁用。 | 3572| callback | AsyncCallback<void> | 是 | 回调函数。当调用成功,err为undefined,否则为错误对象。 | 3573 3574**错误码**: 3575 3576以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 3577 3578| 错误码ID | 错误信息 | 3579| -------- | ---------------------------- | 3580|201 | Permission denied. | 3581|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3582|801 | Capability not supported. | 3583|2900001 | Service stopped. | 3584|2900011 | The operation is busy. The last operation is not complete. | 3585|2900099 | Operation failed. | 3586|2901003 | The connection is not established. | 3587 3588**示例:** 3589 3590```js 3591import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3592// 创建descriptors。 3593let descriptors: Array<ble.BLEDescriptor> = []; 3594let arrayBuffer = new ArrayBuffer(2); 3595let descV = new Uint8Array(arrayBuffer); 3596descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 3597let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3598 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3599 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; 3600descriptors[0] = descriptor; 3601let arrayBufferC = new ArrayBuffer(8); 3602let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3603 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; 3604try { 3605 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3606 device.setCharacteristicChangeIndication(characteristic, false, (err: BusinessError) => { 3607 if (err) { 3608 console.error('notifyCharacteristicChanged callback failed'); 3609 } else { 3610 console.info('notifyCharacteristicChanged callback successful'); 3611 } 3612 }); 3613} catch (err) { 3614 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3615} 3616 3617``` 3618 3619 3620### setCharacteristicChangeIndication 3621 3622setCharacteristicChangeIndication(characteristic: BLECharacteristic, enable: boolean): Promise<void> 3623 3624client端启用或者禁用接收server端特征值内容变更指示的能力。使用Callback异步回调。<br> 3625- 需要先调用[getServices](#getservices),获取到server端所有支持的能力,且需包含指定的入参特征值UUID。<br> 3626- server端对应的特征值需包含标准协议定义的Client Characteristic Configuration描述符UUID(00002902-0000-1000-8000-00805f9b34fb),server端才能支持发送变更指示。<br> 3627- 若启用该能力,系统蓝牙服务会自动往server端写Client Characteristic Configuration描述符,启用server端的指示能力。<br> 3628- 若禁用该能力,系统蓝牙服务会自动往server端写Client Characteristic Configuration描述符,禁用server端的指示能力。<br> 3629- 通过[on('BLECharacteristicChange')](#onblecharacteristicchange)接收server端特征值内容变更指示。<br> 3630- 若client端收到server端特征值内容变更指示后,系统蓝牙服务会主动回复确认,应用无需关注。 3631- 异步回调结果返回后,才能调用下一次读取或者写入操作,如[readCharacteristicValue](#readcharacteristicvalue)、[readDescriptorValue](#readdescriptorvalue)、[writeCharacteristicValue](#writecharacteristicvalue)、[writeDescriptorValue](#writedescriptorvalue)、[getRssiValue](#getrssivalue)、[setCharacteristicChangeNotification](#setcharacteristicchangenotification)和[setCharacteristicChangeIndication](#setcharacteristicchangeindication)。 3632 3633**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3634 3635**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3636 3637**系统能力**:SystemCapability.Communication.Bluetooth.Core 3638 3639**参数:** 3640 3641| 参数名 | 类型 | 必填 | 说明 | 3642| -------------- | --------------------------------------- | ---- | ----------------------------- | 3643| characteristic | [BLECharacteristic](#blecharacteristic) | 是 | 需要管理的server端特征值。 | 3644| enable | boolean | 是 | 是否启用接收server端特征值指示的能力。<br>true表示启用,false表示禁用。 | 3645 3646**返回值:** 3647 3648| 类型 | 说明 | 3649| ---------------------------------------- | -------------------------- | 3650| Promise<void> | Promise对象。无返回结果的Promis对象。 | 3651 3652**错误码**: 3653 3654以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 3655 3656| 错误码ID | 错误信息 | 3657| -------- | ---------------------------- | 3658|201 | Permission denied. | 3659|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3660|801 | Capability not supported. | 3661|2900001 | Service stopped. | 3662|2900011 | The operation is busy. The last operation is not complete. | 3663|2900099 | Operation failed. | 3664|2901003 | The connection is not established. | 3665 3666**示例:** 3667 3668```js 3669import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3670// 创建descriptors。 3671let descriptors: Array<ble.BLEDescriptor> = []; 3672let arrayBuffer = new ArrayBuffer(2); 3673let descV = new Uint8Array(arrayBuffer); 3674descV[0] = 0; // 以Client Characteristic Configuration描述符为例,表示bit0、bit1均为0,notification和indication均不开启 3675let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3676 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3677 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; 3678descriptors[0] = descriptor; 3679let arrayBufferC = new ArrayBuffer(8); 3680let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3681 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; 3682try { 3683 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3684 device.setCharacteristicChangeIndication(characteristic, false); 3685} catch (err) { 3686 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3687} 3688 3689``` 3690 3691 3692### on('BLECharacteristicChange') 3693 3694on(type: 'BLECharacteristicChange', callback: Callback<BLECharacteristic>): void 3695 3696client端订阅server端特征值变化事件。使用Callback异步回调。<br> 3697- 需调用[setCharacteristicChangeNotification](#setcharacteristicchangenotification)或者[setCharacteristicChangeIndication](#setcharacteristicchangeindication),且启用通知或者指示能力后,才能接收到server端的特征值内容变更通知或者指示。 3698 3699**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3700 3701**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3702 3703**系统能力**:SystemCapability.Communication.Bluetooth.Core 3704 3705**参数:** 3706 3707| 参数名 | 类型 | 必填 | 说明 | 3708| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3709| type | string | 是 | 事件回调类型,支持的事件为'BLECharacteristicChange',表示server端特征值变化事件。<br>当client端收到server端特征值内容变更的通知或者指示时,触发该事件。 | 3710| callback | Callback<[BLECharacteristic](#blecharacteristic)> | 是 | 指定订阅的回调函数,会携带server端变化后的特征值内容。 | 3711 3712**错误码**: 3713 3714以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 3715 3716| 错误码ID | 错误信息 | 3717| -------- | ---------------------------- | 3718|201 | Permission denied. | 3719|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3720|801 | Capability not supported. | 3721 3722**示例:** 3723 3724```js 3725import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3726function CharacteristicChange(characteristicChangeReq: ble.BLECharacteristic) { 3727 let serviceUuid: string = characteristicChangeReq.serviceUuid; 3728 let characteristicUuid: string = characteristicChangeReq.characteristicUuid; 3729 let value: Uint8Array = new Uint8Array(characteristicChangeReq.characteristicValue); 3730} 3731try { 3732 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3733 device.on('BLECharacteristicChange', CharacteristicChange); 3734} catch (err) { 3735 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3736} 3737``` 3738 3739 3740### off('BLECharacteristicChange') 3741 3742off(type: 'BLECharacteristicChange', callback?: Callback<BLECharacteristic>): void 3743 3744client端取消订阅server端特征值变化事件。 3745 3746**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3747 3748**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3749 3750**系统能力**:SystemCapability.Communication.Bluetooth.Core 3751 3752**参数:** 3753 3754| 参数名 | 类型 | 必填 | 说明 | 3755| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3756| type | string | 是 | 事件回调类型,支持的事件为'BLECharacteristicChange',表示server端特征值变化事件。 | 3757| callback | Callback<[BLECharacteristic](#blecharacteristic)> | 否 | 指定取消订阅的回调函数通知。<br>若传参,则需与[on('BLECharacteristicChange')](#onblecharacteristicchange)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 3758 3759**错误码**: 3760 3761以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 3762 3763| 错误码ID | 错误信息 | 3764| -------- | ---------------------------- | 3765|201 | Permission denied. | 3766|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3767|801 | Capability not supported. | 3768 3769**示例:** 3770 3771```js 3772import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3773try { 3774 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3775 device.off('BLECharacteristicChange'); 3776} catch (err) { 3777 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3778} 3779``` 3780 3781 3782### on('BLEConnectionStateChange') 3783 3784on(type: 'BLEConnectionStateChange', callback: Callback<BLEConnectionChangeState>): void 3785 3786client端订阅GATT profile协议的连接状态变化事件。使用Callback异步回调。 3787 3788**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3789 3790**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3791 3792**系统能力**:SystemCapability.Communication.Bluetooth.Core 3793 3794**参数:** 3795 3796| 参数名 | 类型 | 必填 | 说明 | 3797| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3798| type | string | 是 | 事件回调类型,支持的事件为'BLEConnectionStateChange',表示连接状态变化事件。<br>client和server端之间的连接状态发生变化时,触发该事件。<br>当client端调用[connect](#connect)或[disconnect](#disconnect)时,可能引起连接状态生变化。 | 3799| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | 是 | 指定订阅的回调函数,会携带连接状态信息。 | 3800 3801**错误码**: 3802 3803以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 3804 3805| 错误码ID | 错误信息 | 3806| -------- | ---------------------------- | 3807|201 | Permission denied. | 3808|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3809|801 | Capability not supported. | 3810 3811**示例:** 3812 3813```js 3814import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3815function ConnectStateChanged(state: ble.BLEConnectionChangeState) { 3816 console.info('bluetooth connect state changed'); 3817 let connectState: ble.ProfileConnectionState = state.state; 3818} 3819try { 3820 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3821 device.on('BLEConnectionStateChange', ConnectStateChanged); 3822} catch (err) { 3823 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3824} 3825``` 3826 3827 3828### off('BLEConnectionStateChange') 3829 3830off(type: 'BLEConnectionStateChange', callback?: Callback<BLEConnectionChangeState>): void 3831 3832client端取消订阅GATT profile协议的连接状态变化事件。 3833 3834**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3835 3836**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3837 3838**系统能力**:SystemCapability.Communication.Bluetooth.Core 3839 3840**参数:** 3841 3842| 参数名 | 类型 | 必填 | 说明 | 3843| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3844| type | string | 是 | 事件回调类型,支持的事件为'BLEConnectionStateChange',表示连接状态变化事件。 | 3845| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | 否 | 指定取消订阅的回调函数通知。<br>若传参,则需与[on('BLEConnectionStateChange')](#onbleconnectionstatechange)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 3846 3847**错误码**: 3848 3849以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 3850 3851| 错误码ID | 错误信息 | 3852| -------- | ---------------------------- | 3853|201 | Permission denied. | 3854|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3855|801 | Capability not supported. | 3856 3857**示例:** 3858 3859```js 3860import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3861try { 3862 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3863 device.off('BLEConnectionStateChange'); 3864} catch (err) { 3865 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3866} 3867``` 3868 3869 3870### on('BLEMtuChange') 3871 3872on(type: 'BLEMtuChange', callback: Callback<number>): void 3873 3874client端订阅MTU(最大传输单元)大小变更事件。使用Callback异步回调。 3875 3876**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3877 3878**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3879 3880**系统能力**:SystemCapability.Communication.Bluetooth.Core 3881 3882**参数:** 3883 3884| 参数名 | 类型 | 必填 | 说明 | 3885| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3886| type | string | 是 | 事件回调类型,支持的事件为'BLEMtuChange',表示MTU大小变更事件。<br>当调用[setBLEMtuSize](#setblemtusize)方法,client端发起MTU大小协商后,会触发该事件。 | 3887| callback | Callback<number> | 是 | 指定订阅的回调函数,会携带协商后的MTU大小。单位:Byte。 | 3888 3889**错误码**: 3890 3891以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 3892 3893| 错误码ID | 错误信息 | 3894| -------- | ---------------------------- | 3895|201 | Permission denied. | 3896|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3897|801 | Capability not supported. | 3898 3899**示例:** 3900 3901```js 3902import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3903try { 3904 let gattClient: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3905 gattClient.on('BLEMtuChange', (mtu: number) => { 3906 console.info('BLEMtuChange, mtu: ' + mtu); 3907 }); 3908} catch (err) { 3909 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3910} 3911``` 3912 3913 3914### off('BLEMtuChange') 3915 3916off(type: 'BLEMtuChange', callback?: Callback<number>): void 3917 3918client端取消订阅MTU(最大传输单元)大小变更事件。 3919 3920**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3921 3922**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 3923 3924**系统能力**:SystemCapability.Communication.Bluetooth.Core 3925 3926**参数:** 3927 3928| 参数名 | 类型 | 必填 | 说明 | 3929| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3930| type | string | 是 | 事件回调类型,支持的事件为'BLEMtuChange',表示MTU大小变更事件。 | 3931| callback | Callback<number> | 否 | 指定取消订阅的回调函数通知。若传参,则需与[on('BLEMtuChange')](#onblemtuchange-1)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 3932 3933**错误码**: 3934 3935以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 3936 3937| 错误码ID | 错误信息 | 3938| -------- | ---------------------------- | 3939|201 | Permission denied. | 3940|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3941|801 | Capability not supported. | 3942 3943**示例:** 3944 3945```js 3946import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3947try { 3948 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3949 device.off('BLEMtuChange'); 3950} catch (err) { 3951 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3952} 3953``` 3954 3955## ble.createBleScanner<sup>15+</sup> 3956 3957createBleScanner(): BleScanner 3958 3959创建一个[BleScanner](#blescanner15)实例对象,可用于发起或停止BLE扫描等流程。 3960 3961**原子化服务API**: 从API version 15开始,该接口支持在原子化服务中使用。 3962 3963**系统能力**:SystemCapability.Communication.Bluetooth.Core 3964 3965**返回值:** 3966 3967| 类型 | 说明 | 3968| ------------ | ------------- | 3969| [BleScanner](#blescanner15) | 返回一个BleScanner的实例。 | 3970 3971**示例:** 3972 3973```js 3974import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3975import { ble } from '@kit.ConnectivityKit'; 3976let bleScanner: ble.BleScanner = ble.createBleScanner(); 3977console.info('create bleScanner success'); 3978``` 3979 3980## BleScanner<sup>15+</sup> 3981 3982BLE扫描类,提供了扫描相关的操作方法。<br> 3983- 使用该类的方法前,需通过[createBleScanner](#blecreateblescanner15)方法构造该类的实例。<br> 3984- 通过创建不同的该类实例,可以管理多路不同的扫描流程。 3985 3986### startScan<sup>15+</sup> 3987 3988startScan(filters: Array<ScanFilter>, options?: ScanOptions): Promise<void> 3989 3990发起BLE扫描流程。使用Promise异步回调。<br> 3991- 该接口只能扫描BLE设备。<br> 3992- 扫描结果会通过[on('BLEDeviceFind')](#onbledevicefind15)的回调函数获取到。<br> 3993- 调用[stopScan](#stopscan15)可以停止该方法开启的扫描流程。 3994 3995**需要权限**:ohos.permission.ACCESS_BLUETOOTH 3996 3997**原子化服务API**:从API version 15开始,该接口支持在原子化服务中使用。 3998 3999**系统能力**:SystemCapability.Communication.Bluetooth.Core 4000 4001**参数:** 4002 4003| 参数名 | 类型 | 必填 | 说明 | 4004| ------- | -------------------------------------- | ---- | ----------------------------------- | 4005| filters | Array<[ScanFilter](#scanfilter)> | 是 | 扫描BLE广播的过滤条件集合,符合过滤条件的设备会被上报。<br>- 若该参数设置为null,将扫描所有可发现的周边BLE设备,但是不建议使用此方式,可能扫描到非预期设备,并增加功耗。<br>- 围栏模式下([ScanReportMode](#scanreportmode15)设置为FENCE_SENSITIVITY_LOW或FENCE_SENSITIVITY_HIGH时),该参数不可设置为null,需传入非空过滤器。<br>- 过滤器资源为所有应用共享,建议单个应用使用过滤器数量不超过3个,否则过滤器资源占满将导致开启扫描失败,返回2900009错误码。 | 4006| options | [ScanOptions](#scanoptions) | 否 | 扫描的配置参数。 | 4007 4008**返回值:** 4009 4010| 类型 | 说明 | 4011| ---------------------------------------- | -------------------------- | 4012| Promise<void> | Promise对象。无返回结果的Promis对象。 | 4013 4014**错误码**: 4015 4016以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 4017 4018| 错误码ID | 错误信息 | 4019| -------- | ---------------------------- | 4020|201 | Permission denied. | 4021|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 4022|801 | Capability not supported. | 4023|2900001 | Service stopped. | 4024|2900003 | Bluetooth disabled. | 4025|2900009 | Fails to start scan as it is out of hardware resources. | 4026|2900099 | Operation failed. | 4027|2902050 | Failed to start scan as Ble scan is already started by the app.| 4028 4029**示例:** 4030 4031```js 4032import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 4033import { ble } from '@kit.ConnectivityKit'; 4034let bleScanner: ble.BleScanner = ble.createBleScanner(); 4035function onReceiveEvent(scanReport: ble.ScanReport) { 4036 console.info('BLE scan device find result = '+ JSON.stringify(scanReport)); 4037} 4038try { 4039 bleScanner.on("BLEDeviceFind", onReceiveEvent); 4040 let scanFilter: ble.ScanFilter = { 4041 deviceId:"XX:XX:XX:XX:XX:XX", 4042 name:"test", 4043 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb" 4044 }; 4045 let scanOptions: ble.ScanOptions = { 4046 interval: 500, 4047 dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER, 4048 matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE, 4049 reportMode: ble.ScanReportMode.FENCE_SENSITIVITY_LOW 4050 } 4051 bleScanner.startScan([scanFilter],scanOptions); 4052 console.info('startScan success'); 4053} catch (err) { 4054 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 4055} 4056``` 4057 4058### stopScan<sup>15+</sup> 4059 4060stopScan(): Promise<void> 4061 4062停止正在进行的BLE扫描。<br> 4063- 停止的扫描是由[startScan](#startscan15)触发的。<br> 4064- 当应用不再需要扫描BLE设备时,需主动调用该方法停止扫描。 4065 4066**需要权限**:ohos.permission.ACCESS_BLUETOOTH 4067 4068**原子化服务API**:从API version 15开始,该接口支持在原子化服务中使用。 4069 4070**系统能力**:SystemCapability.Communication.Bluetooth.Core 4071 4072**返回值:** 4073 4074| 类型 | 说明 | 4075| ---------------------------------------- | -------------------------- | 4076| Promise<void> | Promise对象。无返回结果的Promis对象。 | 4077 4078**错误码**: 4079 4080以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 4081 4082| 错误码ID | 错误信息 | 4083| -------- | ---------------------------- | 4084|201 | Permission denied. | 4085|801 | Capability not supported. | 4086|2900001 | Service stopped. | 4087|2900003 | Bluetooth disabled. | 4088|2900099 | Operation failed. | 4089 4090**示例:** 4091 4092```js 4093import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 4094import { ble } from '@kit.ConnectivityKit'; 4095let bleScanner: ble.BleScanner = ble.createBleScanner(); 4096try { 4097 bleScanner.stopScan(); 4098 console.info('stopScan success'); 4099} catch (err) { 4100 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 4101} 4102``` 4103 4104### on('BLEDeviceFind')<sup>15+</sup> 4105 4106on(type: 'BLEDeviceFind', callback: Callback<ScanReport>): void 4107 4108订阅BLE设备扫描结果上报事件。使用Callback异步回调。 4109 4110**需要权限**:ohos.permission.ACCESS_BLUETOOTH 4111 4112**原子化服务API**:从API version 15开始,该接口支持在原子化服务中使用。 4113 4114**系统能力**:SystemCapability.Communication.Bluetooth.Core 4115 4116**参数:** 4117 4118| 参数名 | 类型 | 必填 | 说明 | 4119| -------- | ---------------------------------------- | ---- | ----------------------------------- | 4120| type | string | 是 | 事件回调类型,支持的事件为'BLEDeviceFind',表示BLE设备扫描结果上报事件。<br>当调用[startScan](#startscan15) 后,开始BLE扫描,若扫描到BLE设备,触发该事件。 | 4121| callback | Callback<[ScanReport](#scanreport15)> | 是 | 指定订阅的回调函数,会携带扫描结果的集合。 | 4122 4123**错误码**: 4124 4125以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 4126 4127| 错误码ID | 错误信息 | 4128| -------- | ---------------------------- | 4129|201 | Permission denied. | 4130|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 4131|801 | Capability not supported. | 4132|2900099 | Operation failed. | 4133 4134**示例:** 4135 4136```js 4137import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 4138import { ble } from '@kit.ConnectivityKit'; 4139function onReceiveEvent(scanReport: ble.ScanReport) { 4140 console.info('bluetooth device find = '+ JSON.stringify(scanReport)); 4141} 4142let bleScanner: ble.BleScanner = ble.createBleScanner(); 4143try { 4144 bleScanner.on('BLEDeviceFind', onReceiveEvent); 4145} catch (err) { 4146 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 4147} 4148``` 4149 4150### off('BLEDeviceFind')<sup>15+</sup> 4151 4152off(type: 'BLEDeviceFind', callback?: Callback<ScanReport>): void 4153 4154取消订阅BLE设备扫描结果上报事件。<br> 4155- 若不再需要扫描BLE设备,调用[stopScan](#stopscan15)方法后,需要调用此方法取消订阅。 4156 4157**需要权限**:ohos.permission.ACCESS_BLUETOOTH 4158 4159**原子化服务API**:从API version 15开始,该接口支持在原子化服务中使用。 4160 4161**系统能力**:SystemCapability.Communication.Bluetooth.Core 4162 4163**参数:** 4164 4165| 参数名 | 类型 | 必填 | 说明 | 4166| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 4167| type | string | 是 | 事件回调类型,支持的事件为'BLEDeviceFind',表示BLE设备扫描结果上报事件。 | 4168| callback | Callback<[ScanReport](#scanreport15)> | 否 | 指定取消订阅的回调函数通知。<br>若传参,则需与[on('BLEDeviceFind')](#onbledevicefind15)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 | 4169 4170**错误码**: 4171 4172以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 4173 4174| 错误码ID | 错误信息 | 4175| -------- | ---------------------------- | 4176|201 | Permission denied. | 4177|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 4178|801 | Capability not supported. | 4179|2900099 | Operation failed. | 4180 4181**示例:** 4182 4183```js 4184import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 4185import { ble } from '@kit.ConnectivityKit'; 4186function onReceiveEvent(scanReport: ble.ScanReport) { 4187 console.info('bluetooth device find = '+ JSON.stringify(scanReport)); 4188} 4189let bleScanner: ble.BleScanner = ble.createBleScanner(); 4190try { 4191 bleScanner.on('BLEDeviceFind', onReceiveEvent); 4192 bleScanner.off('BLEDeviceFind', onReceiveEvent); 4193} catch (err) { 4194 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 4195} 4196``` 4197 4198## GattService 4199 4200GATT服务结构定义,可包含多个特征值[BLECharacteristic](#blecharacteristic)和依赖的其他服务。 4201 4202**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4203 4204**系统能力**:SystemCapability.Communication.Bluetooth.Core 4205 4206| 名称 | 类型 | 只读 | 可选 | 说明 | 4207| --------------- | ---------------------------------------- |---- | ---- | ---------------------------------------- | 4208| serviceUuid | string | 否 | 否 | 服务UUID,标识一个GATT服务。例如:00001888-0000-1000-8000-00805f9b34fb。 | 4209| isPrimary | boolean | 否 | 否 | 是否是主服务。true表示是主服务,false表示是次要服务。 | 4210| characteristics | Array<[BLECharacteristic](#blecharacteristic)> | 否 | 否 | 当前服务包含的特征值列表。 | 4211| includeServices | Array<[GattService](#gattservice)> | 否 | 是 | 当前服务依赖的其它服务。 | 4212 4213 4214 4215## BLECharacteristic 4216 4217GATT特征值结构定义,是服务[GattService](#gattservice)的核心数据单元。 4218 4219**系统能力**:SystemCapability.Communication.Bluetooth.Core 4220 4221| 名称 | 类型 | 只读 | 可选 | 说明 | 4222| ------------------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | 4223| serviceUuid | string | 否 | 否 | 特征值所属的服务UUID。例如:00001888-0000-1000-8000-00805f9b34fb。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4224| characteristicUuid | string | 否 | 否 | 特征值UUID。例如:00002a11-0000-1000-8000-00805f9b34fb。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4225| characteristicValue | ArrayBuffer | 否 | 否 | 特征值的数据内容。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4226| descriptors | Array<[BLEDescriptor](#bledescriptor)> | 否 | 否 | 特征值包含的描述符列表。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4227| properties | [GattProperties](#gattproperties) | 否 | 是 | 特征值支持的属性。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4228| characteristicValueHandle<sup>18+</sup> | number | 否 | 是 | 特征值的唯一标识句柄。当server端BLE蓝牙设备提供了多个相同UUID特征值时,可以通过此句柄区分不同的特征值。<br>**原子化服务API**:从API version 18开始,该接口支持在原子化服务中使用。 | 4229| permissions<sup>20+</sup> | [GattPermissions](#gattpermissions20) | 否 | 是 | 特征值读写操作需要的权限。<br>**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 | 4230 4231 4232## BLEDescriptor 4233 4234GATT描述符结构定义,是特征值[BLECharacteristic](#blecharacteristic)的数据单元,用于描述特征值的附加信息和属性。 4235 4236**系统能力**:SystemCapability.Communication.Bluetooth.Core 4237 4238| 名称 | 类型 | 只读 | 可选 | 说明 | 4239| ------------------ | ----------- | ---- | ---- | ---------------------------------------- | 4240| serviceUuid | string | 否 | 否 | 特征值所属的服务UUID。例如:00001888-0000-1000-8000-00805f9b34fb。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4241| characteristicUuid | string | 否 | 否 | 描述符所属的特征值UUID。例如:00002a11-0000-1000-8000-00805f9b34fb。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4242| descriptorUuid | string | 否 | 否 | 描述符UUID。例如:00002902-0000-1000-8000-00805f9b34fb。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4243| descriptorValue | ArrayBuffer | 否 | 否 | 描述符的数据内容。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4244| descriptorHandle<sup>18+</sup> | number | 否 | 是 | 描述符的唯一标识句柄。当server端BLE蓝牙设备提供了多个相同UUID描述符时,可以通过此句柄区分不同的描述符。<br>**原子化服务API**:从API version 18开始,该接口支持在原子化服务中使用。 | 4245| permissions<sup>20+</sup> | [GattPermissions](#gattpermissions20) | 否 | 是 | 描述符读写操作需要的权限。<br>**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 | 4246 4247 4248## NotifyCharacteristic 4249 4250描述server端特征值发生变化时,server端发送特征值通知的参数结构。 4251 4252**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4253 4254**系统能力**:SystemCapability.Communication.Bluetooth.Core 4255 4256| 名称 | 类型 | 只读 | 可选 | 说明 | 4257| ------------------- | ----------- | ---- | ---- | ---------------------------------------- | 4258| serviceUuid | string | 否 | 否 | 特征值所属的服务UUID。例如:00001888-0000-1000-8000-00805f9b34fb。 | 4259| characteristicUuid | string | 否 | 否 | 内容发生变化的特征值UUID。例如:00002a11-0000-1000-8000-00805f9b34fb。 | 4260| characteristicValue | ArrayBuffer | 否 | 否 | 特征值对应的数据内容。 | 4261| confirm | boolean | 否 | 否 | true表示发送的是指示,需要client端回复确认。false表示发送的是通知,不需要client端回复确认。 | 4262 4263 4264## CharacteristicReadRequest 4265 4266描述server端订阅client端读特征值请求事件后,接收到的事件参数结构。 4267 4268**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4269 4270**系统能力**:SystemCapability.Communication.Bluetooth.Core 4271 4272| 名称 | 类型 | 只读 | 可选 | 说明 | 4273| ------------------ | ------ | ---- | ---- | ---------------------------------------- | 4274| deviceId | string | 否 | 否 | client端蓝牙设备地址。例如:"XX:XX:XX:XX:XX:XX"。 | 4275| transId | number | 否 | 否 | client端读请求的标识符,server端回复时需填写相同的transId。 | 4276| offset | number | 否 | 否 | client端读数据的偏移值。例如:k表示从第k个字节开始读。<br>server端回复响应时需填写相同的offset。 | 4277| characteristicUuid | string | 否 | 否 | client端需要读取的特征值UUID。例如:00002a11-0000-1000-8000-00805f9b34fb。 | 4278| serviceUuid | string | 否 | 否 | 特征值所属的服务UUID。例如:00001888-0000-1000-8000-00805f9b34fb。 | 4279 4280 4281## CharacteristicWriteRequest 4282 4283描述server端订阅client端写特征值请求事件后,接收到的事件参数结构。 4284 4285**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4286 4287**系统能力**:SystemCapability.Communication.Bluetooth.Core 4288 4289| 名称 | 类型 | 只读 | 可选 | 说明 | 4290| ------------------ | ------ | ---- | ---- | ---------------------------------------- | 4291| deviceId | string | 否 | 否 | client端蓝牙设备地址。例如:"XX:XX:XX:XX:XX:XX"。 | 4292| transId | number | 否 | 否 | client端写请求的标识符,server端回复时需填写相同的transId。 | 4293| offset | number | 否 | 否 | client端写数据的偏移值。例如:k表示从第k个字节开始写。<br>server端回复时需填写相同的offset。 | 4294| isPrepared | boolean | 否 | 否 | 收到client端写请求后,是否立即回复。<br>true表示稍后回复,false表示立即回复。 | 4295| needRsp | boolean | 否 | 否 | 是否需要回复client端。<br>true表示需要回复,false表示不需要回复。 | 4296| value | ArrayBuffer | 否 | 否 | client端需要给特征值写入的数据。 | 4297| characteristicUuid | string | 否 | 否 | client端需要写入的特征值UUID。例如:00002a11-0000-1000-8000-00805f9b34fb。 | 4298| serviceUuid | string | 否 | 否 | 特征值所属的服务UUID。例如:00001888-0000-1000-8000-00805f9b34fb。 | 4299 4300 4301## DescriptorReadRequest 4302 4303描述server端订阅client端读描述符请求事件后,接收到的事件参数结构。 4304 4305**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4306 4307**系统能力**:SystemCapability.Communication.Bluetooth.Core 4308 4309| 名称 | 类型 | 只读 | 可选 | 说明 | 4310| ------------------ | ------ | ---- | ---- | ---------------------------------------- | 4311| deviceId | string | 否 | 否 | client端蓝牙设备地址。例如:"XX:XX:XX:XX:XX:XX"。 | 4312| transId | number | 否 | 否 | client端读请求的标识符,server端回复时需填写相同的transId。 | 4313| offset | number | 否 | 否 | client端读数据的偏移值。例如:k表示从第k个字节开始读。<br>server端回复响应时需填写相同的offset。 | 4314| descriptorUuid | string | 否 | 否 | client端需要读取的描述符UUID。例如:00002902-0000-1000-8000-00805f9b34fb。 | 4315| characteristicUuid | string | 否 | 否 | 描述符所属的特征值UUID。例如:00002a11-0000-1000-8000-00805f9b34fb。 | 4316| serviceUuid | string | 否 | 否 | 特征值所属的服务UUID。例如:00001888-0000-1000-8000-00805f9b34fb。 | 4317 4318 4319## DescriptorWriteRequest 4320 4321描述server端订阅client端写描述符请求事件后,接收到的事件参数结构。 4322 4323**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4324 4325**系统能力**:SystemCapability.Communication.Bluetooth.Core 4326 4327| 名称 | 类型 | 只读 | 可选 | 说明 | 4328| ------------------ | ----------- | ---- | ---- | ---------------------------------------- | 4329| deviceId | string | 否 | 否 | client端蓝牙设备地址。例如:"XX:XX:XX:XX:XX:XX"。 | 4330| transId | number | 否 | 否 | client端写请求的标识符,server端回复时需填写相同的transId。 | 4331| offset | number | 否 | 否 | client端写数据的偏移值。例如:k表示从第k个字节开始写。<br>server端回复时需填写相同的offset。 | 4332| isPrepared | boolean | 否 | 否 | 收到client端写请求后,是否立即回复。<br>true表示稍后回复,false表示立即回复。 | 4333| needRsp | boolean | 否 | 否 | 是否需要回复client端。<br>true表示需要回复,false表示不需要回复。 | 4334| value | ArrayBuffer | 否 | 否 | client端需要给描述符写入的数据。 | 4335| descriptorUuid | string | 否 | 否 | client端需要写入的描述符UUID。例如:00002902-0000-1000-8000-00805f9b34fb。 | 4336| characteristicUuid | string | 否 | 否 | 描述符所属的特征值UUID。例如:00002a11-0000-1000-8000-00805f9b34fb。 | 4337| serviceUuid | string | 否 | 否 | 特征值所属的服务UUID。例如:00001888-0000-1000-8000-00805f9b34fb。 | 4338 4339 4340## ServerResponse 4341 4342描述server端回复client端读或者写请求的响应参数结构。 4343 4344**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4345 4346**系统能力**:SystemCapability.Communication.Bluetooth.Core 4347 4348| 名称 | 类型 | 只读 | 可选 | 说明 | 4349| -------- | ----------- | ---- | ---- | -------------------------------------- | 4350| deviceId | string | 否 | 否 | client端蓝牙设备地址。例如:"XX:XX:XX:XX:XX:XX"。 | 4351| transId | number | 否 | 否 | 收到client端请求的标识符,与订阅client端读或者写请求事件携带的transId保持一致。 | 4352| status | number | 否 | 否 | 响应的状态,设置为0即可,表示正常。 | 4353| offset | number | 否 | 否 | client端读或者写请求的数据偏移值,与订阅client端读或者写请求事件携带的offset保持一致。 | 4354| value | ArrayBuffer | 否 | 否 | 回复的数据。 | 4355 4356 4357## BLEConnectionChangeState 4358 4359描述GATT profile协议连接状态。 4360 4361**系统能力**:SystemCapability.Communication.Bluetooth.Core 4362 4363| 名称 | 类型 | 只读 | 可选 | 说明 | 4364| -------- | ------------------------------------------------- | ---- | ---- | --------------------------------------------- | 4365| deviceId | string | 否 | 否 | 对端蓝牙设备地址。例如:"XX:XX:XX:XX:XX:XX"。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4366| state | [ProfileConnectionState](js-apis-bluetooth-constant.md#profileconnectionstate) | 否 | 否 | GATT profile连接状态。 <br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4367| reason<sup>20+</sup> | [GattDisconnectReason](#gattdisconnectreason20) | 否 | 是 | GATT链路断连原因,仅在连接状态为 [STATE_DISCONNECTED](js-apis-bluetooth-constant.md#profileconnectionstate) 时提供,其他连接状态下断连原因默认为undefined。<br> **原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。| 4368 4369 4370## ScanResult 4371 4372扫描到符合过滤条件的广播报文后,上报的扫描数据。 4373 4374**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4375 4376**系统能力**:SystemCapability.Communication.Bluetooth.Core 4377 4378| 名称 | 类型 | 只读 | 可选 | 说明 | 4379| -------- | ----------- | ---- | ---- | ---------------------------------- | 4380| deviceId | string | 否 | 否 | 扫描到的蓝牙设备地址。例如:"XX:XX:XX:XX:XX:XX"。<br>基于信息安全考虑,此处获取的设备地址为虚拟MAC地址。<br>- 若和该设备地址配对成功后,该地址不会变更。<br>- 若取消配对该设备或蓝牙关闭后,再次重新发起扫描,该虚拟地址会变更。<br>- 若要持久化保存该地址,可使用[access.addPersistentDeviceId](js-apis-bluetooth-access.md#accessaddpersistentdeviceid16)方法。 | 4381| rssi | number | 否 | 否 | 扫描到的设备信号强度,单位:dBm。 | 4382| data | ArrayBuffer | 否 | 否 | 扫描到的设备发送的广播报文内容。 | 4383| deviceName | string | 否 | 否 | 扫描到的设备名称。 | 4384| connectable | boolean | 否 | 否 | 扫描到的设备是否可连接。true表示可连接,false表示不可连接。 | 4385 4386 4387## AdvertiseSetting 4388 4389描述BLE广播的发送参数。 4390 4391**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4392 4393**系统能力**:SystemCapability.Communication.Bluetooth.Core 4394 4395| 名称 | 类型 | 只读 | 可选 | 说明 | 4396| ----------- | ------- | ---- | ---- | ---------------------------------------- | 4397| interval | number | 否 | 是 | 广播发送间隔。<br>取值范围:[32, 16777215],单位:slot(时间槽),一个slot代表0.625毫秒,默认值为1600。<br>其中传统广播的最大值是16384。 | 4398| txPower | number | 否 | 是 | 广播发送功率。取值范围:[-127, 1],单位:dBm,默认值为-7。<br>考虑到发送广播的性能和功耗,建议高档取值为1,中档取为-7,低档取值为-15。 | 4399| connectable | boolean | 否 | 是 | 是否是可连接广播。true表示发送可连接广播,false表示发送不可连接广播,默认值为true。 | 4400 4401 4402## AdvertiseData 4403 4404描述BLE广播报文数据内容,也可以用作回复扫描请求的广播报文数据内容。当前只支持传统广播,因此报文最大长度为31个字节。若超出最大长度(31个字节)限制,会导致启动广播失败。若携带了所有参数,尤其是携带了蓝牙设备名称,需要注意广播报文长度。 4405 4406**系统能力**:SystemCapability.Communication.Bluetooth.Core 4407 4408| 名称 | 类型 | 只读 | 可选 | 说明 | 4409| --------------- | ---------------------------------------- | ---- | ---- | --------------------------- | 4410| serviceUuids | Array<string> | 否 | 否 | 要携带的服务UUID。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4411| manufactureData | Array<[ManufactureData](#manufacturedata)> | 否 | 否 | 要携带的制造商数据内容。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4412| serviceData | Array<[ServiceData](#servicedata)> | 否 | 否 | 要携带的服务数据内容。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4413| includeDeviceName | boolean | 否 | 是 | 是否携带蓝牙设备名称。true表示携带,false表示不携带,默认值为false。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4414| includeTxPower<sup>18+</sup> | boolean | 否 | 是 | 是否携带广播发送功率。<br>true表示携带广播发送功率,false表示不携带广播发送功率,默认值为false。<br>携带该值后,广播报文长度将多占用3个字节。<br>**原子化服务API**:从API version 18开始,该接口支持在原子化服务中使用。 | 4415 4416 4417## AdvertisingParams<sup>11+</sup> 4418 4419首次启动BLE广播时设置的参数。 4420 4421**系统能力**:SystemCapability.Communication.Bluetooth.Core 4422 4423| 名称 | 类型 | 只读 | 可选 | 说明 | 4424| ------------------- | ------------------------------- | ----- | ----- | ------------------------ | 4425| advertisingSettings<sup>11+</sup> | [AdvertiseSetting](#advertisesetting) | 否 | 否 | 广播的发送参数。 | 4426| advertisingData<sup>11+</sup> | [AdvertiseData](#advertisedata) | 否 | 否 | 需要发送的广播报文数据内容。 | 4427| advertisingResponse<sup>11+</sup> | [AdvertiseData](#advertisedata) | 否 | 是 | 回复扫描请求的广播报文数据内容。 | 4428| duration<sup>11+</sup> | number | 否 | 是 | 发送广播的持续时间。取值范围:[1, 65535],单位:10ms。<br>如果未指定此参数或者将其设置为0,则会持续发送广播。 | 4429 4430## AdvertisingEnableParams<sup>11+</sup> 4431 4432启动指定标识的BLE广播时设置的参数。 4433 4434**系统能力**:SystemCapability.Communication.Bluetooth.Core 4435 4436| 名称 | 类型 | 只读 | 可选 | 说明 | 4437| ------------------- | --------------------- | ----- | ----- | ------------------------ | 4438| advertisingId | number | 否 | 否 | 需要启动的广播标识。 | 4439| duration | number | 否 | 是 | 发送广播的持续时间。取值范围:[1, 65535],单位:10ms。<br>如果未指定此参数或者将其设置为0,则会持续发送广播。 | 4440 4441## AdvertisingDisableParams<sup>11+</sup> 4442 4443停止指定标识的BLE广播时设置的参数。 4444 4445**系统能力**:SystemCapability.Communication.Bluetooth.Core 4446 4447| 名称 | 类型 | 只读 | 可选 | 说明 | 4448| ------------------- | --------------------- | ----- | ----- | ------------------------ | 4449| advertisingId | number | 否 | 否 | 需要停止的广播标识。 | 4450 4451## AdvertisingStateChangeInfo<sup>11+</sup> 4452 4453描述BLE广播启动、停止的状态信息。 4454 4455**系统能力**:SystemCapability.Communication.Bluetooth.Core 4456 4457| 名称 | 类型 | 只读 | 可选 | 说明 | 4458| ------------------- | --------------------------------------- | ----- | ----- | ------------------------ | 4459| advertisingId | number | 否 | 否 |首次启动广播时会分配该值,后续用于标识当前操作的广播。 | 4460| state | [AdvertisingState](#advertisingstate11) | 否 | 否 | 操作广播后,收到的BLE广播状态。 | 4461 4462## ManufactureData 4463 4464描述BLE广播报文中制造商数据内容。 4465 4466**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4467 4468**系统能力**:SystemCapability.Communication.Bluetooth.Core 4469 4470| 名称 | 类型 | 只读 | 可选 | 说明 | 4471| ---------------- | ------------------- | ---- | ---- | ------------------ | 4472| manufactureId | number | 否 | 否 | 制造商的标识,由蓝牙技术联盟分配。 | 4473| manufactureValue | ArrayBuffer | 否 | 否 | 制造商特定的数据。 | 4474 4475 4476## ServiceData 4477 4478描述BLE广播报文中的服务数据内容。 4479 4480**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4481 4482**系统能力**:SystemCapability.Communication.Bluetooth.Core 4483 4484| 名称 | 类型 | 只读 | 可选 | 说明 | 4485| ------------ | ----------- | ---- | ---- | ---------- | 4486| serviceUuid | string | 否 | 否 | 服务UUID。 | 4487| serviceValue | ArrayBuffer | 否 | 否 | 服务数据。 | 4488 4489 4490## ScanFilter 4491 4492扫描BLE广播的过滤条件,只有符合该条件的广播报文才会上报。 4493 4494**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4495 4496**系统能力**:SystemCapability.Communication.Bluetooth.Core 4497 4498| 名称 | 类型 | 只读 | 可选 | 说明 | 4499| ------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | 4500| deviceId | string | 否 | 是 | 过滤该BLE设备地址的广播报文。例如:"XX:XX:XX:XX:XX:XX"。 | 4501| name | string | 否 | 是 | 过滤该BLE设备名称的广播报文。 | 4502| serviceUuid | string | 否 | 是 | 过滤包含该服务UUID的广播报文。例如:00001888-0000-1000-8000-00805f9b34fb。 | 4503| serviceUuidMask | string | 否 | 是 | 搭配serviceUuid过滤器使用,可设置过滤部分服务UUID。例如:FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF。 | 4504| serviceSolicitationUuid | string | 否 | 是 | 过滤包含该服务请求UUID的广播报文。例如:00001888-0000-1000-8000-00805F9B34FB。 | 4505| serviceSolicitationUuidMask | string | 否 | 是 | 搭配serviceSolicitationUuid过滤器使用,可设置过滤部分服务请求UUID。例如:FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF。 | 4506| serviceData | ArrayBuffer | 否 | 是 | 过滤包含该服务数据的广播报文。例如:[0x90,0x00,0xF1,0xF2]。 | 4507| serviceDataMask | ArrayBuffer | 否 | 是 | 搭配serviceData过滤器使用,可设置过滤部分服务数据。例如:[0xFF,0xFF,0xFF,0xFF]。 | 4508| manufactureId | number | 否 | 是 | 过滤包含该制造商标识符的广播报文。例如:0x0006。 | 4509| manufactureData | ArrayBuffer | 否 | 是 | 搭配manufactureId过滤器使用,过滤包含该制造商数据的广播报文。例如:[0x1F,0x2F,0x3F]。 | 4510| manufactureDataMask | ArrayBuffer | 否 | 是 | 搭配manufactureData过滤器使用,可设置过滤部分制造商数据。例如:[0xFF,0xFF,0xFF]。 | 4511 4512 4513## ScanOptions 4514 4515BLE扫描的配置参数。 4516 4517**系统能力**:SystemCapability.Communication.Bluetooth.Core 4518 4519| 名称 | 类型 | 只读 | 可选 | 说明 | 4520| --------- | ----------------------- | ---- | ---- | -------------------------------------- | 4521| interval | number | 否 | 是 | 扫描结果上报的延迟时间,单位:ms,默认值为0。搭配[ScanReportMode](#scanreportmode15)使用。<br>- 在常规或围栏扫描上报模式下,该值不生效,扫描到符合过滤条件的广播报文后立即上报。<br>- 在批量扫描上报模式下,该值生效,扫描到符合过滤条件的广播报文后,会存入缓存队列,延迟上报。若不设置该值或设置在[0, 5000)范围内,蓝牙子系统会默认设置延迟时间为5000ms。延迟时间内,若符合过滤条件的广播报文数量超过硬件缓存能力,蓝牙子系统会提前上报扫描结果。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4522| dutyMode | [ScanDuty](#scanduty) | 否 | 是 | 扫描模式,默认值为SCAN_MODE_LOW_POWER。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4523| matchMode | [MatchMode](#matchmode) | 否 | 是 | 硬件的过滤匹配模式,默认值为MATCH_MODE_AGGRESSIVE。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4524| phyType<sup>12+</sup> | [PhyType](#phytype12) | 否 | 是 | 扫描中使用的物理通道类型,默认值为PHY_LE_1M。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4525| reportMode<sup>15+</sup> | [ScanReportMode](#scanreportmode15) | 否 | 是 | 扫描结果数据上报模式,默认值为NORMAL。<br>**原子化服务API**:从API version 15开始,该接口支持在原子化服务中使用。 | 4526 4527 4528## GattProperties 4529 4530描述GATT特征值支持的属性。决定了特征值内容和描述符如何被使用和访问。 4531 4532**系统能力**:SystemCapability.Communication.Bluetooth.Core 4533 4534| 名称 | 类型 | 只读 | 可选 | 说明 | 4535| -------- | ------ |---- |---- | ----------- | 4536| write | boolean | 否 | 是 | 该特征值是否支持写入操作。<br>true表示支持,且被写入时需要回复对端设备,false表示不支持。默认值为true。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4537| writeNoResponse | boolean | 否 | 是 | 该特征值是否支持写入操作。<br>true表示支持,且被写入时无需回复对端设备,false表示不支持。默认值为true。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4538| read | boolean | 否 | 是 | 该特征值是否支持读取操作。<br>true表示支持,false表示不支持。默认值为true。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4539| notify | boolean | 否 | 是 | 该特征值是否支持主动向对端设备通知特征值内容。<br>true表示支持,且对端设备不需要回复确认,false表示不支持。默认值为false。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4540| indicate | boolean | 否 | 是 | 该特征值是否支持向对端设备指示特征值内容。<br>true表示支持,对端设备需要回复确认,false表示不支持。默认值为false。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 | 4541| broadcast<sup>20+</sup> | boolean | 否 | 是 | 该特征值是否支持作为广播内容由server端发送。<br>true表示支持,server端可将特征值内容以[ServiceData](#servicedata)类型在广播报文中携带,false表示不支持。默认值为false。<br>**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 | 4542| authenticatedSignedWrite<sup>20+</sup> | boolean | 否 | 是 | 该特征值是否支持签名写入操作,通过对写入内容进行签名校验替代加密流程。<br>true表示支持,且该特征值权限[GattPermissions](#gattpermissions20)中的writeSigned或writeSignedMitm需设置为true,否则该属性不生效,false表示不支持。默认值为false。<br>**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 | 4543| extendedProperties<sup>20+</sup> | boolean | 否 | 是 | 该特征值是否存在扩展属性。<br>true表示存在扩展属性,false表示不存在。默认值为false。<br>**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 | 4544 4545 4546## GattPermissions<sup>20+</sup> 4547 4548描述读写GATT特征值或描述符需具备的权限。 4549 4550**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 4551 4552**系统能力**:SystemCapability.Communication.Bluetooth.Core 4553 4554| 名称 | 类型 | 只读 | 可选 | 说明 | 4555| -------- | ------ |---- |---- | ----------- | 4556| read | boolean | 否 | 是 | 是否允许读取该特征值或描述符内容。<br>true表示允许,false表示不允许。默认值为true。 | 4557| readEncrypted | boolean | 否 | 是 | 读取该特征值或描述符内容是否需要加密。<br>true表示需要加密后,方可读取内容,false表示不需要普通方式加密。默认值为false。 | 4558| readEncryptedMitm | boolean | 否 | 是 | 读取该特征值或描述符内容是否需要防中间人攻击的加密。<br>防中间人攻击表示操作需要经过认证,防止数据被第三方篡改。true表示需要防中间人攻击的加密后才能读取内容,false表示不需要防中间人攻击的加密。默认值为false。 | 4559| write | boolean | 否 | 是 | 是否允许写入该特征值或描述符内容。<br>true表示允许,false表示不允许。默认值为true。 | 4560| writeEncrypted | boolean | 否 | 是 | 写入该特征值或描述符内容是否需要加密。<br>true表示需要加密后,方可写入内容,false表示不需要普通方式加密。默认值为false。 | 4561| writeEncryptedMitm | boolean | 否 | 是 | 写入该特征值或描述符内容是否需要防中间人攻击的加密。<br>true表示需要防中间人攻击的加密后才能写入内容,false表示不需要防中间人攻击的加密。默认值为false。 | 4562| writeSigned | boolean | 否 | 是 | 写入该特征值或描述符内容是否需要经过签名处理。<br>true表示内容需要签名处理后方可写入,false表示不需要签名处理。默认值为false。 | 4563| writeSignedMitm | boolean | 否 | 是 | 写入该特征值或描述符内容是否需要经过防中间人攻击方式的签名处理。<br>true表示需要防中间人攻击方式的签名处理后方可写入,false表示不需要以防中间人攻击方式签名处理。默认值为false。 | 4564 4565 4566## GattWriteType 4567 4568枚举,写入特征值的方式(不同的取值,对端蓝牙设备的表现不一样)。 4569 4570**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4571 4572**系统能力**:SystemCapability.Communication.Bluetooth.Core 4573 4574| 名称 | 值 | 说明 | 4575| ------------------------------------| ------ | --------------- | 4576| WRITE | 1 | 写入特征值后,对端蓝牙设备需要回复确认。 | 4577| WRITE_NO_RESPONSE | 2 | 写入特征值后,对端蓝牙设备不需要回复。 | 4578 4579 4580## ScanDuty 4581 4582枚举,扫描模式,表示不同的扫描性能和功耗情况。 4583 4584**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4585 4586**系统能力**:SystemCapability.Communication.Bluetooth.Core 4587 4588| 名称 | 值 | 说明 | 4589| --------------------- | ---- | ------------ | 4590| SCAN_MODE_LOW_POWER | 0 | 低功耗模式,扫描性能较低,功耗也较低。 | 4591| SCAN_MODE_BALANCED | 1 | 均衡模式,平衡扫描性能和功耗。 | 4592| SCAN_MODE_LOW_LATENCY | 2 | 低延迟模式,扫描性能较高,但功耗也较高。 | 4593 4594 4595## MatchMode 4596 4597枚举,硬件过滤匹配模式。 4598 4599**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4600 4601**系统能力**:SystemCapability.Communication.Bluetooth.Core 4602 4603| 名称 | 值 | 说明 | 4604| --------------------- | ---- | ---------------------------------------- | 4605| MATCH_MODE_AGGRESSIVE | 1 | 当广播报文信号强度较低或者短时间内广播报文的发送次数较少时,可以更快地上报。 | 4606| MATCH_MODE_STICKY | 2 | 广播报文信号强度较高或者短时间内广播报文的发送次数较多时,才会上报。 | 4607 4608## AdvertisingState<sup>11+</sup> 4609 4610枚举,不同操作对应的BLE广播状态。 4611 4612**系统能力**:SystemCapability.Communication.Bluetooth.Core 4613 4614| 名称 | 值 | 说明 | 4615| -------- | ---- | ------------------------------ | 4616| STARTED<sup>11+</sup> | 1 | 调用[startAdvertising](#blestartadvertising11)方法后,广播首次启动成功,且会分配相关资源。 | 4617| ENABLED<sup>11+</sup> | 2 | 调用[enableAdvertising](#bleenableadvertising11)方法后,广播启动成功。 | 4618| DISABLED<sup>11+</sup> | 3 | 调用[disableAdvertising](#bledisableadvertising11)方法后,广播停止成功。 | 4619| STOPPED<sup>11+</sup> | 4 | 调用[stopAdvertising](#blestopadvertising11)方法后,广播停止成功,且会释放首次启动广播时分配的相关资源。 | 4620 4621## PhyType<sup>12+</sup> 4622 4623枚举,指定扫描过程中接收BLE广播报文的物理通道。 4624 4625**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 4626 4627**系统能力**:SystemCapability.Communication.Bluetooth.Core 4628 4629| 名称 | 值 | 说明 | 4630| -------- | ---- | ------------------------------ | 4631| PHY_LE_1M<sup>12+</sup> | 1 | 使用1M PHY类型扫描。 | 4632| PHY_LE_ALL_SUPPORTED<sup>12+</sup> | 255 | 使用所有支持的PHY类型扫描。 | 4633 4634## ScanReport<sup>15+</sup> 4635 4636上报的扫描数据。 4637 4638**原子化服务API**:从API version 15开始,该接口支持在原子化服务中使用。 4639 4640**系统能力**:SystemCapability.Communication.Bluetooth.Core 4641 4642| 名称 | 类型 |只读 |可选 | 说明 | 4643| --------- | ----------------------- | ---- | ---- | ------------------------------ | 4644| reportType | [ScanReportType](#scanreporttype15) | 否 | 否 | 扫描结果上报类型。 | 4645| scanResult | Array<[ScanResult](#scanresult)> | 否 | 否 | 扫描到符合过滤条件的BLE广播报文后,上报的扫描数据。 | 4646 4647## ScanReportType<sup>15+</sup> 4648 4649枚举,扫描结果上报类型。 4650 4651**系统能力**:SystemCapability.Communication.Bluetooth.Core 4652 4653| 名称 | 值 | 说明 | 4654| -------- | ---- | ------------------------------ | 4655| ON_FOUND | 1 | 扫描到符合过滤条件的BLE广播报文时,触发上报,可搭配常规和围栏上报模式使用。 <br> **原子化服务API**:从API version 15开始,该接口支持在原子化服务中使用。 | 4656| ON_LOST | 2 | 当不再扫描到符合过滤条件的BLE广播报文时,触发上报,只搭配围栏上报模式使用。 <br> **原子化服务API**:从API version 15开始,该接口支持在原子化服务中使用 | 4657| ON_BATCH<sup>19+</sup> | 3 | 扫描到符合过滤条件的BLE广播报文时,以[ScanOptions](#scanoptions)中的interval字段为周期触发上报。 <br> **原子化服务API**:从API version 19开始,该接口支持在原子化服务中使用 | 4658 4659## GattDisconnectReason<sup>20+</sup> 4660 4661枚举,指定GATT链路断开的原因。 4662 4663**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 4664 4665**系统能力**:SystemCapability.Communication.Bluetooth.Core 4666 4667| 名称 | 值 | 说明 | 4668| -------- | ---- | ------------------------------ | 4669| CONN_TIMEOUT | 1 | 连接超时。 | 4670| CONN_TERMINATE_PEER_USER | 2 | 对端设备主动断开连接。 | 4671| CONN_TERMINATE_LOCAL_HOST | 3 | 本端设备主动断开连接。 | 4672| CONN_UNKNOWN | 4 | 未知断连原因。 | 4673 4674## ScanReportMode<sup>15+</sup> 4675 4676枚举,扫描结果上报模式。 4677 4678**系统能力**:SystemCapability.Communication.Bluetooth.Core 4679 4680| 名称 | 值 | 说明 | 4681| -------- | ---- | ------------------------------ | 4682| NORMAL | 1 | 常规扫描上报模式,扫描到符合过滤条件的BLE广播报文后就会立刻上报。<br>**原子化服务API**:从API version 15开始,该接口支持在原子化服务中使用。 | 4683| BATCH<sup>19+</sup> | 2 | 批量扫描上报模式。<br>- 该模式可通过降低蓝牙芯片上报扫描结果频率,使系统更长时间地保持在休眠状态,从而降低整机功耗。<br>- 该模式下,扫描到符合过滤条件的BLE广播报文后不会立刻上报,需要缓存一段时间([ScanOptions](#scanoptions)中的interval字段)后上报。 <br>**原子化服务API**:从API version 19开始,该接口支持在原子化服务中使用。 | 4684| FENCE_SENSITIVITY_LOW<sup>18+</sup> | 10 | 低灵敏度围栏上报模式。<br>- 围栏模式表示只在广播进入或离开围栏时上报。<br>- 扫描到的广播信号强度高且广播数量多时,可进入低灵敏度围栏。<br>- 首次扫描到广播即进入围栏,触发一次上报。<br>- 一段时间内扫描不到广播即离开围栏,触发一次上报。<br>**原子化服务API**:从API version 18开始,该接口支持在原子化服务中使用。 | 4685| FENCE_SENSITIVITY_HIGH<sup>18+</sup> | 11 | 高灵敏度围栏上报模式。<br>- 围栏模式表示只在广播进入或离开围栏时上报。<br>- 扫描到的广播信号强度低且广播数量少时,可进入高灵敏度围栏。<br>- 首次扫描到广播即进入围栏,触发一次上报。<br>- 一段时间内扫描不到广播即离开围栏,触发一次上报。<br>**原子化服务API**:从API version 18开始,该接口支持在原子化服务中使用。 |